Drupal Panels/Views conflict

Question: I'm using Drupal 7 along with the Panels and Views modules. I've got a view with a page display, but I want to place it in a panel/page. I need the view's display to be that of a page because it has exposed filters, and I can't rely solely on AJAX for the filters because of 508 standards compliance concerns.
However, because the paths of the panel and the view are the same, the view takes precedence, and the panel never shows up. How do I get the view working inside the panel?
Answer: Create your view as a content pane instead of a page. Then on your panel insert the content pane. You can also look at something like http://drupal.org/project/panels_everywhere as a more general solution.

Drupal Panels/Views conflict


Flutter app text turning to white when I set usematerial3: true in MaterialApp

Question: I got excited when I was knowing that Google have introduced Material 3 for flutter apps. This means we can design Flutter Apps with Material 3 design, but when I code a UI for testing Material 3, whole texts and Icons colour share the same colour as the background colour in my App which means they're all white, example from screenshot:

This is what I'm expecting about (I colored the text and icon for example):

Anyone ever face this problem?
This is my main.dart "MaterialApp" code:
MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            useMaterial3: true,
          ),
          routes: AppRoute.routes,
          initialRoute: AppRoute.mainPageRoute,
        ),

and this is my tab code:
TabBar(
          tabs: const [
            Tab(
              icon: Icon(Icons.chrome_reader_mode),
              text: "List Hadits",
            ),
            Tab(
              icon: Icon(Icons.search),
              text: "Search Books",
            ),
          ],
          controller: _controller,
        ),

UDPDATE: Also, I'm using material theme builder for defining my colour scheme:
ThemeData(
            useMaterial3: true,
            colorScheme: lightColorScheme,
          ),
          darkTheme: ThemeData(
            useMaterial3: true,
            colorScheme: darkColorScheme,
          ),

Comment: can you share your main.dart file
Answer: You can use this property for TabBar Widget
 labelColor: Colors.blue, //<-- selected text color
 unselectedLabelColor: Colors.black, //<-- Unselected text color


How to test - with rspec - what template is used when creating an email? (Rails 3.0.7)

Question: I'm trying to write some tests for emails generated with a mailer class using rspec and email_spec (Ruby on Rails 3.0.7)
I would like to check if the layout used for rendering the email is the layout that was specified in the mailer class.
Any idea on how to do this? I've spent 3 hours searching for a solution but couldn't find anything.
Thanks!
Comment: What are you trying to accomplish with this test?
Comment: If I remember correctly the situation, I had multiple email templates and wanted to test that the emails get sent with the right template
Answer: (I realize this is a pretty late response. You've probably found a solution already)
I won't be able to update this answer much, but does this page help? It describes how to check if a layout was rendered. You could make a get request with parameters (example here) then check if the result renders the layout you want it to render.
Comment: Nope unfortunately this does not work with mailer spec
Answer: This is cheating a little bit, since you're not really checking which template got generated...
However, I just wanted to perform a quick sanity check that the right email is (probably) being generated - so this was good enough for my needs:
<code># In RSpec:
expect(ActionMailer::Base.deliveries.last.subject)
  .to eq I18n.t("name.of.email.subject")

# In MiniTest:
assert_equal I18n.t("name.of.email.subject"),
  ActionMailer::Base.deliveries.last.subject
</code>


How to calculate the value (wind direction) of "maximal effect" in a linear-circular correlation?

Question: I am trying to evaluate the effect of wind direction (circular variable) on a dependent linear variable. I have used circular-linear regression to find the correlation coefficient between the two variables, shown in the code sample below.
import numpy as np
import pandas as pd
import scipy as sp
from scipy import stats

data = pd.read_csv('Data_example.csv')

x = data.Rate # dependent linear variable
theta = data.WindDir_deg * (3.14159265359/180) # corresponding measured wind directions (converted to radians)

rxc = np.array(sp.stats.pearsonr(x,np.cos(theta)))
rxs = np.array(sp.stats.pearsonr(x,np.sin(theta)))
rcs = np.array(sp.stats.pearsonr(np.cos(theta),np.sin(theta)))

rho = np.sqrt(((rxc)**2 + (rxs)**2 - (rxc)*(rxs)*(rcs)) / (1 - (rcs)**2))

print("Correlation coefficient, ", rho)

Example Data
     Rate       WindDir_deg
0   -0.102186   180
1   -0.051093   200
2   -0.026898   40
3   -0.012773   180
4   -0.004927   0
5   -0.002488   50
6   0.000000    180
7   0.000000    160
8   0.000000    180
9   0.018639    170
10  0.019800    320
11  0.021236    160
12  0.025028    20
13  0.026400    240
14  0.030280    160
15  0.033402    150
16  0.037174    190
17  0.040175    180
18  0.041331    160
19  0.049942    190
20  0.051093    120
21  0.052635    140
22  0.052800    360
23  0.057955    170
24  0.057955    170
25  0.057955    30
26  0.059413    330
27  0.060490    170
28  0.060560    20
29  0.063866    190
30  0.070678    170
31  0.072444    240
32  0.085714    160
33  0.101950    0
34  0.105600    0
35  0.110216    40
36  0.120980    180
37  0.121660    170
38  0.145200    10
39  0.173865    180
40  0.204372    180
41  0.242240    30
42  0.351462    180
43  0.360800    170
44  0.423920    30
45  0.592800    160
46  0.741000    190
47  1.937873    170

Now how do I estimate the actual wind direction that has the maximal effect on the linear variable? For example in the data shown in this plot, the wind direction with maximal effect on the linear variable appears to be somewhere between 150° and 200°, but how to I calculate this mathematically?
Comment: Can you make your code reproducible, by making your dataset available?
Comment: Isn't this a restatement of your previous question at https://stats.stackexchange.com/questions/568870/how-can-i-quantify-this-non-linear-relationship-where-y-values-peak-within-a-nar?
Comment: No not exactly. My previous question was asking how to quantify a relationship between the two variables, which I have now done by calculating the correlation coefficient (see code example). This new question is asking specifically how to estimate the actual value (degree direction) that has the maximal effect on the linear variable.
Comment: Of course. I have edited my question to include a snippet of the dataset
Comment: For future readers: I recommend horizontal axis labels 0(45)360 not 0(50)350.  Text such as N NE ... NW may make more sense too.
Answer: The circular-linear correlation coefficient is the square-root of the fraction of variance explained by a linear model
$$x = a \cos(\theta) + b \sin(\theta) + c$$
Fit this regression with least squares and obtain $(a,b)$. The direction where $x$ is the largest should then be $\tan^{-1}(b/a)$. Use arctan2(b,a) to calculate this. Alternatively, you can view $a + ib$ as a complex number, and recover the phase via np.angle(a+1j*b). (Incidentally, the magnitude $|a + ib|$ captures the depth of modulation and is vaguely analogous to slope in linear regression).
Comment: I think you're right. Things also get awkward when data are limited and $\theta$ isn't sampled uniformly. IMO the linear regression is clearer, but you need to be careful. If you want the best R² on your data, then you fit this with OLS, which will react to induced correlations in the sine and cosine of θ. But, if you want a "ground truth" estimate of best direction, we *know* that sine/cosine will be zero mean, uncorrelated, and have variance ½. IMO this is feels better in some sense, and the circular-linear correlation seems worryingly biased.
Comment: Why would this estimate the direction of "maximum effect", especially with a distribution that empirically looks multimodal?


How easy is it for a LF to play RF and vice versa?

Question: Most outfielders have a designation where they play every game.  It seems that in parks like Minute Maid Park (home of the Houston Astros) and Fenway (home of the Boston Red Sox), left field would be the position where you'd place the outfielder with the least athletic ability.
How often do managers swap these positions when visiting other ballparks?
Answer: The skills required to play left and right field are identical, with one exception: the configuration of the bases. A left fielder and right fielder are equally far away from second base and home plate. The right fielder is closer to first base, and the left fielder is closer to third base. For this reason, the corner outfielder with the better arm is typically put in right field, as they are more equipped to make long throws to third base (Throws from the outfield to first base almost never happen, and the few that do happen are usually from right field anyway). Arm strength is the typical criteria used to decide who plays LF/RF.
If one player is significantly worse defender than the other, they may also be put in RF, as balls are slightly more likely to be hit to LF than RF, due to right handed batters being more common than left handed batters.
I am not aware of any case of those positions switching due to the opposing teams field dimensions, although the players would certainly be capable of it.
Comment: The way balls would curve from hitters would differ between LF and RF, but that should be easy to adjust to.


Moving footer that disapears when you Reach the End

Question: OK my boss just asked to do a moving footer(other than the original static footer) that moves with the page as you scroll down and then disappears when you reach the bottom of the page, i have no idea what so ever any suggestions?
Thanks
Comment: How about making the footer fixed and then at the bottom of the page have a div with a higher z-index so the footer effectively goes under this and disappears - this would mean nothing but CSS?
Comment: Is this a comment or an answer?
Comment: It's a comment as I don't know what you have tried so far or what your page looks like and whether you want things like velocity on your footer?
Comment: @Matthew Riches Nice idea, but wouldn't that result in top half of the footer showing as it started to overlap, leaving a gap between the top of the footer and the bottom of the browser window?
Comment: @DarrenCrabb Yeah it would be an ugly transition but with the right measurements it should work. The alternative is to use JS to determine when the footer is at the bottom of the page, OP do you want a JS or CSS solution?
Comment: @Matthew Riches Thanks for the suggestions, anyway if you got a solid idea on how to do i'll be thankful
Answer:
<code>$(window).scroll(function () {
   if ($(window).scrollTop() + $(window).height() == $(document).height())
       $(".footer").css({"display": "none"});
   else if (!$(".footer").is(":visible"))
       $(".footer").css({"display": "block"});
});
</code>
<code>.footer {
 position:fixed; height:20px; width:100%;
 background:blue; bottom:0; left:0;  z-index:1;
}
</code>
http://jsfiddle.net/4WWhf/1/
Answer: You really should post some code so people can see what you are trying to achieve.
Try Using a fixed footer to lock it to the screen.
<code>.Footer {
    position: fixed;
    bottom: 0;
 }
</code>
Use javascript to change it to position absolute when you want it to no longer be fixed.
I cant show you code suggestions because I have no idea of your ultimate objective.
Answer: You could set the CSS to place the footer in a fixed position:
<code>#footer {
    position:fixed;
    bottom:0px;
    left:0px;
}
</code>
Then use jQuery to determine when the bottom of the page has been reached.
<code>$(window).scroll(function(){
    if($(window).scrollTop() == ($(document).height() - $(window).height())) $("#footer").fadeOut();
})
</code>
If you need to account for pages that don't scroll you would need additional logic.
But it would be handy if you could explain more your ultimate goal or even show us?
Comment: I cant show you i haven't started yet i was just getting some ideas on how to do it,anyway thanks for your help


How to customize the SMTP message

Question: When a message is send to the user a message like this is shown to him :
message screenshot

SMTP -> FROM SERVER: ...........
  SMTP -> FROM SERVER: .......
  ............................................................................
  SMTP -> FROM SERVER: .......
  SMTP -> FROM SERVER: ......
  SMTP -> FROM SERVER: .....................
  SMTP -> FROM SERVER: ................................
  SMTP -> FROM SERVER: .....................................
  Further instructions have been sent to your e-mail address.

I only want the last one: "Further instructions have been sent ..." to show. Is it also possible to personalize it ?
Comment: Are you using the SMTP module for mail delivery?
Comment: yes i'm using the module SMTP Authentication Support and phpmailer
Comment: Did you try disabling the debug messages in the SMTP module settings?
Comment: http://prntscr.com/bx0glk i try this but i still got the the same message
Comment: Do you have the devel module enabled?
Comment: No http://prntscr.com/bx16sx
Answer: Those messages are shown as the result of enabling logging in the SMTP module. It's only set once from the smtp_debugging variable. If it's still logging after disabling it, you to debug the issue as there's no one cause (e.g. caching, forcing the setting in settings.php/settings.local.php, code base hack, etc.) and is out of scope of Q&A.
As for altering the "Further instructions have..." message, there are many ways to do this (e.g. form alter, translation files), but the simplest is probably utilizing the String Overrides module which will let you override any message wrapped in a t() function.
Answer: I found an alternative method to solve my prob by using this two modules: Disable Messages Module and String Overrides Module

How to customize the SMTP message


No parameterless constructor defined for this object error

Question: I'm getting this error in my wcf services all of a sudden:
An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
<code>System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension:
System.ServiceModel.Description.DataContractSerializerOperationBehavior contract:
http://tempuri.org/:IListingService ----> System.MissingMethodException: No parameterless constructor defined
for this object.
at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) at
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) at
System.Activator.CreateInstance(Type type, Boolean nonPublic) at
System.Runtime.Serialization.SchemaExporter.InvokeGetSchemaMethod(Type clrType, XmlSchemaSet schemas, XmlQualifiedName stableName) at
System.Runtime.Serialization.SchemaExporter.ExportXmlDataContract(XmlDataContract dataContract) at
System.Runtime.Serialization.SchemaExporter.Export() at
System.Runtime.Serialization.XsdDataContractExporter.Export(Type type)
</code>
I have public constructors with no parameters in every single class and it still gives me this error. What am I missing?
Comment: Found the issue, I was using an OId for a property type (a 3rd party type from MongoDB), which had no default constructor. Changed this to an int and it started working. The weird thing though is that the OId property worked fine for weeks, I wonder what changed...
Comment: If you solved your problem, please post the solution as an answer.
Answer: Found the issue, I was using an OId for a property type (a 3rd party type from MongoDB), which had no default constructor. Changed this to an int and it started working. The weird thing though is that the OId property worked fine for weeks, I wonder what changed...
Answer: I had the same issue with a slightly different solution.
(Obviously, this is an old post, but for those who found this question like I did and the original answer didn't help...)
I think it's pretty reasonable to say that every object referenced by your Interface signature(s) need to be marked as serializable. Sometimes in simple projects, we don't think about this because many (or most?) of the native .NET objects we play with already have this ability. For example, "ObjId as Guid" wont cause any problems in the signature for an interface-implemented member.
The problem I experienced was that I had multiple custom objects ("Class1, Class2, whatever) as properties in the object that was actually referenced by my signature. THAT object (say MyMainClass) had the  attribute set on it, but my custom property objects did not. As soon as I added the  attribute to those classes, the error shown above went away.


How to get the cumulative sum of different linearized line plots when they are overlapped

Question: So I have the following pandas dataframe
Start time | End time | Value|
0;50;50
20;100;800
10;45;700
which each row represents a line in plot from start time til end time linearized (time are x axis)
the result dataframe should have
x | value
0;0
10;10
20;220
45;995
50; 1050;
100; 1550
each value correspond a point in the graphic and are connected by a line plot
e.g: start time: 0 End time: 5, there will be a linearized line from 0 til 5.
The problem is that when there are two rows that are having overlaps of time. For the overlapping part I want to get the cumulative sum of the fraction of each row. (and this should be applied to the rest of the lines too)
How could I achieve this? I tried to sort by start time but have no clue how to continue.
Example
I will draw a graphic to better illustrate what I want to achieve
So as you can see, each circle in the second graph corresponds the sum of the fraction of the lines that are overlapped
Thanks in advance!!!
Comment: Could you create (in code) a set of test data (e.g. 3 rows)? And the corresponding plot?  How should "Value" be interpreted? Is that linearly increasing from 0 at the Start and the given value at the End (the current example doesn't contain a 'Value')?
Comment: yes, gonna add it
Answer: This may not be scalable depending on the size of your DataFrame.
Some data to get us started.
import pandas as pd
from plotnine import *

df = pd.DataFrame({
    'StartTime':(0,20,10),
    'EndTime':(50,100,45),
    'Value':(50,800,700)
})

First, create a DataFrame of x-coordinates for all the inflection points.
xyCoordinates = df['StartTime']
xyCoordinates = xyCoordinates.append(df['EndTime']).sort_values()
xyCoordinates = xyCoordinates.reset_index(drop=True)
xyCoordinates = xyCoordinates.to_frame('x')
xyCoordinates['y'] = 0

Then iterate over each of the rows in df and iterate over each of the inflection points in xyCoordinates, and for each x-coordinate in xyCoordinates calculate the y-coordinate based on the slope of the line. Iteratively add this value to the y-coordinate in xyCoordinates.  Because in your example the value when x=50 is given as 1050 rather than 350, I am assuming that once a line ends, it stays at its maximum value and contributes to the cumulative total rather than disappears to 0.
for df_index, df_row in df.iterrows():
    for xy_index, xy_row in xyCoordinates.iterrows():
        if (xy_row['x'] >= df_row['StartTime']):
            y = ( df_row['Value'] / (df_row['EndTime']-df_row['StartTime']) ) * ( min(xy_row['x'],df_row['EndTime'])-df_row['StartTime'])
            xy_row['y'] += y

This produces:

Can we can plot as:
p = (ggplot(xyCoordinates, aes(x='x',y='y'))
  + geom_line()
)
p


Find the second derivative of a double integral

Question: Problem: Find $F''(\pi)$ if
$$
F(x) = \int_x^{\sin x}  \left(\int_0^{\sin t} (1+u^4)^{0.5} \,du\right)\,dt
$$
Context
I don't know how to integrate the inner part. What to do to the integral inside when differentiating? Do I have to differentiate it also?
Comment: think of fundamental theorem of calculus ($\frac{d}{dt}\int^b_t f(u)du=-f(t)$ and notice that $f(t)=\int_0^{sint} (1+u^4)^{0.5} \,du$ for some function $f$.
Comment: i dont know how to integrate the inner part. Thats why i cannot start the problem.
Comment: You have asked four question now, but you haven't shown any effort in any of the questions...
Comment: Im trying to do it. But i dont know what to do to the integral inside when differentiating? Do i have to differentiate it also?
Comment: now i understand. I can move the dy/dx inside right?
Answer: Hint
The first derivative is, using the fundamental theorem of calculus,
$$F(x)=\int_x^{sinx}  \left(\int_0^{sint} (1+u^4)^{0.5} \,du\right)\,dt \\ \implies F'(x)=\cos x\int_0^{\sin (\sin x)}(1+u^4)^{1/2}du-\int_0^x(1+u^4)^{1/2}du.$$
Can you continue from here?
Comment: how did you come to F'(x)?
Comment: Are you familiar with the fundamental theorem of calculus? http://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
Comment: Yes. but i only know how do the simple problems.
Comment: This is the same, but with more steps. To get the first derivative just consider $F(x)=\int_x^{\sin x}=\int_0^{\sin x}-\int_0^x$ and apply it. Just be confident, it is the same as in simpler cases.
Comment: i still do not get it. Sorry but what should i do with the integral o to sint of (1+u^4)^{1/2} inside
Comment: where does this cos x come from?
Comment: From the derivative of the upper limit of the integral, that is, $\sin x.$
Comment: in F'(x) i t should be (sint)^4 in the first integrand after substituition right?
Comment: In the last step, the second integral, shouldn't the limit be from 0 to sin(x)?
Comment: @Winther Typo fixed. Thank you for noticing it.
Answer: Let's rewrite $F(x)$ a little bit. Therefore, let $G$ be the antiderivative of $g$, i.e. $G'(x)=g(x)$ for all $x$. Then, using the fund. theorem of calculus, we can write
$$
F(x) = \int_x^{\sin x}  \left(\int_0^{\sin t} (1+u^4)^{0.5} \,du\right)dt =: \int_x^{\sin x} g(t)\,dt = G(\sin x) - G(x).
$$
Now it is easier to handle:
$$F'(x) = G'(\sin x) \cdot \cos x - G'(x) = g(\sin x) \cdot \cos x -g(x)$$
and, using the product rule, we find
$$F''(x) = g'(\sin x) \cdot \cos^2 x - g(\sin x) \cdot \sin x - g'(x).$$


warning: Illegal offset type in isset or empty

Question: I am running drupal 6 and I get this warning on every page.
warning: Illegal offset type in isset or empty in /var/www/my-website/includes/common.inc on line 915.

And this is what I have from lines 914 to 917 in common.inc file
// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$langcode][$string])) {    /* Line: 915 */
  $string = $custom_strings[$langcode][$string];
}

What could be the possible reasons for the warning and how to get rid of it? Any help is appreciated. Thanks.
Edit:
   This warning appears only for anonymous users and it is not visible for authenticated users.
Comment: Did you recently install any modules?  Try turning off the modules you have enabled one by one.  Each time you turn off a module, clear the cache.  Then check to see if the error still appears.  Once you find which module is causing the problem, edit your question with the new information.
Comment: Have you tried switching back to a default theme (if you are using a custom one). Does the error persist? Have you defined a new region in your theme .info file and not included it in your page.tpl.php?
Comment: Looks like a translation / Multilanguage issue perhaps translating an object or similar instead of string.
Comment: @PatrickKenny: Thx for your comment. I will do that.
Comment: @PatrickKenny: I disabled all the modules one by one and cleared all cache everytime but still no luck. The warning still appears on all the pages.
Answer: I have fixed the problem. I think this will help you. For me it works perfectly:
BEFORE:
// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}

AFTER:
// Custom strings work for English too, even if locale module is disabled.
if ($custom_strings[$langcode] && isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}

Answer: if you still need help solving the issue, you can try setting your own error handler to print a debug_backtrace to see exactly where the source of error is.
More details: http://blog.ryantan.net/2012/12/debugging-illegal-offset-type-in-isset-or-empty-in-for-drupal-7/
Comment: There is Devel module.


Meu programa roda normalmente mas aparece uma mensagem de erro envolvendo a função main()

Question: Decidi fazer um projeto para criação de conta bancaria, o programa roda normalmente no Code::Blocks, porém no VS Code aparece a seguinte mensagem de erro envolvendo a função main:

Banco.c: In function 'criar': Banco.c:43:16: warning: implicit declaration of function 'main' [-Wimplicit-function-declaration]
        case 9: main();

#include <stdio.h>
#include<string.h>

#define MAX 100
int esc1,esc2;
int u=0;
char nome[MAX],sobrenome[MAX],data[MAX],email[MAX],cpf[MAX],tel[MAX],contatip[MAX],esc3[MAX],esc4[MAX];

int criar()
{

    printf("\n A seguir voce ira adicionar informacoes para a criacao da sua conta. Aperte qualquer tecla para continuar ou caso queira voltar ao menu digite 9\n\n");
        scanf("%i",&esc2);
           getchar();

    printf("\nDigite seu nome e sobrenome: ");
        scanf("%s%s",&nome,&sobrenome);
            fflush(stdin);

    printf("\nDigite sua data de nascimento: ");
        fgets(data,MAX,stdin);
    printf("\nDigite seu email: ");
        fgets(email,MAX,stdin);
    printf("\nDigite seu CPF: ");
        fgets(cpf,MAX,stdin);
    printf("\nDigite seu numero de telefone: ");
        fgets(tel,MAX,stdin);

   printf("\n1.Corrente\n\n2.Poupanca\n\n");
        scanf("%s",&contatip);
        if(strcmp(contatip , "1")==0){
            strcpy(contatip, "Corrente");}
        else (strcmp(contatip,"2")==0);{
                strcpy(contatip, "Poupanca");}

   printf("Conta criada com sucesso !!!\n\nDigite 8 para sair da aplicacao ou 9 para voltar ao menu.\n\n");
        scanf("%i",&esc2);

    u = 1;

   switch(esc2)
   {
       case 9: main();
   }
}

int ver()
{
    if(u == 1){
        printf("%s %s\n%s\n%s\n%s\n%s\n%s\n", nome,sobrenome,data,email,cpf,tel,contatip);
            printf("\nGostaria de voltar ao menu? S/N ");
                scanf("%s",esc3);}
                    if(strcmp(esc3,"s")==0){
                        main();}
                            else if(strcmp(esc3, "S")==0){
                                 main();}

        else if(u == 0)
            printf("\nVoce nao possui uma conta, gostaria de criar uma? S/N\n\n");
                scanf("%s",&esc3);

            if(strcmp(esc3, "s")==0)
                criar();
               else if(strcmp(esc3, "S")==0)
                    criar();
}

int mudar()
{
    if(u==1){
    printf("\nAtualize o seu nome e sobrenome: ");
        scanf("%s%s",nome,sobrenome);
    printf("\nAtualize sua data de nascimento: ");
        scanf("%s",&data);
    printf("\nAtualize seu email: ");
        scanf("%s",&email);
    printf("\nAtualize seu CPF: ");
        scanf("%s",&cpf);
    printf("\nAtualize seu numero de telefone: ");
        scanf("%s",&tel);

   printf("\n1.Corrente\n\n2.Poupanca\n\n");
        scanf("%s",&contatip);
        if(strcmp(contatip , "1")==0)
            strcpy(contatip, "Corrente");
        else if (strcmp(contatip,"2")==0);
                    strcpy(contatip, "Poupanca");

                printf("Pronto, suas mudancas foram salvas, gostaria de voltar ao menu? S/N \n");
                    scanf("%s",&esc4);
                if(strcmp(esc4,"s")==0)
                        main();}

    else if(u==0){
        printf("Voce nao possui uma conta em nosso banco, gostaria de criar uma agora? S/N\n");
            scanf("%s",esc4);
        if(strcmp(esc4,"s")==0)
            criar();}
        else if(strcmp(esc4,"S")==0)
                criar();}

int main()
{
    int esc;

    printf("   Bem vindo ao menu ! ! ! \n\n1.Criar uma nova conta\n2.Ver informacao da conta\n3.Atualizar informacao da conta\n4.Excluir conta\n6.Sair\n\n");
        scanf("%i",&esc1);

    switch(esc1)
    {
        case 1: criar();
        break;

        case 2: ver();
        break;

        case 3: mudar();
        break;
    }
}

Answer: Isso é só um warning de um compilador mais cuidadoso do que o que estava usando. Antes seria bom dar uma lida em O que é linguagem de programação, IDE e compilador?. Então funciona, mas não é adequado, em qualquer compilador, só que alguns nem te avisam disso, outros avisam. Warnings não impedem a compilação mas são erros.
Já adianto que o código é confuso e usa várias outras coisas que não são boas em programação, portanto eu escolheria outro método ou fontes melhores para seu estudo. Algumas delas sequer funcionam em certos compiladores (algumas silenciosamente).
O problema aí é que chama uma função que será declarada só depois, então o compilador nem tem certeza se a chamada está correta.
Mas não é dito aí sobre o problema mais grave. Ele nem deve causar problemas em exercício, o que é pior porque você acredita que o código está certo. O que todo iniciante (alguns que já trabalham há vários anos na área) erra na programação é acreditar que se o código funcionar ele está certo. E isso está longe de ser verdade, se a pessoa não domina o que está fazendo e acha que está aprendendo porque o código funciona ela está fadada ao fracasso. E esse código funciona, mas está errado, porque não funcionará em todas situações.
Você está criando um laço involuntário, está chamando uma função que chama a função anterior. Isso chama-se recursão e se executava várias vezes provocará o que chama-se stack overflow. Então não pode chamar main() ali, precisar retornar normalmente e controlar a repetição na própria main() através de um laço. O mesmo vale para outras chamadas de funções que vai criando um caminho maluco. As chamadas devem ser feitas de forma estruturadas, não pode chamar qualquer cosia em qualquer lugar, porque vai funcionar em exemplo simples, quando for fazer algo mais complexo fará igual porque foi o que aprendeu e terá problemas sérios.
Nem entrei no mérito de ter usado várias globais por não sabe usar funções, então não a use até aprender. Treinar o erro fará você fazer errado a vida inteira.
Se isso está confuso é porque pulou etapas e ainda não aprendeu sobre essas coisa, seria interessante voltar um pouco atrás, aprender esses conceitos todos antes de fazer algo mais complexo. Procure um material que ensina programação de forma estruturada. Especialmente em C não dá para aprender na base do "bumba meu boi", ou você aprende como as coisas funcionam ou aprenderá tudo errado.
Não adianta muito consertar o erro que o VS mostra, o resto continuará errado, e se for para ficar errado então é só ignorar o warning.


How do I optimise c++ legacy boiler plate code?

Question: I am a Java user trying my hand at c++.
In the below legacy code, I have multiple derived classes.
The contents of the map in each derived class are similar differing by just a few.
The function pr() is repetitive.
I would like to optimize such piece of code.
Do let me know ideas/suggestions?
Thanks
#include <iostream>
#include <map>
#include <string>
#include <functional>
using namespace std;
#include <memory>

class X {
public:
    virtual void pr ()=0;

};

class Y: public X {
        std::map<string,int> fm{ {"mem1", 33},
                                 {"mem2", 44},
                                 {"YYY", 999}};

public:
    virtual void pr () {
        for(auto const &[k,v] : fm)
        {
             std::cout<<k <<"  :  "<<v <<std::endl;
        }
    }
};

class Z: public X {
    sstd::map<string,int> fm{ {"mem1", 33},
                              {"mem2", 44},
                              {"ZZZ", 777}};

public:
    virtual void pr () {
        for(auto const &[k,v] : fm)
        {
            std::cout<<k <<"  :  "<<v <<std::endl;
        }
    }
};

void fn(std::unique_ptr<X> x)
{
    x->pr();
}

int main()
{
   fn(std::make_unique<Y>());
}

Comment: TBH, the one solution that strikes would be the same as in Java: Make `X::pr` non-abstract, move the definition  from derived classes to `X`, move `fm` to X as well and either initialize it with default value and modify in derived classes constructor or create `X` constructor that receives ready-made map.
Comment: "optimize" is extremely vague. I suppose you want to reduce repetition of similar code, is that right?
Answer: I would drop the derived classes, you only have a difference in construction.
#include <map>
#include <string>
#include <utility>

class X {
    std::map<string,int> fm;
public:
    X(std::map<string,int> fm): fm(std::move(fm)) {}
    void pr () {
        for(auto const &[k,v] : fm)
        {
             std::cout<<k <<"  :  "<<v <<std::endl;
        }
    }
};

X Y(){ return X({ {"mem1", 33}, {"mem2", 44}, {"YYY", 999}}); }
X Z(){ return X({ {"mem1", 33}, {"mem2", 44}, {"ZZZ", 777}}); }

int main()
{
    Y().pr();
}

Answer: This is not called optimization. This is called refactoring code to make use of inheritance. Apparently, in your code, repetition is in data member fm and pr() function definition.
If your both classes have them in common, you can just move pr function definition and data member fm to base class so that you do not have to rewrite. Then you can initialize value of fm, which is only difference between two classes.  =0 makes a virtual function pure, which should be overriden by all inheriting classes. In this case, they do not override, instead they reuse pr function, so pure function is not needed.
#include <iostream>
#include <map>
#include <string>
#include <functional>
#include <memory>
using namespace std;

class X {
public:
    virtual void pr (){
         for(const auto item : fm)
        {
             std::cout<<item.first <<"  :  "<<item.second <<std::endl;
        }
    };
    protected:
    std::map<string,int> fm;
};

class Y: public X
{
    public:
    Y(){
      fm =   { {"mem1", 33},
             {"mem2", 44},
             {"YYY", 999}};
    }
};

class Z: public X
{
    public:
    Z(){
      fm =   { {"mem1", 33},
                              {"mem2", 44},
                              {"ZZZ", 777}};
    }
};

void fn(std::unique_ptr<X> x)
{
    x->pr();
}

int main()
{
   fn(std::make_unique<Y>());
      fn(std::make_unique<Z>());

 return 0;
}

Comment: what did you change and why did you change it?
Comment: you should initialize the map in the constructors member initializer list


Meaning of "Stochastic Data Models"

Question: I was reading the famous "Statistical Modelling: The Two Cultures" paper by Leo Breiman (researcher who invented the Random Forest algorithm) - and he presents the following argument:

My Question: Does anyone know what is meant by "stochastic data models"? What is an example of a "stochastic data model"?
If I were to make general comments, I would have guessed that "stochastic data models" are predictive models that contain a "stochastic component". I have seen the term "stochastic" often used to describe the "Markov Property", e.g. the n + 1 th value depends on some function of only the n th value - as well as "stochastic" being used to describe something "completely random" (e.g. using the R programming language, the output of the command rnorm(100,100,100) ). There are many such examples within the domain of time series (e.g. ARMA/ARIMA, GARCH, Brownian Motion). Some can even argue that standard linear regression models also contain a "stochastic component", seeing as the "error term" within regression models is considered to be "random realizations" from a probability distribution function (e.g. normal distribution).
However, my guess is that Breiman is not exactly referring to what I have described above. I think he might be referring to fitting entire probability distributions to the data and calculating the conditional probability of observing a certain series of realizations from this probability distribution (provided the probability distribution fits the data well)?
Can someone please comment on this? What is meant here by "stochastic data models"?
Thanks!
Reference: https://projecteuclid.org/journals/statistical-science/volume-16/issue-3/Statistical-Modeling--The-Two-Cultures-with-comments-and-a/10.1214/ss/1009213726.full
Comment: In the first paragraph of section 5, Breimann writes: "This enterprise has at its heart the belief that a statistician, by imagination and by looking at the data, can invent a reasonably good parametric class of models for a complex mechanism devised by nature." It seems to me that the key word is *parametric*.
Answer: I think that what Breiman refers to as "algorithmic models" would roughly correspond to what statisticians would recognise as non-parametric methods --- i.e., methods that do not assume an underlying parametric model for the data.  Likewise, what he refers to as a "stochastic data model" would roughly correspond to what statisticians would recognise as parametric-models --- i.e., models that assume an underlying probability distribution within a restricted class parameterised by a relatively small number of parameters.  The examples given on the first page of the paper (linear regression, logistic regresion, Cox model) are of this type.
Brieman's argument is essentially that statisticians rely on parametric models that often do not conform to the underlying processes generating the data.  He discusses this in Section 5 of the paper, where he notes that "If the model is a poor emulation of nature, the conclusions maybe wrong."  One might argue that this criticism is overbroad, since statisticians using parametric models can use diagnostic testing to check if their model assumptions are contradicted by the observed data (and then form a different model or use non-parametric methods if the present model is no good).  On this point, Brieman is of the view that this is not done with sufficient regularity.  He states that "A few decades ago, the commitment to data models was such that even simple precautions such as residual analysis or
goodness-of-fit tests were not used.  The belief in the infallibility of data models was almost religious." (p. 202)
If I may offer an analysis of Brieman's views here, I think it is certainly fair to point out that analysts using parametric models do not always do their due diligence by looking at diagnostic plots and tests.  I think it is also fair to say that analysts sometimes make inferences from models that are heavily affected by untested model assumptions, and which are not robust to changes in assumptions (e.g., making inferences about tail probabilities in parametric regression models).  I don't think it is statisticians who are primarily making these errors, but evidently Brieman does.  If you do proper diagnostic testing of a parametric model, and are careful with the kind of inferences you make, this significantly blunts the critique made by Brieman, since there is then an empirical test of the model assumptions affecting the inferences.
Many "machine learning" models like the random forest model can be regarded as non-parametric statistical methods.  Guys like Breiman have done a great service in developing these models.  I'm not convinced that this is a separate field to what statisticians have always considered as the broad class of non-parametric methods.

Meaning of "Stochastic Data Models"


How do I show this inequality

Question: The original question is to show the $f_n(x) = nx \exp(-nx^2)$ converges pointwise and determine the limit function.
I was given the solution, if $x\ne 0$, then
$|f_n(x)| = \frac{n|x|}{\exp(nx^2)} \le \frac{2n|x|}{(nx^2)^2} = \frac{2}{n|x|^3} \rightarrow 0$
if $x = 0$ then $f_n(0) = 0$ for all $n \in \mathbb{N}$
Hence $f_n \rightarrow 0$ pointwise
I don't understand why $\frac{n|x|}{\exp(nx^2)} \le \frac{2n|x|}{(nx^2)^2} $
Can someone give me a proof of this?
Answer: Hint: Use the Taylor series
$$\exp(nx^2) = \sum_{k=0}^\infty \frac{(nx^2)^k}{k!} > \frac{(nx^2)^2}{2}$$
Comment: The principle here is the exponential function with positive argument grows faster than any polynomial.

How do I show this inequality


Q-Test of Heterogeneity for only two effect sizes?

Question: I am using the Q-Test of Heterogeneity to investigate if several effect sizes derived from two different studies are significantly different from each other.
More precisely, I have, for every effect of interest, a Cohen's d from one study, and one from the other, and their respective variances. I calculate the Q-value (using the formula from Cochran 1954), and if it is higher than the critical value of the chi-squared-distribution with 1 df (3,84), I assume the two effect sizes to be significantly different.
Now my question is: are there any statistical or theoretical objections to this method?
I understand that the Q-Test is normally used in Meta-analyses to make sure that effect sizes are homogenous, not heterogenous. But can it also be "abused" in the way I am proposing?
Also, I read in several sources that the Q-test is lacking in power when applied on small sample sizes. However, I used it with the smallest possible sample size (2 studies) and found a number of highly significant and theoretically interesting differences. Is there any statistical problem with my approach that I am missing?
As I would like to imply this procedure in my master thesis, I would also be incredibly thankful if somebody could give me a reference on this topic, for example a paper with a critical discussion of this procedure, or a study where it was successfully applied. (Unfortunately, the statistical training at my university hasn't even scratched the surface of the wide field of meta-analysis...)
Thank you a lot in advance!
Answer: First of all, some terminology. In my opinion, it is arbitrary whether we call it the "Q-test of homogeneity" or the "Q-test for heterogeneity". Under the null hypothesis, we assume homogeneity, so calling it the Q-test of homogeneity would emphasize that we are testing this assumption. But the alternative hypothesis states that the true effects/outcomes are heterogeneous, so we could also say that we using it to test for (whether) heterogeneity (is present). Some may disagree -- but in the end, there is just the Q-test, whatever we call it.
As for using the Q-test when there are only two studies: That is equivalent to testing the null hypothesis that the true effect for the first study is the same as the true effect for the second study. That should be clear if we write down the null hypothesis for the Q-test, namely $$H_0: \theta_i = \theta \mbox{  for all  } i = 1, \ldots, k,$$ which for $k = 2$ is identical to $$H_0: \theta_1 = \theta_2,$$ where $\theta_i$ denotes the true effect/outcome for the $i$th study.
We can also demonstrate this with an example. I'll use R with the metafor package for this.
library(metafor)

yi <- c(.14, .75)   # observed effect size estimates
vi <- c(.083, .042) # corresponding sampling variances
di <- c(0, 1)       # dummy variables to distinguish the two studies

### fixed-effects model
rma(yi, vi, method="FE")

The results are:
Fixed-Effects Model (k = 2)

Test for Heterogeneity:
Q(df = 1) = 2.9768, p-val = 0.0845

Model Results:

estimate       se     zval     pval    ci.lb    ci.ub
  0.5450   0.1670   3.2638   0.0011   0.2177   0.8723       **

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So, we find $Q(1) = 2.9768$ with $p = 0.0845$. Now let's fit a (fixed-effects) meta-regression to these data, adding the dummy variable to the model that distinguishes the first from the second study:
### meta-regression model
rma(yi, vi, mods = ~ di, method="FE")

This yields:
Fixed-Effects with Moderators Model (k = 2)

Test for Residual Heterogeneity:
QE(df = 0) = 0.0000, p-val = 1.0000

Test of Moderators (coefficient(s) 2):
QM(df = 1) = 2.9768, p-val = 0.0845

Model Results:

         estimate      se    zval    pval    ci.lb   ci.ub
intrcpt    0.1400  0.2881  0.4859  0.6270  -0.4247  0.7047
di         0.6100  0.3536  1.7253  0.0845  -0.0830  1.3030  .

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Note that the p-value of the dummy variable is exactly the same as that of the Q-test. If we square the z-value, we in fact get the chi-square value of the Q-test. That is actually the value of the $Q_M$ test, which is the omnibus test of all coefficients (except for the intercept), but since there is only one coefficient in the model (the one for the dummy variable), that is identical to just testing whether the coefficient for the dummy variable is significantly different from zero.
So, "mechanically speaking", that all works out as expected. Is this a valid procedure? I don't see anything wrong with this -- you are just testing whether the effects of study 1 and study 2 are significantly different from each other or not.
Power is of course always an issue we have to keep in mind. And yes, power may be low. So, quite importantly, if you do not find a significant difference, you should be very cautious how you interpret that. In particular, it simply means that you do not have sufficient evidence to reject the null hypothesis, but the true effects could very well still differ from each other.
On the other hand, if you use this approach to carry out lots of tests, it is in fact likely that some significant findings are just Type I errors. So, you also need to be cautious in interpreting any significant findings, especially if you do not correct for multiple testing.
Comment: Wow! Thank you for this very detailed and extremely useful answer! Especially the equivalence (in this special case) of the Q-Test and the meta-regression model is solid gold for me!


Statistical analysis for nominal data-advice

Question: Please, can someone advise me on how I can approach my nominal data and test its significance.
I measured jerking movement as a behavioural effect in a fish exposed to each of Chemical A and Chemical B at different concentrations (or treatments) based on below metrics:
No effect = 1
Low effect = 2
Moderate effect = 3
High effect = 4
I want to now evaluate if there is a significant difference between effect of Chemical A from B. This is how the data look:
Answer: You could do a chi-square analysis, but you probably have too few participants - you could try a Fisher's Exact Test, but again statistical tests work best with lots of respondents so you may have to rely on descriptives (crosstabulations) and graphs.
Answer: This is not a nominal but ordinal data, hence I think kuskal wallis followed by man whitney will be more appropriate


Setting Up A Windows 2008 NPS Server As A Radius Server For A Cisco AP541N Cluster

Question: I have a cluster of Cisco AP541N access points.  I am trying to use the Radius authentication for WPA-Enterprise authentication, but I cannot get the APs to query the server properly.
Does anyone know of a cookbook or recipe for setting up the NPS server to provide authorization?
My current configuration is as follows.
The APs are simple, they just have a Radius Server IP field and a Radius Secret field.  The SSID has all the options set: WPA, WPA2, Enable pre-authentication, TKIP, CCMP(AES) and Use Global Radius Server Settings.
On the server, each AP is defined as a client, each with a unique friendly name (cap-1 through cap-3).  The secret is the same as on the AP cluster.  Each AP is defined as a Cisco, and has the Access-Request Messages must have the Message-Authenticator Set box checked.
There is a single Network Policy, set as:

policy enabled
grant access
unspecified network access server

Conditions:

Windows Group Membership (a user group)

Constraints:

Auth methods: EAP PEAP and EAP-MSCHAPv2; MS-CHAP-v2; MS-CHAP; CHAP; PAP/SPAP

Settings:

all Standard Attributes have been removed (the PPP framing type etc).

When I try to connect to the AP, the AP logs:
<code> cap-4th-2 hostapd: wlan0vap2: RADIUS Possible issue with RADIUS server connection - no reply received for first three attempts
</code>
Around the same time, the Windows server logs:
<code>NPS: 18: An Access-Request message was received from RADIUS client 10.17.15.247 with a Message-Authenticator attribute that is not valid.
</code>
Answer: This worked for me.
On the AP541N:
Set the Global Radius settings:

Radius server IP
Radius secret

Set the SSID to connect to by selecting all:

WPA
WPA2
Enable pre-authentication
TKIP
CCMP (AES)
Use global RADIUS server settings

NPS Pre-configuration:
The role to install is Network Policy and Access Services, the service is Network Policy Server.
Once it is installed, right-click on NPS (local) and select Register Server In Active Directory.
(Also note that I usually have to stop and then start the NPS Service after running through the below configuration the first time; future changes seem to take effect right away.)
Define the RADIUS clients: Server Manager -> Roles -> Network Policy and Access -> NPS (Local) -> Radius Clients -> Radius Clients
Create a new client:

Make sure it is enabled
Short, friendly name
IP address or DNS name
Manual shared secret
Repeat this set up for each AP in the cluster.

Define the Connection Request Policy:
Under Connection Request Policy, create a new policy. On the overview tab:

make sure it is enabled
the type of network access server is Unspecified

On the Conditions tab:

Client Friendly Name, set to soemthing which matches the Client Friendly Names you set above; for example, I have cap-1, cap-2, and cap-3, so my Client Friendly Name in the connection policy is cap-*

On the Settings tab, Authentication methods:

select Override network policy authentication settings
Add EAP Types EAP-MSCHAP-v2 and PEAP
select MS-CHAP-v2
select MS-CHAP
leave all the other boxes unselected

You shouldn't need any other values.
Define the Network Policy:
On the Overview tab:

make sure it is enabled
Grant access
clear Ignore user account dial-in properties
Type of network access server is Unspecified

On the Conditions tab:

Windows Groups: set to the windows user group that will grant access
Client Friendly Name: same as the connection policy above

On the Constraints tab:

leave everything as default; but ideally it should look the same as the connection policy above

On the settings tab:

remove the Standard Radius Attributes (PPP Framing type etc) because you don't need them

Configure Domain Clients:
Wireless Properties:

Connect automatically

Security tab:

WPA2-Enterprise
AES
PEAP
Remember my credentials

PEAP Settings:

clear Validate Server Certificate
Select Authentication Method: EAP-MSCHAP-v2
Enable Fast Reconnect

Security tab, Advanced Settings:

Specify authentication mode: user authentication

Configure Non-Domain Windows Clients:
As above, except:
EAP-MSCHAP-v2 Configure:

clear Automatically Use my Windows logon name and password (and domain if any)

Further Refinements
I added a second Network Access policy that permits access to computers that are members of a particular group.
I then changed the Security Tab -> Advanced Settings -> Specifiy Authentication Mode to Computer authentication.
Finally a co-worker created a GPO that pushes out a pre-defined SSID network definition with the settings above to all domain member computers.
Now all domain laptops automatically connect to the wireless.
Non-domain member computers can still join as long as the Specify Authentication Mode is set to User authentication.
Configuring tablets, phones, and non-Windows computers is left as an exercise for the reader.
(Further updates to this will appear on my wiki page at http://wiki.xdroop.com/space/Windows/Server/2008/Radius+Server+for+Cisco+AP541N )
Comment: Alternatively, set the WiFi network as a GPO.  This eliminates local configuration errors, which is the biggest problem to this solution.


Can you help me solve this space optimization problem?

Question: I am a high school student doing a mathematics research project and I am in dire need of help! My math project is "determining the crystals needed to bedazzle a top" and the topic might seem extremely silly to most, but when choosing what to write about, I simply could not think of anything else.
So far, I have calculated the total area of the pattern piece, which is about 1144,758 cm^2 and I divided this result by the area of a single crystal with a diameter of 8.4 mm, which gave me the absolute maximum amount of the crystals needed, which is about 2067 pieces.
Afterwards, I divided the total area of the pattern piece by the square in which the crystal fits, which is 0.7056 cm^2, which gave me 1623 pieces which is the minimal amount of the crystals needed. This all due to the fact that I will be placing the crystals in the way that minimizes the space unused as seen in the second picture that I attached.
As you can see, the produced interval is quite huge and I would like to make it more precise. I have been trying to read many articles and solutions to problems like these and I know that @RobPratt specializes in space optimization, however, I am a high school student and these scientific papers are quite...well...scientific..., which I find a bit confusing.
I attached the photo of the pattern pieces and its measurements are 43.2 X 42.0 cm. I will be extremely helpful for any help:)
pattern piece
the placement of the crystals
Comment: @JeanMarie Search Google for 'bedazzled top' images.
Comment: @Daniel Mathias Thanks ! I wasn't one the right track at all !
Answer: You must find an appropriate polygon for the circle and (perhaps) the container. True, "circles" (for simplicty) behave like a squares but a hexagon is a better approximation for a circle than a square and I can see one in the center of your diagram. It's very much like how Archimedes caclulate $\pi$ using polygons. Better your approximation, the more efficient the utilization of space. It's also a tiling problem from the looks of it.
Both size and shape matter as far as I can tell.
Comment: *packing problem* may be more accurate.
Comment: Précisément! On target!


Can dual numbers be extended to a non-power of 2 dimension?

Question: The complex numbers are built the real numbers but add an unknown unit which squares to $-1$ (as no number in the reals squares to $-1$) called $i$ for "imaginary",  because such numbers were considered a hack at the time of their discovery by mathmetician Bombeli. The sum of a real number and the product of $i$ and a real number is called a complex number, represented in the form $a+bi$. These numbers have found many applications due to the connection between polar complex multiplication and rotation on the 2D plane, as $(r,\theta)*(s,\iota)$ = $(rs,\theta+\iota)$.
Soon after the discovery or invention of the complex numbers, people tried to see if the previously mentioned rotational behavior of complex multiplication could be extended to 3 dimensions. William Hamilton, the person known for creating quaternions, proposed that a tricomplex number represented as $a+bi+cj$ where $i^2=j^2=ij$ would do the trick, but soon he realized he needs a four dimensional system, with 3 dimensions for the rotation, and one for other measures. This system did work, and became known as the quaternions from the Latin prefix quatern- meaning 4.
But the next real-based algebra to find a use after quaternions were octonions, which has 8 dimensions. The next one after that is called the sedenions, and has 16 dimensions, and the next one after that has 32, and so on, with every dimension being a power of 2.A theorem known as the Frobenius theorem proves that these power-of-2 algebras are the only complex-based division algebras, so it is impossible to have a 3-ion or 5-ion number without giving up closure under division.
However another real-based algebra known as the dual numbers might be able to combat this, mainly because they aren't a field/divison algebra to start  with. Dual numbers are numbers of the form $a+b\epsilon$, where $\epsilon^{2} = 0 $ and $\epsilon \ne 0$, and have a few applications like automatic differntiation. They aren't a field because $a/b\epsilon$ is undefined, as this would be the equivalent of saying $\sqrt{a/0}$, which explodes to infinity, but they are a ring. Because they aren't a field due to that no-real component case, it is it possible to extend dual numbers to any dimension, and keep them a ring, without violating the Frobenius theorem, as they aren't a field in a niche case where the real components are 0? (For instance a trial or 3-dual number would be $a+b\epsilon+c\zeta$ where $\epsilon^2 = \zeta^2 = \epsilon\zeta = 0$ and $\epsilon \ne \zeta \ne 0$)
Comment: Well, in every step after the complex numbers, we are losing a property. Quaternions are not commutative, Octonions are neither associative, so actually not all $2$-powers give reasonable division algebra. The dual numbers, however, do generalize to arbitrary dimensions..
Answer: First, note that the usual dual numbers (over a field $k$) can be realized as the quotient ring $k[\varepsilon]/(\varepsilon^2)$. More generally, if $m:=(\varepsilon_1,\dots,\varepsilon_n)\subseteq R:=k[\varepsilon_1,\dots,\varepsilon_n],$ so that $m^2=(\{\varepsilon_i\varepsilon_j\}_{1\leq i\leq n, \\ 1\leq j\leq n}), $ elements in the quotient ring $R/m^2$  are of the form $a_0+a_1\varepsilon_1+\dots+a_n\varepsilon_n$, and $\varepsilon_i\varepsilon_j=0$ for all $i, j$.


Uses and estimation of Student-t distribution

Question: My question relates to a confusion between how the Student-t distribution is often documented versus how it is used.
In the documentation the Student-t is used (from Wikipedia):

when estimating the mean of a normally distributed population in
  situations where the sample size is small and population standard
  deviation is unknown

As per this definition, the degrees of freedom parameters is equal to n-1 where n = number of observations.
My confusion comes from the fact that the Student-t is often used to model not the difference between the true mean of a population and the sample mean, but to estimate the distribution of the population itself. As such, is this a misuse of the Student-t distribution? If not:

The degrees of freedom cannot be defined as n-1 as there is no notion that as the sample size increases the sample mean converges to the population mean. Rather, it is posited that the population is distributed as a t(v) no matter what the sample size, i.e. as n increases it doesn't converge to a normal. Hence, how is the degrees of freedom chosen/estimated in this case? The only answer is I can come up with is iteratively trying different values and selecting the value with the best model fit.
Similarly, when standardising and un-standardising the practice of multiplying by the square root of n shouldn't be necessary as the underlying assumption of that is that as n increases the difference in mean will go to zero. However, if you are using the Student-t to estimate the population distribution that is not the purpose. As such, I would assume you would standardise and un-standardise without the square root of n part. Is that correct?

E.g. the below is how the t-stat is estimated, however this method isn't valid if one is not estimating the t-stat, i.e. testing if the difference is zero
$$\frac{X  −μ}{(σ/√n)} \thicksim t(v)$$
Similarly, I have seen other people use the following to un-standardise:
$$t*\frac{\sigma}{√(v/(v-2))} + \mu$$
Where v is the degrees of freedom here
Apologies if this is a silly question, the answer me be very obvious. I ask this as I often see the degrees of freedom for Student-t distributions being chosen just as if out of a hat and different ways of un-standardising samples from the Student-t, which don't seem to make sense given the purpose/context.
Answer:
when estimating the mean of a normally distributed population in situations where the sample size is small and population standard deviation is unknown

This is simply one application of the t-distribution.
The t-distribution can be defined in terms of its density or its distribution function, (or in other ways - say in terms of its characteristic function); in any case, however defined it has a particular functional form that includes a parameter that defines its shape, which we call the degrees of freedom parameter. In the general case there will also be location and scale parameters.
The t-distribution can - like any other distribution - be used for any situation for which it is deemed a suitable model.

As per this definition, the degrees of freedom parameters is equal to n-1 where n = number of observations.

I would not call that a definition of the t-distribution. It describes a circumstance that results in a t-distribution for a particular statistic (which is why it's an application of the t).

My confusion comes from the fact that the Student-t is often used to model not the difference between the true mean of a population and the sample mean, but to estimate the distribution of the population itself. As such, is this a misuse of the Student-t distribution?

Your confusion stems from conflating an application with a definition of a distribution. If I buy a box of crayons that has a drawing of a cat on the front of the box, that doesn't mean the crayons must be used for drawing cats -- I'm still allowed to draw trees with it!

Hence, how is the degrees of freedom chosen/estimated in this case?

The same ways that parameters are estimated, or even chosen more generally.
So you might choose to optimize some criterion for example (e.g. maximum likelihood), or you might match moments, or any number of other ways in which parameters are arrived at.

The only answer is I can come up with is iteratively trying different values and selecting the value with the best model fit.

Well once you have a criterion (you need something that defines what 'better' is in order to select 'best'), that could work but it would be slow. You're unfamiliar with optimization methods?

Similarly, when standardising and un-standardising the practice of multiplying by the square root of n shouldn't be necessary as the underlying assumption of that is that as n increases the difference in mean will go to zero. However, if you are using the Student-t to estimate the population distribution that is not the purpose. As such, I would assume you would standardise and un-standardise with the square root of n part. Is that correct?

Again, you're conflating the application with the tool.
Comment: Thank you @Glen_b, I have been using the model for years but I was thrown off by the Wikipedia description and also how a colleague was using the distribution, which made me question my understanding. I am familiar with optimisation methods, I asked about estimating the DoF as the MASS package in R doesn't seem to have a function that will estimate DoF - I'll just write one myself.
Comment: The MASS package *does* have a function that will estimate degrees of freedom: `fitdistr`. If even gives an example of doing it right there in the help --- it just explicitly warns against doing it (not without reason - the likelihood function needn't have a global maximum, let alone a unique mode).
Comment: @Celeste Alternatively, there's some functions in the package [VGAM](http://www.inside-r.org/packages/cran/vgam/docs/studentt), and you might like to investigate the various options for parameter estimation in the `fitdist` function in the package `fitdistrplus` (including method of moments, quantile matching and maximum goodness of fit estimation).
Answer: The block quote is incorrect. the t-distribution is used to make inference (pvalues, CIs) about the mean of a normal population, not estimate the mean directly. the point estimate of the mean is the sample mean.
to answer your questions, the t-distribution is a probability distribution indexed by the parameter called the degrees of freedom and the t-distribution can be used for other things, not just the one sample t-test where the degrees of freedom equals n-1. Have a look at the wikipedia page about the t-distribution.
Comment: The block quote is directly from Wikipedia and I have read the Wikipedia page, which I don't think answers my two questions: (1) how to estimate the DoF and (2) whether it is still required to divide the sample SD by the square root of n when standardising if one is not modelling the sample mean from a normal population
Comment: actually, the block quote starts mid-sentence after you began with "it is used"... that's not what the wikipedia page says... it says that the t-distribution "arises when estimating...", which i don't disagree with. moving on... if you have data from a t-distribution you can estimate the degrees of freedom by maximum likelihood, or you could notice from the wikipedia page that the variance is v=df/(df-2), which suggests estimating df as 2v/(v-1). your second question only seems to make sense in the context of the t-test and seems to have nothing to do with analyzing data that is t distributed.
Comment: Okay, to me then the Wikipedia page is misleading in that it doesn't sufficiently explain the more general use. In terms of the dof, that was obvious I missed that. I asked second question as I have notice some people standardising and un-standardising in a context that only makes sense in a t-test as you say, but I don't think is correct
Comment: i suggest you give an example of this standardization you've seen other people do outside the context of calculating a t statistic. standardization can have uses other situations which i'm sure you can learn about by searching the internet or even this site, but i'm not aware of any that are specific to the situation where the population is t distributed.


Jensen's inequality over definite positive matrices.

Question: From the fact  that inversion operator   $A  \to A^{-1}$ is convex over the set of  positive definite matrices. I would like to know if it is correct to use  Jensen's inequality with the standard Lowner order. I.e
$$ (E(X))^{-1} \leq E(X^{-1}) $$
Does the following equation also hold?
$$\lambda_{max}(E(X)) \leq E(\lambda_{max}(X))$$
where $\lambda_{max}$ stands for the maximum eigenvalue of a matrix.
Answer: ***Question 1
Here is a positive answer to the first question. Let $\mathcal{P}_n$ be the set of all symmetric and positive definite $n \times n$ matrices. Note that if $A \in \mathcal{P}_n$ then $A^{-1}$ exists and $A^{-1} \in \mathcal{P}_n$.  For $A$ and $B$ in $\mathcal{P}_n$ we write $A\leq B$ if and only if $B-A$ is symmetric and positive semi-definite.
Claim:
If $X \in \mathcal{P}_n$ and if $E[X]$ and $E[X^{-1}]$ are finite then $E[X]^{-1}$ exists and
$$  E[X^{-1}] \geq E[X]^{-1}$$
Proof:
Let's use the following facts:
Fact 1: If $A$ and $B$ are in $\mathcal{P}_n$ then for all $\theta \in [0,1]$ we have $\theta A + (1-\theta) B \in \mathcal{P}_n$ and
$$ (\theta A + (1-\theta) B)^{-1} \leq \theta A^{-1} + (1-\theta)B^{-1}$$
Fact 2: Fix $m$ as a positive integer. If $\mathcal{Y} \subseteq \mathbb{R}^m$ and $Y$ is a random vector that takes values in $\mathcal{Y}$ has finite expectation $E[Y]$, then $E[Y] \in Conv(\mathcal{Y})$ (denoting the convex hull of $\mathcal{Y}$).
Now define the set $\mathcal{Y}$ as the set of all pairs of $n\times n$ matrices $(R, S)$ such that $R \in \mathcal{P}_n$, $S \in \mathcal{P}_n$, and  $S \geq R^{-1}$.   From Fact 1 it is easy to show that the set $\mathcal{Y}$ is a convex set. [Indeed if $(R, S)$ and $(A, B)$ are two elements in $\mathcal{Y}$ then for any $\theta \in [0,1]$ we have
$\theta R + (1-\theta)A \in \mathcal{P}_n$ and since $S \geq R^{-1}$ and $B \geq A^{-1}$ we get
$$ (\theta S + (1-\theta)B) \geq (\theta R^{-1} + (1-\theta)A^{-1}) \geq (\theta R + (1-\theta)A)^{-1} $$
where the inequality holds by Fact 1.]
The set $\mathcal{Y}$ can viewed as a convex subset of $\mathbb{R}^{2n^2}$.  Now notice that if $X$ is a random matrix  in $\mathcal{P}_n$ then $(X, X^{-1}) \in \mathcal{Y}$ and so, assuming the expectations $E[X]$ and $E[X^{-1}]$ are finite, we get by Fact 2:
$$ E[(X, X^{-1})] \in Conv(\mathcal{Y}) = \mathcal{Y}$$
where equality holds because $\mathcal{Y}$ is a convex set.
That is
$$ (E[X], E[X^{-1}]) \in \mathcal{Y}$$
and by definition of $\mathcal{Y}$ this means that $E[X] \in \mathcal{P}_n$ and $E[X^{-1}] \geq E[X]^{-1}$. $\Box$.
**Question 2
Let $||y||=\sqrt{y_1^2 + ... + y_n^2}$. For any random square matrix $A$ we have by convexity of $\sup$ and of $||\cdot||$:
\begin{align}
E\left[ \sup_{||x||\leq 1} || Ax|| \right] &\geq \sup_{||x||\leq 1} E[||Ax||] \\
&\geq \sup_{||x||\leq 1} ||E[A]x||
\end{align}
So the expected largest singular value of the random matrix $A$ is greater than or equal to the largest singular value of $E[A]$. If $A$ is a random symmetric positive semi-definite matrix then $E[A]$ is also, and the largest singular value corresponds to the largest eigenvalue.
Comment: This is truly a neat and elegant answer. Wish I could upvote again. Thanks!


How do I configure the route to the add form for a content type created as a bundle class?

Question: I've got a custom content entity type, created for me by drush generate and I'm extending that using bundle classes.  I've got a MyContentType class and a MyBundle class that extends it and provides some additional fields.  I'm able create MyBundle entities just fine with drush php or in a kernel test, so I know all that works.  Now I'm trying to create MyBundle entities in the UI.
The annotation for the MyContentType class provides the path to my form handler
"add" = "Drupal\my_content_type\Form\MyContentTypeForm"
and a link to the form to add a new entity
"add-form" = "/my_content_type/add/{my_content_type}".
But when I try going to /my_content_type/add/my_bundle, I get a Page not found.
Following what I see in node.routing.yml, I've got this in my_module.routing.yml
my_content_type.add:
  path: '/my_content_type/add/{my_content_type}'
  defaults:
    _title: 'Add some content'
    _form: 'Drupal\my_content_type\Form\MyContentTypeForm'
  requirements:
    _permission: 'administer site configuration'
  options:
    parameters:
      my_content_type
        type: entity:my_content_type

Once I've created and saved one of my entities using drush php, the edit page loads fine.  So, what's the silly little thing I'm missing here?
Comment: This is a bit confusing, the same name for entity type and bundle. And don't use the node entity as example, this was probably the first Drupal 8 entity. Newer entities don't use a routing file, they use a route provider class.
Comment: That's what I was hoping, too, but it's not doing the trick
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     }'''
Answer: I think you should be using _entity_form rather than _form. See: https://www.drupal.org/docs/drupal-apis/routing-system/structure-of-routes (search for _entity_form).
Comment: Drat, that looks like just the kind of silly thing I was wondering about, but changing `_form: 'Drupal\my_content_type\Form\MyContentTypeForm'` to `_entity_form: my_content_type.add` didn't do what I hoped it would.
Comment: Maybe it should be `_entity_form: my_content_type.add_form`
Comment: No luck yet.  Time to dig in with xdebug.


What should be the responsibility of a presenter here?

Question: I have a 3 layer design. (UI / BLL / DAL)
UI = ASP.NET MVC
In my view I have collection of products for a category.
Example: Product 1, Product 2 etc..
A user able to select or remove (by selecting check box) product's from the view, finally save as a collection when user submit these changes.
With this 3 layer design how this product collection will be saved? How the filtering of products (removal and addition) to the category object?
Here are my options.
(A)
It is the responsibility of the controller then the pseudo Code would be

Find products that the user selected or removed and compare with existing records.
Add or delete that collection to category object.
Call SaveCategory(category); // BLL CALL

Here the first 2 process steps occurs in the controller.
(B)
It is the responsibility of BLL then pseudo Code would be

Collect products what ever user selected
SaveCategory(category, products); // BLL CALL

Here it's up to the SaveCategory (BLL) to decide what products should be removed and added to the database.
Thanks
Answer: The logic should live in the business layer and not the controller.  Your controller should be as thin as possible and just orchestrate communication between the view and the other layers that deal with your models and business requirements.
Comment: So it means I need to use DTO to transfer user collection to BLL. Right? I am trying to avoid DTO and use the entity straight from the controller. Basically user can add or remove anything from presenter, but in BLL it will be validated.


Wildcard DNS like "*-test.example.com"

Question: Is it possible to set up a wildcard domain like "*-test.example.com"?
The main reason I'm asking is because I'm in the process of setting up Continuous Integration with Jenkins, and we'd like to automate the setting up of QA sites to test out specific branches of the codebase.
Say user A is working on a feature in a branch called 'awesome-feature-one', and user B is working on 'boring-code-cleanup'.
What I'd like to have is the DNS setup with something like '*-test.example.com' so that we have domains like 'awesome-feature-one-test.example.com' and 'boring-code-cleanup-test.example.com' without having to set up a DNS record for each and every one.
This way, we don't have to bug our network admin each time we start working on a new feature, it's already set up and we just have to make sure our web server is set up to point them to the proper place -- ie, 'awesome-feature-one-test.example.com' points to the folder /var/www/awesome-feature-one, etc, etc.
Lastly, part of the reason is that these sites use SSL, but our SSL cert is only set up to do wildcard for "*.example.com", so in order to set up wildcard for "*.test.example.com" we'd have to get another SSL cert ( which I may float as a solution if "*-test.example.com" won't work for DNS ).
So, is this possible, or am I looking at a pipe dream?
Comment: Depending on the client, your wildcard SSL may work for multi level subdomains (ie *.test.example.com). I do this with a wildcard for our highest domain (example.net) then use it for site-specific services (whatever.site.example.net) and have very little issue.
Answer: No. Wildcards in DNS entries are much more limited and only a wildcard like <code>*.example.com</code> would be possible. See RFC 1034 and RFC 4592.
Comment: Of course we are assuming a standard DNS server that doesn't do any magic.  You could probably do something like this if you were using PowerDNS with the [pipe backend](http://doc.powerdns.com/html/backends-detail.html#pipebackend) and developed your own tool to perform the wildcard functionality.

Wildcard DNS like "*-test.example.com"


Compensating for brass wound guitar strings when using a sound hole magnetic pickup in an acoustic guitar

Question: I use D'Addario 85-15 strings brass wound and steel unwound strings on a dreadnought Blue Ridge acoustic guitar.  I also use a Dean Markley Pro Mag in-hole magnetic pickup because I send an acoustic guitar signal when playing rhythm and an overdriven electric guitar signal when soloing.
One thing I've noticed is that the unwound strings send more signal through the magnetic pickup than the wound strings.  This results in a very bright unprocessed sound.
I've been thinking of just EQing the signal pre FX but one sound guy used an octaving effect to get a fuller tone.  Is one of these better than the other or should I use a different method to get a balanced frequency range that's closer to the acoustic guitar's acoustic sound?
Comment: Any way you can move the pup so that it's closer to the bottom/ further from the top strings?
Comment: @Tim no, sorry.
Answer: The problem (difficult to solve with EQ) with "Bronze/Brass" Wound Acoustic guitar strings with magnetic pickups is the windings are not magnetic and therefore the magnets in your sound hole magnetic pick up can only detect the steel core deep inside the winding.  Electric guitar strings are nickel wound and the nickel windings respond to the magnets in your pickup.
The larger diameter bass acoustic strings (E and A) will be less responsive than a wound D or G string because there is more material insulating the steel core from the magnets.  The plain steel strings on electric and acoustic sets are the same material and equally responsive to a magnetic pickup.
On the acoustic guitar I play that uses a magnetic soundhole pickup, the best solution I found was using nickel flat wound electric strings for my wound strings.   I found the flat wound strings sounded more like an acoustic guitar (mellower) which was the sound I was going for.
Another solution (besides using electric guitar strings) is Zebra Strings by DR DR Website.  The Zebra strings are alternately wound in both phosphor bronze and nickel (giving them a striped appearance) and therefore respond to magnetic pickups while retaining a brighter acoustic tone. They are marketed as a string that is both Acoustic AND Electric - because they will work for either type guitar.
They offer 7 different sets with various gauge combinations.  Pictured below is a box of what they call "Custom Light".

An alternative solution (if you don't want to solve the issue by string selection) is to add either an internal or external microphone based pickup, or a soundboard transducer pickup in addition to your magnetic soundhole pickup. These type pickups are not dependant on the magnetic properties of your strings.
Soundboard Transducer Pickups attach to the guitar top and sense the vibrations of the top.  They can be permanently mounted (check out the K & K Pure Mini K & K Webstite) or can be found in a removable external version.  The K & K Hotspot (pictured below) attaches with removable adhesive (I would attach the input to my strap) on the guitar soundboard.  You can get different tones by moving it to different areas on the guitar top.

Hotspot External Soundboard Transducer Pickup
If you add either a Guitar Mounted Mic Pickup or Soundboard Transducer, you could then use an A/B/Y footswitch to choose either your magnetic soundhole pickup, your alternate pickup or blend them together to get various sounds and tones to fit the musical situation.

Good luck!
Comment: Thanks for your detailed answer.  Changing strings at this point is not an option because since I play so much, I have a lot of string sets which I'm loathe to discard.  I also can't use a transducer or a mic because my lead guitar tone is overdriven which causes transducer squeal and microphone feedback.
Comment: You might try at least one set of Zebra's (whatever is closest to your current string gage) just to see how you like the results.  You can always use your stockpile on a different guitar without a magnetic pickup.  Or sell them on eBay.  If you love the way your guitar sounds with the Zebra strings, it might be worth the sacrifice.
Comment: As far as the mic squeal when using overdrive (valid point) that is the reason for the A/B/Y switch.  When using overdrive you would switch to the magnetic pickup only.
Answer: EQ-ing would be my recommendation. An octave effect will significantly change your sound, add latency and affect the dynamics of your tone.
That said, try both, and go with the one you like best. There really are no hard and fast rules in this :-)


How to select node in xpath?

Question: I have video html tag like that:
<video controls loop muted preload="metadata"></video>
How to select video by using attribute like: controls, muted in xpath?
Answer: you can achieve this with //video[@controls] or even //video[@controls,@muted]. I can only recommend you to use an online tester, it really makes work easy. Check this one out for example: http://xpather.com.

How to select node in xpath?


Using SQL to determine whether a user has previously seen a question

Question: I have a table which looks like the following:

I would like to add a new feature 'question_seen', which determines whether a user has previously seen the particular question. The table with the new feature will look like this:

How can I create this new feature using SQL commands?
Answer: Use a window function with conditional logic:
select t.*,
       (row_number() over (partition by user_id, question_id order by row_id) > 1) as question_seen
from t;

Note:  This returns a boolean rather than 0/1.  I prefer booleans for a flag, but it is easy to change to 0/1.
Answer: Consider below approach
select *,
  count(1) over user_question_history - 1 question_seen
from data
window user_question_history as (partition by user_id, question_id order by row_id)


POSIX FIFO freezes when opened in blocking mode

Question: By default a POSIX FIFO is opened in blocking mode.  My problem is that when I open it in blocking mode it just freezes (blocks) and nothing else happens.
Originally I opened both sides with the RDWR flag and I had no problems because RDWR makes it nonblocking because "Under Linux, opening a FIFO for read and write will succeed both in blocking and nonblocking mode" (https://linux.die.net/man/7/fifo).  But in nonblocking mode I sometimes get dropped records, so I need to open it in blocking mode.
Here's how I call mkfifo:
int64_t fifo_setup(char * fifo_name)
{
    if (mkfifo(fifo_name, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE); }

   return 0; }

My original call to open:
int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_RDWR);}
    if (read_write == 2) {
        c = open(fifo_name, O_RDWR);}

    perror("open");

    return (c);
}

Then I changed it to:
int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_WRONLY);}
    if (read_write == 2) {
        c = open(fifo_name, O_RDONLY);}

    perror("open");

    return (c);
}

My program reaches the open call for the writer threads (this is a NASM call to C):
Open_FIFO_Write:
lea rdi,[fifo_name]
mov rsi,1
call fifo_open wrt ..plt
mov [fifo_write_fd],rax

But then the Putty terminal freezes (blocks) and nothing else happens.  I never get to the block that opens the reading side.  Specifically it blocks just before it reaches perror("open") in the fifo_open code above:
According to the Linux man page at https://www.man7.org/linux/man-pages/man7/fifo.7.html, "Normally, opening the FIFO blocks until the other end is opened also."  That's great but I can't get to the code that opens the writer because the reader blocks all further progress.  It's like a Mexican standoff.
Of course there must be a way but my research hasn't found it yet.
Thanks for any help on this.
Comment: An anonymous pipe uses less resources than a named pipe. And as both ends are created and returned fully opened with a single system call, you won't have a deadlock situation to worry about (not for that part anyway). But for inter-thread communication consider something that use even *less* resources and don't have to pass through the user-kernel border a couple of time. For example a circular queue implemented all in user-space. There are bound to be lock-less implementations available for you to use.
Comment: Are you trying to open both ends of the pipe in a single process? Why? Why use a pipe inside one single process? And if you intend to pass it on to a child-process that you `fork`, why use a named pipe instead of an anonymous pipe as created by the `pipe` system call?
Comment: What's the benefit of using an anonymous pipe vs a named pipe?  I've never heard that IPCs can't be used to communicate between threads of the same process, which is what I'm doing.  My only problem is dropped records when the pipe buffer fills.
Answer: Three options:

FIFOs themselves don't drop messages in nonblocking mode. If your code is dropping messages, fix your code to stop doing that, and then just use nonblocking mode.
Open the FIFO in nonblocking mode, then once you get both ends open, use fcntl to change it to blocking mode.
Use a separate thread or process to open each half of the FIFO.
Comment: 1. If you do a non-blocking write with the buffer full, it will fail with `EWOULDBLOCK`. If you didn't notice that, then it means you're not checking `write`'s result, which is always a  bug. 2. No they're not. In the code in your question, both ends are opened in the same thread.
Comment: I'll try #2.  The two sides are opened in separate threads, but I don't get past the open on the reader side.  As for #1, if a pipe is opened in nonblocking mode and the pipe buffer is full then I believe the write side will drop the record.  That's how nonblocking IPC;s generally work.
Comment: Thanks for your info.  As a minor point, the two C code blocks in my code are called from different threads -- they just appear in the same C file.


Highest Density Interval for the measure of central tendency

Question: When samples are skewed, mean is not a good estimation of central tendency. But instead, median is a better choice.
For cauchy distribution, I heard that there's a completely different estimator (which i didn't understand) that captures the central tendency of it.
And then I came to this new technique called the Highest Density Interval (HDI). It captures the range in which the distribution has the most amount of data points.
Question: If the goal is to measure the central location of a distribution, isn't it simpler to just always report HDI instead of worrying about mean, median, mode, and other more advanced estimators.
Answer: Statistical inference problems involving estimation of any aspects of a distribution arise only when the distribution is unknown.  If the distribution is known then the centre can be located exactly, as can any other aspect of the distribution.  Thus, even if you are interested in a HDI on the distribution rather than the mean, this is still something that would need to be estimated for an unknown distribution.
Now, the HDI is essentially just a generalisation of the mode (it shrinks down to the mode as its coverage probability approaches zero).  It is certainly a useful object of inference in some cases, but it is not usually considered to be a measure of central location; indeed, in some cases the HDI can be quite far from the "centre" of the distribution (particularly when dealing with bimodal distributions).  Whether estimation of the HDI is more important than estimation of the mean, median, etc., will depend on the context of the problem and what you want to know.
Comment: Can you give me an example in which HDI is more important than the other estimators?
Comment: As noted in the question, to compare apples with apples, it would be the *estimated* HDI, not the HDI, that you would compare with other estimators.  The estimated HDI is useful when you want to estimate a range of values that have high coverage probability over the distribution.  I don't have any particular examples in mind, but this can arise in essentially any statistical problem.


How can I edit #text child node text value as element with beautifulSoup?

Question: I want to get every part of inner text of parsed
 tag as soup-element with beautifulSoup in Python. I'm currently migrating the parser from php to Python. Here is some code on php and my attempt to translate the code using Python and beautifulSoup:
PHP (this code works)
foreach($pTagNode->childNodes as $innerNode){
    if($innerNode->nodeName == "#text"){
        # Editing and parahrasing text part of
 tag...
    }
    else if($innerNode->nodeName == "a"){
        # Do something with "a" tag, like removing blacklisted link or chaning text...
    }
}

Python (this code doesn't work)
node = soup.select("p")[0]

#  tag
for pnode in node.select("a"):
    print("link found: " + pnode.string");
# <#text> tag
for pnode in node.select("#text"):
    print("text found: " + pnode.string) # This message doesnt shown :(

HTML structure I want to parse:

Some text 1 and this is the link

Some text 2 and this is the another link

Some text 3 and this is the link 3

I want to do something like this:
[Some text 1 and this is ] = "My new link is "
[the link] = "here!"

I am looking for a way how I can get and set #text as an element. For example, php has DomXPath that allows you to do this. Does anyone have any ideas? If something else is needed, I can edit this question.
Answer: If I understand you correctly, this should get you there (or close):
list(soup.select_one('p').stripped_strings)

Output from the html in your question:
['Some text 1 and this is', 'the link']

Comment: Ye, that works. But I need to change text inside. I tried to do this with using your answer, but it doesnt work. `i = 0; while i < len(list(node.stripped_strings)): list(node.stripped_strings)[i] = "any val here"; i += 1; pass`
Comment: @cyberfrogg Well, in your question you said you want to get the text element, not to set it. And the same with your expected output. You should probably post this new issue as a separate question (per SO policy) and in there indicate exactly what the new output (with the `any val here`) should look like.


Counterexample: If $f: \mathbb{Q}(\alpha) \to \mathbb{Q}(\alpha)$ is an isomorphism of fields, then $\beta=f(\alpha)$.

Question: State whether the statement below is true or false:
If $f: \mathbb{Q}(\alpha) \to \mathbb{Q}(\beta)$ is an isomorphism of fields, then $\beta=f(\alpha)$.
If true, provide a proof; if false, provide a counter-example.
I know that this statement is false but I can't think of a counter-example.
Comment: What's $\beta$?  Did you mean to speak of an isomorphism $f:\mathbb Q(\alpha) \rightarrow \mathbb Q(\beta)$
Comment: What is $\beta$? Is $\alpha$ algebraic?
Comment: $\beta$ and $\alpha$ are not specified in this problem, and $f$ is an isomorphism
Answer: f the identity of Q=Q(1)=Q(-1), a counterexample
Comment: Ok to make sure. So when I proving that this is indeed a counterexample, I would do the following $$f(\alpha-1)=f(\alpha)-f(1)=\beta-1\neq \beta$$
Answer: For an example where $Q(a)\ne Q$, let $a=\sqrt 2$ and $b= -a$. We have $Q(a)=Q(b)=\{x+y a :z,y\in Q\}$. Every $z\in Q(a)$ is equal to $x_z+y_z a$ where $x_z , y_z \in Q$ and are uniquely determined by $z$.  Let $f(x_z+y_za)=x_z-y_za$. This is a field isomorphism (a certain kind,called  an involution, because $f(f(z))=z)$.Observe that $f(a)=b\ne a$.


import all csv files in directory as pandas dfs and name them as csv filenames

Question: I'm trying to write a script that will import all .csv files in a directory to my workspace as dataframes. Each dataframe should be named as the csv file (minus the extension: .csv).
This is what i have so far, but struggling to understand how to assign the correct name to the dataframe in the loop. I've seen posts that suggest using exec() but this does not seem like a great solution.
path = "../3_Data/Benefits"                     # dir path
all_files = glob.glob(os.path.join(path, "*.csv")) #make list of paths

for file in all_files:
    dfn = file.split('\\')[-1].split('.')[0] # create string for df name
    dfn = pd.read_csv(file,skiprows=5) # This line should assign to the value stored in dfn

Any help appreciated, thanks.
Comment: what about saving your DFs as a dictionary of DFs, where keys would be named as you wish?
Comment: I think @MaxU's solution is the best as it allows your to specify variable names without explicitly defining a variable
Comment: Thanks @MaxU, i did want each of the dfs to be accessible directly, but will use dictionary as suggested for now.
Answer: DataFrame have no name their index can have a name. This is how to set it.
import glob
import os

path = "./data/"
all_files = glob.glob(os.path.join(path, "*.csv")) #make list of paths

for file in all_files:
    # Getting the file name without extension
    file_name = os.path.splitext(os.path.basename(file))[0]
    # Reading the file content to create a DataFrame
    dfn = pd.read_csv(file)
    # Setting the file name (without extension) as the index name
    dfn.index.name = file_name

# Example showing the Name in the print output

#      FirstYear  LastYear
# Name
# 0         1990      2007
# 1         2001      2001
# 2         2001      2008