vb6 winsock control RemoteHostIP truncates the last digit from IP address

Question: Hi i am writing a socket client/server application in VB6.
i have the following code
Private Sub sockMain_ConnectionRequest(ByVal requestID As Long)
    If sockMain.State <> sckClosed Then
        sockMain.Close
    End If
    sockMain.Accept requestID
    Debug.Print "Accepted connection from: " & sockMain.RemoteHostIP & vbCrLf
End Sub

its printing the IP but the last digit is missing example, if my connection is from "192.168.1.123" then it shows "192.168.1.12" only
Comment: If socket connection is established are you sure the connection is established from 192.168.1.123. Did you check what IP is shown as the remote IP in tcpview software.
Comment: If the IP shows 192.168.1.123 then i dont there is any problem with the socket APIs. The problem will be with the way you are printing the IP.
Comment: I am able see the active connection and able to transfer data, and in the debug mode if i check the connection state, the socket is in Connected state only. there is no issue with the connection. but the control RemoteHostIP is always shows the IP by truncating the last digit, is i connect client from local i am getting 127.0.0. instead of 127.0.0.1
Answer: I've tried the exact same code and it works on my machine.  I tried using telnet from the same machine, and also from a laptop and the correct IP address was printed in both cases.
I have to agree with ckv and say that its the way you are printing RemoteHostIP.
Comment: If you used exact same code you must have used same function to print the IP also right? So you mean with same code as Dharma has mentioned above you are getting correct IP.
Comment: Hi CKV and quamrana, still i am not getting why in my system the last digit is missing. even if i set a watch for the socket object and checked during debug, still shows the RemoteHostIP by truncating the last character.
Comment: @Dharma: OK, that's bad.  Can you try a minimal version of the program on some different hardware/OS?
Comment: Except vb6 winsock control, other programming languages line VC++, C# and VB.Net i am able to get the RemoteIP address complete.
Comment: @Dharma: So what hardware/OS *are* you using to get the symptoms you describe in your question?
Comment: Pentium(R)D CPU 2.8 GHz/Windows XP sp2
Comment: @Dharma: Any chance of trying it on Vista or Windows 7?  btw My machine is Windows XP SP3.
Comment: Currently i am tied with other schedules..i will check this later,may be this week end.
Answer: This is a known bug in KB957924 Microsoft Visual Basic 6.0 Service Pack 6 Cumulative Update (link) in both v1 and May 2009 v2.   This is why some people can duplicate it and some can't.  It also is limited to the second and subsequent usage of the control.
It is discussed here.
As a really ugly workaround you can call recvfrom in the wsock32.dll lib with the sockMain.SocketHandle, a small buffer and the MSG_PEEK parameter (&H2) to retrieve the socket address directly.  This must be done before calling sockMain.GetData().  Then you have to parse out the IP address yourself.  I can post code that does this for the specific case I'm using (UDP) if requested.
I'm not sure it will work in your case since it looks like you're using TCP and Accept.


find formula to count of string

Question: I have to find pattern of count of series.
Lenght of series is $2n$. It is neccessary to use exaclty double times every number in range $[1...n]$ and all of neighboring numbers are different.
Look at example.
$a_0 = 0$
$a_1 = 0$
$a_2 = 2$    (because of $1212$ and $2121$)
And my idea is:
$$ a_{n+1}= {2n+1\choose 2}a_n $$
Is it properly ?
Comment: It's a good idea
Comment: Is it easy to find pattern without recursion ? Maybe generating function ?
Comment: I don't know..seems recursion is the easiest way here.
Answer: For $a_3$, you'll add two $3$'s somewhere to each one of those so they're not next to each other.  There are $5$ possible places: the two ends, and three in between two numbers, so there are ${5 \choose 2}$ ways of putting the two $3$'s in so they're not next to each other.
For case $a_n$:  There are $2n+1$ possible places to place $n+1$ in each of the ${a_n}$ series of length $2n$, so there are ${2n+1 \choose 2}$ ways to place the two $n$'s in each series.
Or,
$$a_{n+1} = {2n+1 \choose 2} a_n.$$
We can see the closed form by inspection:
$$a_{n} = {2n-1 \choose 2} a_{n-1} \\ = {2n-1 \choose 2}{2n-3 \choose 2}{2n-5 \choose 2} \cdots {7 \choose 2}{5 \choose 2}a_2 \\ = \frac{(2n-1)(2n-2)}{2}\frac{(2n-3)(2n-4)}{2}\frac{(2n-5)(2n-6)}{2} \cdots \frac{7 \cdot 6}{2}\frac{5 \cdot 4}{2}\cdot 2,$$
so
$$a_n =\frac{(2n-1)!}{3 \cdot 2^{n-2}}, n \geq 3.$$
Comment: To find a closed form, note that ${2n+1 \choose 2}=\frac {2n(2n+1)}2$  Look at the numerators of $a_n$ for a while-it looks like a factorial.  Then you can justify a closed form.
Comment: So How to find pattern without recursion ?
Comment: Could you help say more about your idea?  When it comes to my idea: $a_n = {2n-1\choose 2}a_{n-1} = {2n-1 \choose 2}\cdot {2n-3\choose 2}\cdot {2n-5 \choose 2} \cdot... \cdot {3\choose 2}$  And it is the same that I choose : ${2n-1 \choose n}$. But id doesn't work. What do I do wrong ?
Comment: I agree with your recursion formula. Note that $a_2 = 2.$ Your formula in the comment above takes it down one too far, I think. It should end with $\cdots {7 \choose 2}{5 \choose 2}\cdot 2$.

find formula to count of string


Diagram for correlation and regression

Question: I would like to include a diagram for a set of correlations of IVs with a DV. I have also run a multiple regression model. Would something like the below diagram look ok? And possibly writing: H1, H2... on the arrows representing the hypothesized relationships? (which were tested using Pearson Correlation). Or does the below represent the whole regression? I am not using SEM, do let me know if such diagram is only applicable to SEM.

(source: popularsocialscience.com)
Answer: From just the graph, I will associate this with a conceptual framework or a multiple linear regression model. If you put H1, H2 on each arrow, I will more incline to think those are hypotheses for each association after the other three independent variables are adjusted for. For this reason, I'd consider using it to show pair-wise correlation test hypotheses a bad idea.
You may use the arrow to show regression coefficients from the multiple regression, however. Acceptance for such practice may differ field by field, I'd survey around before making the decision.
This kind of graph is associated with SEM, but I do not think SEM exclusively owns it. Other methods such as path analysis (heavily related to SEM), directed acyclic graph, and even general conceptual framework use this kind of graphical expression. Even if it's considered as an SEM, it's still correct; the current form is how one would specify in SEM in order to run a very simple multiple linear model.
And a side comment, given the number of predictors being just four and the structure not being overly complicated, I don't think this graph is a space-conscious choice. You could have described the method in two sentences, and report the result of the regression in a 5x4 table (5 rows for title and 4 predictors, 4 columns for variable names, regression coefficient, SE or CI, and p-value.)
Comment: I will definitely report the values and tables but I would have liked to insert a diagram before the regression results aswell as a visual aid to explain what I am proposing.
Answer: If you want to report bivariate correlations of salary with your other variables, I'd do so in a table-formatted correlation matrix. Readers will generally appreciate knowing other bivariate correlations as well, as between age and competence, and they really don't take any extra space to include, e.g.:

Table 1. Fake correlation matrix.
Variable    Salary     Gender    Age    Education
Competence  -.50**     -.70***   .15    .40*
Education    .30       -.10      .20
Age          .30        .00
Gender       .20

Note. *$p<.05$. **Dilbert Principle. ***Tactical surrender.

In Table 1, $|r|<.40$ do not achieve $p<.05$; only larger, significant correlations get asterisks. This is the easy, conventional way to embed information about null hypothesis tests of no relationship.
As @Penguin_Knight says, your figure does imply a structural equation model where salary is regressed onto the other four variables simultaneously (i.e., multiple regression, not Pearson's $r$). Since you're not estimating latent variables, it would please the structural equation modelers among us if you use rectangular boxes instead of circles around your variables – this indicates that you measured your variables directly (simple sums or averages of several items on a scale would also count as measured directly enough). Figures with all rectangular boxes represent path analyses, which are just structural equation models with only measured variables...and multiple regression models are just very simple path analyses! In that sense, you actually have fit very simple SEMs.
Standard path diagrams put regression coefficients next to unidirectional (regressive or asymmetric) paths. I would recommend following this convention as well. If you want to represent information about null hypothesis tests visually, path diagrams sometimes do this by drawing paths as dotted lines instead of solid lines to indicate that the path coefficient did not differ significantly from zero. If you have more unusual hypotheses in mind, I don't think you should try to depict these visually, unless you've got very many unusual hypotheses of the same kind to represent.
Comment: Hi, so if I understood well, I should do a diagram like this one: https://support.sas.com/documentation/cdl/en/statug/63347/HTML/default/images/statug_calis0924.png  for my regression. Is there no need to include the constant term?
Comment: For your multiple regression, yes, but with all four independent variables. If any of those do not improve the model of `salary` significantly, you may wish to draw the insignificant paths as dotted lines. I recommend **not** using such a figure for bivariate correlations like Pearson's $r$.
Comment: yes I understand thanks. So let's say all my IVs are significant predictors p<.05, should I include a separate box with the constant term?
Comment: I'm not sure what you're asking; do you mean the intercept of the multiple regression model? If so, this constant can be represented as a triangle (the symbol for constants – as distinct from variables) with a 1 inside, and the intercept's value appears as a coefficient next to a path leading from it to the DV. See the [multiple regression path diagram example here](http://openmx.psyc.virginia.edu/docs/OpenMx/0.2.0-905/Examples_Path.html). As you'll see, even more details could be included, such as IV means, variances, and covariances...but much of this is optional.
Comment: yes I meant the intercept. Ok thanks will do that (though will not be including any paths between my IVs or the intercept with the IVs)
Comment: Yup, that makes sense to me!
Answer: A matrix of pairwise correlations is a fairly standard plot for multiple regression, something you'd often do before you started to assess multicolinearity etc. There are plenty of examples at this rblogger's article. For your data, you might get a plot something like this.

(produced using splom from lattice package)
Comment: think you forgot to link the rbloggers article

Diagram for correlation and regression


Thread : start, suspend, resume

Question: I was making an Android app (min SDK : 8, target SDK : 19)
now I want to set a loading icon to appear at the start until the application checks internet cennectivity
until now I have no problem
I had this method do it for me :
void setLoader(boolean T, String msg){
    View LAY = findViewById(R.id.loaderLayout);
    TextView MTV = (TextView) findViewById(R.id.loader_msg);
    if(T && !loaderStarted){
        loader.start();
        LAY.setVisibility(View.VISIBLE);
        MTV.setText(msg);
        loaderStarted = true;
    }
    else if (!T && loaderStarted) {
        loader.interrupt();
        LAY.setVisibility(View.GONE);
        loaderStarted = false;
    }
}

Then I needed to get user&pass then lock the UI with that thread again to check user&pass
The problem is :
  I have problem pausing a thread :|
my primary programming language isn't java
so please help me with this I have the Thread like this :
//first make loading icon visible then call :

    final private Thread loader = new Thread(new Runnable(){

    @Override
    public void run() {
        int i = 0;
        while (true){
            if(loader.isInterrupted()){
                return;
                }
            try {Thread.sleep(25);} catch (InterruptedException e) {}
            final int j = i;
            runOnUiThread(new Runnable(){
                public void run() {
                    ImageView imageView = (ImageView) findViewById(R.id.loaderImage);
                    Matrix matrix = new Matrix();
                    imageView.setScaleType(ScaleType.MATRIX);
                    int newWIDTH = imageView.getWidth();
                    int newHIEGHT = imageView.getHeight();
                    matrix.postScale(((float)(newWIDTH))/imageView.getDrawable().getBounds().width(), ((float)(newHIEGHT))/imageView.getDrawable().getBounds().height());
                    matrix.postRotate((float) j, newWIDTH/2, newHIEGHT/2);
                    imageView.setImageMatrix(matrix);
                }
            });
            i = (i + 15) % 360;
        }
    }
});

then I need a method like this :
void setLoader(boolean T, String msg){
    View LAY = findViewById(R.id.loaderLayout);
    TextView MTV = (TextView) findViewById(R.id.loader_msg);
    if(T && !loaderStarted){
        loader.start();
        LAY.setVisibility(View.VISIBLE);
        MTV.setText(msg);
        loaderStarted = true;
    }
    else if(T && loaderSuspended && loaderStarted){
        loader.resume();
        LAY.setVisibility(View.VISIBLE);
        MTV.setText(msg);
        loaderSuspended = false;
    }
    else if (loaderStarted && !loaderSuspended) {
        loader.suspend();
        LAY.setVisibility(View.GONE);
        loaderStarted = false;
        loaderSuspended = true;
    }
}

to suspend the thread then resume it
(.suspend() and .resume() are deprecated)
Thanks in advance :)
And sorry for the awful English ( :D )
Comment: The reasons the answers are suggesting different implementation is because a java thread cannot _directly_ call sleep on another thread. This way, you know the thread making itself sleep is not in the middle of doing something that would be dangerous to sleep during. (Holding locks during synchronization and such)
Comment: You have horrible variable naming standards... You should consider following the standards so your code is more readable.
Answer: You could try adding fields:
// defines the paused state
private volatile boolean isPaused = false;

// a monitor object for wait/notify pattern
private final Object suspender = new Object();

Then in your logic:
void pause(){
     synchronized(suspender){
         isPaused = true;
     }
}

void resume(){
     synchronized(suspender){
         isPaused = false;
         suspender.notify();
     }
}

while (true){
    if(loader.isInterrupted()){
        return;
    }

    // this outside loop is needed to deal with spurious wakeup
    synchronized (suspender){
        while(isPaused){
            suspender.wait();
        }
    }

    ...
}

More about wait and notify: A simple scenario using wait() and notify() in java
Comment: if you resume and notify suspender, and then context is switched to your worker thread (`isPaused` is still `true`), you get inside loop and wait one more time - resume failed
Comment: I must admit that I haven't tested it, I've fixed what I think could be an error. Did you try running this, or do you think it is conceptually wrong?
Comment: I think changing order does not help either. There is a small chance to lock job thread in both cases. With the new code if you call `pause()` / `resume()` quickly one by one you can stuck in `wait()` call too.
Comment: Ok, I see. I've added `synchronized` blocks for atomic state transitions, they should fix the issue. Thanks for pointing out!
Answer: It is preferred to introduce boolean flag in your Thread implementation:
final private volatile boolean isSuspended = false;

Then you can set this flag to true/false and rewrite your suspend logic in run method like this:
while (true) {
    while (isSuspended) {
        try {Thread.sleep(25);} catch (InterruptedException e) {}
    }
    ...
}

Comment: min SDK is : 8
is it OK ?
I mean the device's cpu is low that it isn't upgraded to 2.3.6
then doesn't this code reduce the program's running speed ?

Thread : start, suspend, resume


WinUI 3 How to make DataTemplate usable in all pages?

Question: WinUI 3 c++/winrt. The DataTemplate is listed at the top of the page:
<Page.Resources>
    <DataTemplate x:Key="SomeViewTemplate" x:DataType="local:SomeModel">
        <StackPanel>
            <TextBlock Text="{x:Bind val1}"/>
            <RatingControl MaxRating="{x:Bind val2}" />
        </StackPanel>
    </DataTemplate>
</Page.Resources>

Everything works fine on this page. How can I make this DataTemplate usable on other pages? In what place (file) should it be placed?
Comment: As [Lookup behavior for XAML resource references](https://learn.microsoft.com/en-us/windows/apps/design/style/xaml-resource-dictionary#lookup-behavior-for-xaml-resource-references) said, *If the requested resource is not found in the immediate resources, the next lookup step is to check the Application.Resources property. **Application.Resources** is the best place to put any app-specific resources that are referenced by multiple pages in your app's navigation structure.* @breadman any update?
Comment: @YangXiaoPo-MSFT If I put DataTemplate (as in question) in App.xaml in  in  I get error "WMC9999 ImplementsIObservableVector: XamlType does not have metadata"
If you put it in other places in this file - it also does not work. That other proposed solution also does not work as it should.
Answer: Let's say you have your DataTemplate in a ResourceDictionary "DataTemplates.xaml". Note that you need to use Binding instead of x:Bind.
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DataTemplateExample">

     <DataTemplate x:Key="SomeViewTemplate">
         <StackPanel>
             <TextBlock Text="{Binding val1}"/>
             <RatingControl MaxRating="{Binding val2}" />
         </StackPanel>
     </DataTemplate>

</ResourceDictionary>

Add it to App.xaml,
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />

            <ResourceDictionary Source="DataTemplates.xaml" />
        </ResourceDictionary.MergedDictionaries>

    </ResourceDictionary>
</Application.Resources>

Then you should be able to use it.
<ListView
    ItemTemplate="{StaticResource SomeViewTemplate}"
    ItemsSource="{x:Bind Items, Mode=OneWay}" />

Comment: I want to add items to GridView in this way:

`

`

Everything worked fine before, but now all elements (val1, val2) are empty: Text = "", MaxRating by default 5.
Comment: By the way, in c#, this xaml code works as it should. Perhaps the problem is in the implementation of the SomeModel class in c++. But then why did everything work when the template was specified at the beginning of the page (template as in the question).
Comment: I cannot reproduce. You can refer to [XAML controls; bind to a C++/WinRT property](https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/binding-property) and [XAML items controls; bind to a C++/WinRT collection](https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/binding-collection) for c++.
Comment: @YangXiaoPo-MSFT "I cannot reproduce" - You cannot reproduce behavior that I described? That is, did you manage to create a DataGrid, as in my comment above, using a DataTemplate that can be used in all pages (files) in c++? If you mean this, it would be sooooooo grateful if you share the complete application code in which this simple functionality is implemented.
Answer: When I placed DataTemplate in App.xaml or a separate ResourceDictionary as @AndrewKeepCoding answered, a Xaml Compiler error at x:DataType, XamlCompiler error WMC0612: The XAML Binary Format (XBF) generator reported syntax error '0x09C4' : Property Not Found, was raised. However, It's necessary to specify x:DataType in order to make the DataTemplate take effect.
So, my conclusion is DataTemplate cannot be global in c++ and DataTemplate also states limited properties to use.
Binding to a C++/WinRT collection costs me a long time until I find PhotoEditor sample. Must specify IInspectable instead of a custom runtime class name.

import "BookSku.idl";

namespace App1
{
    [default_interface]
    runtimeclass MainWindow : Microsoft.UI.Xaml.Window
    {
        MainWindow();
        Int32 MyProperty;
        Windows.Foundation.Collections.IVector<IInspectable> BookSkus{ get; };
    }
}

Update:
According to Resource dictionaries with {x:Bind}, It's possible to use x:Bind and x:DataType in Resource dictionaries. That's why it works in c#. But there is no document about how to implement it in cppwinrt. A related thread: https://stackoverflow.com/a/98422/15511041
Comment: @breadman I have updated my answer about [why it works in c#](https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth#resource-dictionaries-with-xbind).


Using nonce in OCSP stapling

Question: When using openssl in c to verify nonce in regular OCSP (non stapling) i use this:
OCSP_check_nonce(request, basic response).
if I want to validate nonce as a client in OCSP stapling, how do I do it since I don't have the request?
Is there a way to tell the server what nonce to use?
Thanks.
Answer: Nonces make no sense in stapled OCSP responses. The idea behind OCSP Nonce is to instruct OCSP server to invalidate its own cache and generate/sign new response.
When web server uses OCSP stapling, server gets a response in advance and caches it. This is literally the same as querying OCSP server without nonce (with a chance to get cached response). Technically, OCSP without nonce and OCSP stapling mean dealing with cached information and is not compatible with nonce.
If you want to validate the certificate with nonce, you must ignore stapled OCSP response, create your own OCSP request (with nonce) and submit it to OCSP server.
Comment: Thank you very much

Using nonce in OCSP stapling


My high E string broke one week after replacing my guitar strings. Could that be an installation issue?

Question: I'm not sure if it's even possible for the string to break based on how it was installed. The only reason I can think of is that it was installed on a loose tuning peg, which it wasn't (I made sure to slightly tighten the extra-loose ones).
I'm a beginner guitar player, so the other issue that I can think of is that I'm playing incorrectly. The song I've been learning after re-stringing my guitar is "Layla" by Eric Clapton, which involves a lot of bending. I'm sure it contributed, but one week shouldn't be enough to break the string, right?
And I should mention that they are cheap strings: they're called "Ernie Ball" strings. However, I think they are the same kind that were already on the guitar when I got it about six months ago, and I haven't had to re-string the guitar until this one time (when the D string broke a few weeks ago).
Is this common? If not, what are some issues I should watch out for?
Thanks for taking a look!
Comment: [Similar Question](http://music.stackexchange.com/questions/4080/why-does-the-d-string-in-a-guitar-breaks-so-often) (It's about nylon strings, but we didn't know that at first.)
Comment: One broken string is not a pattern. Once you have to replace it a few times, should that happen, you'll get a sense of what the issues are.
Comment: Could you please mention : - how many hours a day you play - where exactly your string broke at (near a fret ? at the end ?) - which E string is it about ? The 1st or the 6th ?
Comment: Sure: that week I played about an hour or two a day. The string broke near the thirteenth fret (where the bend is), and it was the high E string.
Comment: Sorry the "high" string was already in the title :). I would definitely put the break on a flawed string. Strings just do not break like this. Especialy in the middle ... where the bendling radius is at its lowest when you press or pull it.
Comment: Could be. I guess I'll get a few sets of strings as @WheatWilliams suggested.
Comment: @VarLogRant You're right. I posted here because it was the second time for a string to break, but I haven't broken them since.
Comment: Unsolicited English lesson, with apologies if it is unwelcome: "broke after one week of replacing" means that you replaced the string repeatedly over the course of one week, and then it broke. An analogous sentence might be "my shopping bag broke after a week of using it to carry bricks."  I assume you mean that you replaced the string once and it broke a week later.  If I am wrong, please revert my edit.
Comment: No you're not wrong @phoog, I probably should have proofread that. Thanks
Answer: With a top E, there are a number of things which could do this, but the most likely if this is your first time stringing the instrument is that you damaged the string on installing it - for example if it slipped at all when you were tightening the tuning pegs you may have the part of the string that was on the edge of the peg now between the peg and nut - with tension on it this will be weaker than the rest of the string.
Alternatively, any sharp edge at bridge, nut or even a worn fret could do this. When you do the high bend, are you pressing hard, grinding it along the fret?
Or did you just tune it too high? Worth checking if you are new to this.
The thinner the string, the easier it is to snap - what gauge are you using? A .008 is quite weak, whereas a .010 is quite strong.
Ernie Ball strings are generally well regarded, so as long as they are new I'd be surprised if it was a string fault.
Have a look at where it snapped - this can help you diagnose the issue.
Comment: I don't think I tuned it too high, since I used my computer to tune it. However, I suspect you're right about the sharp fret. Yes, I do press hard on the string and push it up when I bend it. And it did snap near the thirteenth fret, where the bend is in that song.
Comment: running a soft pencil in the grove on the nut can help lubricate that safely. You can also get a fret burnishing tool. But given your diagnosis I'd be tempted to take it back to the shop, explain the problem, and ask them to dress the frets.
Answer: Yes, there are issues involved in the way the guitar is set up and calibrated that can impact breaking strings.
But most importantly, beginning guitarists frequently break strings because they play with too much force. Don't worry. This requires practice. You need to develop enough technique to know how not to strike the strings too hard, and how to hold and use the guitar pick.
Second, there are many different gauges of strings you can purchase and put on your guitar. Lighter, thinner strings are easier to bend, but also easier to break. Many guitarists prefer heavier strings because they produce a stronger tone in addition to being more durable and harder to break. But they also require more strength in the left hand to make them bend, and you have to practice frequently to build up this strength.
Many professional electric guitarists put a complete new set of strings on their guitar every night. Most guitarists can't afford this (and it seems kind of wasteful). Some guitarists, particularly those that use the lightest gauge of strings, however, insist that the strings they play have to be new and bright all the time.
But everybody breaks strings every now and then, even the best of the pros with the best guitars.
You will always be subject to strings breaking. You should have an extra new set of all six strings with you at all times (maybe two sets), and you should get good at changing your own strings quickly. It's part of being a guitarist.
Answer: One issue to be aware of is what string gauge your guitar is setup for.
The first time I had to replace my strings, I bought medium gauge, thinking it didn't matter too much. I ended up breaking a string every 2-3 weeks for a while. I eventually figured out that the nut was the problem. It was setup for very light gauge strings, meaning the grooves were very narrow. It was putting too much stress on the medium strings, causing them to fatigue and break very quickly at that point.
I widened the grooves myself using a craft knife, and the problem went away (although the nut didn't look very good after that!) Using a more appropriate string gauge is arguably a better solution though, depending on the tone you want.
The reverse situation can cause the same problem as well. If the nut is setup for a considerably heavier gauge than you're using, then the strings can slide around sideways in the grooves and wear down.
Answer: You can buy 6 E strings in a pack as the 6th string, the E string is the easiest to snap. I have never broken any other string and I bend with the best.  lol.
Answer: In my strat like guitar string retainers were set too low (and also too sharp). It was cutting the E and B strings every two days. I minimally raised them and problem disappeared.
If you broke string it is important to check where it was cut.


3-manifolds: connected sum & handle decomposition

Question: Suppose we are given a 2 diagrams for an handle decomposition of two closed, orientable 3-manifold M and $\tilde{M}$. Each of these diagrams consists in an handlebody of genus $g$ (respectively $\tilde{g})$, and  closed curves $\{\gamma_1,\dots, \gamma_g\}$ (respectively $\{\tilde{\gamma}_1,\dots, \tilde{\gamma}_\tilde{g}\})$ drawn on them representing the attacching spheres of the 2-handles.

How can we construct a diagram of the connected sum $M\#\tilde{M}$  from the given diagrams?
Comment: See the first paragraph of Section 3.2 here: https://arxiv.org/pdf/math/0007144.pdf
Answer: Thanks to Arnaud Mortier's comment. As it can be read in paragraph 3.2 Reducible splittings page 9 of https://arxiv.org/pdf/math/0007144.pdf Martin Scharlemann's survey "Heegaard Splittings of compact 3-manifolds", the diagram for the connected sum is obtained just connecting the two handlebodies with a single 1-handle.
Thus the diagram for $M\#\tilde{M}$ consists in an handlebody of genus $g+\tilde{g}$ with the curves $\{\gamma_i\}$ drawn on the first $g$ 1-handles of the handlebody and the curves $\{\tilde{\gamma}_i\}$ drawn on the second set of $\tilde{g}$ 1-handles.
We obtain this by removing cleverly a 3-disk from $M$ that intersects the first handlebody's surface in a 2-disk (thus half of the 3-disk lies in the 3-handle of $M$ and half of it lies in the 1-handlebody induced by the diagram).
We remove similarly a 3-disk from $\tilde{M}$, now we have to glue the new $\mathbb{S}^2$ boundary components, to do so we use a 1-handle to glue two hemispheres and a single last 3-handle to cap the resulting $\mathbb{S}^2$ boundary.
We can also decompose this procedure as follows, first we  add an isolated 2-handle to the diagram of $M$ and the diagram of $\tilde{M}$ (this accounts to removing the  balls). Then we connect the diagrams joining with a 1-handle the  disks bounded by these new 2-handles. We end up with 3 boundary components isomorphic to $\mathbb{S}^2$s. We can cap them with 3-handles.
Reflecting on this construction one sees that the two 2-handles and two 3-handles cancels out thus we have just added a 1-handle and capped all with a single 3-handle.


Trying to retrieve Message Text from Azure Queue using web api but message text is encoded. how do i remove encoding

Question: when i retrieve  something the output is encoded.
QueueClient queue = new QueueClient(connectionString, "outqueue");
string value = await RetrieveNextMessageAsync(queue);
        return value;

RetrieveNextMessageAsync:
if (await theQueue.ExistsAsync())
        {
            QueueProperties properties = await theQueue.GetPropertiesAsync();

            if (properties.ApproximateMessagesCount > 0)
            {
                QueueMessage[] retrievedMessage = await theQueue.ReceiveMessagesAsync(1);
                string theMessage = retrievedMessage[0].MessageText;
                await theQueue.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
                return theMessage;
            }

output:
enter image description here
Comment: Could you please tell me how you define method `RetrieveNextMessageAsync`?
Comment: Would need more information about RetrieveNextMessageAsync. How does it look?
Comment: As far as I knew, in default, if we use V12 SDK to manage Azure queue, the mesage is just UTF-8 string. For more details, please refer to https://github.com/Azure/azure-sdk-for-net/issues/10242#issuecomment-735949498. Could you please check the message encoding vai Microsoft Storage explore?
Comment: @Dhatri Do you have any updates?
Answer: If your message encoding is base64, you can use the following code to retrieve it with package Azure.Storage.Queues
[HttpGet("getMessage")]
        public async Task<string> GetMessageAsync() {
            string connectionString = "";
            var options = new QueueClientOptions {
                MessageEncoding= QueueMessageEncoding.Base64
            };
            var queue = new QueueClient(connectionString, "myqueue", options);

            var message = await RetrieveNextMessageAsync(queue);
            return message;
        }
        static async Task<string> RetrieveNextMessageAsync(QueueClient theQueue)
        {
            if (await theQueue.ExistsAsync())
            {
                QueueProperties properties = await theQueue.GetPropertiesAsync();

                if (properties.ApproximateMessagesCount > 0)
                {
                    QueueMessage[] retrievedMessage = await theQueue.ReceiveMessagesAsync(1);
                    string theMessage = retrievedMessage[0].MessageText;
                    await theQueue.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
                    return theMessage;
                }

                return null;
            }

            return null;
        }

Regarding how to check message encoding, you can use Azure Storage Explorer


TList of Record types leaking memory

Question: Code that looks approximately like the following leaks memory for each string instance in each TMyRecord created.  I presume I must visit each record and free it somehow -- can that be done without nilling each individual string?
function TMyForm.RecordFromThing(thing): TMyRecord;
begin
   result.StringVal1 = thing.SomeProperty;
   result.StringVal2 = thing.SomeOtherProperty;
end;

function TMyForm.RecordsFromItems: TList<TMyRecord>;
begin
   result := TList<TMyRecord>.Create;
   for thing in things do
   begin
     result.Add(RecordFromThing(thing));
   end;
end;

procedure TMyForm.Button1Click(Sender: TObject);
var Items: TList<TMyRecord;
begin

  Items := RecordsFromItems;
  try
    //Stuff
  finally
    // What goes here to free those records?
    Items.Clear;
    Items.Free;
  end

end;

As per David's request, here is actual code cut-and-pasted from my application.  If I run Button1Click then FastMM reports string memory leaks.
  type TPremiumPaymentInstruction = record
    SupplierID: string;
    FirstName: string;
    LastName: string;
    PolicyNo: string;
    CarrierName: string;
    PayAmount: string;
    DueDate: string;
    PayMethod: string;
    Comments: string;
    Payee: string;
    Address: string;
    Address2: string;
    City: string;
    State: string;
    Zip: string;
    InRe: string;
    BankName: string;
    BankABA: string;
    AccountName: string;
    AccountNo: string;
    CreditTo: string;
  end;

function TPremiumPaymentManager.RecordFromItem(Item: TListItem): TPremiumPaymentInstruction;
var PolicyID: integer;
    Instructions: TDataSet;

    function FormatNote(PolicyNo, First, Last: string): string;
    begin
      result := 'Policy# ' + PolicyNo + '; Insured Name: ' + Last + ' ' + First;
    end;

begin

  FillChar(result, SizeOf(result), 0);

  result.SupplierID  := Item.Caption;
  result.FirstName   := Item.SubItems[INSURED_FIRST_NAME_COLUMN];
  result.LastName    := Item.SubItems[INSURED_LAST_NAME_COLUMN];
  result.PolicyNo    := Item.SubItems[POLICY_NUMBER_COLUMN];
  result.CarrierName := Item.SubItems[CARRIER_NAME_COLUMN];
  result.PayAmount   := Item.SubItems[ACTUAL_COLUMN];
  result.DueDate     := Item.SubItems[DATE_DUE_COLUMN];
  result.PayMethod   := Item.SubItems[PAYMENT_METHOD_COLUMN];

  PolicyID := GetSingleValue('SELECT PolicyID FROM PremiumsDue WHERE PremiumID = :PremiumID;', [(Item as TAdvListItem).KeyValue], 0);
  Instructions := GetDS('SELECT I.* FROM Policies P INNER JOIN CarrierPaymentInstructions I ON P.CarrierID = I.CarrierID AND P.PaymentInstruction = I.InstructionDescription WHERE P.PolicyID = ?;', [PolicyID]);

  try

    Instructions.Open;
    Instructions.First;

    if result.PayMethod = 'Check' then
      begin
        result.Comments := Item.SubItems[PAYMENT_NOTE_COLUMN];
        result.Payee    := Instructions.FieldByName('PayTo').AsString;
        result.Address  := Instructions.FieldByName('Address1').AsString;
        result.Address2 := Instructions.FieldByName('Address2').AsString;
        result.City     := Instructions.FieldByName('City').AsString;
        result.State    := Instructions.FieldByName('State').AsString;
        result.Zip      := Instructions.FieldByName('ZipCode').AsString;
        result.InRe     := FormatNote(result.PolicyNo, result.FirstName, result.LastName);
      end
    else
      begin
        result.BankName    := Instructions.FieldByName('PayTo').AsString;
        result.BankABA     := Instructions.FieldByName('ABANumber').AsString;
        result.Address2    := Instructions.FieldByName('Address2').AsString;
        result.AccountName := Instructions.FieldByName('AccountName').AsString;
        result.AccountNo   := Instructions.FieldByName('AccountNumber').AsString;
        result.CreditTo    := FormatNote(result.PolicyNo, result.FirstName, result.LastName);
      end;

  finally

    Instructions.Free;

  end;

end;

function TPremiumPaymentManager.RecordsFromItems: TList<TPremiumPaymentInstruction>;
var item: TListItem;
begin

  result := TList<TPremiumPaymentInstruction>.Create;

  for item in lvPremiums.Items do
  begin
    if (not (Item as TAdvListItem).Strikeout) and (Item.SubItems[ACTUAL_COLUMN] <> '')  then
      result.Add( RecordFromItem(item) );
  end;

end;

procedure TPremiumPaymentManager.Button1Click(Sender: TObject);
var Items: TList<TPremiumPaymentInstruction>;
begin

  Items := RecordsFromItems;
  Items.Clear;
  Items.Free;

end;

Comment: Cut-and-paste from my failing code has been added to the question.
Comment: Use `result := Default(TPremiumPaymentInstruction)` to initialize your record.
Answer: Strings are managed types. The compiler takes charge of their allocation and deallocation. The compiler writes code that maintains reference counts to the string data. When the reference count goes to zero, the memory is deallocated.
As such, you don't need to deallocate strings or indeed perform any explicit management. Any attempt to do so will likely clash with that performed by the compiler. For instance, if you perform raw memory access on a string variable, saw with a call to FillChar, then the reference counting will be bypassed.
The code in your question, beyond being incomplete and in parts not compiling, is essentially fine. When you are done with your TList<TMyRecord> simply free it. The compiler will generate code to release all references. No need even to clear it.
List := TList<TMyRecord>.Create;
try
  List.Add(...);
  // etc.
finally
  List.Free;
end;

That's all you need.
Since the code in you question is essentially the same as this, I conclude that the cause of your leak is elsewhere.

What do you know, your edit contains that tell-tale call to FillChar. Replace that with
Result := Default(TPremiumPaymentInstruction);

You do always need to initialize return values. Even return values that are managed types which often are initialized. But not when the call is made inside a for loop in the manner of yours. Go figure. Anyway, always initialize return values. And Default(T) is your friend.
Comment: `Result` contains the content of the previous call, when the caller is in that for loop. All should be clear from there. Compiler doesn't warn about managed types being initialized. Golden rule, always initialize all variables.
Comment: I cut-and-pasted the actual code into the question.  Please note that I *am* using FillChar on each record as without that initialization I was getting string pointers apparently repeated from record to record.
Comment: Thanks, working now.  I have a faint glimmer of why this failed, but only faint.  Will look at it again later to see if I can figure out why. . .
Comment: It failed because you bypassed reference counting by doing a raw memory write. Nothing actually released the references to the strings since you wrote over the references. Behind the compiler's back. FillChar is not your friend here, not with managed types.
Comment: Is it the FillChar leak, or the result var already initialized that is stumping you?
Comment: Primarily why using FillChar means that the later strong assignment cannot be freed by the compiler, but also why the strings in the record must be manually initialized when (I believe) that's not generally true of strings. And why, in that case, the compiler does not produce an "X may not have been initialized" type message.
Comment: Aha!  I assumed that the new Record having the same string values as the last one (which surprised me to begin with) was an artifact of memory management (not a deliberate language construct) and it never struck me that that constituted an additional reference to the strings in the old Record.  Also, despite many years of on-and-off Delphi (and Turbo Pascal before that) I'm embarrassed to say I never ran into `Default()` before.
Comment: `Default(T)` is new, to support generics. Not well documented, if documented at all. Grr. So not surprising you've not seen it. `Result` is actually a `var` parameter technically. Implicit of course. Implemented that way for types that don't fit in registers or are managed. So, being a `var` parameter, they may have a value on entry. Compiler thinks it's a `var` and so neglects to warn you. The entire handling of function return values in Delphi is, in my opinion, a total screw up.

TList of Record types leaking memory


Equations with integrals

Question: In a math-textbook I have, they have solved the equation $$ -c_{2}\int_{0}^{S}f(x)dx+c_{1}\int_{S}^{\infty}f(x)dx=0$$ as $$\int_{S}^{\infty}f(x)dx=\frac{c_{2}}{c_{1}+c_{2}}$$. Anyone who know how they arrived at this answer?
Comment: Have you that $\int_0^{+\infty}f(x)dx=1$ as hypothesis ? If yes, use $\int_0^s=\int_0^{+\infty}-\int_s^{+\infty}$.
Comment: Yes, that was the hypothesis. Thank you very much Kelenner, you are golden!
Comment: You are welcome.
Answer: I forgot to mention that
$$ \int_{0}^{\infty}f(x)dx=1$$
So the expresion can be written
$$\int_{0}^{S}f(x)dx=\int_{0}^{\infty}f(x)dx-\int_{S}^{\infty}f(x)dx$$
$$-c_{2}\int_{0}^{\infty}f(x)dx+c_{1}\int_{S}^{\infty}f(x)dx=0$$
$$-c_{2}\int_{0}^{\infty}f(x)dx+c_{2}\int_{S}^{\infty}f(x)dx+c_{1}\int_{S}^{\infty}f(x)dx=0$$
$$(c_{1}+c_{2})\int_{S}^{\infty}f(x)dx=c_{2}$$
$$
Answer: As per Kelenner's comment. If you have $\int_0^{\infty} f(x) \, \mathrm{d}x = 1$ then $$\int_0^s f(x) \, \mathrm{d}x + \int_s^{\infty} f(x) \, \mathrm{d}x= \int_0^{\infty} f(x) \, \mathrm{d}x = 1$$
And so $$\int_s^{\infty} f(x) \, \mathrm{d}x =1 - \int_0^s f(x) \, \mathrm{d}x$$ and therefore $$c_1\int_s^{\infty} f(x) \, \mathrm{d}x = c_2\left(1 - \int_s^{\infty} f(x) \, \mathrm{d}x\right)$$
so rearranging gives $$\int_s^{\infty} f(x) \, \mathrm{d}x = \frac{c_2}{c_1 + c_2}.$$

Equations with integrals


Call WCF service 404 Not Found

Question: I've created an AJAX-enabled WCF Service and I want call it using POST. But the service was 404 not found  and i don't understand why. I saw some examples but can't find why my service is inaccessible. I've already changed my web config but there is no difference. What do I do wrong?
namespace ATSite
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SendEmailService
    {
        [OperationContract]
        public string HelloWorld(string id)
        {
            return "Hello world " + id;
        }
    }
}

Calling the service:
function helloWorld() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "../SendEmailService.svc/HelloWorld",
        data: '{"Id": "2"}',
        dataType: "json",
        success: function (result) {
            onSuccess(result);
        },
        error: alert('Erro')
    });
}
function onSuccess(result) {
    alert(result);
}

This is my web.config
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ATSite.SendEmailServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service name="ATSite.SendEmailService">
        <endpoint address="" behaviorConfiguration="ATSite.SendEmailServiceAspNetAjaxBehavior"
          binding="webHttpBinding" contract="ATSite.SendEmailService" />
      </service>
    </services>
  </system.serviceModel>

Thanks!
Comment: Did you check ../SendEmailService.svc/HelloWorld path is correct?
Comment: I have the exact same problem, did you manage to solve this? Moving the service to another application is not an option for me as the functionality depends too much on the project it is in.
Answer: I don't think you can call it that way. Here is an example on how to consume a wcf service http://www.codeproject.com/Articles/42643/Creating-and-Consuming-Your-First-WCF-Service
Comment: But for that I have to create a new project -> WCF service application
Answer: The WebInvoke attribute gives you some options:
    [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
    public string MyAwesomeServiceMethod(Decimal value)
    {
        return value.ToString("F2");
    }

Call WCF service 404 Not Found


Is the Neyman-Pearson paradigm for hypothesis testing adequate in the social sciences, and if not, is calculating a priori power still adequate?

Question: I'm reading about Fisherian vs. Neyman-Pearson paradigms relative to hypothesis/significance testing. (NB: I'm new to this and self-studying it, so I'd be glad to be corrected if I misinterpret concepts or misuse words.)
In this article (pdf file), the author argues that the Neyman-Pearson paradigm is less adequate in the social sciences than the Fisherian paradigm, because the population is changing constantly -so you can't conduct exact replications of a study, but exact replications are an assumption of Neyman-Pearson.
Assuming the author is right (I don't know if he is), then does it still make sense to compute sample sizes if we are in another paradigm (Fisherian, Bayesian, or others I may not know)?
Let's say I'm interested in detecting some minimal effect size of interest in the sample I collect (if this effect exists in the "temporary" population of interest), what are my options outside Neyman-Pearson? (given that exact replications on the long run in the real world are impossible).
Comment: The calculations of sample sizes under the two paradigms (NP and Fisher) use exactly the same mathematical models and yield exactly the same results. Because a Bayesian procedure differs mathematically, it might come up with a different sample size.  (It really ought to when the researcher adopts a strong prior distribution, because that is giving information equivalent to a preliminary sample and so the computed sample size ought to be lower in such cases.) In the end, how you compute sample sizes depends on how you intend to analyze the data.
Comment: Welcome to CV. Your link to the pdf is not working. In general though, the validity of the N-P approach does not rely on actual replications of the _same_ experiment. Replications can be hypothetical or the long run involved can be across independent different experiments.
Comment: @GrahamBornholt strange, the link works for me. Here is an alternative link:  https://philpapers.org/archive/RUBWTO (if this one does not work either, the title is "What type of Type I error? Contrasting the Neyman–Pearson and Fisherian approaches in the context of exact and direct replications" if you want to google it). In the paper, page 16 (mid-page), the author gives an example of real-life direct (not *exact*) replications under the NP paradigm, example which failed.
Answer: Rubin, the author of the linked paper, is probably correct in saying that the Neyman–Pearsonian hypothesis testing approach is inferior to a Fisherian significance testing approach for most scientific purposes (social science or otherwise). He is also correct in pointing out that the long-run series of exact replications of an experiment imagined by Neyman as a justification of the error rates is impossible in many real-world circumstances. (I'm not sure that the justification requires more than an imaginary series, however.)
However, I think that the coining of the term "Fisherian sample-specific type I error probability" is unfortunate. I'm pretty sure that Fisher did not ever adopt the term "type I error" for any description of the result of his significance testing. Certainly he argued against the idea that a p-value could be used as a probability statement linked to the null hypothesis, and that would preclude its use as a type I error rate:

It [the p-value] is more primitive, or elemental than, and does not justify, any exact probability statement about the proposition [the null hypothesis]. (Fisher, 1956)

Instead of calling the p-value an error probability it is more helpful, in my opinion, to call it an index of evidence. That allows the distinction between evidence and error rates to be clear (Lew, 2020).
Now, your question boils down to one of how to determine sample size. You can do what is commonly done and use a sample size that seems reasonable, taking effort and cost into account, and then post-hoc set up a sample size calculation to yield that size by adjusting the 'expected' effect size to suit. (No, don't do that!)
The Neyman–Pearsonian error rate paradigm has limited utility in the analysis of the results scientific experiments, but that does not mean that it is not useful before the experiment. You suggest that you have in mind a minimal effect size of interest, so plug that in to a power calculation routine and determine the sample size needed for an acceptable power. (Then increase the sample size a bit to take into account the miss-match between the statistical model and the real world data generating and sampling mechanisms...) Such Neyman–Pearsonian planning does not affect the Fisherian interpretation of the experimental results in any way. Nothing that you do before the data are obtained alters the evidential meaning of the data.
There are a couple of alternative views of the pre-experiment power analysis that are worth consideration. One plots the power against effect size for any sample size, and another plots the expected p-value against effect size. Either or both will improve your intuitions regarding experimental power and sample size planning. See section 2.5 in Lew, 2020.

Fisher, R.A. 1956 Statistical Methods and Scientific Inference, 1956. p.46 in the Oxford Science Publications reprint of 2003.

Lew, M.J. 2020 A Reckless Guide to P-values: local evidence and global errors
Comment: @Coris Further to whuber's comment, a famous article by Lehmann demonstrates the similarity between the Fisher and Neyman-Pearson testing methods. It can be found via  another answer : https://stats.stackexchange.com/a/192098/343075
Comment: @GrahamBornholt Yes, that's an interesting article, but to me it reads more as an attempt to reconcile the unreconcilable. It does not seem to me to be a correct representation of Fisher's approach and instead casts Fisherian analysis in terms of fixed levels of alpha rather than graded levels of p-values. A famous paper, perhaps, but not one that I would go to.
Comment: @GrahamBornholt Fisher found 5% and 1% interesting but in large part because he was working from tables of critical values or test statistics rather than exact p-values. He did say that anyone using 5% would not be too often wrong, but that was in the context of work where interesting results were followed up upon with repeated experimentation. He never approved of the one-and-done type of 'significant' that comes from Neyman and Pearson. See here: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3419900/ and here: https://link.springer.com/chapter/10.1007/164_2019_286 for my take on the issues.
Comment: I find the Cox and Hinkley 1974 book "Theoretical Statistics" is an excellent reference book for significance testing. Cox's 1958 paper long ago made the point that statistical inference is only a part, sometimes a small part, of scientific inference, and his warning is as apt today as it was then. Cox was a Fisherian in most things (as am I).
Comment: Your answer and the comment by whuber makes things much clearer and reassuring to me. Thank you both.
Comment: I did not think it went quite that far. Fisher did not fix alpha level before hand but at times he did find p-values below 5% and 1% particularly interesting. In contrast, Neyman-Pearson fixed alpha levels for their optimisations but what the fixed values were depended on the specific problem. However, people now believe 5% and 1% were Neyman-Pearson's idea.
Comment: @Micheal Lew Interestingly, Neyman-Pearson also used 1% and 5% because of Fisher's tables! Thanks for the references to your papers. I have read the first one. The surprise was the the description of the Neyman-Pearson tester in Example 2. Perhaps you are right in the claim that Neyman Pearson rejections are final, with experiments never to be repeated after just one sample. If so, I am confident that there are no scientists following the Neyman-Pearson method literally in this regard  (probably neither Neyman or Pearson did either). All conclusions in statistics are provisional. ctd
Comment: @MichaelLew Just finished your chapter. Very nice article.


Installing Pillow on MacOS Sierra

Question: The default Python is 2.7 that's come prebuilt into the OS.
When trying to install Pillow using the commands:

sudo pip install Pillow

It installs it into my Python 2.7 direction, rather than the latest 3.x version I've installed. How do I go about solving this issue? Is there a way to point the installer to the correct directory?
Comment: Use pip3 to install for python3. `sudo pip3 install Pillow`
Comment: @MohammadYusufGhazi I think that worked thanks!
Answer: Have you tried this? Moreover, read about homebrew installation (Homebrew, pillow, pip).
<code>Sudo pip3 install Pillow
</code>

Installing Pillow on MacOS Sierra


mapping naked domain (www.example.com) to static website saved in s3

Question: I am developing a web application. I recently purchased a domain from godaddy.com and am using  google apps for email, calendar, docs and other services as well.
Now I just need to show that "my site is under construction". I have a static page which is put on S3. Now I need to map "www.example.com" to that static page which is stored on s3. I am kinda of newbie/novice to this so kindly help me.
Answer: There is article on Amazon Web Service blog Host your static website on Amazon S3


1-norm and symmetry

Question: Define the fidelity function for positive operators by $F(\rho, \sigma) = \lVert \sqrt{\rho}\sqrt{\sigma}\rVert_1$. Here, $\lVert\cdot\rVert_1$ is the Schatten 1-norm and defined as $\lVert A\rVert_1 = \operatorname{Tr}(\sqrt{A^{\dagger}A})$.
I'm having some trouble showing that $F$ is symmetric in its arguments. Physics textbooks do it through the idea of purifications but I thought there should be a mathematical argument.

How does one see that $F(A,B) = F(B,A)$ given that $F(\rho, \sigma) = \operatorname{Tr}(\sqrt{\sqrt{\rho}\sigma\sqrt{\rho}})$?

My original idea to prove it was to try and use cyclicity of trace and assume that $\sqrt{AB} = \sqrt{A}\sqrt{B}$, but it seems this is invalid even for positive operators? Can someone also comment on this seemingly simple statement being false?
Answer: We know that $F( \rho, \sigma) = \text{Tr}( \sqrt{ \sqrt{\rho} \sigma \sqrt{\rho}})$. Now consider
\begin{align*}
F( \sigma, \rho) &= \lVert \sqrt{\sigma} \sqrt{\rho} \rVert_1 = \text{Tr} \big( \sqrt{(\sqrt{\sigma} \sqrt{\rho})^\dagger \sqrt{\sigma} \sqrt{\rho}} \big) \\
&= \text{Tr}\big( \sqrt{ \sqrt{\rho} \sigma \sqrt{\rho}} \big) = F( \rho, \sigma).
\end{align*}

1-norm and symmetry


If a and b are dependent variables, what's the probability of a,b both happen?

Question: Bayes' theorem tells me
$$P(a \cap b)= P(a)P(b|a) \tag{1}$$
which I interpret as a happens, and b happens on condition of a. Then why don't we need to consider b happens first, ie.
$$P(a \cap b)= P(a)P(b|a)+P(b)P(a|b) \tag{2}$$
?
Further, if I need to find the probability of a or b, but not both, should it be
$$(1-P(b|a))P(a)+(1-P(a|b))P(b) \tag{3}$$
?
Comment: "$P(a \cap b)= P(a)P(b|a)$" is not Bayes' theorem but a fundamental result called the (general) product rule or the chain rule; indeed you can use it to prove Bayes theorem. see https://en.wikipedia.org/wiki/Chain_rule_(probability)#Two_events
Comment: A) The RHS of your second expression has two terms. They are both equal to the LHS so the LHS = 2 * RHS. B) Not clear to me where that last expression came from but  the probability of A or B  is equal to the probability of the union of A and B, P(A U B) ,  which is equal to P(A) + P(B) - P(A and  B)..
Answer: So, you have already answered the title question in your first statement. But let's add a bit more to it:
$$P(A \cap B) = P(B|A)P(A) = P(A|B)P(B)$$
As @Glen_b pointed out, this relationship, upon which Bayes theorem is based, has only to do with how probability is defined. Because the 2nd and 3rd equations are equivalent, it must be true that the order in which $A$ and $B$ does not come into play.
If you do want to consider time ordering, then you would be looking for something like this:
$$P(A_{t'>t} \cap B_t) = P(B_t|A_{t'>t})P(A_{t'>t}) = P(A_{t'>t}|B_t)P(B_t)$$
In the 2nd equation, you are actually conditioning on an event which happened in the future, which is ok as you might be trying to figure out something that happened further back in time.
As @mlofton pointed out, and this is another fundamental result of the definition of probability,
$$P(A \cup B) = P(A) + P(B) - P(A \cap B)$$
Nevertheless, I do believe your last equation, which expand out to
$$P(A) + P(B) - 2P(A \cap B)$$
The explanation of the formula for $P(A \cup B)$ can be seen in this Venn diagram:

is that the last term corrects for having double counted the intersection area when you "add up" the areas in the "A" part and the "B" part. For "and not both" you need to actually cut the intersectcion part out. So subtracting $P(A \cap B)$ again does the trick.
To add one last thing: do be careful about confusing dependency with intersection. A and B can have an intersection while being independent.
Comment: I'm much clear now. FYI, I added numbers to my equations, so it's easier to reference them.


SourceMap header is ignored on different host

Question: If I'm serving bundle.js from http://localhost:5000 with the SourceMap: /bundle.js.map it works fine, however when I include  on http://localhost:5001 (serving the files as before), the browser (Chrome 71) won't load the source map. Is this a bug in the browser or something else?
Answer: Yes it does not work in Chrome. The solution is to include the source map not via the header but via the //# sourceMappingURL=<url>.map.
Comment: Why doesn't it work? There is any source indicating that? It's supposed to be supported and works fine on Firefox


Find the item in an array with the largest property

Question: I have a struct like this
struct Point {
    pub x: i32,
    pub y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Self {
        Point { x, y }
    }
}

And an array like this
[Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];

How do I pull the item with largest point.x from this array?
Answer: Use Iterator::max_by_key:
let a = [Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
let max = a.iter().max_by_key(|p| p.x);

There's also Iterator::min_by_key.
See also:

How can min_by_key or max_by_key be used with references to a value created during iteration?
Using max_by_key on a vector of floats
What is the idiomatic way to get the index of a maximum or minimum floating point value in a slice or Vec in Rust?


What does "WB" and "OB" mean for the decathlon?

Question: I only caught this during yesterday's Olympic broadcast.  For the men's decathlon, for the 1500m event, it showed in the upper left of the screen:
<code>WB: 4 min and change
OB: 4 min and change
</code>
I'm wondering what does OB and WB stand for?  I saw OR and WR for other events (track, swimming), which is Olympic Record and World Record respectively so I assume OB and WB is Olympic B-something and World B-something.
Thanks in advance.
Answer: OB stands for "Olympic Best" :-)

Q. Some of the times in the heptathlon were marked 'WB' and 'OB' instead of 'WR' and 'OR'. What's the difference? Mrs G Winkworth
A. World records are rare in the heptathlon. The athletes are all-rounders, but not necessarily the world's finest in each discipline. So the "world best" score or time means the best in that event during a heptathlon. Ditto "Olympics best". It is the same in the decathlon.

http://www.independent.co.uk/sport/olympics/news/olympic-question-time-wbob-man-on-a-motorbike-ainslies-dinghy-8009044.html
Answer: For many sports, there are official records kept for the best performances by the sport's governing body.  As an example, the world record for 100m dash is ratified by World Athletics.  When they exist, they will be indicated with OR for olympic record and WR for world record.
There are some cases where no such records are kept.  The question refers to the decathlon.  While there are official records for best decathlon score, there are not official records for the individual events within as a decathlon participant.
Another example are the rowing events.  Because individual races are strongly influenced by the weather, official record times are not recognized by FISA.
When these official records don't exist, the best times that meet some criteria may be displayed with OB (olympic best) or WB (world best).  The olympic website has some other initialisms in use (like ODB for olympic decathlon best and OHB for olympic heptathlon best), but I've not seen those used on broadcast graphics myself.


Android layout button lower than others in horizontal linearlayout

Question: for some reason the button on the right comes out lower. I have attempted to edit the different parts, am I missing a margin difference or is it because of space fitting in. It is simply a linear layout horizontal with a textview, edit text and button.
Screenshot of the XML design
Please check the picture in the link
<code>        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/txtv_ISBN"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dip"
            android:layout_weight="3"
            android:background="@android:color/holo_blue_light"
            android:gravity="center"
            android:minHeight="60dip"
            android:minWidth="80dip"
            android:text="@string/isbn"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textStyle="bold" >
        </TextView>

        <EditText
            android:id="@+id/edt_ISBN"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dip"
            android:layout_weight="3"
            android:background="@color/White"
            android:hint="@string/barcode_hint"
            android:inputType="textPassword|number"
            android:minHeight="60dip"
            android:textAppearance="?android:attr/textAppearanceLarge" >
            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/btn_pallet_isbn_clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dip"
            android:layout_weight="3"
            android:minHeight="60dip"
            android:minWidth="100dip"
            android:text="@string/clear"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </LinearLayout>!
</code>
Comment: where is screenshot ? I don't see any iimage
Answer: add
<code>android:gravity="center_vertical"
</code>
to your linear layout
Answer: try this
<code> <Button
        android:id="@+id/btn_pallet_isbn_clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="6dip"
        android:layout_weight="3"
        android:minHeight="60dip"
        android:minWidth="100dip"
        android:singleLine="true"   <------that
        android:text="@string/clear"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</code>
Comment: This also works, but I really wanted the answer below. But thanks.


How Can Poisson Regression Predict a Count of Zero?

Question: I am reading "Modelling Count Data" by Hilbe and I feel I am missing something fundamental about Poisson Regression.
$\hat{\mu} = \exp(\alpha + \sum\beta_ix_i)$
One of the requirements for using it is that the underlying distribution generating my data is capable of producing counts of zero.
What I don't understand: how can such a model predict a count of zero? If it can't, how is this a useful model of my data?
Example (in R)
library("ggplot2")
library("COUNT")

# Simulation weights
b0 = 1
b1 = 0.5
b2 = 0.01

# Simulation variables and observations
obs.num = 10000
x1 = rnorm(obs.num)
x2 = rnorm(obs.num)
py = rpois(obs.num, exp(b0 + b1*x1 + b2*x2))

# Poisson Regression
model.poisson = glm(py ~ x1 + x2, family=poisson)

# Inspect Results
summary(model.poisson)
ggplot() + aes(py) + geom_histogram(bins=120)
ggplot() + aes(predict(model.poisson, type="response")) + geom_histogram(bins=120)

The summary looks good in-so-far as it gets the estimates:
Call:
glm(formula = py ~ x1 + x2, family = poisson)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-3.3435  -0.8094  -0.1061   0.5842   3.8852

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) 1.002306   0.006376 157.205   <2e-16 ***
x1          0.501053   0.005659  88.535   <2e-16 ***
x2          0.012516   0.005675   2.205   0.0274 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 18964  on 9999  degrees of freedom
Residual deviance: 11070  on 9997  degrees of freedom
AIC: 37494

Number of Fisher Scoring iterations: 5

But the plot of the predictions shows that no 0 predictions were made:
Comment: Note that $\hat{\mu}$ is a prediction of $\mu$ (a conditional population mean). How  would the mean for a non-negative variable that includes non-zero values be zero?
Answer: The poisson regression model does not predict counts, it predicts a rate.
The poisson model is:
$$ y \mid X \sim \text{Poisson} \left( \mu = \exp(\beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k) \right) $$
So the model predicts $\mu$, which is interpreted as the rate parameter of the conditional distribution $y \mid X$.  Even though the rate parameter cannot be zero (as an outcome of a fit model), it is still consistent with the data (which are counts) being zero.
This is exactly analogous to the situation in logistic regression: the predicted probabilities cannot be zero or one, but the data is always a zero or a one.


__getitem__ for a list vs a dict

Question: The Dictionary __getitem__ method does not seem to work the same way as it does for List, and it is causing me headaches.  Here is what I mean:
If I subclass list, I can overload __getitem__ as:
class myList(list):
    def __getitem__(self,index):
        if isinstance(index,int):
            #do one thing
        if isinstance(index,slice):
            #do another thing

If I subclass dict, however, the __getitem__ does not expose index, but key instead as in:
class myDict(dict):
    def __getitem__(self,key):
        #Here I want to inspect the INDEX, but only have access to key!

So, my question is how can I intercept the index of a dict, instead of just the key?
Example use case:
a = myDict()
a['scalar'] = 1  # Create dictionary entry called 'scalar', and assign 1
a['vector_1'] = [1,2,3,4,5]  # I want all subsequent vectors to be 5 long
a['vector_2'][[0,1,2]] = [1,2,3]  # I want to intercept this and force vector_2 to be 5 long
print(a['vector_2'])
[1,2,3,0,0]
a['test']  # This should throw a KeyError
a['test'][[0,2,3]]  # So should this

Comment: Dictionaries **have no order**, there is no index.
Comment: `key` and `index` are just *local names*; you can use `supercalifragilisticexpialidocious` for all Python cares.
Comment: They implement the same way because you call them the same way: `dict[0]` is looking up the value for key `0`, and `list[0]` is looking up the value in the first index. `dict` doesn't have an order, so you probably want to iterate over `.keys()`
Comment: `a['vector_2'][0,1,2]` does not conform with `a['vector_1'] = [1,2,3,4,5]`; the former varies on 4 dimensions (str -> int -> int -> int) but the latter on 2 (str -> int).  I can get to the 5 `vector_1` as `a['vector_1'][4]`, but the 2 in vector_2 would be something like `a['vector_2'][0, 1, 2][1]`.  It's not clear at all what the shape of your data should be.
Comment: @IfLoop: I have updated my buggy indexing to include internal []'s.  Sorry.
Comment: your indexing was fine, at least it means (almost) the same thing before and after the edit.  Can you elaborate on what problem you're trying to solve?  If I printed out the contents of `a`, once it's got a good amount of data in it, what would it look like?
Answer: Dictionaries have no order; there is no index to pass in; this is why Python can use the same syntax ([..]) and the same magic method (__getitem__) for both lists and dictionaries.
When you index a dictionary on an integer like 0, the dictionary treats that like any other key:
>>> d = {'foo': 'bar', 0: 42}
>>> d.keys()
[0, 'foo']
>>> d[0]
42
>>> d['foo']
'bar'

Chained indexing applies to return values; the expression:
a['vector_2'][0, 1, 2]

is executed as:
_result = a['vector_2']  # via a.__getitem__('vector_2')
_result[0, 1, 2]         # via _result.__getitem__((0, 1, 2))

so if you want values in your dictionary to behave in a certain way, you must return objects that support those operations.

__getitem__ for a list vs a dict


How to find path of file by file name in python

Question: is there any way to find file path not in same dir of project by file name only
I don't want to save file to project dir and use it .
Comment: https://docs.python.org/3/library/os.path.html#os.path.abspath?
Comment: https://stackoverflow.com/a/48393588/4788546 might help.
Comment: This would need to search all directories where the file could be.
Comment: how could i search all dirs
Comment: @Khalid You could use *find* on any \*nix type system. There may be an equivalent on Windows. You could also *os.walk()* from the root directory (\*nix) or, on Windows, I guess you'd need to figure out what drive letters are "in play" then walk those
Answer: You can use the os module, which provides several functions for interacting with the file system.
<code>import os

filename = "my_file.txt"
# Search in <search_path>
search_path = "C:/Users/MyUserName/Documents"

for root, dirs, files in os.walk(search_path):
    if filename in files:
        file_path = os.path.join(root, filename)
        print(f"The path of {filename} is {file_path}")
</code>
The os.walk() function traverse the directory tree rooted at search_path.
If we find the file, we can use the os.path.join() function to concatenate the directory path with the file name, giving us the full path to the file.


How to filter multiple columns with condition using excel VBA

Question: Scenario
I have the following excel sheet with values

What I need
I want to filter out values only when the following conditions met
If Status = "RO" OR Status = "SS" OR (Status = "NO" AND StartDate <>"") OR Status = "INVEST")
using excel filter with VBA.
This is a very big table and if it is possible through filtering techniques, it will be faster rather than doing comparison of values one by one and copy one by one. That is why I want to use filter. Is this possible?
A normal recording giving only the following which I can't figure out how to do in my situation
Eg: ActiveSheet.Range("$A$3:$D$21").AutoFilter Field:=4, Criteria1:="SS"
But how to check with filter if blank on start date and a particular value on Status?
Answer: Set your data up as an Excel table by selecting a cell in the populated range and pressing Ctrl+T.
Add an additional column at the end called Include.
In the top cell of that column put the following (it will autofilter down all rows):
=OR([Status] = "RO", [Status]  = "SS", AND([Status] = "NO",[Start Date] <>""),[Status] = "INVEST")

The use the following VBA lines in your code:
With ThisWorkbook.Worksheets("Yoursheetname").ListObjects("YourTableName").Range
    .AutoFilter
    .AutoFilter Field:=5, Criteria1:= _
    "TRUE"
End With

Data:


Which screen resolution should i consider while designing an android application?

Question: I have searched for a while, to know which screen resolution i should consider before starting to design an android app.
I found these things:
xlarge screens are at least 960dp x 720dp
large screens are at least 640dp x 480dp
normal screens are at least 470dp x 320dp
small screens are at least 426dp x 320dp
Which device resolutions should be kept in mind when developing Android Apps?
but actually these are not what i wanted.
what i wanted to know is should i design my application for each of these resolution or take the most used resolution alone into consideration
or
if i am not using any hardcoded values for widths, heights and margins etc.., i never need to worry about the screen resolutions
or
how good is this - find the device width and height using Display metrics and create all views according to these values Dynamically ?
Comment: You should design your application to be resolution-independent, the way desktop and Web developers have done for a couple of decades.
Answer:
Should I design my application for each of these resolution or take the most used resolution alone into consideration.

You should make sure your application works correctly on all screens, not just the most popular one. I would begin from the bottom up... first make sure it works correctly on small/normal screens (and in doing so, you make sure it works on all screens). Then you can optimize your layouts for tablets by using multi-pane layouts, etc.

If I am not using any hardcoded values for widths, heights and margins etc., I never need to worry about the screen resolutions.

Not sure what you are trying to say here, but you should always be wary about different screen resolutions by using dp (density independent pixels) instead of px.

Find the device width and height using Display metrics and create all views according to these values dynamically?

This should be a last resort. Most of the time, your layouts won't be that complicated though, and it won't be necessary. A lot of the time you'll use wrap_content and match_parent to set the widths/heights, and often times you'll use RelativeLayouts to space the views relative to one another. You only really need to measure the widths/heights of the views if you find its absolutely necessary.
Comment: You should never use `px`, as it doesn't scale well for devices w/ different densities. Its ok to use `dp` as long as it isn't ridiculous. i.e., if you have a button whose width is `20dp`, that's perfectly fine in 99% of cases. You just need to be aware of the boundaries... i.e., if you set the width of a button to go off the edge of the screen, that's when you would want to use display metrics to check the width of the screen, for example. But again, this shouldn't be a problem too often. This is another reason why simple layouts w/ less views makes your life easy :)
Comment: Yes, using `dp` is density independent and will make your layout consistent across devices w/ different densities. This is why using `px` is bad practice... because different devices (w/ different densities) represent pixels in different ways. `100 px` on a high-res device could be a half of an inch, whereas the same `100 px` on a low-res device could be 2 inches. Well, maybe the measurements are a bit unrealistic, but you get the idea :). Glad it helped.
Comment: by the 2nd point i mean....using only wrap content, fill parent, match parent etc.., instead of 10dp/10px
Comment: okay...so using dp alone will solve my problem?...thanks a lot
Comment: btw, I assume you have read this: http://developer.android.com/guide/practices/screens_support.html
Comment: actually i asked a graphics designer to design screens for my application. He asked me "are we targeting 320x480 resolution?". So i started searching about it. So what must me the answer?....i think after this discussion it actually doesn't matter for him, it all depends on how i code it in the application following his screens?? right?
Comment: I don't know why he needs to know the exact number of pixels... as far as I'm concerned, all he really needs to do is design a layout that works well on a rectangular screen, right? It'll be your job to make sure it works for multiple Android devices... the graphics designer should only really be responsible for the layout. You should also make sure he is familiar with Android navigation/guidelines, as described in the "design" section of the developers site. Also... maybe he was just asking for the aspect ratio, not the exact # of pixels.
Comment: but when i am using images in my application, i need to  design images for all the ldpi, mdpi, hdpi, xhdpi and keep them in there respective resource folders??...and when i use @drawable/myImage, in my code it automatically gets the image depending on the device pixel density?
Comment: @Archie.bpgc Yes, that is correct. `mdpi` and `hdpi` are the most important, and cover most devices, but it's good practice to cover all devices. [**This website makes handling icons incredibly easy.**](http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html).
Answer: IMHO you should always code your application such that every device is supported. From the launcher icon which is detailed here (different resolution for different screen size): http://developer.android.com/guide/practices/ui_guidelines/icon_design_launcher.html to the layout of your app which should be designed so that everything is placed relative to the screen size (by using attributes such as match_parent and wrap_content).
You can try to code it such that the views are created dynamically after discovering screen size, but I think its easier and just as effective to do your first idea!
Comment: so you are elaborating my 2nd point right? if i understood your answer correctly
Comment: Yes, this one "if i am not using any hardcoded values for widths, heights and margins etc.., i never need to worry about the screen resolutions"
Answer: Best option is to get the screen width and height dynamically using simple height and width getting parameters.
DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int wwidth = displaymetrics.widthPixels;

other option is to do create it for device with highest screen width and height and then handle it mathematically for respective screen size.
Answer: Well, it is recommended to design for all the sizes. But I know it is a lot of overhead.
So what you could do is design for the largest device you're aiming for and have the devices adjust the images based on their sizes. Do not use hard coded values. Use wrap_content or fill_parent.
And yes, dynamically adjusting the images is a good idea, even though it requires more coding on your side. This is the technique I use.


Different types of strings on the same guitar

Question: My Epiphone SG is strung rather strangely. All but one of the strings are Elixir strings, but the G string is a Gibson string. This is because the G string broke while I was restringing, so I had to make do with what I had.
Is there any problem with this? Does it damage the guitar or the strings in any way? Does it alter the sound?
Comment: I'm sure if this 100% correct, but if they are pretty much the same quality, there won't be much of a difference
Comment: Far more relevant is the gauge of the string. If it's the same as the original, there will be little difference, except if the original belongs to a set that's been on for ages. A G string could be anything from .010 to .020, which is a pretty large discrepancy.
Answer: I often, though not always, find a difference in the quality of sound between new and old strings because of the age of the strings. I usually change them all when one single string breaks, for this reason.
Some brands have a different quality of metal, or nylon, but for the most part the quality is consistent across brands. I have a negative opinion of the Gibson strings, and a positive one of Elixir, but there is probably not a significant difference. Except of course that the polyweb and nanoweb coating is a significant difference.
It is true that if the gauge is different then what the old string was, it will effect the sound, balance, tuning, and setup of the guitar in some slight way.
For certain types strings there is a difference in the materials in strings when looking at acoustic vs. electric vs. classical. This could account for a significant difference in the effectiveness and sound of the strings. Most string manufacturers sell many types of strings that fit into those three categories.
To Fully address the question: There could be some difference in sound quality depending on the factors previously stated, but there is unlikely to be any damage to the guitar from mixing brands of string.
Answer: If the replaced string is a different gauge from the string that you broke it might sound different and it also might sound odd if the gauge is not similar to the string gauge that is already on your guitar.
And for the changing brand of string if it is different material it might sound different, and all different string brands and types have a different sound from each other, but with saying that have a listen to it and if it sounds bad to you then replace the whole set of strings on the guitar, and if not keep it but you decide if you like it.
And by replacing the string it will not damage the strings in anyway.
Answer: I've heard that non-wound steel and electric strings all use the exact same wire regardless of manufacturer. Whether that is true or not, it certainly seems to be the case that it is virtually impossible to tell the difference between two new non-wound strings of the same gauge.
For wound strings this is not the case. It's quite possible for two wound strings of the same gauge to be quite different both in sound and appearance.
Whether a mixture of strings from different manufacturers (or a mixture of strings of different ages) is acceptable is up to you.
Mixing strings is certainly something I avoid, and I tend to change the whole set at once. But when a string snaps when installing a brand new set I'd probably go ahead and put another one on.
Non-wound strings are, as I say, virtually identical, and your guitar store should be able to sell you a single string of the right gauge. Wound strings would be best from the same manufacturer as the original set, if your store has them in stock. For electrics, it's fortunate that the thinnest unwound string generally goes first. For acoustics it's often the thinnest wound string, which is more of a pain...
Answer: Guitarists of all stripes and abilities mix and match strings all the time.  Sometimes it's intentional and deliberate, sometimes it's just because (as in your case) that's all they had laying around at the time.
Many pro guitarists buy an inventory of individual strings instead of buying prepackaged sets...they prefer a slightly lighter gauge this string or a slightly heavier gauge that string than what the string company sets up as a "standard" set, or they buy a G string that's an entirely different manufacturer or metal type...based on their years of experience.
Mind you, the difference between a professional guitarist and the OP is that the pro is likely changing strings every night if not more, and the OP is likely changing strings only when they break.
The guitar itself cares not.
Answer: String manufacturers put together string sets based on what they expect that the guitarist will want.  They know that some guitarist want light strings, others medium and a few may even want heavy gauge strings.
Within each classification (super light, extra light, light, custom light, medium, heavy etc.) the string makers will choose a gauge for each individual string, that is consistent in terms of the amount of tension needed to tune that string to concert pitch relative to the tension required to tune the other strings in that particular set to concert pitch - assuming standard tuning.
Guitars are also "set up" either in the factory or by a luthier or guitar technician based on the gauge of strings that are most likely to be used - or in the case of a custom set up, the actual gauge that the user specifies.  The set up will be completely different for medium strings than for light strings.
One thing that will be different in the set up would be the truss rod tension - which compensates for the string tension - which will be different with different gauge strings.  Another thing that might be different would be the width of the slots in the nut and possibly the height of the bridge.  Heavier strings will have a wider oscillation pattern but also have a higher tension.  These factors can affect how much clearance the strings need from the frets to prevent buzzing.
For a given guitar, set up for a particular gauge string, you could mix and match strings from different manufacturers without damaging the guitar or affecting the playability - as long as the gauge was close to what the guitar was set up for.
The type string and manufacturer of a mis-matched string, even if the gauge is the same as what was in the original set, could affect the tone. And it may feel different than the other strings - especially if you mix coated and non coated strings or flat wound with round wound.
But to answer your question - you could get by with a G string from a different manufacturer and of a different type (don't put a wound acoustic  string on an electric guitar).   As long as the gauge is not radically different (the other strings are ultra light and your oddball string is from a medium set) you should be able to get by with it with no issues.
As a side note, the G string is the string that breaks most often on sets with a wound G string (includes almost all acoustic sets).  That's because the steel core of a wound G string is thinner than even the high E-string.  That's why I order extra individual G strings and keep at least one extra G string in my guitar case (along with a full replacement set) so if I break a G string during a live show, I only have to change the one string and I don't have to rob the G string from a full set.
I also sometimes customize my string sets and have my guitar's set up accordingly. I like to use a different combination than what the manufacturers deem as the most common.  For example - I have a guitar that is a little weak on the bottom end, so I use heavier bass strings.  But again I have the guitar set up specifically for that type of custom string set.
One other note that is on the subject of guitar strings and breaking strings.  You should change your guitar strings on a regular basis if you want them to sound good and not break.  As you play - pressing the strings against metal frets will wear flat spots on the strings where they contact the frets.  Also, the sweat and oils from your fingers will contribute to corrosion of the strings.  Even if you don't play the guitar much, the natural oxidation of the metals will cause the strings to weaken and begin to sound dull over time.
There are many excellent answers and recommendations to this question on Music Stack Exchange When and Why to replace guitar strings  It is recommended reading for any guitarist.


What's the easiest way of importing content of a custom D6 content type into a D8 site?

Question: I have a Drupal 6 site with three custom content types. We have tried using the Migrate Drupal UI module to migrate these to our new Drupal 8 site, but this resulted in all of the plain text fields being imported as long text fields (field type string_long when they should be string).
To fix this, I deleted all content of those types, exported the configuration created by the UI module with drush cex and used drush cim to re-import the YAML config files after changing all instances of string_long to string.
After about 3 hours of fiddling with this, I finally had a working D8 configuration with the same fields, forms and views as the original D6 site. Now it's time to migrate the content data across.
I have spent another ~6 hours researching and experimenting on how to do this, having tried the views_data_export and Feeds modules, as well as reading several resources on creating custom migration modules.
The former solution was tedious to set up and the default form for creating a feed type wouldn't allow me to create nodes with the original node IDs. So I tried to step through the code and figure out how to extend the module by myself, since the API documentation is severely outdated. This got me nowhere but extremely tired, confused and frustrated, and about 2 hours closer to my eventual demise.
I'm not even game to try the latter solution, since that would probably be just as hard. So now I've started investigating the DB structure in the hope of writing my own SQL update script...only to discover that there are not only node, node_field_data, node_revision and node_field_revision tables to contend with, but also node__<field_machine_name> and node_revision__<field_machine_name> tables for every defined field (35 of them in my case)!
This seriously can't be this hard! Surely I must be missing some crucial piece of documentation from my Google search results. So what would be the easiest method to accomplish what I want?
Comment: Asking for the easiest or best of something always is an opinion-based thing. What's easy for you might be difficult for others. Some might say you should hook into the D6 database from your new D8 site and import all content programmatically using a batch process, others might say go for Migrate and adjust it the way you need it.
Comment: @leymannx I totally agree, but perhaps I gave you the impression that I expect the 100% undeniable "best" solution. That is obviously impossible to give though, for the reasons you stated. Hence I am really just looking for ideas that I could explore further on my own.
Comment: The two options here is the inline D6>D8 migration, or to use the Migrate API + Migrate Plus (if needed) directly to write your own migrations. The latter has example migrations you can look at. There is never going to be a case or scenario where you will want to write a manual SQL migration script. You should not need Views or Feeds for this - the Migrate API has source plugins that can connect to databases or other data sources to query and pull data.
Comment: Thanks @Kevin! If you write up your comment as an answer I'll gladly accept it :D
Comment: Does that technically answer it though?
Answer: The two options here is the inline D6>D8 migration, or to use the Migrate API + Migrate Plus (if needed) directly to write your own migrations. The latter has example migrations you can look at. There is never going to be a case or scenario where you will want to write a manual SQL migration script. You should not need Views or Feeds for this - the Migrate API has source plugins that can connect to databases or other data sources to query and pull data.
Here is a docs page outlining how to migrate from a SQL source:
https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/migrating-data-from-a-sql-source
You would set the two databases side by side in MySQL, create a connection setting as mentioned and create a source. The class controls certain aspects of querying and the migration YAML(s) map the fields to their new destinations.
For all the nuanced aspects, I would recommend joining the migration channel in the Drupal Slack, people are always willing to help there.
Comment: Thanks mate, and re: drupal slack's migration channel, I have asked questions there before without getting much response. I'll give it a go next time though ;-)


How can one calculate $\sum_{n=1}^{\infty} \frac{(-1)^n}{n^2}$?

Question: I am working through a textbook for my Fourier Series class and I came across the series $\sum_{n=1}^{\infty} \frac{(-1)^n}{n^2}$. I know from the context of the question that the answer has to be $-\frac{\pi^2}{12}$, but I am not sure how to arrive at this answer. I tried partial fraction decomposition to see if there was any telescoping behavior, but I had an issue with the $(-1)^n$ part.
Comment: I think the sum is negative though?
Comment: Hello, thank you for editing the title, I am just starting with LaTeX for my grade 10 mathematics class, and I did not know about the \infty representation of infinity.
Comment: Asked [so often](https://approach0.xyz/search/?q=%24%5Csum_%7Bn%3D1%7D%5E%7B%5Cinfty%7D%20%5Cfrac%7B(-1)%5En%7D%7Bn%5E2%7D%24&p=1)... Let yourself choose the best fit.
Comment: Maybe check this post https://math.stackexchange.com/q/620825/254075
Answer: Assuming that you know $S:=\sum_{n\geq 1} \frac{1}{n^{2}} = \frac{\pi^{2}}{6}$, we get (and I'll replace $(-1)^{n}$ with $(-1)^{n-1}$ which seems that you actually intended to be positive)
$$
\frac{1}{1^2} -\frac{1}{2^{2}} + \frac{1}{3^{2}} - \frac{1}{4^{2}} + \cdots \\
= \frac{1}{1^{2}} + \frac{1}{2^{2}} + \frac{1}{3^{2}} + \frac{1}{4^{2}} + \cdots \\
- 2 \left(\frac{1}{2^{2}} + \frac{1}{4^{2}} + \frac{1}{6^{2}} + \cdots\right) \\
= S - 2\cdot \frac{1}{2^{2}}S = \frac{1}{2}S = \frac{\pi^{2}}{12}
$$
Comment: Thanks so much!


How to identify seasonal time series?

Question: I am having sales volume data for 100 stock-keeping units (SKUs). Is there a statistical way of identifying seasonal time series?
Comment: Perhaps it's too obvious to mention but I'd always start with plotting data against time of year (for the usual meaning of seasonality), and time of month, time of week, time of day as suitable. Telling us about your time unit (sales are measured hourly, daily, weekly or what?) and about you want to do with your data would allow expanded answers.
Answer: Seasonality is a periodic signal in the data.  The most basic tool for detecting periodic signals is to transform your data into the frequency domain using a Discrete Fourier Transform (DFT).  In the frequency domain, periodic signals show up as frequency 'spikes' (usually with harmonics at multiples of that frequency), which are generally easy to see unless there is too much noise.
If you are looking to progress further to statistical modelling of the signal, you can add a seasonal component (a number of sine waves) to your time-series model and use your model-fitting to estimate the parameters of the signal (number of sine waves, amplitude, frequency, phase-shift).  If you do this you will automatically have a non-seasonal model built in, which is the special case when the number of signals is zero.  You can use this fact to do a hypothesis test to see whether there are signals in the data.
If you would like a specific example of a test for seasonal components in a time-series, you can have a look at the permutation-spectrum test in O'Neill (2020) and the accompanying function spectrum.text in the ts.extend package in R.  This test uses the maximum Fourier intensity as its test statistic and it tests this against its simulated null distribution computed by permuting the elements of the input time-series vector.  The test can detect periodic signals in noise with reasonable power and it does not require any assumption for the distribution of the noise part of the input.  The linked paper explains the test and shows how to implement it.
Answer: One possibility would be to fit both a nonseasonal and a seasonal exponential smoothing model to each SKU's time series. Note each model's AICc. SKUs where the seasonal model yields a lower AICc are "more seasonal".
The absolute difference in AICc measures the strength of the evidence (to a degree). As a rule of thumb, Burnham & Anderson suggest that a difference in AICc of about 2 constitutes weak evidence, a difference of 5 constitutes clear evidence and a difference of 10 constitutes strong evidence that the model with the lower AICc describes the data better.
Alternatively, use a holdout sample for each time series. Fit seasonal and nonseasonal models to the initial data, forecast into the holdout sample and check whether a seasonal or a nonseasonal model provides better forecasts. If you need a statistical test as to whether the forecast improvement is significant, you can use the diebold-mariano test.
Look at ets in the forecast package for R. While you are there, look at the seasonplot command to visualize seasonality.

How to identify seasonal time series?