"[Error] request for member in something not a structure or union"

Question: Galera, eu to tentando fazer uma struct que recebe informações do usuário e apos isso exiba as informações. Mas está apresentando esse erro quando vou compilar '[Error] request for member in something not a structure or union".
Segue o Código...
#include <stdio.h>
#include <stdlib.h>

struct funcionario
{
    char nome[40];
    char cargo[40];
    int cpf[11];
};

cad_func[2];

int main(void) {

    int i;

    printf("INSIRA SEUS DADOS.\n\n\n");

    for(i=0; i<2; i++)
    {
        printf("nome: ");
        fflush(stdin);
        gets(cad_func[i].nome);

        printf("cargo: ");
        fflush(stdin);
        gets(cad_func[i].cargo);

        printf("cpf: ");
        scanf("%d", &cad_func[i].cpf);

    }

    printf("Dados dos funcionarios:\n\n");

    for(i=0; i<2; i++){
        printf("Nome: %s", cad_func[i].nome);
        printf("Cargo: %s", cad_func[i].cargo);
        printf("Nome: %d", cad_func[i].cpf);

    }
    return 0;
}

Obrigado!!!
Answer: Esse erro está ocorrendo, pois você não informou o tipo da variável cad_func[2].
Para corrigir isso, basta informar o tipo, que é a struct funcionario:
struct funcionario cad_func[2];

Com isso seu programa já passa a compilar e executar.


Reuse fields programmatically

Question: Conceptually and for performance purposes it is advisable to reuse existing fields in Drupal. This is very easy to do manually, but my question is, how can I do this programmatically?
I have the following code:
<code>$all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('taxonomy_term', $vid);

if (!isset($all_bundle_fields['field_image'])) {
  FieldStorageConfig::create(array(
    'field_name' => 'field_image',
    'entity_type' => 'taxonomy_term',
    'type' => 'entity_reference',
    'settings' => [
      'target_type' => 'media',
    ],
    'cardinality' => 1
  ))->save();

  FieldConfig::create(array(
    'field_name' => 'field_image',
    'entity_type' => 'taxonomy_term',
    'bundle' => $vid,
    'label' => 'Logo',
    'description' => 'Logo to represent the term.',
    'required' => FALSE,
  ))->save();
}
</code>
In this example, I extract all the fields from the vocabulary and only create the field if and only if it does not exist previously in this vocabulary. The above code works.
What does not work here is if that field has already been created for another entity or vocabulary. This is what I would like to find out in order to make a complete reuse of the fields.
Thanks in advance.
Comment: By design Drupal is reusing fields because the field storage is not bundle specific. You can check for existing field storages with `FieldStorageConfig::loadByName`. This question, for a different but related issue, contains the code  https://drupal.stackexchange.com/questions/298957/how-to-display-configuration-updates-when-deleting-fields-programatically
Answer: Until someone tells me how an existing field can be reused I have got a remedy. As my "need" was to reuse fields that I have been creating in various vocabularies, what I have done is the following:

Create a function that goes through all the existing vocabularies and checks if a certain field, passed by parameter, exists.
If so, it returns me the name of the vocabulary where it already exists. This saves me from creating the corresponding database table.
Then I check if the vocabulary where the field exists is my own vocabulary. In case it is not, I link it.

This would be the final result. First, the function:
<code>function existsField($field) {
  $vocabularies = taxonomy_vocabulary_get_names();

  foreach($vocabularies as $vocabulary) {
     $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('taxonomy_term', $vocabulary);
     if (isset($all_bundle_fields[$field])) {
        return $vocabulary;
     }
  }
}
</code>
Next, the final code:
<code>$vocabulary = existsField('field_image');

if (empty($vocabulary)) {
  FieldStorageConfig::create(array(
     'field_name' => 'field_image',
     'entity_type' => 'taxonomy_term',
     'type' => 'entity_reference',
     'settings' => [
        'target_type' => 'media',
     ],
     'cardinality' => 1
  ))->save();
}

if (empty($vocabulary) || $vocabulary != $vid) {
  FieldConfig::create(array(
     'field_name' => 'field_image',
     'entity_type' => 'taxonomy_term',
     'bundle' => $vid,
     'label' => 'Logo',
     'description' => 'Logo to represent the term.',
     'required' => FALSE,
  ))->save();
}
</code>

Reuse fields programmatically


Finding roots of a polynomial using numpy

Question: Following code will find roots of a polynomial:
import numpy as np
print("Roots of the first polynomial:")
print(np.roots([1, -2, 1]))

But i cannot get output for roots if use:
import numpy as np
print("Roots of the first polynomial:")
print(roots([1, -2, 1]))

I assume since roots is a sub module,
we need to access roots using alias of numpy ie np;
I could not find in detail about roots, please share your thoughts on the same.
Answer: roots is a function, not a submodule. When you call np.roots, you're accessing the function through the numpy module's namespace. Run help(np.roots) if you want to see more.

roots(p)
  Return the roots of a polynomial with coefficients given in p.

If you want to bring roots into your own namespace, you use the from .. import .. syntax:
import numpy as np
from numpy import roots

Which imports numpy and brings the roots function into your own namespace so you can call it as you were doing so in the second snippet.


Why does nginx select a location block with a non-matching regex?

Question: In my nginx config file I have this location block (modified for debugging purposes):
location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
    expires 1;
    log_not_found off;
    return 515 "Request URI is $request_uri. Caught you";
}

When I request this URI from the server:
/img/signup/be0e1d34fabf2514d49db9baec09f858.png?w=198&h=198&s=9a7d22504c5ae176a936a0f18cccacba
sure enough, it matches and I get a 515 response with this body:
Request URI is /img/signup/be0e1d34fabf2514d49db9baec09f858.png?w=198&h=198&s=9a7d22504c5ae176a936a0f18cccacba. Caught you
Why? The regex doesn't match, at least not intuitively (either it must end in a question mark followed by a series of digits, or in .png etc.), nor when I sense-checked it at Regex101.com.
Comment: nginx considers the URI in the location directive to be only the part before the question mark
Comment: Got it, thanks @FedericoSierra. Based on the [documentation for the `location` directive](http://nginx.org/en/docs/http/ngx_http_core_module.html#location) referring to the 'request URI' as the string to be compared against, I guessed it was equivalent to the `$request_uri` variable :-( Feel free to add this as an answer!
Answer: Nginx isn't actually matching against the section after the question mark. Those are the query args. Nginx is only seeing up until the end of the path (.png). Since that's the case, it matches just fine.


nth-of-type selection not working

Question: So I have 7 divs with the class test. I want divs 1-3 to be red and divs 5-7 blue. I managed to get 1-3 working but not the latter.
I would appreciate if someone would tell me how this works because it seems I don't really grasp the concept here. So how does this work?

.test:nth-of-type(-n+3) {
  background: red;
}
.test:nth-of-type(-4n+3) {
  background: blue
}

1

2

3

4

5

6

7

I also tried -2n + 3, -7n + 3, -4n + 7...
Answer: -4n+3 doesn't match the range 5–7. It only matches the third element and nothing else.
If you always want the last three elements, you can use :nth-last-of-type(-n+3) instead (which mirrors your :nth-of-type(-n+3) for the first three elements).
Note that .test:nth-of-type(...) probably doesn't mean what you think it means — you may want to qualify your selectors with div to make it clearer what it actually does.
Comment: It works but how does the logic work? So it counts backwards? Is it like a reverse loop?
Comment: @Asperger: A negative value of n, plus a certain number (let's say x), selects only the first x elements in :nth-of-type(), and only the last x elements in :nth-last-of-type(). So yes, you can think of it like a reverse loop.
Answer: You can use nth-last-of-type when start at the end
nth-of-type(-n+3) means start from 0 (n) and move 3 items (+3) and then cycle backwards (-), which will target the first 3 items.
When you use nth-last-of-type(-n+3) means the same thing, it just starts at the last item.

.test {
  height: 20px;
  background: yellow;
}

.test:nth-of-type(-n+3) {
    background: red;
}

.test:nth-last-of-type(-n+3) {
    background: blue
}

Comment: It works but how does the logic work? So it counts backwards? Is it like a reverse loop?
Comment: @Asperger You can say that. `-n` means start from 0 and `+3` means 3 items. `nth-last-of-type` starts at then end.
Comment: Ah I see. So that means its impossible to start somewhere in the middle and go from there right?
Comment: In a matter of fact, reverse looping through the array is faster than looping from the beginning in most cases
Comment: @Asperger Yes. When you use the (-n+3) form it means a cycle that either go forwards or backwards.

nth-of-type selection not working


How to interpret forecast output in words

Question: May I ask you guys regarding forecast in R?
How should I interpret this graph? Please describe it in easy-understandable words.
Answer: ets() (which stands for "Error-Trend-Seasonality" and implements a state space formulation of standard exponential smoothing algorithms) has fit a model with additive error, no trend and no seasonality (A,N,N). That is: it believes your observations are iid and there is essentially no structure to them, apart from a constant expectation and variance.
The future expected value is about 5000, for each future time point. We expect 80% of future observations to lie in the interval [1700,9200], and 95% in [-50,11100]; the last two are prediction-intervals. All numbers read off the graph, of course.
You might profit from reading an introductory forecasting testbook. I recommend the excellent free online book Forecasting: Principles and Practice (2nd ed.) by Athanasopoulos & Hyndman.


Android - Cance/Stop/Kill AsyncTask Forcefully without loop

Question: Anyone know if it possible to kill/stop AsyncTask without loop.
There was many examples with loop but the task which I should do in doInBackground() function only one function which in some cases take long time and I shall stop it for example in onPause. If it possible or I should use another task for example Futuretask.
Thanks in advance.
The code like this:
class ProcessTask extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        Log.i(TAG, " ---- ProcessTask -- doInBackground ----");
        // Task
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        Log.i(TAG, " ---- ProcessTask -- onPostExecute ----");
    }

    @Override
    protected void onCancelled(Boolean result) {
        super.onCancelled(result);
        Log.i(TAG, " ---- ProcessTask -- onCancelled ----");
    }
}

...
ProcessTask myTask;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    myTask = new OCRProcessTask();
    myTask.cancel(false);
    myTask.execute();
}

@Override
public void onPause() {
    myTask.cancel(true);
}

Answer: You can cancel the AsyntTask by setting cancel(true) to the task.
new MyAsyncTask().cancel(false);

Comment: I add code. You mean such ?
If I try lick that **doInBackground** function not called.
If something I understand not right?
Comment: You can't cancel and execute in the same time, I guess. What you can do is, by checking the Async Status and cancel it if it's still running or something.
Comment: That mean that I should have loop on "doInBackground" function, yes??? And I can not stop it without loop ?


Distribution of number of objects in Simple Random Sampling with Replacement (SRSWR)

Question: Suppose we have an urn containing $m \in \mathbb{N}$ objects and we sample with replacement $n \in \mathbb{N}$ times with equal chance of sampling any object in any draw.  Let $1 \leqslant K \leqslant \min(n,m)$ be the number of different objects we sample.  We can represent this problem as follows:
$$\mathbf{N} \sim \text{Multinomial}(n, (\tfrac{1}{m}, \cdots, \tfrac{1}{m})) \quad \quad \quad \quad K \equiv \sum_{i=1}^m \mathbb{I}(N_i >0).$$
Find the probability mass function for $K$ (in its simplest form).
Answer: The probability that $K = k$ is given by
$$
p(k) = \frac{\binom{m}{k} f(n,k)}{m^n}
$$
where $f(n,k)$ is the number of sequences consisting of only the integers $i = 1, \ldots, k$ of length $n$ in which each $i$ occurs at least once. To see this, note that we want the probability that exactly $k$ unique entries appear in a sequence of $n$ draws from a discrete uniform on $1, \ldots, m$. We can get this in two steps by (1) selecting which $k$ entries of the $m$ will appear and (2) choosing a sequence in which each appears at least once. The total number of sequences of length $n$ is $m^n$ which gives the denominator.
If one considers the Stirling numbers of the second kind to be "closed form" then $f(n,k)$ can be simplified as
$$
f(n,k) = S(n,k) k!
$$
Recall that $S(n,k)$ counts the number of ways to partition $n$ objects into $k$ non-empty equivalence classes. So, we simply partition each of our $n$ draws into $k$ classes, such that the entries in each equivalence class will be associated to the same $i \in \{1,\ldots,k\}$. Next, we need to actually associated each $i$ to the equivalence classes, and there are $k!$ ways to do this. Simplifying, we get
$$
p(k) = \frac{m! S(n,k)}{(m-k)! m^n}
$$
for the final answer. This should be as simple as the answer can possibly get, because Stirling numbers cannot be simplified.
Some R code to verify that this is correct, Stirling code taken from here:
<code>Stirling2 <- function(n,m)
{
    ## Purpose:  Stirling Numbers of the 2-nd kind
    ##      S^{(m)}_n = number of ways of partitioning a set of
    ##                      $n$ elements into $m$ non-empty subsets
    ## Author: Martin Maechler, Date:  May 28 1992, 23:42
    ## ----------------------------------------------------------------
    ## Abramowitz/Stegun: 24,1,4 (p. 824-5 ; Table 24.4, p.835)
    ## Closed Form : p.824 "C."
    ## ----------------------------------------------------------------

    if (0 > m || m > n) stop("'m' must be in 0..n !")
    k <- 0:m
    sig <- rep(c(1,-1)*(-1)^m, length= m+1)# 1 for m=0; -1 1 (m=1)
    ## The following gives rounding errors for (25,5) :
    ## r <- sum( sig * k^n /(gamma(k+1)*gamma(m+1-k)) )
    ga <- gamma(k+1)
    round(sum( sig * k^n /(ga * rev(ga))))
}

set.seed(123)
n <- 7
m <- 5

f <- function(k) {
  choose(m,k) * Stirling2(n,k) * factorial(k) / m^n
}

foo <- t(replicate(100000, sample(1:m, n, replace = TRUE)))
foo2 <- apply(foo, 1, function(x) length(unique(x)))

f_hat <- mean(foo2 == 3)
f_hat + c(-1,0,1) * 1.96 * sqrt(f_hat * (1 - f_hat) / 100000)
## [1] 0.2276407 0.2302500 0.2328593
f(3)
## [1] 0.231168
sum(Vectorize(f)(1:m))
## [1] 1
</code>
Comment: This is a great answer (+1).  I assume from your reasoning that you are proceeding for the case where $n \leqslant m$.  Can you verify that this sums to one over the allowable range?
Comment: @Ben $n > m$ is allowed. I checked that it sums numerically (my example code is in this case). The easiest proof that this sums to 1 is probably the proof that it is the pmf of $K$, but it is possible also to do by computing $f(n,k)$ by inclusion-exclusion I think.
Answer: Having now done some more study on this problem I have found that this is actually a distribution that has received quite a lot of attention in the mathematical literature.  The general problem is called the "classical occupancy problem" and the resulting distribution of the number of occupied groups is called the "occupancy distribution".  This distribution has been studied in detail (see e.g., Johnson and Kotz 1977; Kolchin et al 1978).  The mass function is:
$$p_K(k) = \frac{(m)_k \cdot S(n,k)}{m^n} \quad \quad \quad \text{for all } 1 \leqslant K \leqslant \min (m,n),$$
where the values $(m)_k = m (m-1) \cdots (m-k+1)$ are the falling factorials.  This distribution is included in some books on discrete distributions, but it is more obscure than the standard discrete distributions, and as a result, it is not well-known.  Nevertheless, the distribution has been studied in great detail and its moments and generating functions are known.

Moments: The form of the distribution leads to a simple formula for the expected falling factorials:
$$\mathbb{E}((m-K)_r) = (m)_r \Big( 1-\frac{r}{m} \Big)^n.$$
Since $(K)_r$ is a polynomial of degree $r$ in $K$, this leads to corresponding results for the raw and central moments.  These get very messy for the higher-order moments, but the formulae for the mean and variance are fairly simple:
$$\begin{equation} \begin{aligned}
\mathbb{E}(K) &= m \bigg[ 1 - \Big( 1-\frac{1}{m} \Big)^n \bigg], \\[8pt]
\mathbb{V}(K) &= m \bigg[ (m-1) \Big( 1-\frac{2}{m} \Big)^n + \Big( 1-\frac{1}{m} \Big)^n - \Big( 1-\frac{1}{m} \Big)^{2n} \bigg]. \\[6pt]
\end{aligned} \end{equation}$$

Asymptotic results: There are various well-known limiting results that look at the asymptotic form of the distribution as $m \rightarrow \infty$ and $n \rightarrow \infty$.  Results depend on the "domain of convergence", but for a broad limiting domain the distribution of the number of empty cells converges to either a normal distribution or a Poisson distribution (see Kolchin et al 1978, Ch 4).  For finite parameter values the Poisson approximation suffers from the fact that it constrains the variance, so it it a poor approximation except for very large $n$.  Nevertheless, for very large $n$ we have:
$$m-K \sim \text{Pois}(m \cdot e^{-n/m}).$$
The normal approximation is generally a preferable approximation, since it allows freedom of the mean and variance.  For large $n$ and $m$ we have the approximation:
$$K \sim \text{N}(\mu = \mathbb{E}(K), \sigma^2 = \mathbb{V}(K)).$$

References

Johnson, N.L. and Kotz, S. (1977) Urn Models and their Applications. John Wiley and Sons: New York.

Kolchin, V.F., Sevast'yanov, B.A. and Christyakov, V.P. (1978) Random Allocations. John Wiley and Sons: New York.


Como printar texto digitado em uma GUI do tkinter no console?

Question: Eu queria criar um texto em uma janela e, apertando um botão, o meu texto aparecer no console. O meu código é esse:
from tkinter import *
class janela:
    def __init__ (self, janela):
        self.frame=Frame()
        self.frame.config(height=300,width=300,bg='black')
        self.frame.pack()
        janela.config(bg='black')
        janela.title('TITULO')

        text1 = Text (self.frame, width=20, height=5)
        text1.pack()
        confirm = Button (self.frame, text='Confirmar texto', fg='red', command=
                            lambda: print(text1))
        confirm.pack()

jan1 = Tk()
janela(jan1)
jan1.mainloop()

Answer: Você fez quase tudo certo, mas faltou notar que o texto é um atributo do seu frame, não o frame em si. Note que, da forma como está, seu programa está printando o nome do objeto (!frame.!text). Para obter o texto, você precisa adicionar o método get. Abaixo código com a correção:
from tkinter import *
class janela:
    def __init__ (self, janela):
        self.frame=Frame()
        self.frame.config(height=300,width=300,bg='black')
        self.frame.pack()
        janela.config(bg='black')
        janela.title('TITULO')

        text1 = Text(self.frame, width=20, height=5)
        text1.pack()
        confirm = Button (self.frame, text='Confirmar texto', fg='red', command=
                            lambda: print(text1.get(1.0, "end-1c")))
        confirm.pack()

jan1 = Tk()
janela(jan1)
jan1.mainloop()


In the summary of output of the regression analysis in R, is there a way to display categorical variable with just one coefficient

Question: I am doing a linear regression analysis in R with logarithmic dependent variable. One of the control variables is categorical and describes an industry. There are 6 industries and thereby R automatically creates a separate coefficient for each Industry. However, I just want to see if that variable is significant or not and am not interested in separate coefficient for each factor.
Is there a way to program it in a way that the summary of the model just says if the influence of industry was significant for at least one factor or not?
Comment: If I understand, you want to use the *Anova* function in the *car* package.
Comment: R should be creating 6-1=5 coefficients unless you are fitting a model without an intercept..
Comment: Thats Right, R creates 6-1 coefficients but I just want 1 coefficient to tell me whether the influence of any category is significant. I don't want to know which one specfically
Answer: It only makes sense to calculate a single coefficient for an independent variable if the following conditions are met:

The values of the variable are ordered; i.e. each increment/decrease of one value indicates an increase/decrease in the represented phenomenon.
The values of the variable are equidistant. i.e any increment of one level on the variable indicates a similar increase in the represented phenomenon.

Continuous variables often meet these criteria, but categorical variables only do in certain cases: if the categories are ordinal and equidistant (e.g., number of production facilities, income strata etc.).
I suppose your variable 'Industry' is nominal instead of ordinal, so calculating a single regression coefficient instead of separate coefficients for each of the 5 dummy-variables  would not make sense.Instead, you could consider an omnibus test to test for overall differences across categories (e.g. ANOVA).


Android Automotive Emulator "no system images installed for this target"

Question: I have installed Android Studio 3.5 from the stable channel. I am trying to build the Android Automotive Emulator but I am receiving the following error

no system images installed for this target

I have downloaded the following system image

Google APIs Intel x86 Atom_64 System Image

This image is shown when I try to make a phone/tablet emulator. I am using  Mac Mojave. Do I need to install the Android 10 system image to solve this error?
Comment: sadly, no @user3448282
Comment: Hi there, did you find a solution? I'm facing the same problem recently.
Comment: please post the answer if you found.
Comment: Sorry, no answer found yet, I am trying to build the emulator from the aosp site instead
Comment: @Shaan_B  I have twitted to several people, let's see. Can you please tell how to build emulator from AOSP?  is it possible to share if any material links?
Comment: hi @Selva can you please create this as a new question, I will share the links and steps to create the emulator
Comment: https://stackoverflow.com/questions/58057045/android-aosp-automotive-emulator
Comment: @Selva did you get any answers on Twitter? Or could you link those questions, to make it possible to monitor these?
Answer: For Automotive OS (not Android Auto) you must add system image (at the moment only for Volvo Polestar 2 image)

In Android Studio, select Tools > SDK Manager
Click the SDK Update Sites tab
Click Add icon
Enter the following Name and URL, then click OK

Name: Polestar 2 System Image
URL: https://developer.polestar.com/sdk/polestar2-sys-img.xml
Click Apply, then click OK and create a car AVD
Comment: >create a car AVD: In my case, Polestar AVD could only be added via the search bar (by entering Polestar) in Virtual Device Configuration, not via Category-> Automotive
Comment: You need to use Canary channel not a stable build (as commented above)
Comment: As of Android Studio 4.2.2, I didn't need a Canary build of Android Studio to get this to work.
Answer: You are not on the Canary channel for Android Studio, so you are not receiving updates for the Automotive Image. Your Android Studio version is only receiving updates for stable releases of Android. This can be fixed by switching over to the Canary channel in the Android Studio Preferences or downloading the Canary version.
Go to 'Android Studio >> Preferences >> Appearance & Behavior >> System Settings >> Updates'. From there you should a drop-down menu for "Automatically check updates for 'Stable Channel'". Go to the drop-down menu and switch over to 'Canary Channel'.
Another solution is to download the Canary version of Android Studio listed here: https://developer.android.com/studio/archive. Look for the releases that are labelled 'Canary'.
Comment: That doesn't seem to help. The channel is for studio updates, I'm not sure it's related to which system images are being downloaded. In any case, this doesn't help me at all, no system images suitable for car simulators show up after this, but I did get an offer to download a beta version of AS.
Comment: I would recommend installing the Canary version separately from your stable version. After download/install, I went directly to the AVD Manager and was able to create an auto emulator with a system image. I can now use it in my stable-version setup.
Comment: Automotive emulator system image for API 33 is now available in stable version of Android Studio. PTAL https://stackoverflow.com/questions/74370132/automotive-intel-x86-atom-system-image-not-showing-in-android-studio-dolphin/74412420#74412420
Answer: I had a very similar issue and wrote a little guide how I solved it : https://maltewolfcastle.medium.com/how-to-setup-an-automotive-android-emulator-f287a4061b19
Basically I had to import the device profile that comes with the Polestar 2 system image. You can select that from the Table category then and run any Automotive System Image you installed with it.
Comment: Although you are the author of the article you need to keep in mind links may become broken in the future and render your answer obsolete. Posting the images here aswel is likely to help you preventing downvoters or bot flagging for low quality answer marking of the answer. EoR.
Answer: Android Automotive emulator :-> you need to add system image of polestar and for that select Tools > SDK Manager
Then , Click the SDK Update Sites tab
Now Click on Add Icon
Enter Name and Url for image
Name: Polestar 2 System Image
URL: https://developer.polestar.com/sdk/polestar2-sys-img.xml
Comment: This worked for me thanks! I think I also needed to install the Android Pie SDK as well.
Answer: I was able to get it to work on a stable release (3.5.1).
I went to Android Studio > Preferences > Appearance & Behavior > System Settings > Android SDK > SDK Tools and then selected Android Auto API Simulators and Android Auto Desktop Head Unit emulator. Then, back in the AVD Manager, I was able to select and download Pie for the system image.
Comment: This is for Android Auto, not Android Automotive. Blame Google for the naming confusion :-)
Comment: I still can't get an auto system image and i've done exactly this. Any suggestions?
Comment: This works, it's currently only in the Android 9 SDK though, not 10.
Answer: Now, you can download API 33 Android Automotive system image from stable version of Android Studio. PTAL Automotive Intel x86 Atom System Image not showing In Android Studio Dolphin for more detail.
Update @ Jan 12 2024

Android Studio Hedgehog | 2023.1.1 Patch 1
From this version, you can use "Automotive (1080p landscape)" device config for Automotive
And, you can download Android Automotive TM emulator system image for x86_64 and arm64


Get value from specific row

Question: I am trying to fetch a specific value from the following query:
 var query = from a in db.Questions
        where a.CategoryId == 1
        select a;

Essentially I want to get an integer in the result in the 3rd row of the following query in 'a.questionId' and cast it to an interger. I imagine its something like:
int qNum = query.single(Row 3).questionId;

Comment: Your query is returning all questions of a specific category, but it is difficult to understand what you are after given it isn't clear how a row figures into your questions.
Answer: You could try:
int qNum = query.Skip(2).First().questionId;

Comment: The fastest gun in the west.
Comment: @Omribitan - That's only if the OP wants the results ordered first. It's never stated that the 3rd row is the 3rd of any specific order.
Comment: you first need to `OrderByDescending` of `questionId`
Comment: @JustinNiessner Technically you are right, I just assumed that the 3rd row meant the 3rd question so ...
Answer: int qNum = query.Skip(2).First().questionId;

Answer: int qNum = query.Skip(2).First().questionId;

Get value from specific row


Using MGF for multivariate random variables

Question: How do you use MGF for solving moment based questions for multivariate random variables?
For the single variable case, we:
find $E(e^{tX})$, find the interval in which it exists (around 0), differentiate it n times and plug in t as 0 to receive the n'th moment $E(X^n)$.
With a general multivariate distribution like $f_{XY}(x,y)$, how do I use MGF to find stuff like $E(X), E(XY), E(Y)$ etc?
I read wikipedia and some other pages but they keep losing me at some point.
I understand the MGF will be  $E(e^{t'X})$ where t and X are now vectors but where do I go from here?
Answer: Let's write down what your last expression means in $2$ dimensions:
$$
m(t_1,t_2) =  E[e^{t_1X_1 + t_2 X_2}],
$$
then we get
$$
\frac{\partial m}{\partial t_i} = E[X_i e^{t_1X_1 + t_2 X_2}]
$$
and we can evaluate at $t_1=t_2 = 0$ to get $E[X_i]$ for $i = 1,2$.
More interesting:
$$
\frac{\partial m^2}{\partial t_1 \partial t_2} = E[X_1 X_2 e^{t_1X_1 + t_2 X_2}]
$$
and again evaluating at $t_1=t_2 = 0$ to get $E[X_1X_2]$ which we need for the covariance.
Play with the derivatives and you should get all mixed moments.
Comment: Shouldn't the derivatives be partial?
Comment: Yes, I did not use the proper "d" but of course partial.


How to execute HTTP DELETE request in AWS Lambda Nodejs function

Question: I am trying to create an AWS Lambda transform function for a Firehose stream that sends records directly to an Elasticsearch cluster.
Currently, there is no way to specify an ES document id in a Firehose stream record, so all records, even duplicates, are inserted. However, Firehose does support transformation functions hosted in Lambda, which gave me an idea:
My solution is to create a Lambda transform function that executes a DELETE request to Elasticsearch for every record during transformation, then returning all records unmodified, thereby achieving "delete-insert" behaviour (I am ok with the record disappearing for a short period).
However, I know very little about Nodejs and even though this is such a simple thing, I can't figure out how to do it.
Is there a Node package available to Lambda that I can use to do this? (Preferably an AWS Elasticsearch API, but a simple HTTP package would do).
Do I have to package up some other module to get this done?
Can something like Apex help me out here? My preferred language is Go, but so far I have been unable to get apex functions to execute or log anything to Cloudwatch...
Thanks in advance.
Answer: It seems a simple task to do, so I guess no framework is needed.
A few lines of code in Node.js would get the things done.
There are two packages that can help you:

elasticsearch-js
http-aws-es (If your ES domain is protected and you need to sign the requests)

The API doc: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html


Find $\lim_{x\to0}{\frac{\arctan (2x)}{3x}}$ without using '0/0=1'

Question: Find limit as
$$
\lim_{x \to 0} \frac{\arctan (2x)}{3x}
$$
without using $\frac{0}{0} = 1$.
I wanted to use
$$
\frac{2}{3} \cdot \frac{0}{0} = \frac{2}{3} \cdot 1,
$$
but our teacher considers $\frac{0}{0}$ a "dangerous case" and we are not allowed to use this method.
We have not studied integrals yet, so I cannot use integral formulas. We have only studied a bit of derivative taking...
I tried many substitutions, but failed :( Any suggestion?
Comment: The argument that "$0/0 = 1$" is not only a dangerous method, it is utterly and completely FALSE. It is never allowed and your teacher should say so clearly.
Comment: @user283294 What do you mean "without 0/0 = 1" ? What are the rules of calculating this limit?
Comment: Did you do L'Hospital rules yet?
Comment: @user283294 I agree with 5xum - you should use L'Hospital's Rule as it is a $0/0$ case.
Answer: Let $u=\arctan(2x)$ Then as $ x \rightarrow 0$ we have $u \rightarrow 0$ So $\lim_{x \rightarrow 0} \frac{\arctan(2x)}{3x}=\lim_{u \rightarrow 0} \frac{u}{3 \frac{tan(u)}{2}}=\frac{2}{3}\lim_{u \rightarrow 0 } \cos(x) \cdot \frac{u}{\sin(u)}=\frac{2}{3} \lim_{u \rightarrow 0} \frac{u}{\sin(u)} \cdot \lim_{u \rightarrow 0} \cos(u) $
Comment: This is the best approach, in my view. Exactly how I did it. +1 for you.
Answer: This is really just the derivative of the function $f(x) = \frac{1}{3} \arctan 2x$ at $x = 0$, written down using the definition. Since you know that $\frac{d}{dx} \frac{1}{3} \arctan 2x = \frac{1}{3} \frac{2}{1 + (2x) ^2}$ (check this!), you obtain the result $\frac{2}{3}$ by substituting $x = 0$.
Answer: You may use L'Hospital's rule:
$$
\lim_{x\to0}{\frac{\arctan (2x)}{3x}}=\lim_{x\to0}{\frac{\frac{2}{1+4x^2}}{3}}=\frac23.
$$
Answer: With equivalents:
We know $\arctan u\sim_0u$, hence
$$\frac{\arctan 2x}{3x}\sim_0\frac{2x}{3x}=\frac23.$$


Installing alfresco 3.4 on jboss with mysql

Question: I am trying to install alfresco 3.4 into an already existent jboss instance but the documentation I have followed appears to be incorrect. First issue is the docs mention an extensions folder that does not exist in any of the Alfresco downloads that I have found. Second issue is in the documentation on how to configure the database for alfresco. It tells me to run a script that is located inside "extra/databases/mysql", again in this case the extra dir does not exist in my dist of alfresco. I have been google-ing but many of the other howtos I see are even more impossible to follow.
link to docs I have been trying to follow
Comment: What version of Alfresco are you trying to install, Community or Enterprise? That doc is for enterprise which is slightly different to community.
Answer: First: If you have an Enterprise version, then you can just download the *.EAR file from the network Downloads. Run the following lines in a MySql window:
<code>create database alfresco default character set utf8 collate utf8_bin;
grant all on alfresco.* to 'alfresco'@'localhost' identified by 'alfresco' with grant option;
grant all on alfresco.* to 'alfresco'@'localhost.localdomain' identified by 'alfresco' with grant option;
</code>
(it's the same as that should be in the extras/databases.. location)
It should contain an extension folder. And you don't need an extension folder to start Alfresco.........
Second: You have community edition.......
Just look at this wiki page: WIKI
Don't forget to put the mysql jdbc jar in the server default lib folder.
Comment: Can I download the enterprise version of alfresco for free or does that cost money?
Comment: You can download the enterprise version with a 30 day Trial I guess. http://www.alfresco.com/products/ecm/enttrial/?product_module=DM , The community version is completely free.


Consulta com duas tabelas

Question: Estou em um projeto, tenho a tabela cliente e trabalho.
Um trabalho tem um cliente. Já relacionei as tabelas, mas preciso fazer um select que a partir do id do cliente na tabela trabalho, retorne o nome do cliente.
Tenho que fazer uma consulta para exibir no meu código em php.
Alguém pode me ajudar por favor?
Answer: Supondo que suas tabelas sejam assim:
CLIENTE
    id int,
    nome_cliente VARCHAR
TRABALHO
    id int
    id_cliente int
    descr_trabalho VARCHAR
Você poderia fazer assim:
<code>SELECT a.id, a.descr_trabalho, b.nome_cliente from TRABALHO a
    left join CLIENTE b on
       a.id_cliente = b.id
</code>

Consulta com duas tabelas


JButtons in JTable cell change shape on row selection

Question: I have a single cell (column) per row based table and the cell is a panel with 2 buttons on it. TableCellRenderer and TableCellEditor are implemented correctly to allow render and edit the cell. But when i click the row or even the button, the shape of the buttons change. It looks like the size of the button shrinks to fit the button text. Please see the attached images.

If I set a preferred size of the buttons then the size doesn't seem to change but the button text shift towards right.  Below is the code of the table cell panel. Running this panel from a main in the same class like shown below dosn't show this behavior. This behavior is only visible when using this panel as a cell in the single column table row. Don't know which property of what to set/change.
public class PartitionsTableRowPanel extends javax.swing.JPanel {

    /**
     * Creates new form PartitionsTableRowPanel
     */
    public PartitionsTableRowPanel() {
        initComponents();
        postInitAdjustments();
    }

    private void postInitAdjustments() {
//        infoButton.putClientProperty("JButton.buttonType", "roundRect");
//        scanButton.putClientProperty("JButton.buttonType", "roundRect");
//
//        infoButton.addActionListener((e) -> {
//            log.info("info clicked");
//        });

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(1000, 59));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton1.setText("Info");
        add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, -1, -1));

        jButton2.setText("jButton2");
        add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 20, -1, -1));
    }// </editor-fold>

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            FlatDarkLaf.install();
            JFrame f = new JFrame("TestProgressBar");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new PartitionsTableRowPanel());
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });

    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration
}

Below is what my main JFrame looks like:
public class MainAppWindow extends javax.swing.JFrame {

    /**
     * Creates new form MainWindow1
     */
    public MainAppWindow() {
        initComponents();
        postInitAdjustments();
    }

    private void postInitAdjustments() {

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        northPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        partitionDetailsTable = new javax.swing.JTable();
        centerPanel = new javax.swing.JPanel();
        messageDetailsTextPaneScrollPane = new javax.swing.JScrollPane();
        messageDetailsTextPane = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sentry Disk Helper");
        setName("mainFrame"); // NOI18N
        setPreferredSize(new java.awt.Dimension(984, 606));

        northPanel.setName("northPanel"); // NOI18N

        partitionDetailsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        partitionDetailsTable.setFocusable(false);
        partitionDetailsTable.setName("partitionsTable"); // NOI18N
        jScrollPane1.setViewportView(partitionDetailsTable);

        javax.swing.GroupLayout northPanelLayout = new javax.swing.GroupLayout(northPanel);
        northPanel.setLayout(northPanelLayout);
        northPanelLayout.setHorizontalGroup(
            northPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(northPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1048, Short.MAX_VALUE)
                .addContainerGap())
        );
        northPanelLayout.setVerticalGroup(
            northPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(northPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(northPanel, java.awt.BorderLayout.NORTH);

        centerPanel.setBounds(new java.awt.Rectangle(2, 4, 0, 0));
        centerPanel.setName("centerPanel"); // NOI18N

        messageDetailsTextPane.setFocusable(false);
        messageDetailsTextPaneScrollPane.setViewportView(messageDetailsTextPane);

        javax.swing.GroupLayout centerPanelLayout = new javax.swing.GroupLayout(centerPanel);
        centerPanel.setLayout(centerPanelLayout);
        centerPanelLayout.setHorizontalGroup(
            centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(messageDetailsTextPaneScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1048, Short.MAX_VALUE)
                .addContainerGap())
        );
        centerPanelLayout.setVerticalGroup(
            centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, centerPanelLayout.createSequentialGroup()
                .addComponent(messageDetailsTextPaneScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(centerPanel, java.awt.BorderLayout.CENTER);

        getAccessibleContext().setAccessibleName("Sentery Disk Helper");

        setSize(new java.awt.Dimension(984, 628));
        setLocationRelativeTo(null);
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainAppWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainAppWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainAppWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainAppWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                 //FlatIntelliJLaf.install();
                new MainAppWindow().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel centerPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane messageDetailsTextPane;
    private javax.swing.JScrollPane messageDetailsTextPaneScrollPane;
    private javax.swing.JPanel northPanel;
    private javax.swing.JTable partitionDetailsTable;
    // End of variables declaration
}

Adding a sample code to help reproduce the problem. Run the main in the NewJFrame1 class to see the issue. Uncomment and Run the main in the TableRowPanel1 private class to see the default correct working. If i use the table cell panel component directly in a JFrame it works fine. But same component used as table cell via an editor shows the problem. Really need help with this please.:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.swing.test.demo.ui;

import com.formdev.flatlaf.FlatDarkLaf;
import com.swing.test.demo.ui.components.TableRowPanel;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class NewJFrame1 extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame1
     */
    public NewJFrame1() {
        initComponents();
        postInit();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
        //</editor-fold>
        FlatDarkLaf.setup();
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewJFrame1 newJFrame1 = new NewJFrame1();
                newJFrame1.setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration

    private void postInit() {
        List<Data> modelData = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Data data = new Data();
            data.value = "Data_" + i;
            modelData.add(data);
        }
        jTable1.setDefaultRenderer(Data.class, new MyCellRenderer());
        jTable1.setDefaultEditor(Data.class, new MyCellEditor());
        jTable1.setModel(new MyTableModel(modelData));
        jTable1.setRowHeight(52);
        jTable1.revalidate();
        //
    }

    private class Data {

        String value;
    }

    private class MyTableModel extends AbstractTableModel {

        private List<Data> data;

        public MyTableModel(List<Data> data) {
            this.data = data;
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data.get(rowIndex);
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return Data.class;
        }

    }

    private class MyCellRenderer implements TableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            System.out.println("fff");
            return new TableRowPanel1();
        }

    }

    private class MyCellEditor extends AbstractCellEditor implements TableCellEditor {

        @Override
        public Object getCellEditorValue() {
            return null;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            System.out.println("ddd");
            return new TableRowPanel1();
        }

    }

    private class TableRowPanel1 extends javax.swing.JPanel {

        /**
         * Creates new form TableRowPanel
         */
        public TableRowPanel1() {
            initComponents();
        }

        /**
         * This method is called from within the constructor to initialize the
         * form. WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {

            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();

            jButton1.setText("jButton1");

            jButton2.setText("jButton2");

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(jButton1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton2)
                                    .addContainerGap(250, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addGap(14, 14, 14)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jButton1)
                                            .addComponent(jButton2))
                                    .addContainerGap(14, Short.MAX_VALUE))
            );
        }// </editor-fold>

        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        // End of variables declaration

//        public static void main(String[] args) {
//            EventQueue.invokeLater(() -> {
//                FlatDarkLaf.setup();
//                JFrame f = new JFrame("TestProgressBar");
//                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//                f.setContentPane(new TableRowPanel());
//                f.pack();
//                f.setLocationRelativeTo(null);
//                f.setVisible(true);
//            });
//
//        }
    }

}

Comment: This seems like a FlatLAF problem. Removing the FlatLAF theming resolves the issue.
Comment: Any ideas about how to rectify this? Don't want to let go of Flatlaf but this is very very disappointing.
Answer: According to the source code, the border inset of the table cell editor is 0 according to the FlatBorder specification.
com/formdev/flatlaf/ui/FlatBorder.java
protected boolean isCellEditor( Component c ) {
    return FlatUIUtils.isCellEditor( c );
}

@Override
public Insets getBorderInsets( Component c, Insets insets ) {
    // ...

    if( isCellEditor( c ) ) {
        // remove top and bottom insets if used as cell editor
        insets.top = insets.bottom = 0;
        // ...

com/formdev/flatlaf/ui/FlatUIUtils.java
public static boolean isCellEditor( Component c ) {
    // check whether used in cell editor (check 3 levels up)

Any ideas about how to rectify this?

Make the cell editor panel hierarchy three or more levels.
class TableRowPanel1 extends JPanel {
  protected final JButton jButton1 = new JButton("jButton1");
  protected final JButton jButton2 = new JButton("jButton2");

  public TableRowPanel1() {
    super(new BorderLayout());
    JPanel p2 = new JPanel(new FlowLayout(FlowLayout.LEADING));
    p2.add(jButton1);
    p2.add(jButton2);
    JPanel p1 = new JPanel(new BorderLayout());
    p1.add(p2);
    add(p1);
  }
}

or override FlatBorder#isCellEditor(Component c) method to always return false.
class TableRowPanel1 extends JPanel {
  protected final JButton jButton1 = new JButton("jButton1");
  protected final JButton jButton2 = new JButton("jButton2");

  public TableRowPanel1() {
    super(new FlowLayout(FlowLayout.LEADING));
    FlatBorder border = new FlatButtonBorder() {
      @Override protected boolean isCellEditor(Component c) {
        return false;
      }
    };
    jButton1.setBorder(border);
    jButton2.setBorder(border);
    add(jButton1);
    add(jButton2);
  }
}

NewJFrame2.java
import com.formdev.flatlaf.*;
import com.formdev.flatlaf.ui.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;

public class NewJFrame2 {
  public Component makeUI() {
    List<Data> modelData = new ArrayList<>();
    for (int i = 0; i < 4; i++) {
      Data data = new Data();
      data.value = "Data_" + i;
      modelData.add(data);
    }
    JTable table = new JTable(new MyTableModel(modelData));
    table.setDefaultRenderer(Data.class, new MyCellRenderer());
    table.setDefaultEditor(Data.class, new MyCellEditor());
    table.setRowHeight(52);

    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(table));
    p.add(new TableRowPanel1(), BorderLayout.SOUTH);
    return p;
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      FlatDarkLaf.setup();
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new NewJFrame2().makeUI());
      f.pack();
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

class Data {
  String value;
}

class MyTableModel extends AbstractTableModel {
  private List<Data> data;

  public MyTableModel(List<Data> data) {
    this.data = data;
  }

  @Override
  public int getRowCount() {
    return data.size();
  }

  @Override
  public int getColumnCount() {
    return 1;
  }

  @Override
  public Object getValueAt(int rowIndex, int columnIndex) {
    return data.get(rowIndex);
  }

  @Override
  public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
  }

  @Override
  public Class<?> getColumnClass(int columnIndex) {
    return Data.class;
  }
}

class MyCellRenderer implements TableCellRenderer {
  protected final TableRowPanel1 renderer = new TableRowPanel1();

  @Override
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    return renderer;
  }
}

class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
  protected final TableRowPanel1 editor = new TableRowPanel1();

  @Override
  public Object getCellEditorValue() {
    return null;
  }

  @Override
  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    return editor;
  }
}

class TableRowPanel1 extends JPanel {
  protected final JButton jButton1 = new JButton("jButton1");
  protected final JButton jButton2 = new JButton("jButton2");

  public TableRowPanel1() {
    super(new BorderLayout());
    JPanel p2 = new JPanel(new FlowLayout(FlowLayout.LEADING));
    p2.add(jButton1);
    p2.add(jButton2);
    JPanel p1 = new JPanel(new BorderLayout());
    p1.add(p2);
    add(p1);
  }
}

// class TableRowPanel1 extends JPanel {
//   protected final JButton jButton1 = new JButton("jButton1");
//   protected final JButton jButton2 = new JButton("jButton2");
//
//   public TableRowPanel1() {
//     super(new FlowLayout(FlowLayout.LEADING));
//     FlatBorder border = new FlatButtonBorder() {
//       @Override protected boolean isCellEditor(Component c) {
//         return false;
//       }
//     };
//     jButton1.setBorder(border);
//     jButton2.setBorder(border);
//     add(jButton1);
//     add(jButton2);
//   }
// }

Comment: Thank you. I was fiddling with the table's cell editor in TableUI. Missed to look at the whole layout's repaint and insets. Thank again for the help. Its a workaround but still bearable.


Writing an Axis2 handler

Question: I am trying to write 2 Axis2 handlers but there is there is something missing I can't put my hand on
The first handler is supposed to start at the very beginning before anything else, it will read the message header, parse the information I want from it and save it to a file then move on.
The second handler will execute after Axis2's Rampart finishes operation, which I assume is after the security phase. It will read the file and execute the logic on it (it wont touch the message contex)
I tried reading the guide on Axis2's website but it was not very beginner friendly, if someone can guide me to a simple way to approach this I would be thankful
Answer: You have to make the handlers in order. That is, you have to add the execution phases(In/out/fault flows) and define your handlers in order there. For example, check the axis2.xml, and how they defined the phases/handlers there.
Check this guide

Writing an Axis2 handler


Let the bisection method be applied to a continuous function, resulting in intervals $[a_0, b_0], [a_1, b_1],$ and so on. Let

Question: Let the bisection method be applied to a continuous function, resulting in intervals $[a_0, b_0], [a_1, b_1],$ and so on. Let $r=\lim_{n\to \infty}a_n$. Which of these statements can be false?
(a) $a_0\leq a_1\leq a_2\leq ...$
(b) $|r-2^{-1}(a_n+b_n)|\leq 2^{-n}(b_0-a_0), (n\geq 0)$
(c) $|r-2^{-1}(a_{n+1}+b_{n+1})|\leq |r-2^{-1}(a_n+b_n)|,  (n\geq 0)$
(d) $[a_{n+1},b_{n+1}]\subset [a_n,b_n], (n\geq 0)$
(e) $|r-a_n|=O(2^{-n}) \text{ as } n\to \infty$
(f) $|r-c_n|<|r-c_{n-1}|, (n\geq 0)$
By definition I know that $a_0\leq a_1\leq ...$, besides $|r-c_n|=|r-2^{-1}(a_n+b_n)|\leq 2^{-(n+1)}(b_0-a_0)\leq2^{-n}(b_0-a_0)$, then (a) and $b$ are true, I have the suspicion that (c), (e) and (f) are false but I can not find a counterexample, could someone help me please? Thank you very much.
Comment: Why do you think they may be false? I am afraid all of them are correct.
Comment: @MehrdadZandigohar How would you prove (c)?
For (e), I know that $|r-c_n|=O(2^{-n})$, but I do not know if this also holds for $a_n$ and I would think that (f) is very similar to (b), so I would say that both should be false or true
Answer: Part (e) is true because $\left\{r,a_n\right\}\subset\left[a_n,b_n\right]$ and $b_n-a_n=2^{-n}\left(b_0-a_0\right)$ so $\left|r-a_n\right|\le\left(b_n-a_n\right)=2^{-n}\left(b_0-a_0\right)$.
Part (c) is the same as part (f) and so is false. Let $f(x)=x-\frac25$, $a_0=0$, and $b_0=1$. Then $r=\frac25$ and $c_0=\frac12$ and $\left|\frac25-\frac12\right|=\frac1{10}$. Since $f(a_0)f(c_0)=\left(-\frac25\right)\left(\frac1{10}\right)<0$, $a_1=a_0=0$ and $b_1=c_0=\frac12$. Then $c_1=\frac14$ and $\left|r-c_1\right|=\left|\frac25-\frac14\right|=\frac3{20}$.
Answer:
Part $[c]:$

From part $B$ we can say:
$|r-2^{-1}(a_n+b_n)|\leq 2^{-n}(b_0-a_0), (n\geq 0) \tag 1$
$|r-2^{-1}(a_{n+1}+b_{n+1})|\leq 2^{-(n+1)}(b_0-a_0), (n\geq 0) \tag 2$
Since: $ 2^{-(n+1)}(b_0-a_0) - 2^{-n}(b_0-a_0)<0$ by substracting $2$ from $1$ we have:
$|r-2^{-1}(a_{n+1}+b_{n+1})|-|r-2^{-1}(a_n+b_n)|<0$
$\to |r-2^{-1}(a_{n+1}+b_{n+1})|<|r-2^{-1}(a_n+b_n)|$
In other words: $|r-2^{-1}(a_{n+1}+b_{n+1})|$ is the distance between the ${n+1}_{st}$ iteration value and the final converged value. As we increase $n$ then this distance decreases since it is converging. In ${n+1}_{st}$ iteration we are closer the final value than $n_{th}$ interation. So part $c$ is true.

Part $[f]:$

$|r-c_n|<|r-c_{n-1}|, (n\geq 0)$
This is also true and exactly like part $[c]$ as $c_n=2^{-1}(a_{n+1}+b_{n+1})$. Just substitute it with $c_n$ and everything is the same.

Part $[e]:$

Each step you are dividing your interval by $2$. This makes the accuracy of your answer $2$ times better than the previous iteration, meaning:
$|r-a_n|=O(2^{-n})$
As $n\to \infty$ then $2^{-n} \to 0$ and this means convergence.


How to upload .webp to Image field?

Question: https://www.drupal.org/project/imagewebp lets you upload a regular jpg/png which converts it into webp, but how to upload already a file that is in webp?
Adding it as one of allowed extensions in the field setting does not work.
update
As an alternative this can be solved with https://www.drupal.org/project/file_entity, but this is for the file field and not image field.
The question is about image field. Because in production site that already has image field in use with many images and pages active, it needs .webp extension support added to already existing image field.
Comment: Upgrade to Drupal 9.5 or 10. [WebP is supported](https://www.drupal.org/node/3171135) there.
Comment: I'm afraid this is not a right answer. Question is about Drupal 7 which is still officially maintained at least until Nov 1st 2023. Upgrading to solve all problems is not an answer, especially spending weeks or months upgrading entire platform just to have one file extension support. Thank you.
Comment: Support the efforts to complete https://www.drupal.org/project/drupal/issues/3179554 if you are unable to update to Drupal 9 or 10.
Comment: @cilefen the patch in the link works, can you please post this as the answer to solve and close the question?
Comment: `officially maintained at least until Nov 1st 2023` yes but doesn't mean it gets new features. Your best bet is to upgrade or try the patche(s) in the link cilefen added.
Comment: I'm voting to close this question because it's a known issue on drupal.org and a workaround has been identified already in the question.
Answer: Drupal Core 7 does not yet support WebP but there are reportedly working patches on this in-progress issue: https://www.drupal.org/project/drupal/issues/3179554.

How to upload .webp to Image field?


Taxonomy terms as numbers?

Question: Creating real estate website, i have a lot of exposed filters.
For year when the object is built i have number field which in views is as exposed filter.
When user makes input he puts year 1961 for example.
User searching in exposed filter writes 1961 and filter is set up like "equal or higher" so he gets all objects made 1961 and higher. Works fine.
But i have a problem with floors.
For floors i have vocabulary:
ground floor
1
2
3
4
etc..
attic
I cant use number field because of ground floor and attic so i had to use taxonomy.
But now i cant use equal or higer as exposed filter so if user picks number 3 he only gets appartments with 3 floors.
Answer: You could still use floors as numeric field, having numbers as keys and display output as needed.
Example of "List (integer)" values:

-1|Basement
0|Ground floor
1|1
2|2
3|3
100|Attic

This would allow you the same logic for floors.
EDIT:
When selecting the field as a filter in Views you need to choose the delta value. It looks something like Content: Floors (field_floors:delta). This will give you the integer filter options such as Is greater than or equal to.
Comment: @BigBrother2010 When selecting field you have to choose the delta value.
Comment: This works but how can i achive "equal or higer" in views exposed filter with it ? I tried using slider but it works only with integer (ubfortunately not workung with List(integer)
Comment: For all integer fields you should be able to select `Is greater than or equal` in the field settings under `Filter criteria` in Views.
Comment: I only have: " Is one of, Is all of, Is none of, Is empty (NULL),  Is not empty (NOT NULL). (using "List (integer)" as field).
Comment: Cheers for helping out enzipher, but for some reason delta value is not visible for this field.
Comment: @BigBrother2010 I tried this out with Drupal 7.14 and Views 3.5 and it works for me. I really can't tell why you don't have a delta value for the field. I can only suggest that you double check your field and Views settings to make sure all is correct.
Comment: I am using D7.19 - Views 3.5. I created new view for this content type and delta fields are showing up only for term reference field, image field and text field. For integer, list (integer) and decimal field it does not. I have tried same on another installation and got same result (D7.16 - Views 3.5).

Taxonomy terms as numbers?


Making a REST AJAX call from Basic Page

Question: The following successfully calls a REST Services Module endpoint when contained in a module but I cannot get it to work within the script tags of a basic page.
<code>(function ($) {

  var myapi = {
    'apiPath': '/api/award'
  };

  // REST functions.
  myapi.create = function (award) {
    $.ajax({
      type: 'POST',
      url: 'http://localhost/testsite/api/award',
      data: JSON.stringify(award),
      dataType: 'json',
      contentType: 'application/json'
    });
  };

  myapi.create({ award : 'The Award' });

}(jQuery));
</code>
I am wondering if it is even possible to embed AJAX calls in a Basic Page.
Thanks for any help,
Orville
Comment: What input format do you use? how that input format configured?
Comment: Is there any errors in error console ?
Comment: I am fairly new to Drupal development.  I am not sure what you mean by input format and error console.
Answer: It turned out to be a 401 error that only occurred when the user was not logged in. Changing the 'access arguments' string in the hook_services_resources array fixed the problem.

Making a REST AJAX call from Basic Page


Induction Proof, $n^2$ is even $\implies$ $n$ is even

Question: If $n^2$ is even $\Rightarrow$ $n$ is even.
Test: $n = 1$. $2^2 = 4$ is even $\Rightarrow$ $2$ is even.
Assuming: $P(k)$ is true with $k$ even.
Test: $P(k+2)$: $k+2$ is even.
I can't finish it. I do not know what to do.
Comment: I think you'll find proving the contrapositive is easier:  $n$ odd $\Rightarrow n^2$ is odd.
Comment: What is $P(k)$? What have you tried?
Comment: I think the statement "Given $k^2$ even, $k$ is even".
Answer: $$(k+2)^{2}=k^{2}+4k+4$$
Suppose $(k+2)^{2}$ is even. Then, as $4$ and $4k$ are even, $k^2$ is forced to be even (if it were odd, equality could not hold above as odd does not equal even). Invoking $P(k)$, it follows $k$ is even and therefore $k+2$ is too.
Answer: You start off by assuming the inductive hypothesis. That is, assume that $k^2$ being even implies that $k$ is even. Now, we further assume that $(k+2)^2 = k^2+4k+4$ is even and we set out to prove that $k+2$ is even. Thus, for some integer, say $l$, we have that:
$$k^2+4k+4 = 2l$$
Solving this for $k^2$ gives:
$$k^2 = 2l-4k-4$$
Factoring a two out from the right hand side gives:
$$k^2 = 2(l-2k-2)$$
Thus, by definition, $k^2$ is even. So we can invoke the inductive hypothesis to say that this implies that $k$ is also even. So one can quickly see that this implies $k+2$ is even and the proof is complete.
Answer: HINT: Is $(n+2)^2$ even? Is the addition of even numbers even?
Answer: First, note that $1^2=1$ is odd.  Now assume that we know for some odd $k$ that $k^2$ is odd.  Then $(k+2)^2=k^2+4k+4$ is the sum of an odd term ($k^2$) and an even term ($4k+4$), so it too must be odd.  You have now proved by induction that $k$ odd $\Rightarrow k^2$ is odd, which means that if $k^2$ is even, $k$ must also be even.
You can use a similar argument to prove that in fact any even number does have an even square (in other words, $k$ even $\iff k^2$ is even), but that's not necessary to prove what you've been asked to prove.
Answer: $2$ is prime, so one can apply Euclid's lemma, to get:  $2|n^2\implies (2|n\lor2|n)\implies2|n$.
I don't see any need for induction.


Which distribution should I use when building a GAM in R?

Question: What type of distribution would you consider this data to be? My first thought is an f-distribution, but I suppose it could also be a poisson distribution. I am trying to build a generalized additive model (gam) that takes time compnents of an EMS call (things like response time, time at scene, time to hospital, etc.) to see how well specific parts of an EMS run can explain the overall call time.
The gam function in R (using the mgcv package) uses family=" " to identify the distribution of the gam. The f-distribution is not a family type. Does anyone know why not? Should I go with the poisson distribution? That said, I have tried both gaussian and poisson in test gam models. I had a deviance explained = ~70% for the gaussian gam and only deviance explained = ~50% for the poisson. Should I go with whichever distribution gives me the higher deviance explained value? Thanks!
Answer:
What type of distribution would you consider this data to be?

it's largely irrelevant what that looks like, since you have here the marginal distribution, but the GAM will be modelling the conditional distributions (conditional on the predictors, that is).

My first thought is an f-distribution, but I suppose it could also be a poisson distribution.

If it could be one, it could not possibly be the other, since one is continuous and the other is discrete. But again, it doesn't matter for this problem.

The f-distribution is not a family type. Does anyone know why not?

Because the F is not exponential-family.
If there's a strong need for an F, there are other things you might try (but I see no reason to think that there is any need for an F at all, other than a very superficial similarity of the - irrelevant - shape of the marginal distribution).

Should I go with the poisson distribution?

I don't see why this would be a reasonable choice. Times aren't discrete. Even if that wasn't an issue, I see no reason to expect that the variance will be equal to the mean. Indeed, since you'd expect the spread-mean relationship not to depend on your time-unit, I'd plump for variance proportional to mean-squared (which suggests Gamma or lognormal as two easy options)
My first choice for times would typically be Gamma, with either a log link or an inverse link (or rarely, perhaps identity), depending on my understanding of the circumstances. In some circumstances I might transform times (to speeds or log-times) and try to model those.
There are other possibilities - inverse-Gaussian or Tweedie**, for example
**(not available by default, but there's a package that should make it work with GLMs and GAMs)


Is there any way to attach a database created in MS SQL Server 200808R2 to a SQL08 server?

Question: I created a database using a november CTP preview of MS SQL Server 2008R2. Is it possible to transfer this database to use with older version, SQL Server 2008?
Comment: Have you tried backing it up on the R2 SQL and restoring on the 2008?
Should work. I know 2008 to 2005 doesn't so maybe this is the same.
Comment: No, restoring didn't work. server 2008 showed message that his version is older then the version of server created backup
Answer: No, you can never downgrade by backup/restore or detach/attach
Your best bet is to use the wizard or an SSIS package
From Paul Randall's myth series, item 24h
Comment: I managed to do it whrough import.export wizard and specifying instances using `tcp:ip/instanceName` syntax.
Answer: If backup/restore doesn't work, here's a couple of other ideas:

BCP the data
use replication to copy the data to a 2008 instance
if the dataset isn't ridiculously large, write a script to do it


What if a rule doesnt fire or is interrupted because of server down etc?

Question: I have several rules that need to be fired after certain events.
When an event occurs and the rule starts execution, and something happens to the server, it may not finish.
Is there a way to make sure a rule will always execute?
I am asking for a method like a transaction occurs in MySQL. I need to be sure that a rule is executed to ensure data integrity.
Answer: To my knowledge there is no such thing as "make sure a rule will always execute?" (as in your question). However, by using the Message module, you can create your own custom "Events logging" (to register things that happened in a site).
A great sample of this you can find in Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).
So in your case, if you'd create an appropriate events logging of all sorts of Rules related Events that you're interested in (= are critical enough?), then at least you'd have appropriate data you can use to investigate if anything went wrong.
To actually do so, for any of your Rules, you could add these Rules Actions to them:

create a "Start Rules Action"-message (as the very first action).
create a "Stop Rules Action"-message (as the very last action).

With that, for any set of Rules Actions that started executing, you can check if you have 2 corresponding messages.
Here is a variation that might work also: instead of creating such "Stop Rules Action" message, you could also use the Flag module to flag the corresponding "Start Rules Action" (the Message module creates messages as entities, so you can flag them for sure). Such flagging would indicate that the set of Rules Actions completed without problems. And to list all the groups of Rules Actions that were interrupted, you'd just have to use the Views module to report about all  "Start Rules Action" messages that were NOT flagged ... Piece of cake, no?
Attention: this covers the part related to Rules Actions, not (yet) something like "what are all Rules Events that were triggered but for which not even 1 Rules Action (= create the start-message) had started (because of some kind of interruption).
Comment: @SinanErdem for me having "many rules" is not a reason to not use such approach (it's just a matter of time to get each of them adapted). I don't understand why this may cause problems in data integrity. Though I do agree that **all** (not just "almost all") Drupal systems are susceptible to this. Which is also why afer reading your question I got an idea for a new Rules related wrapper-module (similar to how the execution of online transactions in a mainframe environment work ... with checkpoints, unit of work, etc).
Comment: @SinanErdem : I fully agree, and I bet that anyone who comes up with a robust solution for that, is going to get a lot of interest from the huge Drupal sites. Compare it to banking transactions (running on a Mainframe), where failure is not an option.
Comment: Thank you for your elaboration. I am also doing a similar check for certain rules. But it is very difficult to implement such mechanism for many rules in a system. This may cause problems in data integrity and I think almost all Drupal systems using rules are susceptible to this.
Comment: I couldnt explain myself correctly. I wanted to say, difilculty/absence of that kind of a system causes data integrity problems. Such a tool as you suggest would be very helpful in every rules environment.


Should I completely turn off swap for linux webserver?

Question: Recently my friend told me that it is a good idea to turn off swap on linux webservers with enough memory. My server has 12 GB and currently uses 4GB (not counting cache and buffers) under peak load.
His argument was that in a normal situation server will never use all of its RAM so the only way it can encounter OutOfMemory situation is due to some bug/ddos/etc. So in case swap is turned off system will run out of memory that will eventually crash the program hogging memory (most likely the web server process) and probably some other processes. In case swap is turned on it will eat both RAM and swap and eventually will result in the same crash, but before that it will offload crucial processes like sshd to swap and start to do a lot of swap operations resulting in major slowdown. This way when under ddos system may go into a completely unusable condition due to huge lags and I probably will not be unable to log in and kill webserver process or deny all incoming traffic (all but ssh).
Is this right? Am I missing something (like the fact that swap partition is very useful in some way even if I have enough RAM)? Should I turn it off?
Comment: So, all the answers boil down to statements that 1. more virtual memory is unconditionally better than less, and 2. there must be some swap enabled because it's good neither of which are well grounded.
Comment: It is misguided to think that swap is exclusively meant for 'reserve' memory. Swap is meant for a place to put unused memory (so you can use your actual memory more efficiently). You should always have swap. If your out of memory, then your out of memory - period. This is a problem of capacity management - not tendency to swap. I have a rather long response http://serverfault.com/a/332205/75118 that tries to better explain the virtual memory intentions.
Answer: I would say it depends on your use case and the rest of the answers have covered this pretty well. 4G of swap are after all a cheap way to buy some safety. And I feel that this cheapness is what is making people not want to turn it off.
But let me answer with a rhetorical question. If money is not an issue, and you have a choice between two systems - one with 12G of RAM and 4G of swap, and another with 16G of RAM and no swap - which one would you choose? Unfortunately most people would still answer that they'd choose 16G of RAM and still add 4G of swap, which is missing my point.
And on another note, I personally find a swappy system worse than a crashed system. A crashed system would trigger a standby backup server to take over much sooner. And in an active-active (or load balanced setup) a crashed system would be taken out of rotation much sooner. A win for the no-swap system again.
Answer: It is NOT recommended to turn off swap even if you have enough memory. If your server needs more memory and it did not get it, it will crash. However, this can be prevented (to some extent) when you have a swap area.
Yes, your server performance will degrade when using swap, but at least it will be operational and accessible. Then, you can plan for adding more memory when needed if your server starts using swap.
I found this page talking about swap. Have a look at 3rd section.
Instead of turning off swap, you can control the swapiness.
Comment: In situation I described it will consume *both* swap and RAM and also will crash. It is running for a few months and it never used more than 30% memory. So it is very unlikely that it will jump to 100% so quickly during normal operation. So if some process went crazy and consumed 8GB it means that it will consume as much memory as OS can get, that means all of it.
Comment: @Poma, there are other benefits of swap as well. Also, you can allow the system to live much longer when you have a swap. This is because swap can be larger than memory given the availability of cheap HD drives.
Answer: No, it is not a good idea. 'some process went crazy'  means  you should have proactively already called
ulimit -d
at or before process creation time to set a limit on per process data segment memory -- And maybe a limit to the number of threads
ulimit -T
per process.  ulimit is your friend.  Please consider reading one of the memory tuning guides before you turn off swap. You can change kernel parms as well to some things to try to handle DOS attacks or bad programs.
Look at it this way:
The total memory on your system is RAM + swap.  If you have 12GB of swap, you just effectively cut the system VM capacity in half, by disabling swap.  Bad idea.  This isn't a debate, really, it is simply reading what other people have known from previous bad experiences for years.  It is possible your friend needs to do some reading as well.
Answer: As others have said, you can effectively stop your server using swap except when absolutely necessary by tinkering with the "swappiness" parameter. This controls how aggressively the kernel will swap out memory pages.
You can see what it's currently set to with:
cat /proc/sys/vm/swappiness

and you can edit it "live" with (as root):
# echo "10" > /proc/sys/vm/swappiness

and to make it persist, add the following to /etc/sysctl.conf:
vm.swappiness=10

Answer: Another good thing that you can do is swap into RAM using zRAM. I think that this is a great idea! For performance, is like not having swap at all, but also prevents the crashes when the system is very loaded!
Look at this:
http://www.webupd8.org/2011/10/increased-performance-in-linux-with.html
My experience: In this machine where I'm writing now, I disabled the swap, cause I have 4Gb RAM (in 2009 it was a lot!). I only experienced a couple of problems, one of them was opening like 127 pictures at the same time by mistake!
BUT.. this is a workstation, and I can afford to reboot if it hangs. In a server I think is better to have swap, and the swap-in-RAM sounds good to me.
Answer: As has already been made abundantly clear, this is not a good idea. If nothing else, swap gives you some breathing space for when things aren't quite normal. e.g. On one system I look, which normally has only a few visitors per day, there was a massive traffic spike caused by a page being mentioned in a magazine. This resulted in the web server using swap space for the first time since it was commissioned. Without that swap space things would not have gone very well.
Answer: Not a good idea. You can define 2 swap files with different priority. One smaller that is in use
and one larger that will be used in case the first fills.
Also vm.swappiness can help you control how aggressively the disk swapping occurs.
Answer: If you inset a 0 to vm.swappiness that doesn't necessarily mean that the system will not swap. It is a parameter to determine how aggressive kerne's tendency would be to swap but it doesn't turn off swap.
Again, swapping is not bad but thrashing is. Take a look of the sysstat data and that should give pretty good pointer on it.


Consulta SQLITE retornando valor fora da regra de consulta

Question: Fiz um programa, em linguagem python, que cria um banco de dados SQLITE que armazena informações sobre uma quantidade de portas de uma armário. As informações armazenadas são: id (identificação da porta), tamanho (PQ = pequeno, MD = médio, GD = grande), habilitado (true/false), ocupado (true/false), qtd_ciclos (quantidade de vzs de uso da porta). Segue abaixo o código:
import sqlite3

class Database:
    def __init__(self):
        try:
            self.conn = sqlite3.connect(r'C:\db\teste_sqlite_db.sqlite')
        except sqlite3.Error as e:
            print(str(e))
            raise

    def init_tables(self):
        try:
            # Cria tabela das portas
            self.conn.execute('''CREATE TABLE IF NOT EXISTS porta(
                                id INTEGER PRIMARY KEY,
                                tamanho VARCHAR(2) NOT NULL,
                                habilitado BOOLEAN NOT NULL,
                                ocupado BOOLEAN NOT NULL,
                                qtd_ciclos INTEGER NOT NULL
                                )''')
            self.conn.commit()
        except sqlite3.Error as e:
            print(str(e))
            raise
        finally:
            self.conn.rollback()

    def close(self):
        try:
            self.conn.close()
        except sqlite3.Error as e:
            print(str(e))
            raise

    def insert_porta(self, id: int, tamanho: str, habilitado: bool, ocupado: bool, qtd_cliclos: int):
        ret = 0

        try:
            self.conn.execute('INSERT INTO porta(id, tamanho, habilitado, ocupado, qtd_ciclos) '
                          'VALUES (?, ?, ?, ?, ?)', (str(id), tamanho, str(habilitado), str(ocupado),
                                                     str(qtd_cliclos)))
            self.conn.commit()
            ret = 1
        except sqlite3.Error as e:
            print(str(e))
            raise
        finally:
            self.conn.rollback()
        return ret

    def select_porta_com_menor_qtd_ciclos(self, tamanho: str, habilitado: bool, ocupado: bool):
        try:
            cur = self.conn.cursor()
            cur.execute(
            "SELECT * FROM porta WHERE qtd_ciclos = (SELECT MIN(qtd_ciclos) FROM porta WHERE tamanho='{}' AND "
            "habilitado='{}' AND ocupado='{}');".format(tamanho, habilitado, ocupado))

            rows = cur.fetchall()

            print("========================")
            for row in rows:
                print("ID: {}".format(row[0]))
                print("TAMANHO: {}".format(row[1]))
                print("HABILITADO: {}".format(row[2]))
                print("OCUPADO: {}".format(row[3]))
                print("QTD_CICLOS: {}".format(row[4]))

            cur.close()
        except sqlite3.Error as e:
            print(str(e))
            raise
        return rows

def main():
    database = Database()
    database.init_tables()
    database.insert_porta(1, 'PQ', True, False, 10)
    database.insert_porta(2, 'PQ', True, False, 9)
    database.insert_porta(3, 'MD', True, False, 8)
    database.insert_porta(4, 'MD', True, False, 15)
    database.insert_porta(5, 'GD', True, True, 2)
    database.insert_porta(6, 'MD', True, False, 5)
    database.insert_porta(7, 'PQ', False, False, 8)
    database.insert_porta(8, 'MD', True, False, 5)
    database.insert_porta(9, 'GD', True, False, 7)
    database.insert_porta(10, 'MD', True, False, 7)

    database.select_porta_com_menor_qtd_ciclos('PQ', True, False)
    print("===========================================================")
    database.select_porta_com_menor_qtd_ciclos('MD', True, False)
    print("===========================================================")
    database.select_porta_com_menor_qtd_ciclos('GD', True, False)

    database.close()

if __name__ == "__main__":
    main()

As regras da consulta dos registros das portas é: Retorna do banco a(s) porta(s) com menor uso (qtd_ciclos), sendo que, ela tenha determinado tamanho (PQ, MD ou GD), esteja habilitada (habilitado = true) e desocupada (ocupado = false).
Conforme pode-se verificar no método def select_porta_com_menor_qtd_ciclos(self, tamanho: str, habilitado: bool, ocupado: bool) a query de consulta ficou da seguinte maneira:
cur.execute("SELECT * FROM porta WHERE qtd_ciclos = (SELECT MIN(qtd_ciclos) FROM porta WHERE tamanho='{}' AND habilitado='{}' AND ocupado='{}');".format(tamanho, habilitado, ocupado))

Eu criei a seguinte tabela para testar a consulta:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><title>Exported table: porta</title>

Table: porta

#	id
INTEGER	tamanho
VARCHAR	habilitado
BOOLEAN	ocupado
BOOLEAN	qtd_ciclos
INTEGER

1	1	PQ	True	False	10

2	2	PQ	True	False	9

3	3	MD	True	False	8

4	4	MD	True	False	15

5	5	GD	True	True	2

6	6	MD	True	False	5

7	7	PQ	False	False	8

8	8	MD	True	False	5

9	9	GD	True	False	7

10	10	MD	True	False	7

Document generated by SQLiteStudio v3.1.1 on qua mai 8 10:20:34 2019

Ao fazer o teste, quando procuro pelas portas PQ (pequena) a consulta retorna corretamente as portas de ID 9 e 10, ambas possuem mesma quantidade de ciclos (7). (Verifique na tabela);
Quando procuro pelas portas MD (média) a consulta retorna corretamente as portas de ID 6 e 8, ambas possuem mesma quantidade de ciclos (5). (Verifique na tabela);
Porém, quando procuro pelas portas GD (grade) a consulta retorna erradamente. Era para retornar apenas a porta com ID 9 com 7 ciclos, porém, além da porta com ID 9, a consulta também retorna a porta com ID 10 que é uma porta de tamanho MD (média), mas coincidentemente com 7 cilcos também. (Verifique na tabela);

Alguém saberia me dizer porque a consulta pela porta GD (grande) se comporta dessa maneira? Não estou conseguindo encontrar o problema.
Comment: Poderia elaborar um [mcve] do problema? Há muito ruído na pergunta. Se o problema é que a consulta está retornando dados errados, basta colocar na pergunta a consulta que fez, junto com os dados que estão na tabela, descrevendo qual foi o resultado e qual era o esperado. Parece-me que todo esse código em Python e HTML não tem relação alguma com o problema.
Comment: @AndersonCarlosWoss o próprio código é um exemplo verificável, ele possui uma main que cria o banco, insere os registros exatamente de acordo com a tabela e faz as consultas que citei: Consulta portas PQ (pequena), consulta portas MD (media) e portas GD (grande). Basta copiar o código e rodar o arquivo.
Comment: Eu vou adicionar como eu fiz as consultas ao banco na descrição do problema.
Comment: Isso seria um bom [mcve]: https://www.db-fiddle.com/f/e2dnNjmidkABv2RMXNejTz/0. Você tem a tabela, tem os dados e tem a consulta. Tudo o que você precisa na sua pergunta. É só descrever porque o resultado que obteve não era o resultado esperado. Não precisa ter Python e HTML no meio.
Comment: Eu agradeço pela observação, mas creio ter feito de acordo com o tutorial que você linckou. O código está o mais simples possível com relação ao código real. Ele reproduz o cenário necessário para o erro e o mesmo é gerado. A tabela visual é a tabela que o código cria no banco e que gerará o erro. Resumindo, o código cria o banco, insere as informações exatamente conforme a tabela, faz as consultas citadas na explicação e gera o erro sem precisar editá-lo, talvez, somente editar o diretório do banco. Mas levarei sua crítica em consideração e tentar melhorar minhas próximas perguntas. Obrigado.
Comment: Sim e isso já é de grande ajuda. A questão que eu quis levantar é que mesmo dando para reproduzir o problema você consegue eliminar bastante coisa que é ruído e simplificar bastante a sua pergunta.
Comment: Entendi! Creio que preciso melhorar nisso, mesmo. Vou me atentar mais a isso. Valeu.
Answer: O problema de lógica que você tem não é do Python, e sim do SQL  -
a sua consulta é:
SELECT * FROM porta WHERE qtd_ciclos =
    (SELECT MIN(qtd_ciclos) FROM porta WHERE
          tamanho='{}' AND habilitado='{}' AND ocupado='{}'
     )

Ou seja - o select de fora só tem uma condição de where, que é a "qtd_ciclos". O select interno sim, tem a constraint de tamanho da porta, e habilitado, e ocupado - mas retorna apenas um númrero (no caso do seu exemplo, 7) - e a consulta externa então retorna todas as portas com aquele número de ciclos, independente de tamanho, "habilitado" ou "ocupado".
As soluções óbvias são ou colocar as 3 condições também no select de fora, ou criar um único select, e ordenar a query pela ordem decrescente da qtd_ciclos - os primeiros resultados serão os menores ciclos, e você filtra do lado do Python os valores iguais.
Dito isso - algo importantíssimo no quesito segurança - apesar do Python ter diversas maneiras de formartar strings, ao usar queries SQL - seja sqlite, ou qualquer outro conector, é importante deixar o driver de sql posicionar os parâmetros, e não usar o método .format ou outra forma de formatar a string - isso evita que parâmetros maliciosos possam ser usados para SQL injection.
Aqui vai como pode ficar a chamada ao cursor.execut para os dois estilos.
(outra coisa é que apesar de algumas regras de estilo recomendarem o uso de
" em todas as linhas de strings longas, como o seu SQL, e contar com a concatenação do compilado, é muito mais conveniente usar as strings com aspas triplas - """ -  e colocar toda a query numa única string - isso evita dificuldade de digitação na query, dificuldade na leitura, possíveis problemas
por esquecer ou sobrar uma " em algum lugar, entre outras coisas.  Nunca deixe as "normas de estilo" atrapalharem em vez de ajudarem.
cur.execute("""
    SELECT * FROM porta WHERE
        tamanho=:tamanho AND
        habilitado=:habilitado AND
        tamanho=:tamanho AND
        qtd_ciclos= (SELECT MIN(qtd_ciclos) FROM porta WHERE
              tamanho=:tamanho AND
              habilitado=:habilitado AND
              ocupado=:ocupado
         )
    """,
   {"tamanho": tamanho, "habilitado": habilitado, "ocupado": ocupado}
)

Usando a notação de "named parameters" (https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor ), você passa um dicionário com chaves:valores no segundo parâmetro do execute - e deixa o Python pegar os valores, converter para SQL (valores numéricos, booleanos e datas são convertidos automaticamente para a notação do SQL, por exemplo, sem nunca ser necessário uma conversão explícita do tipo str(...) - além de se evitar qualquer ataque de SQL injection - e, nesse caso, de se passar cada parâmetro uma vez só, mesmo que sejam usdos duas vezes na query. (Parâmetros puramente posicionais - seja como você estava usando o "format", seja com a notação de ? do SQLite
são propensos a erro na ordenação, e de difícil verificação ao se fazer o review do código).
(observe também que o ; final do statement de SQL não deve ser usado - ele é uma sintaxe do uso interativo do SQL, não dos comandos Select - O sqlite o ignora, mas há drivers de banco de dados em que a inclusão do  ; é um erro de sintaxe)
Comment: Obrigado pela ajuda e pela aula. Sou novo tanto em python quanto em SQLITE. Sua explicação ajudou bastante e agregou conhecimento. Valeu!