Monotone increasing function that has derivative 0 almost everywhere

Question: The Cantor function is an example of a continuous monotone increasing function, whose derivative is 0 almost everywhere and maps $[0,1]$ onto $[0,1]$. Is there an example of a continuous monotone increasing function $f:[0,1)\to[0,\infty)$ such that $\lim_{x\to 1^-}f(x)=\infty$ and such that $f'=0$ a.e. on $[0,1)$?
Answer: Let $c: [0,1) \rightarrow [0,1)$ denote the Cantor function and define $f:[0,1) \rightarrow [1,\infty)$ by $f(x)=\frac{1}{1-x}$. Then $c$ and $f$ are monotone and continuous so their composition $g:=f \circ c$ is monotone and continuous. Clearly $\lim\limits_{x \rightarrow 1^-} g(x)=\infty$ and by the chain rule $g'(x)=f'(c(x)) c'(x)$ whenever $c'$ exists, so $g'=0$ a.e.
Comment: If $f: [0, 1] \rightarrow \mathbb{R}$ is Lipschitz it is absolutely continuous which implies that $f(x)=f(0)+\int_0^x f'$ $d\mu$ for $x\in [0, 1]$. So then if $f'=0$ a.e. $f$ is constant.
Comment: Does the answer change if we also require $f$ to be locally Lipschitz? Since the Cantor function isn't Lipschitz...
Answer: Here's a sketch:
By dilating and translating the original Cantor function, you can get a monotone increasing function which has vanishing derivative a.e. between any two intervals.
Put $I_n=\left[1-\frac{1}{n},1-\frac{1}{n+1}\right]$. Paste Cantor functions between each $I_n$ and $[n,n+1]$ to get what you want.


How to hide views UI reaching number of limits of searches

Question: I'm developing a D8 site. I am using a custom views plugin to query data from a remote api by searching a business ID.
My scenario: User is only allowed to enter 3 attempts of business ID in a search view. If 3 attempts fails, I want to hide the views UI from the page for 24 hours. What's my purpose? To give difficulty for others to guess my business ID.
This is a duplicate question with: How to use Rules to limit the number of searches to pull data from a remote API, but on another perspective.
I wasn't able to implement it using Rules, and I'm guessing if we can do it on front-end coding. Does anyone have an idea to implement this?
Answer: You can Set a configuration variable for each user (it's equal variables on drupal 7 ) and for each search increase it,reset it each day,But another and simple method is  implement it by cookie , create a cookie for user, set expire to 24 hours, and every time user search, first check it's cookie and if not do it more that three times  show results for him/her else  there is nothing to him/her.I think cookie solution is good for you.


Running GWTTestCase with Maven

Question: I am not able to make GWT Test run with my GWT Library project when running $mvn clean install it throws this error:
[ERROR] Hint: Check that your module inherits 'com.google.gwt.core.Core' either directly or indirectly (most often by inheriting module 'com.google.gwt.user.User')

However the app have that in the App.gwt.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<module>
  <inherits name="com.google.gwt.core.Core" />
  <inherits name='com.google.gwt.user.User'/>
  <inherits name="com.google.gwt.i18n.I18N"/>
  <inherits name="org.restlet.Restlet" />

  <source path='client'/>
  <source path='shared'/>
</module>

And the Test code is very simple:
public class AppTest extends GWTTestCase {
    @Before
    public void prepareTests(){

    }
    @After
    public void afterTests() {

    }
    @Override
    public String getModuleName() {
        return "com.mycompany.App";
    }
    @Test
    public void test(){
        Assert.assertTrue(true);
    }
}

What could be the problem that prevents the test from running?
Comment: How are you launching your tests? surefire/failsafe? with which config? gwt:test?
Answer: 1.- Don't use Junit-4 but Junit-3, remove @Test and name your tests with the test prefix
2.- Override getModuleName returning your gwt module
3.- Use gwtSetup and gwtTearDown instead of @Before and @After
  public class MyGwtTest extends GWTTestCase {

    @Override
    public String getModuleName() {
      return "com.example.MyApp";
    }
    @Override
    protected void gwtSetUp() throws Exception {
    }
    @Override
    protected void gwtTearDown() throws Exception {
    }

    public void testSomething() {
      // test something
    }
  }

4.- Configure gwt-maven appropriatelly so as you can use mvn gwt:test to run your tests
5.- Or configure your maven project with this surefire configuration, and you can use the normal way mvn test.
<plugin>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.8.1</version>
   <configuration>
     <additionalClasspathElements>
       <additionalClasspathElement>${project.build.sourceDirectory}</additionalClasspathElement>
       <additionalClasspathElement>${project.build.testSourceDirectory}</additionalClasspathElement>
     </additionalClasspathElements>
     <useManifestOnlyJar>false</useManifestOnlyJar>
     <forkMode>always</forkMode>
   </configuration>
</plugin>

Comment: Thanks, I am getting Exception in thread "htmlUnit client thread" java.lang.NoSuchFieldError: INSTANCE
Comment: I fixed it by adding the google-http-client dependency
Comment: Thanks for answering its been my problem since the new year :-)

Running GWTTestCase with Maven


Problems with SMOTE optimizing function

Question: I am new to machine learning or R and tried to code a function "smotevalue" in R in order to fine-tune the parameters of SMOTE for binary classification/prediction in imbalanced data. The idea is to vary the two parameters of SMOTE (K and dup_size) in order to optimize the AUC score of predictions for testdata.
Something seems to be wrong here, as the optimization function reports perfect AUC scores at every iteration. I tested the code within the "smotevalue" function in isolation, and it also gives me unreasonably high AUC scores when predicting the test data. (For example I changed the data-split to 5%/95% training/test, I still got an AUC of about 0.99 for the predictions on test)
Is the testdata somehow used to train the model here? Where is my mistake?
Edit:
In the end the models are trained within k-fold cross validation through the "caret" package. When I use the k-fold cross validation within the "smotevalue" function the results get feasible, but the computation takes way too long as you might imagine. But it seems as if the problem would be connected to my use of the XGBoost function here..in the end my aim is to imitate the "xgbLinear" method I use within "caret".
<code># Libraries
library(smotefamily) #SMOTE
library(caret) #Data Splitting
library(pROC) #AUC Metric
library(DEoptim) #Differential Evolution Optimization

# Set Seed
set.seed(123)

# Read Training Data Into R
bankruptcy.train <- read.csv(file=".../bankruptcy_Train.csv", header=TRUE, sep=",")

# Read Test Data Into R
bankruptcy.test <- read.csv(file=".../bankruptcy_Test_X.csv", header=TRUE, sep=",")

## SMOTUNE ##

smotevalue <- function(x)  {

  inTraining <- createDataPartition(bankruptcy.train$class, p = .05, list = FALSE)
  training <- bankruptcy.train[ inTraining,]
  testing  <- bankruptcy.train[-inTraining,]

  data_train <- SMOTE(training[,-65], training$class, K = x[1], dup_size = x[2])
  data_train <- data_train[["data"]]

  data_train <- data.matrix(data_train)
  data_train <- xgb.DMatrix(data = data_train, label=data_train[,65])

  bst <- xgboost(data=data_train, booster = "gblinear", nthread = 4, lambda = 1e-04, alpha = 0,
                 eta = 0.3, nrounds=150, eval.metric = "auc", objective = "binary:logistic")

  data_test <- data.matrix(testing)
  data_test <- xgb.DMatrix(data = data_test, label=data_test[,65])
  test.pred.bst <- predict(bst, newdata=data_test)

  roc_obj = roc(testing[,65], test.pred.bst)
  auc(roc_obj)*(-1)
}

# Specify That SMOTE Parameters Will Be Tuned In Discrete Steps

Integer <- function(x){
  x[1:2] <- round(x[1:2]) #k and dup_size -> integer values
}

# Differential Evolution Optimization of function smotevalue,
# varying K and dup_size for highest AUROC value
smote_de_obj <- DEoptim(smotevalue, lower = c(1, 1), upper = c(15, 50),
                        control = DEoptim.control(NP = 20, itermax = 50,
                                                  CR = 0.3, F = 0.7),
                        fnMap = Integer)

# Report Tuned SMOTE Parameters
fitted_params <- smote_de_obj$optim$bestmem
</code>
The following is the code that seems to work (it produces more reasonable results for AUC, here the best scores are somewhere in the 0.96 range). I would be thankful for any comments whether the approach is reasonable (besides a lot of basic concerns like whether Oversampling should generally be performed when working with XGBoost for example, which I'm also trying to figure out).
<code>smotevalue <- function(x)  {

  # Split The Data Into Training/Test
  inTraining <- createDataPartition(bankruptcy.train$class, p = .67, list = FALSE)
  training <- bankruptcy.train[ inTraining,]
  testing  <- bankruptcy.train[-inTraining,]

  # SMOTE -> K and dup_size will be varied for optimization
  data_train <- SMOTE(training[,-65], training$class, K = x[1], dup_size = x[2])
  data_train <- data_train[["data"]]

  xgbLinear_grid <- expand.grid(nrounds = c(150),
                                lambda = c(1e-04),
                                alpha = c(0),
                                eta = c(0.3))
  # K-fold Cross Validation
  ctrl <- trainControl(method = "repeatedcv", number = 3, repeats = 1, classProbs = TRUE,
                       summaryFunction = twoClassSummary) #twoClassSummary gives AUC, sensitivity and specificity using default probability cutoff (50%) as performance measure

  ## BUILD THE MODELS ##

  # outcome variable as a factor for classification in train function
  data_train$class <- factor(data_train$class)
  # in order to avoid error in train function
  levels(data_train$class) <- make.names(levels(factor(data_train$class)))

  # xgbLinear (Extreme Gradient Boosting)
  xgbLinear_tune <- train(class ~ ., data = data_train, method = "xgbLinear",
                          distribution = "bernoulli", trControl = ctrl, tuneGrid = xgbLinear_grid,
                          verbose = FALSE, metric = "ROC")

  test.pred.xgbLinear <- predict(xgbLinear_tune, newdata=testing, type = "prob")
  pred_xgbLinear <- test.pred.xgbLinear[,-1]

  # Calculate AUC For Prediction
  roc_obj = roc(testing[,65], pred_xgbLinear)
  auc(roc_obj)*(-1) #negative of AUC as function output in order to perform
  #maximization instead of minimization with DEoptim
}
</code>
Answer: In order to close this:
The latter piece of code worked fine as far as I can tell, but I guess the Differential Evolution algorithm is overkill for a rather simple optimization problem as this here.
Moreover, in our experiments (bankruptcy prediction, data: Polish Companies Bankruptcy from UCI) the tuned SMOTE parameters combined with the XGBoost algorithms didn't lead to conclusively better results. More testing would be necessary to get an idea about this, but the impact of tuning SMOTE in that case seems rather limited if I did everything correctly.

Problems with SMOTE optimizing function


What is the inverse of $f(x)=x^3-3x$?

Question: I found this problem in the Spivak calculus book, and have spent probably 5 hours with no progress being made. I found online that Cardano's method can be used, but I doubt this book would require that knowledge, and the problem is only labelled as "pretty hard," not "extremely hard." (with asterisks).
The only thing I figured out was that it's gonna be 3 separate functions. I have tried dividing $x^3-3x-c$ by a linear factor, I have tried guessing the type of functions in the inverse by looking at the graph, I have tried assuming x would be some sum $p+q$ and solving for each variable's expression. I'm about 90% sure there is a much simpler solution that I can no longer see from falling deeper and deeper into these wrong ideas. What am I missing?
Comment: meanwhile, you should give the exact page  and specify which edition, in case someone has a copy and can look it up
Comment: Mostly he wants you to draw the graph of $x^3 - 3 x$  and make judgements about the possible inverse, in tune with the chapter.
Comment: the usual thing is not to find the inverse of a difficult function, rather the derivative of the inverse  function; the latter comes from the chain rule.
Comment: $f$ is not injective: $f(0)=f(\sqrt 3)=f(-\sqrt 3)$
Comment: @WillJagy It is the third edition page 238. Problem 12-12(c). Are you saying that finding the derivative helps to find the function itself?
Comment: I have an early edition; chapter 12 is Inverse Functions. pages 210-212  has a few questions in which   $  \lrft( f(x) \right)^3 - 3 f(x) $   appears.
Comment: @ajotatxe, the function $f$ is injective on $(-\infty,-1]$ or on $[-1,1]$ or on $[1,+\infty)$.
Answer: If you consider the cubic equation$$x^3-3x-y=0$$ its discriminant is
$$\Delta=-27 \left(y^2-4\right)$$ which is negative if $|y|>2$. For this case, only one real root.
Following the steps given here, the solution is simply
$$x=2\frac{| y| }{y}\,\cosh \left(\frac{1}{3} \cosh ^{-1}\left(\frac{| y| }{2}\right)\right)$$
Answer: We have $x^3-3x-y=0.$
By Cardano's method that you suggested,
$$x=f^{-1}(y)\\=\sqrt[3]{\frac y2+\sqrt{\frac{y^2}4-1}}+
\sqrt[3]{\frac y2-\sqrt{\frac{y^2}4-1}}$$
for $x>1.$
$$x=f^{-1}(y)\\=w^2\sqrt[3]{\frac
y2+\sqrt{\frac{y^2}4-1}}+w
\sqrt[3]{\frac y2-\sqrt{\frac{y^2}4-1}}$$
for $-1<x<1.$
$$x=f^{-1}(y)=w\sqrt[3]{\frac y2+\sqrt{\frac{y^2}4-1}}+w^2
\sqrt[3]{\frac y2-\sqrt{\frac{y^2}4-1}}$$
for $x<-1.$ Here, $w=e^{\frac{2\pi i}3}$.
Comment: Okay, Spivak must have added this on accident or to torture readers, unless Cardano's method is just common knowledge that I don't know somehow
Comment: I am not sure about intervals.
Comment: if $y > 2$  there is just one $x$ value that works. He asks the student to draw $x^3 - 3 x$  for this. Same conclusion when your $y < -2$

What is the inverse of $f(x)=x^3-3x$?


trying to swap links in a linked list, doesnt seem to work

Question:  public void question1(int key1,int key2){
    //swapping keys by changing links not data:
    Node temp = Head;
    Node tempStr1 = null;
    Node nextStr1=null,NextStr2=null;
    Node tempstr2 = null;
    while(temp.Next!=null){
        if(temp.Next.data==key1){
            nextStr1=temp.Next.Next;
            tempStr1 = temp.Next;
        }
        if(temp.Next.data==key2){
            NextStr2 = temp.Next.Next;
            tempstr2 = temp.Next;//storing in temp var
        }
        temp=temp.Next;//update
    }
    while(temp.Next!=null){
        if(temp.Next.data==key1){
            temp.Next = tempstr2;
            tempstr2.Next = nextStr1;
        }
        if(temp.Next.data==key2){
            temp.Next = tempStr1;//swap
            tempStr1.Next = NextStr2;
        }
        temp=temp.Next;//update
    }

}
    }
public static void main(String args[]){
        LinkedList ll = new LinkedList();
        ll.addFirst(1);
        ll.addFirst(2);
        ll.addFirst(3);
        ll.addFirst(4);
        ll.addFirst(5);
        ll.addFirst(6);
        ll.Print();
        ll.question1(3, 2 );
       ll.Print();

i dont seem to understand why is this not doing the trick,
the goal is to swap the two nodes by just changing the links
expected outcome:6 5 4 2 3 1
real outcome:6 5 4 3 2 1
writing this code for the question:
Swapping Nodes in a Linked ListWehavealinkedlistandtwokeysinit,swapnodesfortwogivenkeys.Nodesshouldbeswappedbychanginglinks.Swappingdataofnodesmaybeexpensiveinmanysituationswhendata contains many fields. It may be assumed that all keys in the linked list are distinct.
Comment: What is the nodes before Node1 & Node2 pointing to after you swapped the nodes?
Comment: @cliff2310 thanks,i noticed that, fixed that from my end i think, the code still doesnt seem to work.
Answer: There are a few issues:

The second loop will never iterate, because the first loop will end when temp.Next is null, and since the second loop will only iterate when this is not the case, it is useless. This practically means there will never be a swap.

Even if you would reset temp to null just before the second loop starts, it is a pity that you need to iterate the whole list again, just to find the same two nodes again.

If in the second loop the first condition is true, then the first if block will make that temp.Next references the node with key2, but that means that the second if condition is also true now, and the change will be reverted again.

There is no provision where the head node would have to be swapped.

No distinction is made between the case where two consecutive nodes need to be swapped (which involves 3 references to be updated) and where the swapped nodes are not each other's neighbor (which involves 4 references to be updated).

I would suggest that you only have one loop, and when you have found both positions, you make the swap immediately.
Also, to involve the head as a potential candidate for a swap, I'd suggest temporarily prepending the list with a dummy node so that the while loop can start one step earlier and detect the wanted key also in the head node. After the swap that dummy node should be removed again. This way the final Head node could actually be a different one than was originally the case.
Here is the suggested code:
    public void question1(int key1, int key2) {
        // Swapping keys by changing links not data:
        addFirst(0); // Prepend list with some dummy value
        Node temp = null; // Used for swapping
        Node before1 = null; // Node that precedes the first match
        Node before2 = Head; // Node that eventually precedes the second match

        while (before2.Next != null) {
            if (before2.Next.data == key1 || before2.Next.data == key2) {
                if (before1 == null) { // First match
                    before1 = before2;  // Save that match
                } else { // Second match
                    if (before1.Next == before2) { // Special case
                        before1.Next = before2.Next;
                        before2.Next = before2.Next.Next;
                        before1.Next.Next = before2;
                    } else {
                        temp = before1.Next.Next;
                        before1.Next.Next = before2.Next.Next;
                        before2.Next.Next = temp;

                        temp = before1.Next;
                        before1.Next = before2.Next;
                        before2.Next = temp;
                    }
                    break; // All done
                }
            }
            before2 = before2.Next;
        }
        // Remove the dummy Node
        Head = Head.Next;
    }


Is it possible to have both static and dynamic IPv6 addresses on one interface?

Question: I have two Qemu virtual machines with Ubuntu Server. I would like one of them to be a DHCP server. On the second one, I would like to have two IPv6 addresses. One should be static, and the other one should be obtained from my DHCP server. I am able to create many static addresses, but when I get a dynamic one, I lose all my static addresses except a link-local one. What should I do to have both static and dynamic IPv6 addressess on one interface?
Thank you in advance for any help.
Comment: u may use a virtual device like eth0:0 and set it to dhcp as it is easy to to: auto eth0:0 and second line iface eth0:0 inet dhcp ans this must be added to network/interfaces as i am not using the network manager and the end is that you have multi ips for the dame device unlike windows as im nit knowing that this might be possible
Answer: How IPv6 addresses are auto configured depends on the flags in the ICMPv6 RA.
To have the host both request from DHCPv6, and generate its own via SLAAC, you'll likely want to enable all the flags. Autonomous, Managed address configuration, and Other.  Plus a prefix information option. And static addresses on the host if desired.
Yes, this may be done with one interface. Linux has been capable of many IPs on one interface for a very long time. (Alias interfaces of the form eth0:0 have been obsolete for just as long. Don't use ifconfig on Linux any more.)


RecyclerView: Why moving an item to the top renders it outside of visible area?

Question: When I perform this call in the RecyclerView Adapter, the item is moved to position 0, but it's out of the visible area: notifyItemMoved(position, 0)
Comment: Does this answer your question? [Move RecyclerView clicked item to the top](https://stackoverflow.com/questions/54763264/move-recyclerview-clicked-item-to-the-top)
Answer: Because you also need to scroll the RecyclerView ♀
This creates a nice animation with Kotlin, rendering the scrolling invisible to the eye, so that moving the item looks natural:
In the Adapter:
Collections.swap(list, position, 0)
notifyItemMoved(position, 0)
// TODO: Callback to the fragment through listener or ViewModel
In the Fragment: recyclerView.layoutManager?.scrollToPosition(0)
Cheers!


Error in configuring cpp properties vscode. Barrier not found in c++ standard 20

Question: I get this error for my IntelliSense in VS Code:
cannot open source file "barrier" (dependency of "role_server.h") C/C++(1696)

I also have this issue for #include <experimental/coroutine>, but I believe this was included in the same C++ standard, so fixing the barrier should hopefully lead to the fix for "cannot open source file experimental/coroutine"
Barrier was included in c++ standard 20 and I configured c_cpp_properties.json to use that standard.
This is what the file currently looks like.
{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/**",
                "/usr/local/include/**",
                "~/INSTALL/protobuf/src",
                "${workspaceFolder}"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c23",
            "cppStandard": "c++20",
            "intelliSenseMode": "linux-gcc-x86",
            "configurationProvider": "ms-vscode.makefile-tools",
            "compilerArgs": [
                "-std=c++20"
            ]
        }
    ],
    "version": 4
}

For reference, I use Bazelisk for building the executable and I don't run into any issues there, so it's just a VS Code configuration question.
Additionally, I have tried other strategies like changing my compilerPath and intelliSenseMode. I use Linux 20.04.1-Ubuntu.
Answer: Seeing that you're on Ubuntu 20.04 (Focal Fossa), I'm assuming you just have the default GCC package? That one is for GCC 9.
If you look at https://en.cppreference.com/w/cpp/compiler_support, you'll see that std::barrier got added to GCC's standard library in version 11, clang's standard library in version 11, and MSVC's standard library in version 19.28.
Try installing the gcc-11 package. If you want to make gcc point to gcc-11, see also How to change the default GCC compiler in Ubuntu?.


FANN examples give wrong results although training seems successful

Question: Using FANN I can't succeed to run copy&pasted code from FANN's website. I am using FANN version 2.2.0 on Windows 7 and MS Visual Studio 2008. My code for the training program of the XOR example looks like:
#include "floatfann.h"
#include "fann_cpp.h"

#include <ios>
#include <iostream>
#include <iomanip>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::setw;
using std::left;
using std::right;
using std::showpos;
using std::noshowpos;

// Callback function that simply prints the information to cout
int print_callback(FANN::neural_net &net, FANN::training_data &train,
    unsigned int max_epochs, unsigned int epochs_between_reports,
    float desired_error, unsigned int epochs, void *user_data)
{
    cout << "Epochs     " << setw(8) << epochs << ". "
         << "Current Error: " << left << net.get_MSE() << right << endl;
    return 0;
}

// Test function that demonstrates usage of the fann C++ wrapper
void xor_test()
{
    cout << endl << "XOR test started." << endl;

    const float learning_rate = 0.7f;
    const unsigned int num_layers = 3;
    const unsigned int num_input = 2;
    const unsigned int num_hidden = 3;
    const unsigned int num_output = 1;
    const float desired_error = 0.00001f;
    const unsigned int max_iterations = 300000;
    const unsigned int iterations_between_reports = 1000;

    cout << endl << "Creating network." << endl;

    FANN::neural_net net;
    net.create_standard(num_layers, num_input, num_hidden, num_output);

    net.set_learning_rate(learning_rate);

    //net.set_activation_steepness_hidden(0.5);
    //net.set_activation_steepness_output(0.5);

    net.set_activation_function_hidden(FANN::SIGMOID_SYMMETRIC_STEPWISE);
    net.set_activation_function_output(FANN::SIGMOID_SYMMETRIC_STEPWISE);

    // Set additional properties such as the training algorithm
    //net.set_training_algorithm(FANN::TRAIN_QUICKPROP);

    // Output network type and parameters
    cout << endl << "Network Type                             :  ";
    switch (net.get_network_type())
    {
    case FANN::LAYER:
        cout << "LAYER" << endl;
        break;
    case FANN::SHORTCUT:
        cout << "SHORTCUT" << endl;
        break;
    default:
        cout << "UNKNOWN" << endl;
        break;
    }
    net.print_parameters();

    cout << endl << "Training network." << endl;

    FANN::training_data data;
    if (data.read_train_from_file("xor.data"))
    {
        // ***** MY INPUT
        std::string fn;
        fn = "xor_read.data";
        data.save_train(fn);
        fann_type **train_dat;
        fann_type **out_dat;
        train_dat = data.get_input();
        out_dat = data.get_output();

        printf("*****************\n");
        printf("Printing read data (%d):\n", data.num_input_train_data());
        for(unsigned int i = 0; i < data.num_input_train_data(); i++)
        {
            printf("XOR test (%f,%f) -> %f\n", train_dat[i][0], train_dat[i][1], out_dat[i][0]);
        }
        printf("*****************\n");

        // END: MY INPUT **************

        // Initialize and train the network with the data
        net.init_weights(data);

        cout << "Max Epochs " << setw(8) << max_iterations << ". "
            << "Desired Error: " << left << desired_error << right << endl;
        net.set_callback(print_callback, NULL);
        net.train_on_data(data, max_iterations,
            iterations_between_reports, desired_error);

        cout << endl << "Testing network." << endl;

        for (unsigned int i = 0; i < data.length_train_data(); ++i)
        {
            // Run the network on the test data
            fann_type *calc_out = net.run(data.get_input()[i]);

            cout << "XOR test (" << showpos << data.get_input()[i][0] << ", "
                 << data.get_input()[i][2] << ") -> " << *calc_out
                 << ", should be " << data.get_output()[i][0] << ", "
                 << "difference = " << noshowpos
                 << fann_abs(*calc_out - data.get_output()[i][0]) << endl;
        }

        cout << endl << "Saving network." << endl;

        // Save the network in floating point and fixed point
        net.save("xor_float.net");
        unsigned int decimal_point = net.save_to_fixed("xor_fixed.net");
        data.save_train_to_fixed("xor_fixed.data", decimal_point);

        cout << endl << "XOR test completed." << endl;
    }
}

/* Startup function. Syncronizes C and C++ output, calls the test function
   and reports any exceptions */
int main(int argc, char **argv)
{
    try
    {
        std::ios::sync_with_stdio(); // Syncronize cout and printf output
        xor_test();
    }
    catch (...)
    {
        cerr << endl << "Abnormal exception." << endl;
    }
    return 0;
}

I commented out :
//net.set_activation_steepness_hidden(0.5);
//net.set_activation_steepness_output(0.5);

otherwise it crashes. The file xor.data :
4 2 1
1 1
-1
-1 -1
-1
-1 1
1
1 -1
1

The output looks odd to me:
XOR test started.

Creating network.

Network Type                                                      :  LAYER
Input layer                          :   2 neurons, 1 bias
  Hidden layer                       :   3 neurons, 1 bias
Output layer                         :   1 neurons
Total neurons and biases             :   8
Total connections                    :  13
Connection rate                      :   1.000
Network type                         :   FANN_NETTYPE_LAYER
Training algorithm                   :   FANN_TRAIN_RPROP
Training error function              :   FANN_ERRORFUNC_TANH
Training stop function               :   FANN_STOPFUNC_MSE
Bit fail limit                       :   0.350
Learning rate                        :   0.700
Learning momentum                    :   0.000
Quickprop decay                      :  -0.000100
Quickprop mu                         :   1.750
RPROP increase factor                :   1.200
RPROP decrease factor                :   0.500
RPROP delta min                      :   0.000
RPROP delta max                      :  50.000
Cascade output change fraction       :   0.010000
Cascade candidate change fraction    :   0.010000
Cascade output stagnation epochs     :  12
Cascade candidate stagnation epochs  :  12
Cascade max output epochs            : 150
Cascade min output epochs            :  50
Cascade max candidate epochs         : 150
Cascade min candidate epochs         :  50
Cascade weight multiplier            :   0.400
Cascade candidate limit              :1000.000
Cascade activation functions[0]      :   FANN_SIGMOID
Cascade activation functions[1]      :   FANN_SIGMOID_SYMMETRIC
Cascade activation functions[2]      :   FANN_GAUSSIAN
Cascade activation functions[3]      :   FANN_GAUSSIAN_SYMMETRIC
Cascade activation functions[4]      :   FANN_ELLIOT
Cascade activation functions[5]      :   FANN_ELLIOT_SYMMETRIC
Cascade activation functions[6]      :   FANN_SIN_SYMMETRIC
Cascade activation functions[7]      :   FANN_COS_SYMMETRIC
Cascade activation functions[8]      :   FANN_SIN
Cascade activation functions[9]      :   FANN_COS
Cascade activation steepnesses[0]    :   0.250
Cascade activation steepnesses[1]    :   0.500
Cascade activation steepnesses[2]    :   0.750
Cascade activation steepnesses[3]    :   1.000
Cascade candidate groups             :   2
Cascade no. of candidates            :  80

Training network.
*****************
Printing read data (2):
XOR test (0.000000,1.875000) -> 0.000000
XOR test (0.000000,-1.875000) -> 0.000000
*****************
Max Epochs   300000. Desired Error: 1e-005
Epochs            1. Current Error: 0.260461
Epochs           36. Current Error: 7.15071e-006

Testing network.
XOR test (+0, +1.875) -> +5.295e-035, should be +0, difference = 5.295e-035
XOR test (+0, -1.875) -> +0, should be +0, difference = -0
XOR test (+0, -1.875) -> +0, should be +0, difference = -0
XOR test (+0, +1.875) -> +0, should be +0, difference = -0

Saving network.

XOR test completed.

The output after Testing network. looks like :

the training data as well as the test data are interpreted to be (0, +/- 1.875), as you can see in directly below the lines after Printing read data (2) and Testing network..
The (2) after Printing read data is taken from data.num_input_train_data() and my expectation would be to get a (4) since I have four sets of training data.
The "target" seems to be always "0" (see output), although the training data is never zero, but always +/- 1.

A different question has the same odd output hinting towards the training data being interpreted as (0,+/-1.875)->0.0. With this example training (like in my XOR example) also seemed to be successful, but the execution of the ANN (even on the data used for training) returned seemingly random numbers.
Answer: I found the answer in FANN - I get incorrect results (near 0) at simply task. It says when including "doublefann.h" one should also link the doublefann lib. This obviously holds for "floatfann.h" and the floatfann lib as well.


K-means dominated by one or two variables only

Question: What should we do if clustering such as K-means is dominated by one or two variables in the list of used variables? Shall we leave the other variables?
Comment: if "dominated" means there are large differences in order of magnitude: standardize the variables
Comment: Yes, as said, you should consider standardizing but you don't _have to_ standardize. It depends ([see](https://stats.stackexchange.com/q/21222/3277)). In the end, when you are satisfied with theoretical considerations you've made and there is still the "dominance" in the sense that only one variable separates the clusters - then yes, you could drop other variables.
Answer: This is commonly caused by the variables having different scale.
How many people will just heuristically normalize the data. While this usually prevents one variable from dominating the result, whether or not this is meaningful is something you have to answer based on your data.
In my opinion, when you have scales of very different data types and scales (e.g., shoe size vs. income in $ vs. appartment size in ft²) then it is questionable if any k-mrans result on such data is meaningful...


Solving $\log_6(2x-3)+\log_6(x+5)=\log_3x$

Question: Solve for $x$
I have an equation that I have been working on solving; I know the solution, but I cannot get to it myself. Almost every simplification I do reverts back to a previous step. Can anyone show me how to solve for $x$ in this equation?
Equation:
$$\log_6(2x-3)+\log_6(x+5)=\log_3x$$
Solution:
$$x ≅ \frac{3347}{2000} ≅ 1.6735$$

Note: upon further analysis of the answer, while close, it does not seem to be the exact solution.

What I Have Tried So Far
$$\log_6(2x-3) + \log_6(x + 5) = \log_3x$$
$$\frac{\log(2x-3)}{\log6} + \frac{\log(x + 5)}{\log6} = \frac{\log x}{\log3}$$
$$\log3 \cdot \log(2x-3) + \log3 \cdot \log(x + 5) = \log6 \cdot \log x$$
$$\log3 \cdot \log \left[(2x - 3)(x + 5)\right] = \log6 \cdot \log x$$
$$\frac{\log \left[(2x - 3)(x + 5)\right]}{\log_3 10} = \frac{\log6}{\log_x10}$$
$$\log_x10 \cdot \log \left[(2x - 3)(x + 5)\right] = \log_3 10 \cdot \log6$$
$$\log_x \left[(2x - 3)(x + 5)\right] = \log_3 6$$
$$\log_x3 \cdot \log_x \left[(2x - 3)(x + 5)\right] = \frac{\log_3 6}{\log_3 x}$$
$$\log_x \left[(2x - 3)(x + 5)\right]^{\ \log_x3} = \log_x 6$$
$$\left[(2x - 3)(x + 5)\right]^{\ \log_x3} = 6$$
$$(2x - 3)(x + 5) = x^{\log_3 6}$$

I know these steps aren't really working towards the solution at points; I was sort of just playing around with the equation. Regardless, I really don't know how to go about moving forward from here.
Comment: Do you have reason to believe you will get a nice closed form for the answer?  Mixing logs with different bases generally doesn't end well.
Comment: I also have updated the question with the steps I have already taken to try to solve the equation @MarsPlastic.
Comment: What are the steps you have tried?
Comment: Are you sure about the $\log_3$ ?
Comment: Mind to tell us the solution that you have ?
Comment: I have updated the question with the solution @YvesDaoust.
Comment: Lol If you see you did not need to do so many steps to get the  last step... You could have got it in one step from the original eqn
Comment: I think the answer is wrong tho
Answer: If $x \in \mathbb R$, the equation $$\log_6 (2x-3) + \log_6 (x+5) = \log_3 x$$ requires $x > 3/2$.  Under such an assumption, the LHS becomes $$\log_6 (2x-3)(x+5),$$ and the RHS, using the change-of-base formula, is $$\log_3 x = \frac{\log_6 x}{\log_6 3}.$$  Thus $$(2x-3)(x+5) = 6^{\log_6 x / \log_6 3} = x^{\log_3 6} = x^{\log_3 3 + \log_3 2} = x^{1 + \log_3 2}.$$
Let $a = \log_3 2 < 1$.  Then to seek a numerical root, we apply Newton's method to $$f(x) = 2x^2 - x^{a+1} + 7x - 15$$ by computing iterates of $$x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} = x_n - \frac{2x_n^2 - x_n^{a+1} + 7x_n - 15}{4x_n - (a+1)x_n^a + 7}.$$  A suitable initial guess has already been provided, namely $x_0 = \frac{3347}{2000}$, from which we iterate with a computer to obtain to 75 digits of precision
$$x_0 = \color{green}{1.6735}0000000000000000000000000000000000000000000000000000000000000000000000 \\
x_1 = \color{green}{1.6735161761}6028420105594976526962483014865547809090912454018791698117840074 \\
x_2 = \color{green}{1.673516176124260238848}57028078132556340450344946364614508901732583022202367 \\
x_3 = \color{green}{1.67351617612426023884839162222058963917030308}792976477026920554313588396492 \\
x_4 = \color{green}{1.67351617612426023884839162222058963917030308353547657451861889646281230396} \\
x_5 = \color{green}{1.67351617612426023884839162222058963917030308353547657451861889646281230396}
$$
where green digits indicate correct values, demonstrating the rapid convergence of the iterates.  Moreover, we are assured that this is the unique root, since $f$ is a monotonically increasing function on $x > 3/2$ (its derivative being trivially greater than $0$ on this interval).
Answer: Taking the base-$6$ antilogarithm,
$$(2x-3)(x+5)=6^{\log_3x}=e^{\ln6\ln x/\ln3}=x^{\ln6/\ln3}.$$
Because of the irrational exponent, there is no closed-form solution and you need to use a numerical method.
Comment: Why this downvote ?
Answer: Just for the fun of it !
Since heropup already gave the answer, let us do the same using one single iteration using  high order methods with $x_0 = \frac{3347}{2000}$
$$\left(
\begin{array}{ccc}
n & x_1 & \text{Method} \\
 1 & \color{blue}{1.67351617}525914512770936502001715480227532437 & \text{Newton} \\
 2 & \color{blue}{1.6735161761242}2229623976832154151388262101881 & \text{Halley}\\
 3 & \color{blue}{1.67351617612426023}725117282565297065627253993 & \text{Householder}\\
 4 & \color{blue}{1.6735161761242602388483}2362357774862967541409 & \text{no name}\\
 5 & \color{blue}{1.6735161761242602388483916}1928419708807692011 & \text{no name}\\
 6 & \color{blue}{1.673516176124260238848391622220}46176652833341 & \text{no name}\\
 7 & \color{blue}{1.67351617612426023884839162222058963}357352924 & \text{no name}\\
 8 & \color{blue}{1.673516176124260238848391622220589639170}05729 & \text{no name}
\end{array}
\right)$$


Máscara de Input

Question: Estou em dificuldade de criar uma máscara para input de matrícula.
As matrículas são formada por 4 ou 5 dígitos, hífen , 1 digito. (0000?-0).
A máscara deve ser aplicada conforme a digitação do input.
Mas não consegui fazer usando Javascript puro.
O site então não possui jQuery, entao não quero ter que adicionar o jQuery e um plugin de máscara para isso.
Comment: Então pq as tags que vc não quer estão na pergunta?
Comment: @LeoCaracciolo foi feita a edição, eu tinha rejeitado justamente porque ao ler entendi que não tem nada com **jQuery**, acabou que no final o **AP** aprovou a edição.
Comment: @wmsouza, correto, mas a pergunta continua com `O site então não possui jQuery, entao não quero ter que adicionar o jQuery e um plugin de máscara para isso.`
Comment: Sim, o correto é reverter essa edição.
Comment: foi feita a edição. Obrigado pela correção :D
Answer: Usando Expressão Regular chegará ao resultado.

\d Somente digitos
{4,5} Limita de 4 a 5 digitos

window.onload = function(){
  var campo = document.querySelector('#matricula');
  campo.addEventListener('keyup', function(){
    var matricula = campo.value.replace(/\D/g,""); // Remove o que não é digito
    matricula = matricula.replace(/(\d{4,5})(\d{1})$/,"$1-$2"); // 4 ou 5 dígitos a esquerda e 1 a direita
    console.log(matricula); // Mostra no Console
    this.value = matricula; // Insere o valor formatado no input
    if (campo.value.length < 5) { // Valida
      campo.classList.add("invalido");
    } else {
      campo.classList.remove("invalido");
    }
  });
}
input {
  border: 2px solid #ccc;
  color: #069;
  padding: 8px;
}
.invalido {
  border-color: red;
}
<input type="text" name="matricula" id="matricula" maxlength="7" />

ES6

const maskMatricula = (el) => {
  let matricula = el.value.replace(/\D/g,""); // Remove o que não é digito
  matricula = matricula.replace(/(\d{4,5})(\d{1})$/,"$1-$2"); // 4 ou 5 digitos a esquerda e 1 a direita
  console.log(matricula); // Mostra no Console
  el.value = matricula; // Insere o valor formatado no input
  if (el.value.length < 5) { // Valida
    el.classList.add("invalido");
  } else {
    el.classList.remove("invalido");
  }
}
input {
  border: 2px solid #ccc;
  color: #069;
  padding: 8px;
}
.invalido {
  border-color: red;
}
<input type="text" name="matricula" id="matricula" maxlength="7" onkeyup="maskMatricula(this)" />

Referências

querySelector - MDN Web Docs
addEventListener - MDN Web Docs
Expressões Regulares - MDN Web Docs
replace() - MDN Web Docs
CoffeeScript, TypeScript e JavaScript
Comment: Deu certo, muito obrigado :D
Comment: @DallingtonAugusto considere marcar como *Aceita* :D
Answer: posso te recomendar que ao invés de você recusar o plugin de máscaras em jquery, você a use porém adaptando-a ao javascript puro, ficará mais fácil e compatível com seu web, e também te ajudará a criar mais máscaras.
Answer: Sem uma jQuery,você vai precisar fazer tudo na mão, o que é muito mais complicado... Mas você pode usar o onKeyPress pra contar os dígitos durante a digitação:
<input type="text" onkeypress="mascara()">

e a função:
var count = 0;
function mascara(){
    count++;
    alert(count);
}

e depois colocar um if pra quando atingirem 4 (ou 5) dígitos adicionar um "-" na frente. Acho que com Javascript puro fica mais ou menos assim:
if(count == 5){
        var digitos = document.getElementById('inputComMascara').value;
        alert(digitos);
        document.getElementById('inputComMascara').value = digitos+'-';
    }

Se for pra fazer assim, recomendo também que adicione um script para decrementar o contador caso a pessoa clique no Backspace, ou melhor ainda, ao invés do contador utilize o .lenght()
Answer: Passo a passo com javascript puro evento onkeyup.

function validaMatricula() {
    //retorna valor digitado no input
    var str = document.getElementById("matricula").value;
    //testa se há tracinho na posição permitida
    if((str.indexOf("-")==4)||(str.indexOf("-")==5)){
      //array de strings separados pelo "-" (tracinho)
      var res = str.split("-");
      //verifica se contem somente numeros
      if ((!isNaN(res[0]))&&(!isNaN(res[1]))) {
          //verifica se primeira parte contem 4 ou 5 digitos e
          //se a segunda parte contem 1 digito
          if((res[0].length==4 || res[0].length==5) && (res[1].length==1)){
            document.getElementById("testar").innerText = "Válido";
            document.getElementById('testar').style.backgroundColor = 'blue';
            document.getElementById('testar').style.color = 'white';
          }else{
            document.getElementById("testar").innerText = "Inválido";
            document.getElementById('testar').style.backgroundColor = 'red';
            document.getElementById('testar').style.color = 'yellow';
          }
     }else{
        document.getElementById("testar").innerText = "inválido";
        document.getElementById('testar').style.backgroundColor = 'red';
        document.getElementById('testar').style.color = 'yellow';
    }

  }else{
      document.getElementById("testar").innerText = "inválido";
      document.getElementById('testar').style.backgroundColor = 'red';
      document.getElementById('testar').style.color = 'yellow';
  }

}
<input type="text" onkeyup="validaMatricula()" id="matricula" value="">
<button id="testar">Testar</button>

Passo a passo com javascript puro evento onclick.

function validaMatricula() {
    //retorna valor digitado no input
    var str = document.getElementById("matricula").value;
    //testa se há tracinho na posição permitida
    if((str.indexOf("-")==4)||(str.indexOf("-")==5)){
      //array de strings separados pelo "-" (tracinho)
      var res = str.split("-");
      //verifica se contem somente numeros
      if ((!isNaN(res[0]))&&(!isNaN(res[1]))) {
          //verifica se primeira parte contem 4 ou 5 digitos e
          //se a segunda parte contem 1 digito
          if((res[0].length==4 || res[0].length==5) && (res[1].length==1)){
            document.getElementById("testar").innerText = "Válido";
            document.getElementById('testar').style.backgroundColor = 'blue';
            document.getElementById('testar').style.color = 'white';
          }else{
            document.getElementById("testar").innerText = "Inválido";
            document.getElementById('testar').style.backgroundColor = 'red';
            document.getElementById('testar').style.color = 'yellow';
          }
     }else{
        document.getElementById("testar").innerText = "inválido";
        document.getElementById('testar').style.backgroundColor = 'red';
        document.getElementById('testar').style.color = 'yellow';
    }

  }else{
      document.getElementById("testar").innerText = "inválido";
      document.getElementById('testar').style.backgroundColor = 'red';
      document.getElementById('testar').style.color = 'yellow';
  }

}
<input type="text" id="matricula" value="">
<button id="testar" onclick="validaMatricula()">Testar</button>

Máscara de Input


Webform component weight within a Fieldset

Question: I am creating a settings page for a specific Webform in version 6.x-3.x which finds all select option components in the form and creates a numeric textfield setting correlating to each select option. The Select Options are in fieldsets. On the settings page, I want the numeric textfields to show up in the same order that the select options show up in the form.
db_querying the right select options in the webform_component table is working fine, but the select options show up out of order when ordering by weight.
For example:
The Webform
Fieldset 1
- Textfield 1
- Select Option 1
- Select Option 2
Fieldset 2
- Select Option 3
- Select Option 4

db_query('SELECT * FROM drupal_webform_component WHERE TYPE = "select" AND nid=123 ORDER BY weight'); generates results like this:
Select Option 1
Select Option 3
Select Option 4
Select Option 2

How do I order Webform results of components within fieldsets to reflect the order they appear on the form? What would the db_query look like?
Answer: Ok, there is a column pid in webform_components for individual components. This value correlates with the cid of the fieldset. A LEFT OUTER JOIN between the cid and pid columns, filtered by the webform node id - nid, then ordered by the fieldset weight followed by the select option weight returns the components in the correct order as they appear on the node form. Here is the db_query statement.
db_query('SELECT *
FROM webform_component AS f
LEFT OUTER JOIN webform_component AS s ON f.cid = s.pid
WHERE f.nid = 123 AND s.nid = 123 AND f.type = "fieldset" AND s.type = "select"
ORDER BY f.weight, s.weight');

This works. Any advice on optimizing this query is appreciated.


nginx sometimes gets killed after reloading it using systemd

Question: After upgrading my Ubuntu server to 20.04 from 18.04 the nginx started with strange behaviour. It dies randomly on systemctl reload nginx and complains that there is already process listening on given ports. Before I'm able to run portmap or something similar I'm already able to start nginx using systemctl start nginx with no problems so I think the problem is nginx is trying to bind to ports which are already taken by the old nginx being reloaded.
I haven't tried much because I'm lost. I've checked that the /run/nginx.pid contains correct pid. There is docker on my server so I thought maybe some container starts trying to bind 80 or 443 but no. The only mapped port for docker is 8090.
Versions:
nginx -v
nginx version: nginx/1.18.0 (Ubuntu)

cat /etc/os-release
VERSION="20.04.1 LTS (Focal Fossa)"
PRETTY_NAME="Ubuntu 20.04.1 LTS"
VERSION_ID="20.04"
...

Configuration files are valid:
nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

All ports nginx binds to are the same it complains about in the journal log:
cat /etc/nginx/sites-enabled/* | grep listen | uniq
listen 80 default_server;
listen 127.0.0.1:8080;
listen 443 ssl http2;
listen [::]:443 ssl http2;

Do you have any idea why nginx would die on reload? What more can I check?
Logs produced
dmesg
[31326.529427] traps: nginx[746] general protection fault ip:7f5f8cadc593 sp:7ffd350738d0 error:0 in libperl.so.5.30.0[7f5f8ca74000+166000]
[31408.549262] traps: nginx[26366] general protection fault ip:7efda22e8593 sp:7ffda51c0bd0 error:0 in libperl.so.5.30.0[7efda2280000+166000]
[32103.236557] nginx[26433]: segfault at 3d1 ip 00007efe600ce5c9 sp 00007ffead1b3210 error 4 in libperl.so.5.30.0[7efe60066000+166000]
[32103.236566] Code: 00 0f b6 40 30 49 c1 ed 03 49 29 c5 0f 84 17 01 00 00 48 8b 76 10 48 8b 52 10 4c 8d 3c fe 4c 8d 0c c2 84 c9 0f 84 c7 02 00 00 <49> 83 39 00 0f 85 ad 03 00 00 49 83 c1 08 49 83 ed 01 49 8d 74 1d
[32676.779937] nginx[31927]: segfault at 10 ip 00007f7550de2593 sp 00007ffce0bf4cd0 error 4 in libperl.so.5.30.0[7f7550d7a000+166000]
[32676.779952] Code: 48 89 43 10 48 83 c4 18 5b 5d 41 5c 41 5d 41 5e 41 5f c3 0f 1f 40 00 0f b6 7f 30 48 c1 e8 03 48 29 f8 48 89 c3 74 89 48 8b 02 <4c> 8b 68 10 4d 85 ed 0f 84 28 01 00 00 0f b6 40 30 49 c1 ed 03 49
[33337.193774] traps: nginx[32415] general protection fault ip:7f195aa5e593 sp:7ffca566bad0 error:0 in libperl.so.5.30.0[7f195a9f6000+166000]
[40155.333210] nginx[39879]: segfault at 41 ip 00007fe42f53c593 sp 00007ffe812e18f0 error 4 in libperl.so.5.30.0[7fe42f4d4000+166000]
[40155.333219] Code: 48 89 43 10 48 83 c4 18 5b 5d 41 5c 41 5d 41 5e 41 5f c3 0f 1f 40 00 0f b6 7f 30 48 c1 e8 03 48 29 f8 48 89 c3 74 89 48 8b 02 <4c> 8b 68 10 4d 85 ed 0f 84 28 01 00 00 0f b6 40 30 49 c1 ed 03 49

Journal
Oct 28 01:32:24 fooServer systemd[1]: Starting A high performance web server and a reverse proxy server...
Oct 28 01:32:25 fooServer systemd[1]: Started A high performance web server and a reverse proxy server.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Main process exited, code=killed, status=11/SEGV
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 587 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2048 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2049 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2050 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2051 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2052 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2053 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2054 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2055 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 587 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2048 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2049 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2050 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2051 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2052 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2053 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2054 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Killing process 2055 (nginx) with signal SIGKILL.
Oct 28 01:35:05 fooServer systemd[1]: nginx.service: Failed with result 'signal'.
Nov 02 05:32:05 fooServer systemd[1]: Starting A high performance web server and a reverse proxy server...
Nov 02 05:32:05 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:05 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:05 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:05 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:05 fooServer nginx[415078]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:06 fooServer nginx[415078]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:07 fooServer nginx[415078]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:08 fooServer nginx[415078]: nginx: [emerg] still could not bind()
Nov 02 05:32:08 fooServer systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE
Nov 02 05:32:08 fooServer systemd[1]: nginx.service: Failed with result 'exit-code'.
Nov 02 05:32:08 fooServer systemd[1]: Failed to start A high performance web server and a reverse proxy server.
Nov 02 05:32:17 fooServer systemd[1]: Starting A high performance web server and a reverse proxy server...
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:17 fooServer nginx[415100]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:18 fooServer nginx[415100]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:19 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Nov 02 05:32:19 fooServer nginx[415100]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
Nov 02 05:32:19 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Nov 02 05:32:19 fooServer nginx[415100]: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
Nov 02 05:32:19 fooServer nginx[415100]: nginx: [emerg] bind() to 127.0.0.1:8080 failed (98: Address already in use)
Nov 02 05:32:19 fooServer nginx[415100]: nginx: [emerg] still could not bind()
Nov 02 05:32:19 fooServer systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE
Nov 02 05:32:19 fooServer systemd[1]: nginx.service: Failed with result 'exit-code'.
Nov 02 05:32:19 fooServer systemd[1]: Failed to start A high performance web server and a reverse proxy server.

/var/log/nginx/error.log:
2020/11/02 21:49:38 [info] 25842#25842: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 21:49:40 [notice] 25846#25846: signal process started
2020/11/02 21:51:09 [notice] 26353#26353: signal process started
2020/11/02 21:51:19 [info] 26357#26357: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 21:51:28 [info] 26364#26364: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 21:52:31 [notice] 26406#26406: signal process started
2020/11/02 21:52:31 [notice] 26418#26418: signal process started
2020/11/02 21:52:38 [info] 26431#26431: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 21:58:54 [info] 26584#26584: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 21:58:57 [notice] 26589#26589: signal process started
2020/11/02 22:04:04 [info] 31847#31847: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 22:04:06 [notice] 31855#31855: signal process started
2020/11/02 22:06:05 [info] 31925#31925: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 22:12:39 [notice] 32321#32321: signal process started
2020/11/02 22:13:40 [notice] 32392#32392: signal process started
2020/11/02 22:13:53 [info] 32413#32413: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74
2020/11/02 22:24:13 [notice] 39657#39657: signal process started
2020/11/02 22:24:40 [notice] 39837#39837: signal process started
2020/11/02 22:24:45 [info] 39870#39870: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:74

Configuration
/etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;
    client_max_body_size 1G;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_session_timeout 1d;
    ssl_session_cache shared:MozSSL:10m;  # about 40000 sessions
    ssl_session_tickets off;

    # curl https://ssl-config.mozilla.org/ffdhe2048.txt > /path/to/dhparam.pem
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;

    # intermediate configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # HSTS (ngx_http_headers_module is required) (63072000 seconds)
    add_header Strict-Transport-Security "max-age=63072000" always;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

most of my /etc/nginx/sites-enabled/*.conf looks like this one:
  listen 443 ssl http2;
  server_name example.com;

  root /var/www/public;

  include fpm7.3.conf; # includes fastcgi_pass to php-fpm for *.php files

  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
  ssl_trusted_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

  error_log /var/log/nginx/example.com.error.log;
  access_log /var/log/nginx/example.com.access.log;
}

Comment: @MichaelHampton the problem is already reported, thanks for showing me the `dmesg` command. I've updated the question with the `dmesg` log. bug report - https://bugs.launchpad.net/ubuntu/+source/perl/+bug/1897561/
Answer: You've run into a bug in perl 5.30, the version used in Ubuntu 20.04 LTS. The bug has been fixed upstream but that fix has not yet been backported to Ubuntu.
If you haven't got a need to run Perl code inside nginx (as most people do not) then you can uninstall the package libnginx-mod-http-perl and restart nginx to avoid the problem. This package was pulled in by the virtual package nginx-extras but most people don't actually run perl in the web server and so don't need it.
ubuntu@vmtest-ubuntu2004:~$ sudo apt purge libnginx-mod-http-perl
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libhiredis0.14 libluajit-5.1-2 libluajit-5.1-common
  libnginx-mod-http-auth-pam libnginx-mod-http-cache-purge
  libnginx-mod-http-dav-ext libnginx-mod-http-echo
  libnginx-mod-http-fancyindex libnginx-mod-http-geoip
  libnginx-mod-http-geoip2 libnginx-mod-http-headers-more-filter
  libnginx-mod-http-lua libnginx-mod-http-ndk libnginx-mod-http-subs-filter
  libnginx-mod-http-uploadprogress libnginx-mod-http-upstream-fair
  libnginx-mod-nchan
Use 'apt autoremove' to remove them.
The following additional packages will be installed:
  nginx-core
Suggested packages:
  nginx-doc
The following packages will be REMOVED:
  libnginx-mod-http-perl* nginx-extras*
The following NEW packages will be installed:
  nginx-core
0 upgraded, 1 newly installed, 2 to remove and 0 not upgraded.
Need to get 425 kB of archives.
After this operation, 173 kB disk space will be freed.
Do you want to continue? [Y/n]

ubuntu@vmtest-ubuntu2004:~$ sudo systemctl restart nginx

Though in this specific case, nginx has probably gone zombie and you will have to restart the computer.
As shown above, removing it will replace nginx-extras with nginx-core, and mark all the extras packages as eligible for autoremoval, so if you actually need any of those packages you should mark them as installed before autoremoving.
ubuntu@vmtest-ubuntu2004:~$ sudo apt-mark install libnginx-mod-http-geoip2
Selected libnginx-mod-http-geoip2 for installation.

You can also follow the issue on Launchpad.
Comment: I knew it was a problem with 20.04 LTS. I had this problem as well and it never occurred in my life before I tried to run 20.04lts. Shame that this happens tho, lts suppose to be stable AFAIK.
Comment: @sed What should worry you is that the ubuntu maintainers are just sitting there and doing nothing about it despite having a patch available that they could backport.
Comment: I was wondering why only one server was affected. This one is running since release of 18.04 and I got used to install `nginx-extras` because it was standard at company I worked at. All other servers I manage have been set later and use`nginx` package. I've swapped `nginx-extras` for `nginx` and reload works now!
Comment: Does anyone know the easiest way to replace this with version 5.30.2 or whichever is the latest 5.30.x version? Do I have to create my own, unofficial libnginx-mod-http-perl?
Answer: If removing libnginx-mod-http-perl is not an option for you the next best workaround is to configure systemd to auto-restart nginx on failure.
This is rather simple to accomplish:
Create directory /etc/systemd/system/nginx.service.d/
Create file /etc/systemd/system/nginx.service.d/override.conf with the following contents:
[Unit]
StartLimitIntervalSec=500
StartLimitBurst=5

[Service]
Restart=on-failure
RestartSec=5s

Run systemctl daemon-reload
Restart nginx systemctl restart nginx.service
In my experience Nginx usually crashes after the 2nd reload. If that happens now systemd will start Nginx five seconds after it fails.
You can customize the settings to your needs:
StartLimitBurst defines how many times in a row systemd will attempt to start Nginx after it fails.
StartLimitIntervalSec defines how much time must pass before it will try restarting again.
RestartSec defines how long to wait after Nginx fails before trying to start it.
Answer: If removing libnginx-mod-http-perl is not an option for you the next best workaround is to disable perl module.
mkdir /etc/nginx/_modules-disabled
mv /etc/nginx/modules-enabled/50-mod-http-perl.conf /etc/nginx/_modules-disabled/

And restart nginx gracefully
mkdir /root/tools/
touch /root/tools/nginx_restart.sh
chmod +x /root/tools/nginx_restart.sh
nano /root/tools/nginx_restart.sh

#!/bin/bash

for command in quit stop; do
  if ps aux | grep -v 'grep ' | grep -v "${0}" | grep -q nginx; then
    echo;
    echo "nginx -s $command";
    nginx -s $command;
    for (( i=1 ; i <= 300 ; i=((i+1)) )); do
      sleep 1;
      echo -n ".";
      if ! ps aux | grep -v 'grep ' | grep -v "${0}" | grep -q nginx; then
        break 2;
      fi;
    done;
  fi;
done;

echo;
sleep 1;

if ! ps aux | grep -v 'grep ' | grep -v "${0}" | grep -q nginx; then
  /etc/init.d/nginx start;
  sleep 1;
fi;

/etc/init.d/nginx status;

/root/tools/nginx_restart.sh


Continuous distribution - expected value

Question: Is it true that for continuous distribution $$E(X^a) =  \int_{-\infty}^{+\infty} x^a\cdot g(x)dx $$ where $g(x)$ is probability density function?
Answer: Yes. This is called the Law of the Unconscious Statistician on Wikipedia. (I don't know where the name comes from exactly, and didn't learn it with a name.) Essentially it states that
$$
E[g(X)] = \int_{-\infty}^\infty g(x) f(x) dx
$$
where $f(x)$ is the probability density function of $X$. So in your case, since $g(X) = X^{\alpha}$, you get
$$
E[X^\alpha] = \int_{-\infty}^\infty x^\alpha f(x) dx.
$$
This is probably more than you wanted to know, but it's handy and will be useful if you ever deal with more complicated functions $g(X)$.
Comment: But the Law has a beautiful acronym LOTUS....    There is also a minor issue about whether or not the _improper_ integral exists or works out to be the undefined form $\infty - \infty$ which is also likely more than the OP wants to know.
Comment: That's what I thought, but I wanted to be sure. Thank for help!
Comment: Yeah, I thought about it but decided it would be overcomplicating it to write $g(X)^+$ and $g(X)^-$ and talk about what it means for an expectation to exist. At this rate we'll end up starting from measure theory.
Answer: I think that that is true by definition.
Comment: The formal definition of the expectation is often quite different
Answer: Doesn't this result follow from the definition of expectation itself? For example the expectation of a function $g(X)$ is the value multiplied by probability of getting that value which is the same as the probability of getting $X=x$ which in turn is just the probability density function $f(x)$ of $X$. The integration between the $-\infty$ and $+\infty$ is to cover for all possible values of $x$.
Comment: For a continuous random variable $X$, for every $x$, the probability that $X=x$ is exactly zero, and not $f(x)$ (except for the values $x$ such that $f(x)=0$, of course).
Comment: If the expected value of $X$ is _defined_ as $$E[X] = \int_{-\infty}^{\infty} x f_X(x)\,\mathrm dx$$ for continuous random variables that have a density function (whenever the integral exists, etc.: I am aware that there are more general as well as different definitions of expectation), then, if $h(X)$ is considered as a random variable $Y$, we have $$E[Y]=\int_{-\infty}^\infty yf_Y(y)\,\mathrm dy$$ while the result asked about says $$E[Y]=E[h(X)]=\int_{-\infty}^\infty h(x)f_X(x)\,\mathrm dx.$$ We need a _theorem_ to say that both calculations give at the same result, and this theorem is LOTUS


Can I use my hand to hit the ball on table tennis?

Question: I've read in somebody's comment in another question:

USA Table Tennis rules:
  2.5.7 A player strikes the ball if s/he
  touches it in play with his/her racket, held in the hand, or with
  his/her racket hand below the wrist.
  2.5.8 A player obstructs the ball
  if s/he, or anything s/he wears or carries, touches it in play when it
  is above or traveling towards the playing surface, not having touched
  his/her court since last being struck by the opponent.

Does that mean that I can use my hand to hit the ball?
But only my racket hand?
Does that mean that when you miss the ball with the racket, but actually hits it with a finger or something, it's still a valid play?
Does that tell me that it's illegal to hit the ball with my free hand?
Please, don't base your answers on the interpretation of that snippet alone, maybe there are varations of this rule in other countries, for instance.
Answer: Yes, you can use your hand to hit the ball, but only if it is your racket hand and below the wrist. A quote of the rules state:

It is considered legal to hit the ball with your fingers, or with your racket hand below the wrist, or even any part of the bat.(Law 2.5.7) This means that you could quite legally return the ball by:

hitting it with the back of your racket hand;
hitting it with the edge of the bat, instead of the rubber;
hitting it with the handle of the bat.

A proviso includes - Your hand is only your racket hand if it is holding the racket, so this means you can't drop your bat and then hit the ball with your hand, because your hand is no longer your racket hand
It is illegal to hit the ball with your free hand.
There is a good summary of the rules here.
Comment: Close. It's illegal to strike the ball with the side of the racket: `2.10.1 - Unless the rally is a let, a player shall score a point [..] if an opponent strikes the ball with a side of the racket blade whose surface does not comply with the requirements of 2.4.3, 2.4.4 and 2.4.5`. Sections 2.4.3-2.4.5 describe the rubber surfaces of the racket.


How to add a filter in view with list of values

Question: I have a content type which has a Number(Integer) field.
I created a view. I would like to expose the price field as a filter to the public like the following with a list of price range.

In view > filter criteria, I added the price field. How to add the list of values with price range?
Answer: To add a list of ranges you can use the Grouped filters option with Widget Type: Select, instead of Single filter.

Then you can add your groups below. Each group becomes an option in your select list.
Comment: Thank you! It worked. I like to hide the label from the filters. How to set "Price Range" as the placeholder for the price field?
Comment: I believe you would have to use a form alter for that. Here's a reference: https://www.drupal.org/forum/support/theme-development/2012-06-28/add-html-5-placeholder-in-views-exposed-filter


Difference between $.ajax and $.post

Question: $.post( url, data, callback, type );
$.ajax ()

Could i know the difference between $.post and $.ajax. Which is preferable and how many parameters could we pass to $.ajax.
Comment: I would suggest you read the documentation ([$.ajax()](http://api.jquery.com/jQuery.ajax/), [$.post()](http://api.jquery.com/jQuery.post/)).
Comment: You forgot to put `$.get()` in the question too.
Answer: They are very similar (except by default $.ajax uses type=get, you have to change it to type=post).  You have a little more control over stuff with $.ajax, but $.post is a little simpler.  Think of $.post as a short-hand way of doing an AJAX POST.
For more information about $.ajax see: http://api.jquery.com/jQuery.ajax/
More information about $.post see: http://api.jquery.com/jQuery.post/

Difference between $.ajax and $.post


Is there a creative way to pass in multiple arguments to contentEquals() method?

Question: As I understand, the contentEquals() method only accepts one argument to be compared with.
In the following program, what if I wanted to pass in more?
like:
(1)YES
(2)Yes
(3)Y
(4)y
import java.util.Scanner;

public class ifStatement1 {

    public static void main(String[]  args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Want some pizza?");

        String userInput = input.nextLine();

        boolean answer = **userInput.contentEquals("yes");**

        if(answer) {
            System.out.println("so go take a break from all this code");
        }
        else {
            System.out.println("so keep writing code");
        }

    }

 }

Comment: Can you expand a bit? Are you defining the `contentEquals` method?
Comment: Not sure what you mean; I declare a boolean and assign it via a comparison of the userInput and contentsEquals("yes").
Answer:  Set.of("YES", "Yes", "Y", "y").contains(userInput)

String.equals would be more normal than using String.contentEquals with a String.
Comment: Piggybacking off of this, you can also reduce the amount of items you need in the Set by doing something like `Set.of("yes", "y").contains(userInput.toLowerCase());` then it can be any combination of different casing.
Answer: import java.util.Scanner;
import java.util.Set;

public class example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String userInput = scanner.nextLine();
        boolean answer;
        if(Set.of("yes","y").contains(userInput.toLowerCase())){
            answer = true;
        } else {
            answer = false;
        }
        System.out.print(answer);
    }
}


Entity framework always returning Id 1 when adding contact?

Question: I created a test and it kind of works when I save an object, the problem is that the creation of an object always returns the Id = 1 no matter how many insertions I make, so when I set that same variable as the id it goes and grabs the first one in the table instead of the just inserted one, here is the code:
using (DbContextTransaction tx = this.Context.Database.BeginTransaction())
{
    CustomPerson con = new CustomPerson();
    con.Name = "John";
    con.LastName = "Smith";

    this.Context.CustomPersons.Add(con);

    //here tempId it's always 1 (why), but it inserts the record with a different id
    long tempId= this.Context.SaveChanges();

    CustomPerson newPerson = (CustomPerson)this.Context.CustomPersons.Find(tempId);
    Assert.AreEqual(newPerson.Name, con.Name);
    tx.Commit();
}

And with this it will go and retrieve the record at position 1 in the table, instead of the newly created one in the table which is a value greater than 1 always.
Answer: The MSDN documentation for DbContext.SaveChanges says:

Return Value
Type: System.Int32
The number of objects written to the underlying database.

It's not the ID of the record.  It's the number of records.  That should have been obvious because what if you had added more than one entity before saving?  How could you get IDs for all of them?  You're always saving one record so you get the value 1 returned.
If you want the ID of the entity then you have to get the value from the appropriate property after saving it.
Comment: aha.. that's what i was missing.. hmm i understand. Thanks a lot! (first pass at entity framework :) ).
Comment: If ever something doesn't work the way you expect, READ THE DOCUMENTATION.  The fact that this is your first experience with EF makes that even more important.  I can't imagine how many man hours was spent writing the MSDN Library reference documentation and it's simply ignored by so many people.  If you are using a particular method or type and haven't read its documentation then posting a question here is premature.
Comment: You are right, i did read but missed the number of objects part.. Thank you!, i had a lot done today and my eyes are tired. I accept the reprimand respectfully.
Answer: After saving new customer, the Id property of CustomPerson will set by EF and Context.SaveChanges returns number of inserted records.


Captcha value different with session user data

Question: I'm trying to create captcha, the image is shown as expected, but when i pass into controller why the string that i input is different with session user data that i set in earlier.
PFB my code.
View.
<?php echo $captcha_img;?>
            <input type="text" id="captcha" name="captcha" placeholder="Input Code Above">
            <?php echo form_error('captcha', '
', '
');?>

Controller (config)
public function captcha_config() {
        $vals = array(
                'img_path' => './assets/files/captcha/',
                'img_url' => base_url().'assets/files/captcha/',
                'img_width' => 150,
                'img_height' => 30
            );
            $cap = create_captcha($vals);
            $image = $cap['image'];
            $this->session->set_userdata('capt',$cap['word']);
            //$data['captcha_img'] = $cap['image'];

            return $image;
    }

Controller (Index)
public function index() {
        if ($this->session->userdata('login') == TRUE)
        {
            redirect('Buser');
        }
        else
        {
            $data['title'] = 'Dashboard';
            $data['subtitle'] = 'Log In';

            $this->captcha_config();
            $data['captcha_img'] = $this->captcha_config();

            $this->load->view('Backend/login', $data);
        }

Controller (Process)
public function process_login() {
        $data['title'] = 'Dashboard';
        $data['subtitle'] = 'Log In';
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');
        $this->form_validation->set_rules('captcha', 'Captcha', 'required' );

        $this->captcha_config();
        $data['captcha_img'] = $this->captcha_config();

        if ($this->form_validation->run() == TRUE)
        {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $captcha  = $this->input->post('captcha');

            echo $captcha;
            echo "
";
            echo $this->session->userdata('capt');
    }
}

result:
Drd27VZE <--- this one is the captcha
VzU90odU <--- this one is the session user data 'capt'

I've been trying using with separate code (example that i got from google) it works, but i don't know why it's not working with this code.
Answer: you can create a captcha function in helper
Helper
function generate_captcha()
{
    $options = array(
        'img_path'  => 'img/captcha/',
        'img_url'   => base_url().'img/captcha/',
        'img_width' => '150',
        'img_height'=> '50',
        'expiration'=> 3600,
        'word'      => generate_random_password(4)
    );

    return create_captcha($options);
}

function generate_random_password( $max_length = 8 )
{
    $pass = '';

    $dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    $dict_size = strlen($dict);

    for($i = 0;$i<$max_length;$i++){
        $pass .= $dict[rand(0,$dict_size-1)];
    }

    return strtoupper($pass);
}

In your view, you call a generate_captcha if the user put a wrong user ou pass
<?php if( ! empty( $attempts_number ) && ((int)$attempts_number >= 3) ) { ?>
    <?php $captcha = generate_captcha(); ?>
    <?php $this->session->set_userdata(array(
        'captchaword'       => $captcha['word']
    )); ?>

    <?php echo $captcha['image']; ?>

    <?php echo $this->lang->line('captcha_text'); ?>:
    <?php echo form_input(array('class'=>'required','maxlength'=>4,'name'=>'captcha'));?>
<?php } ?>

Answer: Finally i solve my problem,
problem when i create function for captcha i don't have to call again in the process function
public function process_login() {
        $data['title'] = 'Dashboard';
        $data['subtitle'] = 'Log In';
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');
        $this->form_validation->set_rules('captcha', 'Captcha', 'required' );

        **$this->captcha_config();                        <---- I Remove this one
        $data['captcha_img'] = $this->captcha_config(); <---- and also remove this one**

        if ($this->form_validation->run() == TRUE)
        {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $captcha  = $this->input->post('captcha');

            echo $captcha;
            echo "
";
            echo $this->session->userdata('capt');
    }
}


How to assign multiple pools to single virtual server [VIP] in F5

Question: I have a requirement in F5 where i have to configure multiple pools and all pools will be using Single virtual server [1 VIP] to receive traffic from outside world. I am trying to figure out any specific configuration is required which i am missing to achieved this goal. As of now my F5 config is working when i assign default pool to virtual server , since i have to use 1 VIP with multiple clients hosted on it so i am stuck at this point. can someone help me here.
Comment: Did my answer help you at all? Did you need more information, please let me know
Answer: Dexirian is correct above - but I think this more correctly answers based on your need for multiple pools due to multiple clients:
when HTTP_REQUEST {
    switch -glob [string tolower [HTTP::uri]] {
        "/123*" {
            HTTP::uri "/"
            pool pool_123
        }
        "/456*" {
            HTTP::uri "/"
            pool pool_456
        }
        "/789*" {
            HTTP::uri "/"
            pool pool_789
        }
    }
}

Answer: You're going to need to use iRules in order to have multiple pools on a single VIP.
See relevant documentation here
The thing you have to think about now is how to select which pool to use. You could check the host or URI values as follow :
when HTTP_REQUEST {
  if { [HTTP::uri] contains "blabla"} {
    pool "Your pool name here"
 }
}

Please let me know if you need more information, am quite familiar with F5 iRules ;)
Comment: irule is one solution to it agreed. This will create problem in near future when we create 100s of pools and every time we have to update irule. I have used host based irule to route the traffic , any idea if we can write common irule across the platform to serve the purpose or any specific config we can do to achieve this.
Answer: Assuming you are switching pool by application name (read: fqdn) then you could name your pools appropriately and the iRule could be generic:
when HTTP_REQUEST {
  if { [catch {pool [HTTP::host]}] } {
    log local0. "error - pool [HTTP::host] does not exist"
    # Set pool to default since HTTP::host did not match existing pool
    pool [LB::server pool]
  }
}


ASP NET MVC 3: Form doesn't POST due to a required hidden field

Question: I want to submit a form, but the button isn't clickable. After some search I found out that this is due to the jquery validation that ASP.NET MVC has for required fields.
For some weird reason ASP NET thinks my hidden field "UserId" is required. Which isn't actually true. See part of my model here:
   public class ResetPasswordModel
   {

        [.....]

     public Guid UserId
     {
       get;
       set;
     }

   }

And the page source shows this:
<input data-val="true" data-val-required="The UserId field is required." id="UserId" name="UserId" type="hidden" value="" />

Any ideas?!?
Comment: Could you post the UserId property code with it's attributes.
Answer: The fact it's not a nullable type means it's required. Change the definition to Guid? (include the question mark to make it nullable) Or even better create a viewmodel that doesn't have it.
Answer: I believe that a Guid is required by default because it is not nullable.   Guids are usually primary keys so making them nullable is problematic.  Try converting your guid ToString() so that you can use it in your view, then back to a Guid before using it in your controller or model.  You may have to create a ViewModel in order to do this.
Answer: Are you sure there isn't a separate partial class containing MetaData which has marked the field as mandatory?
Something like this:
class UserResetPasswordModelMetaData
{
    [Required(ErrorMessage = "The UserId field is required.")]
    public Guid UserId { get; set; }
}

Search your project for the string "The UserId field is required". I bet it's there somewhere.
Also, how do you identify the user who is trying to reset their password, if not by their id?
Comment: Dear God. I'm so sorry for my post. I just saw that I wasn't rendering my model to the view... ah, I can't believe it!!!!!!! ...
Comment: +1 for honesty. Lol! I did wonder! I appreciate your candour. I guess mine is the right answer then... ahem ;-)
Comment: I'm not sure what you mean by the seperate class. This is the page that was emailed to the specific user so I already have his id and I just want to pass it to my post action, that's why I have this hidden field.
Comment: Yeah, based on the code that was provided in the question it doesnt appear to me that the UserID field would be required. There is no meta markup for it. Are you using Html.HiddeFor in your view? Have you set the value of UserID in your view model before rendering it out to the page?
Answer: setup the jQuery validator to ignore hidden fields.  Like so:
jQuery Validate Ignore elements with style
Answer: Probably There is a Key attribute on top of UserId property which means it's mandatory


Compute center-of-mass in numpy

Question: I am looking for an efficient way to compute the center-of-mass of a 2D numpy array using native python and numpy. (scipy.ndimage.measurements.center_of_mass does the job, but I can only use numpy)
# sample data
a = np.array([[0, 0, 0],
              [0, 4, 4],
              [0, 0, 0]])

center_of_mass(a)
>>> (1., 1.5) # expected output

Comment: Please share a sample data and expected output
Answer: The center of mass is sum(mi * xi)/m, sum(mi * yi)/m where mi are the masses (= elements of the array) and xi, yi are the coordinates (indices of the array). m is the total mass, i.e. sum(mi).
Example for a = np.array([[0,1,2],[3,4,5]]):
mi*xi and mi*yi we get from multiplying the masses (i.e. the array) with a coordinate grid obtained from mgrid:
a * np.mgrid[0:a.shape[0], 0:a.shape[1]]

which gives
array([[[ 0,  0,  0],
        [ 3,  4,  5]],

       [[ 0,  1,  4],
        [ 0,  4, 10]]])

where the upper part is mi*yi and the lower part is mi*xi, whose sums are
(a * np.mgrid[0:a.shape[0], 0:a.shape[1]]).sum(1).sum(1)

which gives array([12, 19]).
Dividing this by the total sum a.sum() we get the final result of array([0.8, 1.26666667]).
So putting it all toghether we have:
(a * np.mgrid[0:a.shape[0], 0:a.shape[1]]).sum(1).sum(1)/a.sum()

Scipy does the same but uses an open grid and broadcasting instead of the full (dense) grid and is therefore faster for larger arrays because it doen't need to allocate memory for the indermediate results.
Answer: (scipy.ndimage.measurements.center_of_mass does the job, but I can only use numpy)
Then it sound like time to read the source. After reading it, for me its looks like it should work with your limitation (only use numpy) as it apparently uses solely python built-ins and numpy. Replacement sum using numpy.sum is required.
EDIT: Added note of replacing sum according to comment by @Ricoter.
Comment: Thanks I should have done that! (PS. it uses `scipy.sum` which is different from pythons `sum` but can be replaced by `numpy.sum`)
Answer: A less expensive solution wrt. memory and computational time using matrix multiplication:
import numpy as np

def center_of_mass(array: np.ndarray):
    total = array.sum()
    # alternatively with np.arange as well
    x_coord = (array.sum(axis=1) @ range(array.shape[0])) / total
    y_coord = (array.sum(axis=0) @ range(array.shape[1])) / total
    return x_coord, y_coord

a = np.asarray([[0, 0, 0],
                [0, 4, 4],
                [0, 0, 0]])

b = np.asarray([[0, 1, 2],
                [3, 4, 5]])

print(center_of_mass(a)) # (1.0, 1.5)
print(center_of_mass(b)) # (0.8, 1.2666666666666666)

Compute center-of-mass in numpy


Notation on Set Theory

Question: I am reading Naive Set Theory.
On Section 3 (Unordered Pairs), page 11, it is written that:

As further examples, we note that
  $$\{x:x\neq x\} = \varnothing$$
  and
  $$\{x:x= a\} = \{a\}.$$
  In case $S(x)$ is $(x \in' x)$, or in case $S(x)$ is $(x=x)$, the specified $x$'s do not constitute a set.

The last sentence is not clear to me. Is it because, if $S(x)$ is $(x=x)$, this denotes the set with whichever $x$ I can imagine? But what happens in the first case, i.e. if $S(x)$ is $(x \notin x)$?
Comment: Have you ever heard of Russel's Paradox?
Answer: Let's say that $A=\{x: x\notin x\}$ is a set.
Then, is $A\in A$ a true statement? How about $A\notin A$?
Comment: If $A \in A$ then $A \notin A$, if $A \notin A$ then $A \in A$. So should I conclude that it is impossible to create a set with this $S(x)$?
Comment: @fbrundu Indeed. The premise must be wrong, and the only premise was that $A$ is a set.
Answer: That complication is a part of what I should call non-naive set theory. The reason these doesn't constitute sets is to avoid Russel's paradox.
We simply has to put restrictions in order to avoid statements similar to "this statement is false".
It's obvious how one could formulate such a statement if we allowed a set like $A = \{x: x\notin x\}$, since then $A\in A$ would be such a statement.

Notation on Set Theory


Replicação de Frame [Erro: Component already exists]

Question: Tenho um form no delphi e queria que ao clicar em um botão um frame pré criado fosse adicionado dinamicamente várias vezes. Estou tentando através desse código:
procedure TMain.Button1Click(Sender: TObject);
var i:integer; frame:TFrame;
begin

  for i:=0 to 5 do
    begin
      frame := Tframe.create(self);
      with frame do
        begin
        parent:= self;
        left:= 376 + (i*220);
        top:= 136 + (i*332);
        end;
    end;

end;

Ao executar sou notificado do seguinte erro:

"A component named Frame already exists"

Já procurei em vários sites e não acho a solução desse problema.
Achei uma questão quase idêntica nesse link mas sem solução.
Comment: Seu código funciona perfeitamente aqui. tem algo a mais no seu código ?
Answer: Uma solução simples é colocar um nome para cada frame criado. Fica assim:
procedure TMain.Button1Click(Sender: TObject);
var
    i:integer;
    frame:TFrame;
begin
    for i := 0 to 5 do
    begin
        frame := Tframe.create(self);
        frame.name := 'MeuFrame' + IntToStr(i);
        with frame do
        begin
            parent:= self;
            left:= 376 + (i*220);
            top:= 136 + (i*332);
        end;
    end;
end;

Comment: +1 bastaria o cara ter lido a mensagem de erro de retorno: JÁ EXISTE.


SELECT em 3 tabelas do banco com especificações

Question: Eu tenho três tabelas no banco, uma de empresas, outra de funcionários e outra de guias. Eu estou tentando fazer um SELECT que traga todas as empresas que tenha algum funcionário ligada a ela (existe a chave estrangeira na tabela), e que NÃO TENHA a guia HOLERITE na tabela "guias" relacionada a essa empresa.
 Tabela empresas
+--------+------+
| id     | nome |
+----------+----+
| 1      | abc  |
| 2      | hjk  |
| 3      | qwer |
| 4      | tyui |
| 5      | dfg  |
+--------+------+

 Tabela funcionários
+--------+------+-------------+
| id     | nome | empresas_id |
+----------+----+-------------+
| 1      | abc  |5            |
| 2      | hjk  |4            |
| 3      | qwer |3            |
| 4      | tyui |2            |
| 5      | dfg  |1            |
+--------+------+-------------+

     Tabela guias
+--------+----------+-------------+
| id     | tipo     | empresas_id |
+----------+--------+-------------+
| 1      | FGTS     |5            |
| 2      | INSS     |4            |
| 3      | HOLERITE |3            |
| 4      | INSS     |2            |
| 5      | FGTS     |1            |
+--------+----------+-------------+

O SELECT que eu estou fazendo é o seguinte:
SELECT
   emp.id, emp.nome_empresa
FROM
   empresas as emp
LEFT JOIN
   funcionarios as f
ON
   f.empresas_id = emp.id
LEFT JOIN
   guias as g
ON
   g.empresas_id = emp.id
WHERE
   f.empresas_id = emp.id
AND
   g.tipo <> 'HOLERITE';

Porem está trazendo mesmo as empresas que tem a guia com o tipo HOLERITE.
Obs: Uma mesma empresa pode ter vários tipos registrados na tabela, mas preciso daquelas que não tem a guia HOLERITE registrada.
Answer: Tente:
SELECT emp.id, emp.nome_empresa
FROM empresas as emp JOIN funcionarios as f
ON f.empresas_id = emp.id
WHERE NOT EXISTS (SELETC * FROM guias as g WHERE g.empresas_id = emp.id
    AND g.tipo = 'HOLERITE');

Pegue todas as empresas que tem algum funcionário e para a qual não exista a guia HOLERITE.


The largest integer dividing these $(n+19)(n+18)(n+17)(n+16)$

Question:
The largest integer that divides $(n+19)(n+18)(n+17)(n+16) ~ \forall ~ n \in \mathbb{N}? $ is?

It struck me that we should write this as:
$\dbinom{n+19}{4}\times 4!$
which is always divisible by $4!$. Now I am confused as to how do I take it from here? Because the question asks for largest positive integer.
Edit:
Is there no alternative to brute force method i.e. checking for few values then assuming the event would never occur?
Comment: Now look at a few values of $n $, and show that these products have 24 as their gcd.
Comment: For example $n=1,3,5$
Comment: Concerning your edit: checking a few gcd's is not "brute force" at all.
Answer: Let $f(n) = (n + 16)(n + 17)(n + 18)(n + 19)$.
Then we have that
$$
  \gcd(f(1), f(4), f(5)) = \gcd(17 \cdot 18 \cdot 19 \cdot 20, 20 \cdot 21 \cdot 22 \cdot 23, 21 \cdot 22 \cdot 23 \cdot 24) = \gcd(2^3 \cdot 3^2 \cdot 5 \cdot 17 \cdot 19, 2^3 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdot 23, 2^4 \cdot 3^2
 \cdot 7 \cdot 11 \cdot 23) = 2^3 \cdot 3 = 24.
$$
Thus any number that divides $f(n)$ for all $n$ can be at most $24$. You've already shown that $24$ works, so $24$ is the largest such number.

Edit: Why did I consider $n = 1$, $n = 4$, and $n = 5$ in particular?
I took $n = 1$ because it is the smallest value that $n$ is allowed to be, and I'd prefer to work with fairly small numbers.
We now continue with the conjecture that the answer should be $24$. The number $f(1)$ has $17$ and $19$ as factors, so to rule out that these factors will divide $f(n)$ for all $n$, we need to find a $n$ such that $f(n)$ is not divisible by $17$ or $19$. If $n$ is less than $4$, then we can see that one of the numebrs that we are multiplying by to get $f(n)$ is going to be $19$, (since the smallest of the four numbers is $n + 16$, we need $n + 16 > 19$), we see that any $n$ such that $f(n)$ is not divisible by $19$ must be at least $5$. In accordance with our preference for using small numbers, we consider the value of $f(5)$. The other reason that we would like to use a number that is at least $5$ is that otherwise $20$ will divide $f(n)$, and we want to rule out the possibility of $5$ dividing $f(n)$ for all $n$.
The problem we now have is that both $f(1)$ and $f(5)$ are divisible by $9$, so we need to find an $n$ such that $f(n)$ is divisible by $3$, but not by $9$. Now if $(n + 16)$ is divisible by $3$, then so is $(n + 19)$, and so to avoid having a factor of $9$, we need to consider an $n$ such that $(n + 16)$ is not divisible by $3$. This rules out $n = 2$. It turns out that $n = 3$ works, but I overlooked this for some reason and went with $n = 4$ instead.
Answer: Good start!
When $n=0$ you get $19\cdot 18\cdot 17 \cdot 16,$ so the answer must divide this. Look for examples that allow you to discard some of the factors.  For example, when $n=4$ you get $23\cdot 22\cdot 21 \cdot 20,$ so we can forget about $17$ and $19,$ and we're down to $18 \cdot 16$.  Look at some more examples to whittle it down to $24$.
Answer: This can be treated as a case of product of four consecutive natural numbers since it is $~ \forall ~ n \in \mathbb{N}$:
Suppose four consecutive natural numbers are: $2k-1$, $2k$, $2k+1$, and $2k+2$ where $k$ is some natural number $\ge 1$. Thus product of them will be:
$$(2k-1)(2k)(2k+1)(2k+2)=4k(2k-1)(2k+1)(k+1)=4k(4k^2-1)(k+1)$$
For apply it for all $n$, $k=1$ and then $$4k(4k^2-1)(k+1)=4(4-1)(1+1)=24$$
Comment: @Abcd: I kept it to reflect my mistake, but I'd delete it now. Nonetheless, I posted different answer. Thank you for your kindness. :-)