Block device writes

Question: I am trying to understand how block device writes work. My understanding is all writes need to be sector aligned. So if the sector size 512 bytes then all writes are of size 512 bytes. Now let us say I create a file and start writing sequentially into it (no buffering on the application side). Now suppose I start by writing 16 bytes at offset zero of the file. How does this translate into a write at the block level? Is it buffered till I have written a "sector size" amount of data and then pushed out to disk? If fsync is called are the remaining bytes padded and then written out? Is the understanding correct or am I way off.
The follow up question was the following. If I have a file say of size 64K. Let us say I perform a random write of 16 bytes at offset 64. Then the appropriate sector of 512 bytes is read the 16 bytes are written into the buffer at offset 64 and then the 512 bytes written out to disk. Is the understanding correct?
Answer: It's called Read-Modify-Write: you must first read the sector, change the bytes requested, and write it back.
Only in the case of full-sector writes can you ignore this step.
I don't know about Linux, but in Windows' case, it normally performs buffering as you mentioned until the buffer is full (the buffer is likely a multiple of the sector size), or it avoids buffering entirely and throws an exception if the write is unaligned or not a full sector, depending on whether or not you requested buffering.

Block device writes


Recuperar dimensões de matriz em Python

Question: Alguém pode me ajudar a escrever a função "dimensoes(matriz)" que receba uma matriz como parâmetro e imprima as dimensões da matriz recebida, no formato iXj?
def crie_matriz(n_linhas, n_colunas, valor):

    matriz = []

    for i in range(n_linhas):
        linha = []

        for j in range(n_colunas):
            linha.append(valor)
            matriz.append(linha)
    for n in matriz:
        print(''.join(map(str,matriz)))
    return matriz

a = crie_matriz(2,3)

print(a)

O código acima que fiz imprime a saída, mas a questão pede para imprimir a dimensão conforme o exemplo abaixo:
minha_matriz = [[1], [2], [3]]
dimensoes(minha_matriz)
3X1

minha_matriz = [[1, 2, 3], [4, 5, 6]]
dimensoes(minha_matriz)
2X3

Comment: Podes colocar o código que tens sff
Comment: @Miguel adicionei o código que fiz, mas tá incompleto.
Answer: pode usar a biblioteca numpy, que ja vem com o método de retornar as dimensões da matriz/array
ex:
import numpy as np

np.array([[0, 1, 2],
          [3, 4, 5]]).shape

imprime (2,3)
que quando armazenado em uma variavel vc sempre pode chamar .shape
ex:
import numpy as np

x = np.array([[0, 1, 2],
              [3, 4, 5]])

print(x.shape)

ainda se quiser pegar a transposta, ex:
print(x.T)

imprime:
array([[0, 3],
       [1, 4],
       [2, 5]])

boa diversão!
Answer: Podes fazer o seguinte:
tam_matriz = (len(minha_matriz), len(minha_matriz[0]))

Isto vai dar um tuple, neste caso: (2, 3)
Podes imprimir assim:
print('{} x {}'.format(tam_matriz[0], tam_matriz[1]))

Ou com uma função:
def dimensoes(m):
    return (len(m), len(m[0]))

print(dimensoes(minha_matriz)) # (2, 3)

Answer: O código ficaria assim:
def dimensoes(matriz):
tam_matriz = (len(matriz), len(matriz[0]))
print('{}X{}'.format(tam_matriz[0], tam_matriz[1]))

Se a questão pede para imprimir, tem que usar o comando 'print', se pede para retornar ou devolver, use o comando 'return'
Comment: Olá Eduardo Oliveira, tentei como vc falou inseri a variavel e o print, substituindo o "print(''.join(map(str,matriz)))" pelo "tam_matriz = (len(matriz), len(matriz[0]))
print('{}X{}'.format(tam_matriz[0], tam_matriz[1]))". Porém não está dando certo. Por exemplo quando chamo a função "cria_matrizes(2,2,0), o código tá imprimindo "4x2" quatros vezes. Qual o erro do meu código?
Comment: O código é exatamente esse que você pediu, nada mais. Se está pedindo para criar uma função 'dimensoes', não vai ser necessário essa função 'cria_matrizes' que você citou.
Answer: Olha eu fiz desta forma, não é a melhor, porém, funcional:`
def dimensoes(matriz):
colunas = 0
linhas = 0
qtd_colunas = 0
a = ''
for i in range(len(matriz)):
    linhas = linhas + 1 # soma a qtd de linhas
    colunas = matriz[i] # Armazena os itens de cada linha
for w in colunas: # Ira interar a qtd de itens da ->ÚLTIMA<- lista dentro da matriz.
    qtd_colunas = qtd_colunas + 1
a = print('{}X{}'.format(linhas, qtd_colunas))

return a

Recuperar dimensões de matriz em Python


Create bulk nodes - PDOException

Question: Problem
I'm trying to create multiple nodes at once using a CSV file for the data. However my script only creates the first 25 before it throws the following error. Any ideas what might be happening?

PDOException: in drupal_write_record() (line 7166 of C:\XAMPP\htdocs\drupalie\includes\common.inc).

Set-Up
I have a custom form which creates the nodes on submit. The form just has a submit button.
This is the submit handler. I only have one column in my CSV sheet so I don't actually use the delimiter. First I generate an array with each node name.
<code>  if (($handle = fopen("sites/all/modules/custom/generatenodes/nodes_database_import.csv", "r")) !== FALSE) {
    //open the CSV file
    $length = 1000;
    $delimiter = "|";
    //set the length and delimiter.
    while (!feof($handle)) {
      //$line is an array of the csv elements
      $node_name_array[] = fgetcsv($handle, $length, $delimiter);
    }

    fclose($handle);
  }
</code>
The array looks like this:
I then create the nodes:
<code>global $user;
foreach ($node_name_array as $nodename) {
  if($nodename == FALSE) {
    return;
  }

    $values = array(
      'type' => 'school',
      'uid' => $user->uid,
      'status' => 1,
      'comment' => 0,
      'promote' => 0,
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);

    $ewrapper->title->set($nodename['0']);
    $ewrapper->field_country->set($schoolname['0']);
     $ewrapper->save(true);
    entity_save('node', $entity);
}
</code>
But it breaks after the first 25 or so. What have I missed?
EDIT--
So I found the cause. It's to do with the values in my CSV file. Sometimes it likes them othertimes it doesn't. If I replace these values then it works up to the next broken value.
The first problem was a value with an accented e inside. Removing the accent fixed it.
Unfortunately the next two which broke it are not so obvious:

Putian Cambridge English
Zhangzhou Bilingual Middle School

Yet the following values work:

Quanzhou Foreign Language Middle School
International College of Xiamen University

I've only pasted in clean values, but something is breaking it. Any ideas?
Trying to navigate to the content page after causes MySQL to break. Here's the error log:
https://www.dropbox.com/s/jji3cw559filq03/mysqlcrash_log.txt
Comment: @Molot So after some digging I found it's the values in the CSV file which break it. The first was an accented e, but I can't spot a pattern otherwise.
Comment: Are you sure it's the whole message? No exception name, number, message, nothing? Nothing in db_log or server's error.log?
Comment: @Molot I don't think so. The last errors are from two hours ago so unless it updates in periodic chunks and the errors haven't appeared there is nothing in apache or mysql logs.
Comment: That's weird, usually when you get PDO exception, it carry underlying MySQL / PostgreSQL error message. If it does not, it'll be hard to tell what exactly is wrong.
Comment: @Molot MySQL does now crash and create an error log, but only when I go to the content page. Added to the post.
Answer: You should be using migrate for this: https://www.drupal.org/project/migrate, it covers many of the pitfalls you are currently encountering when creating or importing content from a CSV, database or XML file. Don't recreate the wheel when someone has already created it for you.
It's not like the feeds module or other "import" type modules, it's an entirely  code based OOP solution. You just extend the main migration class and map your data. It comes with a number of built in PHP functions to process the data further and it literally covers almost every scenario you could possibly encounter when mass creating or transferring content.
As someone who's been down this path many times, it will save you a lot of time and hair pulling. I recommend looking at the code examples migrate provides.

Create bulk nodes - PDOException


Interpretation of intercept in random-effects only LMM

Question: I am using LME4 to fit models for a repeated measures study in psychology. Before jumping in to my fixed effects, I decided to start by comparing different random effects structures. I fit a number of models with differing random effects structures, and (thought!) I understood the output. But I noticed (see model output below) that each model yields a different overall intercept. I thought the intercept in the models would be the Grand Mean (M = 59.2994) since no fixed effects were specified. But in that case, shouldn't the intercept be the same for all models?
Here are the four random-effects only models I'm comparing:
(subject is a random factor, the fixed factors are prefaced with f_ and refer to aspects of the 'treatment' subjects received).
#RANDOM EFFECTS STRUCTURES
randoms <- list(
  "A" = lmer(r_strength ~ (1|subject), data = df_blocks, REML = FALSE),
  "B" = lmer(r_strength ~ (1 + f_graph | subject), data = df_blocks, REML = FALSE),
  "C" = lmer(r_strength ~ (1 + f_direction | subject), data = df_blocks, REML = FALSE),
  "D" = lmer(r_strength ~ (1 + f_version | subject), data = df_blocks, REML = FALSE)
)

And here is a table (using modelsummary) of the estimates:

Note that model B is the maximal theoretically-justified random effect structure. My planned next step was to compare models adding fixed effects and their interactions, but I don't want to push forward until I really understand the output I have :)
(Thanks in advance! I'm a PhD student and long-timer lurker, first time poster. I have learned so much from this community and am so grateful for the time perfect strangers devote to helping others do better statistics! )
Comment: 0. Welcome to the CV.SE community. 1. Fun little question (+1). $x_0$ has a "special meaning" and it is not something to simply marginalise out (under `REML` or `ML` estimation). Please see my answer below for more details.
Comment: Thank you so much!
Answer: The fixed intercept (effectively a columns of $1$'s in our design matrix $X$) is not "just another $x_j$" variable. That is because it is estimated at the bottom/$0$-th level of our LMM and supersedes any grouping factor we might have. As such, $\beta_0$ corresponds to all variables $x_{ij}$ being set to 0; in models B/C/D  where f_graph, f_direction, f_version are respectively used this changes the interpretation of $\beta_0$. And this is why the r_strength ~ (1|subject) leads to the estimate that is closest to the grand mean; in that case $\beta_0$ is reflecting the "grand mean" as it  marginalises out the random subject-specific variation that is itself hypothesised to be in the form of: $N(0, \sigma_{\text{Subject}})$.


Intuition behind $i^{i}$.

Question: My query is about the $i^{i}$ , where $i$ is defined to be the imaginary unit, and $i \in C$.
I know the proof of this value, we just have to substitute $i$ as $\large{e^{i\left(\frac{\pi}{2}+2n\pi\right)}}$. Where $n$ is any integer because all these values corresponds to "$i$" right?
Which gives us, $i^{i}=\large{e^{-\frac{\pi}{2}+2n\pi}}$ Where $n=0$, is the principal value. $i.e.,$ $e^{-\frac{\pi}{2}}$.
I mean this result always blow my mind, to be honestly speaking. Not only that $i^i$ despite being a complex number raised to a complex number. It also attains a real value! And that too not just one, but many!
My question would be that first, is this result strictly valid in accordance to mathematics? Are there any loopholes in defining it as such? Here's what I think it could be of importance http://www.cut-the-knot.org/do_you_know/complex.shtml as some quotes in this page indicates.
Secondly, is there any intuition behind why could it be so, even if it could, the idea that it can take infinitely many values on $\mathcal R$ just by changing "$n$" is still hard kind of.
Comment: consider just the simple case, $z^{1/2}$, we see, when $z$ is a complex number, that this  "function" has two values for every $z$. In general $z^w$ has a single value only when $w$ is an integer. It has exactly $q$ values when $w=p/q$ is the reduced reprenstation of a rational number. In any other case, it has infinitely many values.
Comment: So $1^i$ even takes on infinitely many values.
Comment: For your first question: indeed, $i = e^{i (\pi/2 + 2n\pi)}$ is a direct consequence of [Euler's formula](https://en.wikipedia.org/wiki/Euler%27s_formula) $e^{ix} = \cos(x) + i \sin(x)$.
Comment: This question is very nicely discussed on this site, [link](http://betterexplained.com/articles/intuitive-understanding-of-eulers-formula/)'this'
Answer: I know that I added a "contradictory" comment as you will see, but a "rigorous" intuition will be,
$i^i=(\cos\frac{\pi}{2}+i\sin\frac{\pi}{2})^i$
Now, by De Moivre's Theorem,
$i^i=\cos i\frac{\pi}{2}+i\sin i\frac{\pi}{2}$
By thee Euler's Formula,
$i^i=e^{i^2\frac{\pi}{2}}$
$i^i=e^{-\frac{\pi}{2}}$
$i^i=\frac{1}{e^\frac{\pi}{2}}$
Which, according to my calculator is, $0.207879576...$.
Which is confirmed by google.
P.S.:I didn't prove it for $2n\pi$, just a case of it.
As far as you want the intuition, think the reverse, isn't it normal for the complex root of a real number to be complex? For example, $2^{\frac1i}$ is complex. So, the question you are asking is just the reverse of it.
I hope it makes sense.

Intuition behind $i^{i}$.


How to improve model fit of my predictive model?

Question: I am building a predictive model and hope to improve its model fit. I have 2 predictors, BMI (continuous variable) and smoking status (binary variable), and my outcome is disease status (yes/no).
Can someone please share how we can improve the model fit? I can only think of two possible approaches: 1) log transformation and 2) adding interaction or squared terms. Are there any other ways we can try?
Comment: If you have checked that the relationship with the predictors and the outcome (logit) is linear, adding a squared term should not be relevant here. You mentioned an interaction term, have you observed any?
Comment: In logistic regression, a relationship between the logit is assumed linear with your predictors. The response is not manipulated as is (meaning 0 and 1) but we are dealing with its log odds. To avoid duplicating content, please have a look at this simple illustration: https://stats.stackexchange.com/a/88607/321901
Comment: It is a broad question and we have few information… what have you done so far ? Have other variables to include in you model? What type of regression are you carrying out?
Comment: Hi, @Pitouille I am carrying out multivariable logistic regression. These two are my final predictors (I tried others and ruled them out). But now I want to make my model even better with just these 2 predictors (no more new predictors). Are those methods I proposed above valid? Hope this provides a bit more context!
Comment: "If you have checked that the relationship with the predictors and the outcome (logit) is linear, adding a squared term should not be relevant here." can you pls explain this part? Also, does this part apply to log transformation as well (i.e. if I observe a linear relationship, I won't need to log-transform my predictor)?
Answer: Your analysis should always be guided by existing knowledge and theory. Don't blindly run many models and pick the "best" one, even if you cross-validate, because you may simply be overfitting to the test set.
In my understanding, there is a reasonable assumption that there may be an interaction between smoking and BMI, so it would make sense to include it.
The relationship between BMI and almost anything else is probably nonlinear, so it would make sense to use a spline transform of the BMI. Frank Harrell's Regression Modeling Strategies provides an excellent overview of splines. These are better than square or other polynomial transformations. Of course, you can use interactions between smoking and spline-transformed BMI.
A binary smoking variable is very crude. "Smoking" can mean two cigarettes per day, or forty. There will be a difference. If you can get an estimate of the actual number of cigarettes smoked per day, it would probably make more sense to include this numerical predictor. You can also spline-transform it. Or use an interaction with BMI (which becomes hard to interpret).
In any case, use proper scoring-rules to assess your model, not accuracy.
Comment: Both are useful. To be honest, I think the difference between these two approaches is less important than making sure you avoid overfitting (which these will only guard against to a certain degree).
Comment: Hm. There is no automatic effect that p values would increase if you add an interaction term. However, the main effects' coefficients are hard to interpret in the presence of an interaction. If your LR test believes the interaction makes sense, then I would go with the model with the interaction, and only interpret the interaction. Best to plot the estimated logit of the response against BMI, separately for smokers and non-smokers, that will show the effect of the interaction.
Comment: Yes, exactly. It would definitely be good to look at the kind of interaction plot I suggested above.
Comment: One can always simulate some data to illustrate a situation like this, did you have something like this in mind? If so, perhaps post a new question, because that would be a bit too large for a comment (feel free to link to the new question here, and I'll try to take a look). Alternatively, here is a paper I was involved in where a spline transform (of traumatic load, interacting with genotype) did improve a logistic regression model (to develop PTSD): https://www.psychiatrist.com/jcp/trauma/ptsd/association-study-trauma-load-slca-promoter-polymorphism/
Comment: We spline transformed traumatic load before feeding the splines into the logistic model.
Comment: Yes, of course. It's just a question of `predict`ing the response for two different values of the predictor (so you would spline transform the predictor and feed it into the model, then predict), then calculate the OR, or any other KPI of interest, from those predictions.
Comment: Can you please create a new post for that question, including a [Minimal Working Example](https://stackoverflow.com/q/5963269/452096)? A helpful answer won't fit into a comment, and a specific thread on this will be helpful for later generations. Also, you might get answers from other people than me. Of course, feel free to link to that new question from here, and I'll try to take a look.
Comment: Meanwhile, perhaps one of [these questions](https://stats.stackexchange.com/search?q=odds+ratio+%5Bsplines%5D) is helpful? These two look especially promising: https://stats.stackexchange.com/q/328545/1352 and https://stats.stackexchange.com/q/127134/1352. You will notice that Frank Harrell answered both of them, his book *Regression Modeling Strategies* is very good.
Comment: I am thinking of using both the likelihood ratio test and AIC (information criteria) to assess my model. What do you think of these 2 approaches?
Comment: Thank you! I actually tried to include an interaction term, and here is what I have:  The model fit gets better (as evident by the LR test) but since I now have 3 predictors (smoking status, BMI, smoking status + BMI) instead of just 2, their respective p-values became higher & insignificant in this final model. My question is: should I still include this interaction term?
Comment: So, I know p-value isn't important when it comes to model prediction, but if the p-value of my interaction term is >0.05 (but this interaction term leads to better model fit), based on what we discussed, you would still include this interaction term in the model, correct?
Comment: Can you pls explain (or provide an example) when the spline transformation will be absolutely necessary for the logistic regression?
Comment: This is such a great paper! It helps me answer some of my questions. I have one question regarding the timing of the use of spline transformational. Do you use it before the analysis to ensure linearity or do it after the analysis to improve the model fit?
Comment: Do you know if it is possible to report the odds ratio from the spline-transformed predictor (or from the GAM)?
Comment: Really? I thought because the spline function creates multiple curvatures so a single odds ratio associated with a 1-unit increase of predictor is no longer possible. Can you pls provide me with an R code (or direct me to any other resource/posts) for how to get an odds ratio for the spline-transformed predictor?
Comment: Hi Stephan - I have posted a new question here. All the feedback is extremely appreciated. https://stats.stackexchange.com/questions/555416/restricted-cubic-spline-function-summary-intepretation
Answer: You could also create further categorical features from the numerical BMI like 'very underweight' up to 'highly overweight'. It might make it easier for your model to get improved predictions.
It might also make sense to change the algorithm. Why do you want to rule out algorithms like SVM and XG Boost before trying to tune them? These algorithms might get actually very good after tunning the parameters to your specific data set.
Comment: Yes, but create meaningful categories. Maybe you split it up into 'very_low_bmi' (x<20) and 'very_high_bmi' (x>35) and 'mid_bmi' for the rest. These were just examples, I am not very familiar on how to best categorise BMI. But in general this would be the idea.
Comment: Do you mean including BMI as a categorical variable (rather than a continuous variable) may improve prediction?


How to add search history functionality in flutter app

Question: I have recently add search functionality in flutter app and I want to add  search history functionality in my flutter app. I am stuck in this I have  no idea that how to add it.
Please give me instuction and also provide suitable code for it .
My code
<code>  TextFormField(
                keyboardType: TextInputType.text,
                textInputAction: TextInputAction.search,
                controller: searchcontroller,
                focusNode: fousnode,
        onChanged: (query) {
          setState(() {
            FirebaseFirestore.instance
                .collectionGroup("Add_product")
                .where("product_name", isGreaterThanOrEqualTo: query)
                .where("product_name", isLessThan: query + 'z')
                .snapshots();
          });
        },

                decoration: InputDecoration(
                  hintText: "Search Product",
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(11)),
                  ),
                ),
              )
</code>
<code>StreamBuilder(
              stream:
              FirebaseFirestore.instance.collectionGroup("Add_product").snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> snapshot) {
                List<QueryDocumentSnapshot> data = snapshot.data!.docs;
                if (searchcontroller.text.isNotEmpty) {
                  data = data.where((doc) => doc["product_name"]
                      .toLowerCase()
                      .contains(searchcontroller.text.toLowerCase()))
                      .toList();
                }
                return GridView.builder(
                  itemCount:data.length,
                  itemBuilder: (itemBuilder, index) {
                      return Container(
                        child: InkWell(
                          onTap: (){
                            Navigator.push(context, MaterialPageRoute(builder: (builder)=>detail(
                              url: snapshot.data!.docs[index]["url"],
                              productName: snapshot.data!.docs[index]["product_name"],
                              productPrice: snapshot.data!.docs[index]["product_price"],
                            )));
                          },
                          child: ListTile(
                            leading: CircleAvatar(
                              backgroundImage: NetworkImage(
                                  snapshot.data!.docs[index]["url"]
                              ),
                            ),
                            title: Text(snapshot.data!.docs[index]["product_name"])
                            ),

                          ),
                        ),
                      );

                  },
                );
              }),
</code>
Answer: every time a search is performed you can create a list or a map and save it locally or in the database according to your needs.  To then make the data that you are going to recover appear under the search bar, I recommend using existing plugins such as material_floating_search_bar
example with shared preferences (locally):
<code>    final prefs = await SharedPreferences.getInstance();

    List<String> _currentResearch = prefs.getStringList("searches") ?? [];

    _currentResearch.add(searchcontroller.text);

    await prefs.setStringList("searches", _ricercheAttuali);
</code>
Comment: Can you explain how I store search history according to my code?
Comment: I am stuck in implimentation
Comment: I added an example using the SharedPreferences


How to solve this inequality algebraically?

Question: |x+3|<-1
 how to solve this algebraically. I can solve it by using graphs.
Comment: Distinguish the cases $x+3\ge 0$ and $x+3<0$
Comment: I edited the question
Answer: An absolute value is non-negative . It can't be $\;<-1$.
Answer: Your given inequality has no solution since $$\vert{x+1\vert}\geq 0$$


indexWidget() unexpectedly returns a NULL pointer

Question: I am attempting to create a model/view application in Qt 4.7.1.  I am a very new Qt developer.
Summary of what I am attempting to do:
I have a treeview that is organized as a rectangular table of rows and columns.  One column of items contains a button.  By default this button is to be transparent and disabled.  A given button is to become visible and enabled when the mouse is hovering over its row.
The approach I am pursuing is to

find the model index for the cell that the mouse is hovering over, and
obtain a pointer to the widget associated with the widget, and
using this pointer manipulate the visibility of the button within said widget.

I cannot get a valid pointer to the widget.
my current code looks like this:
<code>void HistoryTreeView::mouseMoveEvent(QMouseEvent *event)
{
   QAbstractItemModel *m(model());

   // Only do something when a model is set.
   if (m)
   {
      QModelIndex index = indexAt(event->pos());
      if (index.isValid())
      {
         // if the mouse has moved to another row
         if (index.row() != m_currentRow)
         {
           m_currentRow = index.row();

           QMessageBox::information( this, "HistoryTreeView", QString("index(%1)").arg(index.row()));

           QWidget * item = indexWidget(index);
           Q_ASSERT(item != NULL  );
        }
     }
     else  // model is invalid
     {
         m_currentRow = -1;
     }
  }

  QTreeView::mouseMoveEvent(event);
}
</code>
The symptoms:
I expected the call to indexWidget() to return a valid pointer to the widget the mouse is over.  Instead it unexpectedly returns a NULL pointer.
Commentary:
The variable named 'index' is acting as I expected because the QMessageBox shows the correct row value.  Consequently I do not think there is anything wrong with the value I am providing to indexWidget().
This is just debug code. It is missing things like code that selects the column that holds the buttons.
Answer: OK, Here is the nature of my error as I understand it.
I had incorrectly understood that every item in a view is its own widget.  I now understand that the view itself is a widget, but that individual items within the view are not widgets, per se.
Because I had misunderstood that view items were widgets I believed that could:

obtain an index from a given element in a model,
use indexWidget() to obtain a Widget * to the view item associated with the model element
and then use this pointer to manipulate the view item as though it was a widget.

indexWidget() simply returned a NULL because view items are not widgets.
Comment: That is incorrect, you can use setIndexWidget() to set a QWidget in a cell. It returns null if you did not set the index widget for that index.


MySQL ordering list of users acording to last sent messages

Question: I have two tables in my database called 'users' and 'message'.
users:
**id** .  **fname**  . **lname**

`1` . `paul` . `jackson`
`2` . `raj` . `krish`
`3` . `john` . `philip`

message:
**fromId** . **toId** . **sdate** . **txt**

`2` . `1` . `100` . `hi paul`
`2` . `1` . `99` . `hey`
`3` . `1` . `91` . `come on`
`2` . `1` . `56` . `are you there?`
`3` . `1` . `32` . `long time`

I want to be able to select the list of users who have sent a message to 1, and the last message sent to 1 on each of the returned row from users, and order by the user who sent the last message descending.
E.g:
Message from raj krish "hi paul".
Message from john Philip "come on".
So I was able to retrieve the list of user who have sent a message to 1 and also each last messages. But the problem is that, I can't order the list according to the last messaged user.
I'm really a newbie to SQL. Here is the code I tried:
$query = $connection->query("SELECT * FROM users
    WHERE EXISTS(SELECT NULL FROM message
    WHERE users.id = message.fromId AND message.toId = 1)
    ODER BY (SELECT sdate from message
    ORDER BY sdate DESC
    LIMIT 1) DESC")

while($usrs = mysqli_fetch_array($query, MYSQLI_BOTH)){
    $mquery = $connection->query("SELECT * FROM message
        WHERE fromId = " . $usrs["id"] . " AND toId = 1
        ORDER BY sdate DESC
        LIMIT 1");

    while($msg = mysqli_fetch_array($mquery, MYSQLI_BOTH){
        ...... Do some return here! .......

    }
}

How do I order the list of users with the last message sent by each to 1?
Answer: Try to solve problems like this in steps, like first recover the users, then make the complete join, then filter the join results, ect...
I'll give you a simple solution that hope it helps!
v1.0 - No final sorting
SELECT fname, lname, txt FROM users as u
INNER JOIN
(
SELECT fromId, sdate, txt FROM message GROUP BY fromId ORDER BY sdate desc
) m
ON u.Id = m.fromId

This INNER JOIN is very simple like the 101 of making joins with a minor change. Instead of joining the table itself I make a subquery with the suitable records that you want to join with.
Please tell me if anything isn't clear for you.
EDIT:
In response to your comment. That's cannot be true. The GROUP BY would take care of it. I replicate your example and test it, here are the results:

EDIT 2:
You are right! The rows returned arent order by the last message time!
You need to order the join result as well.
v2.0 - With final sorting
SELECT fname, lname, txt, sdate FROM users as u
INNER JOIN
(
SELECT fromId, sdate, txt FROM message GROUP BY fromId ORDER BY sdate desc
) m
ON u.Id = m.fromId
ORDER BY sdate desc

And if you don't want to get sdate in the returning tableset you can make a subset of the results with another subquery:
v3.0 - With final sorting and projection results
SELECT fname, lname, txt FROM
(
SELECT fname, lname, txt, sdate FROM users as u
INNER JOIN
(
SELECT fromId, sdate, txt FROM message GROUP BY fromId ORDER BY sdate desc
) m
ON u.Id = m.fromId
ORDER BY sdate desc
) r

Comment: But returns more than 1 for each user. Do you have any idea how to make it display only the last message of each users?
Comment: I make an update. I don't see anything wrong are you completly sure that you are using the exact query posted in the answer?
Comment: After using the `GROUP BY`, the messages doesn't display according to the last sent date but displays according to the sender id.\
Comment: If you're using the `GROUP BY` statement, the `ORDER BY` statement won't take effect anymore.
Comment: @AkrilBH That thing you just said abour `GROUP BY`isn't true `ORDER BY` don't get "override" because of grouping. That `ORDER BY` applies to the joined query and not on the global query, but nothing more. I make an update, check it out!
Comment: @AkrilBH I tried that indeed, I uses to check my answers hehe :P Glad to hear that your problem is solved!
Comment: This is what i got when i tried your last option: error: Every derived table must have its own alias. Are you sure you've tested that?
Comment: But I've fixed it almost the same way you suggest. a moment I'll post here what I've tried so far.
Comment: This is your last suggestion. It's from my main database I'm using to test this: `"SELECT * FROM (SELECT * FROM users AS u INNER JOIN (SELECT * FROM message GROUP BY ref ORDER BY sdate DESC) m ON u.id = m.ref)  WHERE (sto='$idst') AND (todeleted ='false') ORDER BY sdate DESC"`. check if i have any errors.
Comment: @AkrilBH I make an update to "tag" the code samples with version numbers. If you look closely to sample v3.0 you would see a final `r`, is an alias for the query and is needed to avoid the error you have. So, using `SELECT * FROM (SELECT * FROM users AS u INNER JOIN (SELECT * FROM message GROUP BY ref ORDER BY sdate DESC) m ON u.id = m.ref) r WHERE (sto='$idst') AND (todeleted ='false') ORDER BY sdate DESC` should get rid of the error. But! Since you are no projecting the results and returning `*` you don't need to use sample `v3.0` and you could try sample `v2.0`
Comment: Got it now. i thought the `r` was a piece of error while typing. It works perfectly now. Thanks alot.


Redirect URLs using Google Cloud

Question: I have a domain (example.com) already configured in Cloud DNS. With this domain I can access microservices that are in a GKE cluster. I use istio-ingressgateway IP in CloudDNS to make the association between the cluster
Now I have another domain (newexample.com) with a custom certificate for https connections. Is there a way to redirect all the requests to newexample.com to example.com? I do not want to change anything in gke/istio configuration if possible.
Comment: You can add `A` record to the `DNS` servers to point your domain to the `ingress-gateway` loadbalancer service of Istio however the question is how do you want to add your ssl certificates without modifying your `ingress-gateway` configuration.
Comment: You cannot redirect a domain using `A` records alone. The target SSL certificate must support the domain name that you are redirecting, otherwise you will get a security error in the browser/application.
Comment: As correctly stated in previous comment by John Hanley it will be necessary to change the certificates bound to the `ingress-gateway`. This would require additional changes to your `ingress-gateway` definition as the host would be different (assuming it's not `*`).
Answer: Each method will require some of the reconfiguration in either GKE/Istio side.
One of the solutions to this is to have a CNAME record in a Cloud DNS and a SSL certificate with Alternative Names.
With above solution you will be able to send requests to your GKE/Istio cluster with both domain names assuming correct Istio configuration.

What is CNAME?

CNAME is a Canonical Name Record or Alias Record.
A type of resource record in the Domain Name System (DNS), that specifies that one domain name is an alias of another canonical domain name.

Example of a CNAME record:
DNS name       Type      TTL     Data
old.domain.    A         60      184.108.40.206
new.domain.    CNAME     60      old.domain.

Alternative Names:

A SAN or subject alternative name is a structured way to indicate all of the domain names and IP addresses that are secured by the certificate.
 Enstrustdatacard.com: What is a san and how is it used

You can create SSL cerificate create to support both:

old.domain
new.domain

There are plenty options to do that for example Let's Encrypt or Cert Manager.

Example
I've created an example to show you how to do it:

Configure DNS zone in Cloud DNS
Create a basic app with a service
Create a certificate for example app
Create Istio resources to allow connections to example app
Test

Configure DNS zone in Cloud DNS
You will need to have 2 records:

A record with IP of your Ingress Gateway and name: old.domain
CNAME record pointing to old.domain with name: new.domain

Please take a look on official documentation: Cloud.google.com: DNS: Records
Create a basic app with a service
Below is example app with a service which will respond with a basic hello:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-dp
spec:
  selector:
    matchLabels:
      app: hello-dp
  replicas: 1
  template:
    metadata:
      labels:
        app: hello-dp
    spec:
      containers:
      - name: hello
        image: "gcr.io/google-samples/hello-app:2.0"
        env:
        - name: "PORT"
          value: "50001"
---
apiVersion: v1
kind: Service
metadata:
  name: hello-sv
spec:
  selector:
    app: hello-dp
  ports:
    - name: hello-port
      protocol: TCP
      port: 50001
      targetPort: 50001
  type: ClusterIP

Create a certificate for example app
As said previously, certificate with Alternative Names can be created with Let's Encrypt. I created it with:

GCE VM with Ubuntu 16.04
Open port 80
Domain name old.domain pointing to public ip address of a VM
Guide: Linode.com: Docs: Install let's encrypt to create a SSL certificate
Command to create certificate:

$ ./letsencrypt-auto certonly --standalone -dold.domain-dnew.domain

Certificate created in /etc/letsencrypt/archive/ used in creating tls secret for GKE with command:

$ kubectl create secret tlsssl-certificate--cert cert1.pem --key privkey1.pem

Please have in mind that this certificate was created only for testing purposes and I strongly advise using dedicated solution like: Cert-manager
PS: If you used this method please revert back changes in the Cloud DNS to point the Istio gateway.

Create Istio resources to allow connections to example app
Below are example Istio resources allowing connections to example app with support for HTTPS:
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: hello-gw
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      credentialName: ssl-certificate
    hosts:
    - "old.domain"
    - "new.domain"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: hello-vs
spec:
  hosts:
  - "old.domain"
  - "new.domain"
  gateways:
  - hello-gw
  http:
  - route:
    - destination:
        host: hello-sv
        port:
          number: 50001

Please take a specific look on:
    tls:
      mode: SIMPLE
      credentialName: ssl-certificate

This part will ensure that connection to the cluster will use HTTPS
Additionally:
  hosts:
  - "old.domain"
  - "new.domain"

Above definition in both resources will allow only connections with specified domains.
Test
When applied all of the above resources you should be able to enter in your browser:

https://old.domain
https://new.domain

and be greeted with below message and valid SSL certificate:
Hello, world!
Version: 2.0.0
Hostname: hello-dp-5dd8b85b56-bk7zr

Redirect URLs using Google Cloud


How should you handle questions with answers in the comments?

Question: I've seen this a few times where a question is asked, is answered within the comments but no official answer is posted or selected as the correct answer.
Example: How can i Update My Product Export time consuming period for Bulk export products
I wasn't sure if I should close it, post the answer or if there is another way of handling this?
What should we do in a situation like this?
SR
EDIT: This ended up being a duplicate question, but I'd still like to know what to do in a situation like this.
Answer: This happens a lot on Stackoverflow, especially when the question is simple but the OP didn't realise until they worked it out.
In most cases if it's a typo or something small the question should be closed as such.
In cases where the question and answer are potentially useful in future, I normally leave a comment encouraging whoever posted the "answer/comment" to post it as an actual answer so the OP can accept it.
It's worth encouraging users to follow the process of the StackExchange sites - it helps with site statistics, pointing users to unanswered questions, reputation for users who deserve it as well as many other reasons (a la; the purpose of StackExchange!).
Answer: Sometimes I close them as Unclear what youre asking (questions that went away on its own)
Sometimes I ask the answerer to post the comment as an answer.
Not sure what's the best solution I guess it depends for each case


Classification of integrals not expressible in elementary functions?

Question: Let's consider the smallest set of functions (with real coefficients) closed under addition, multiplication, division, root extraction, and finite compositions containing

constants
exponential and logarithmic functions
trigonometric functions and their inverses

This set is generally known as "elementary functions". It is known that they are closed under all algebraic operations and differentiation, but not closed under inversion and not closed under integration (+infinite sums).
I am wondering if there is any classification, with a proof, of indefinite integrals (antiderivatives) not expressible in elementary functions. If so, we can introduce a minimal number of special functions to integrate elementary functions (once, not repeatedly).
Also, I am not sure about the appropriate tags for this question that are capable of attracting people specialized in related areas. You are welcome to edit accordingly.
Comment: No, there is no such classification.
Comment: I think the following puts this question succinctly:  Does there exist a set $\{f_i\}$ such that the antiderivative of any function $g$ in the closure of $id, c, +, -, *, /, \circ$, where $c \in \mathbb{C}$ lies in the closure of $id, c, +, -, /, \circ, f_i$?  What is the cardinality of the smallest such set $\{f_i\}$?
Comment: @GEdgar: Is there any reason for that?
Comment: Did you ever find a solution to this?  I was composing a similar question and ran across this.
Comment: This question arises without even introducing trigonometric functions or logs.  Certainly division and composition introduces a need for all sorts of stuff to express antiderivatives (e.g. logs and inverse hyperbolics).  I think that the antiderivatives of the closure of +,-,*,$\circ$ are all in that set, so possibly the place to focus attention here is on division.
Comment: @Him: Feel free to edit the question.
Answer: You are talking about 'differential galois theory' or 'the galois theory of (linear) differential equations.' A quick glance at "filter" didn't seem to show any appropriate tags.You could start by looking up those terms in Wikipedia where you will find a bibliography with several fairly recent books.
Answer: Just as in classical Galois theory one can classify exactly when a root can be written in terms of the 'elementary' operations $+,-,*,/,\sqrt[n]{}$, once can use Differential Galois theory to analyze when various solutions to differential equations can be written in terms of elementary functions. Since indefinite integration and solving differential equations are equivalent, this allows us to prove when an elementary antiderivative does not exists. For example, this paper proves that the Gaussian is such a function.
Comment: Can you give me a specific reference on DGT that discusses the classification of indefinite integrals of real elementary functions that are not expressible in elementary functions?


smooth animation of the size of a functional component during state change

Question: As you can see, by clicking on the component underneath, we can change its size. I would like to make a transition between those sizes. Is it possible with CSSTransition ?
export const Liste_planete2 = () => {
    const [height, setHeight] = useState<number>(30)

    const handleClick=()=>{
            setHeight(height+30)
    }
    return(

            Text

    )
}

Answer: Try it:
export const Liste_planete2 = () => {
    const [height, setHeight] = useState<number>(30)

    const handleClick=()=>{
            setHeight(height+30)
    }
    return(

            Text

    )
}

Comment: It's not valid JSX `{{height:height, transition: all 0.5s}}`
Comment: solved, try now
Comment: now it will work
Comment: Perfect Thank you


Distribuir Crystal Report

Question: Tenho uma aplicação rodando em C# windows Form, e preciso instalar o Crysal Report na maquina do cliente. teno esse msi CRforVS_13_0_5, mas quando ele é execultado na maquina cliente, e diz que só pode ser instalado junto com o Visual Estúdio.
Em Outras palavras preciso saber se alguém já passou por isso e como resolver?
Existe algum outro instalado no Crysal Report que possa ser instalado junto com a aplicação?
Por Favor ajude-me.
Comment: instala o odbc de 32 e 64bits. depois configura a conexao. executar...odbc.
Answer: Passei pelo mesmo problema...
http://scn.sap.com/docs/DOC-7824
Os executáveis que estão descrito como MSI são os que você deve instalar na máquina do cliente!
Comment: Vou tentar instalar aqui
Comment: Caso não consiga, por favor me avise o problema.
Comment: O Run time foi blz, mas agora está dando um msg de erro dizendo. Falha ao abrir a conexão. Presumo que seja a conexão ODOBC, do crystal. Estou usando a versão 13 do crystal, baixe e instalei a versão 13.  http://downloads.businessobjects.com/akdlm/cr4vs2010/CRforVS_redist_install_32bit_13_0_13.zip
Comment: Não entendi. A falha acontece em que situação?
Comment: Quando clico no botão para gerar o relatório. Ele aparece uma msg dizendo que conexão falhou, mas não é conexão com o BD, em relação o sistema, é somente com o relatório
Comment: vou editar a pergunta e deixa a msg de erro
Comment: @FabrícioSimoneAlanaMendes Nesse caso será necessário abrir uma nova pergunta detalhando como está seu Report, como ele está recebendo os dados, etc.. Se o problema da instalação foi resolvido vc marca como resposta e abre uma nova pergunta.
Comment: Olá bom dia, Desculpe a demora, mas seguinte qual msi devo baixar para minha aplicação, Abre mas não aparece nada norelatório.
Comment: Vc fala a versão? Se sim, pode instalar a última que está mais atualizada.
Comment: A última em questão seria essa "http://downloads.businessobjects.com/akdlm/cr4vs2010/CRforVS_redist_install_32bit_13_0_14.zip"? Outra coisa, preciso configurar o conector ODBC?
Comment: Essa mesmo. Cara eu nos meus projetos eu n precisava configurar nada. Só instalar no servidor para ter as bibliotecas lá.
Comment: Vou testar aqui, Outra coisa, Há como instalar Silenciosamente no InnoSetup?
Comment: Não sei te dizer. Pra esse caso acho melhor vc abrir outra pergunta.
Comment: Está dano erro ao gerra o relatório, Tipo o sistema para de funcionar. O aplicativo funciona belezinha, mas guando peço para gerar o relatório trava o sistema e para rodar. Ele não dá msg de exceção do sistema, gera msg de erro do windows. O que pode ser? E abrir um post com pergunta anterior veja http://pt.stackoverflow.com/questions/68332/instalar-crystal-report-silenciosamente-com-inno-setup

Distribuir Crystal Report


Apresentar uma soma online

Question: Boa tarde!
Tenho um formulário e uma rotina em JAVASCRIPT.
O meu desejo é que, a partir de uma digitação, apareça automaticamente o valor da soma.
Um exemplo que busco é o site da YOUSE, em que alterando o valor das coberturas do seguro, automaticamente o custo é apresentado (sem "TAB", "BOTÕES").
No meu exemplo, quando você altera, só com o TAB em N2 que atualiza. Outro ponto, que apesar de estar "pré preenchido", não é disponibilizado por exemplo a soma de N1 e N2 (no caso - 50).
FORMULÁRIO:
<input type="number" id="n1" value="20">
<input type="number" id="n2" value="30" onblur="calcularonline()">
<input type="text" id="n3" value="100">
<input name="idade" type="number" placeholder=0 id="id_idade">
<div id="resultado"

<div id="resultado2"

JAVASCRIPT
function calcularonline() {
  var n1 = parseInt(document.getElementById('n1').value, 10);
  var n2 = parseInt(document.getElementById('n2').value, 10);
  document.getElementById('resultado').innerHTML = n1 + n2;

  var n3 = parseInt(document.getElementById('n3').value, 10);
  var n4 = (parseInt(document.getElementById('id_idade').value, 10))*2;
  var n5 = 0;

  if(n4>=10){
      n5 = 10000;
  }
  document.getElementById('resultado2').innerHTML = n3 + n4 + n5;
}

Answer: Olá, veja se é isso de que precisa:

function Somar() {
    var num1 = document.getElementById("num1").value;
    var num2 = document.getElementById("num2").value;

    if (num1 == '') {
        num1 = 0;
    }

    if (num2 == '') {
        num2 = 0;
    }

    var resultado = parseInt(num1) + parseInt(num2);
    document.getElementById("resultado").innerHTML = resultado;
}
<!DOCTYPE html>

    <meta charset='utf-8'>
    <title>Exemplo</title>

Escreva algum número para ativar a função.

    <input type="text" id="num1" oninput="Somar()">
    <input type="text" id="num2" oninput="Somar()">

Comment: Show. Willian, obrigado pela atenção!!

Apresentar uma soma online


How to achieve exact nanosecond precision using Date API in Java 8

Question: We are trying to get exact nanoSeconds with 9 precision values for capturing Time.
Using Java 8 we can able to achieve as mentioned below.
@Test
public void testNanoClock() throws InterruptedException{
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
              .appendInstant(9).toFormatter();
       for (int i=0; i<10; i++) {
       final Clock clock = new NanoClock();
       log.info(formatter.format(clock.instant()));
       Thread.sleep(200);
       }
}

Overriden instant method as below
@Override
public Instant instant() {
  return initialInstant.plusNanos(getSystemNanos() - initialNanos);
}

And the complete implementation of the class  is given below.
public class NanoClock extends Clock {

    private final Clock clock;

    private final long initialNanos;

    private final Instant initialInstant;

    public NanoClock() {
        this(Clock.systemUTC());
    }

    public NanoClock(final Clock clock) {
        this.clock = clock;
        initialInstant = clock.instant();
        initialNanos = getSystemNanos();
    }

    @Override
    public ZoneId getZone() {
        return clock.getZone();
    }

    @Override
    public Clock withZone(ZoneId zone) {
        return new NanoClock(clock.withZone(zone));
    }

    @Override
    public Instant instant() {
        return initialInstant.plusNanos(getSystemNanos() - initialNanos);
    }

    private long getSystemNanos() {
        return System.nanoTime();
    }
}

By using above code we are able to achieve time with nanosecond along 9 precision value:

2017-10-08T16:45:45.232000378Z

but in this case micro seconds are coming as 0's(zeros).
How can we achieve exact nanoSeconds time along with 9 precision values without 0's(zeros)? how does it workout?
Comment: By the way, Java 9 has a new implementation of `Clock` that does capture the current moment in up to nanosecond resolution. You might want to look at its source code in OpenJDK. Keep in mind that mainstream computing hardware is not equipped with clocks sensitive enough to register nanoseconds accurately, as far as I know.
Answer: Your code creates a new instance of NanoClock within the loop. This resets the initialInstant and initialNanos each time, thus you never get to see the effect of the nanos. To make this work at all, you need to move the clock outside of the loop, potentially to a static constant.
You should also be aware that over time, this clock may deviate from real time, as System.currentTimeMillis() and System.nanoTime() are derived from different clock sources in the operating system, and are intended for different purposes (the former is calendar date/wall time, the latter is elapsed time). As such, you are actually measuring the elapsed time since the clock is created (over the course of a day, there may be some deviation between the two).
Comment: @YerriswamyManchi As said in the answer, `System.nanoTime()` is **not** related to current time. Check the [nanoTime javadoc](http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#nanoTime%28%29): *"This method can only be used to measure elapsed time and **is not related to any other notion of system or wall-clock time**."* Anyway, in Java 8, the `Clock` class is limited to millisecond precision. In Java 9, it's using [more precise clocks](https://bugs.openjdk.java.net/browse/JDK-8068730), but only if available in the system
Comment: Thanks Stephen for the reply. I am planning to put this code to a production environment into an application server to capture some events at nanosecond level.
Do you suggest that moving the clock initialization outside the for loop should give me a correct result?

or Do you have any other suggestion to capture the time in nanosecond?


Por que eu não consigo fazer o upload maiores que 2mb com esse script?

Question: <form action="" method="post" enctype="multipart/form-data">
  <input type="file" name="fileUpload"/>

  <button type="submit">Enviar</button>
</form>

<?php
if ($_SERVER["REQUEST_METHOD"]==="POST"){
    $file = isset($_FILES["fileUpload"])?$_FILES["fileUpload"]:"";
    if($file["error"]){

    }

    $dirUploads = "uploads";
    if(!is_dir($dirUploads)){
        mkdir($dirUploads);
    }
   if (move_uploaded_file($file["tmp_name"],$dirUploads.DIRECTORY_SEPARATOR.$file["name"])){
       echo "upload realizado com sucesso"."
";

   }else{
       throw new Exception("Não foi possivel fazer o upload");
  }
}
?>

Comment: Qual a mensagem de erro?
Comment: não dá erro nenhum, simplesmente não envia
Comment: Então aparece a mensagem `upload realizado com sucesso`?
Comment: sim, mas se eu envio um arquivo pequeno envia normal, mas se eu envio um arquivo de uns 3mb simplesmente não vai
Comment: isso no seu computador ou no servidor?
Comment: Essa pergunta resolve o seu problema provavelmente: https://pt.stackoverflow.com/q/15573/3635 (resposta: https://pt.stackoverflow.com/a/15641/3635)
Comment: obrigada amigo .
Answer: Faça um arquivo phpinfo.php usando o código abaixo:
<?php phpinfo(); ?>

E abra-o no navegador. Na parte "Loaded Configuration File", aparecerá o caminho para o arquivo de configuração usado, geralmente, php.ini. Claro, se não for hospedagem compartilhada e você tiver acesso a alterá-lo.
Você também poderá criar um arquivo php.ini na raiz do seu projeto.
No php.ini, altere a parte:
upload_max_filesize: (tamanho máximo para upload)
post_max_size:(tamanho máximo dos dados postados, mas também afeta o upload de arquivos)
memory_limit:(quantidade máxima de memória, em bytes, que o script poderá alocar. Isto deve ser maior que do "post_max_size")
max_execution_time:(Tempo máximo de execução)
Ao carregar arquivos grandes, é importante não deixar um tempo muito curto, pois poderá ocorrer erros caso não dê tempo de enviar todo o arquivo.
Observe também se o usuário possui acesso para gravar no diretório onde será salvo o arquivo enviado.
Referências:
http://php.net/manual/pt_BR/ini.core.php
Comment: muito obrigada amigo


Struggling with long computations. Any advice?

Question: Sorry for the somewhat strange question but I have been struggling with this for some time now.
I am currently in undergraduate Electrical Engineering taking classes on Linear Algebra, Calculus  and ODEs. Whenever I need to solve problems of Linear Algebra, Laplace Transforms and even computing some big integrals, I become disorganized with the long computations required (even simple ones) and I end up with the wrong answer.
I also become very anxious all of a sudden, speeding up with the computations and making silly mistakes on basic operations.
When I finally finish, I find myself with long pages of computations and a wrong answer.
How can I overcome this? How can I keep everything organized even in long problems and stay calm during the entire computation? How do you guys manage long computations like these?
Any advice is greatly appreciated!
Comment: Use [Computer Algebra Systems](https://en.wikipedia.org/wiki/List_of_computer_algebra_systems) especially those with a notebook interface.
Comment: Practice............
Answer: This is an important methodological question.
Yes, there is inevitably a certain rate of (at least) mis-copying error, if nothing else. So we do need sanity checks (which may be easier), and, also, precision-checks, all along the way.
And, in particular, it would be extremely naive to think that "a mere computation" is a trivial thing to accomplish. It is not. Double-checks, checks on sub-cases, sanity-checks, "parity-checks", and all these things are standard operating procedure. At least if the outcome really matters!!! :)
(The idea that proof-checking software, etc., will solve such problems is a bit naive, because it depends on essentially-perfect data entry, and essentially-perfect software set-up. The infinitely-wiser version of this, that can guess what "we meant to say" is not quite here... :)
Comment: @Somos I think Paul does actually address computation in his answer. Your same criticism on my answer, however, is fair.
Comment: Post your own answer if you think you can do better...
Comment: Thank you so much for your answer! I will try to change my mindset that these aren't "mere computations" and approach them more carefully. I've also never had a rigorous method of double-checking every step, I'll definetely try that out, thanks!
Answer: I don't know. There's two aspects when it comes to proving things in Linear Algebra, Calculus etc. a) The proof sketch and b) The proof as a logical sequence of statements. I think being good at the "proof sketch" comes after you've spent lots of time studying the subject. So it takes experience to get good at. For b), The formal logical sequence of statements part, I simply don't allow myself to write anything that is false. If I'm not sure if something is true or false, and I want to determine whether or not something is true, I ask myself whether or not that statement is true as a question ("Is Statement X true or false?"), and then try to figure out whether or not it's true. Because I have invested time doing this, the result as to whether or not Statement X was True, sticks in my memory. I don't just pretend that it's true and roll with it forever, because then you won't remember what's true and what's not.
This approach can help you not accept commonly used false statements like Freshman's Dream, which a lot of students I have tutored use in their working when they're "just trying to get to the answer". You won't get to the answer with false statements. People don't want to spend any serious amount of time doing problems. However, the only way to improve in maths is to study problems and solve them rigorously.
Improving your maths takes serious time and effort, and there's no way round this.
Comment: The OP mentions computations but not proofs.
Comment: That is a fair criticism of my answer.


Search in mongoid/mongo console not work

Question: I have some fields in my model category, tags which contains lots of text
Take the following data for example,
It should be found by these search keywords Iron, Pig, Academic Data
{
    "_id" : "M0130AUSM561NNBR",
    "name" : "Pig Iron Production for United StatesMonthly, Not Seasonally Adjusted,  ",
    "categories" : [
        "Production of Commodities",
        "NBER Macrohistory Database",
        "Academic Data"
    ],
    "tags" : "[\"iron\", \"metals\", \"nber\", \"production\", \"monthly\", \"nation\", \"usa\", \"nsa\"]",
    "updated_at" : ISODate("2014-12-30T03:38:13.954Z"),
    "created_at" : ISODate("2014-12-30T03:38:13.954Z")
}

I tried to query by Indicator.text_search("Pig")
But I got nothing
irb(main):005:0> Indicator.text_search("Pig")
=> #<Mongoid::Contextual::TextSearch
  selector:   {}
  class:      Indicator
  search:     Pig
  filter:     {}
  project:    N/A
  limit:      N/A
  language:   default>

Tried to search with Indicator.any_of({ :text =>  /.*Production.*/ })
I still got nothing.
=> #<Mongoid::Criteria
  selector: {"$or"=>[{"text"=>/.*Production.*/}]}
  options:  {}
  class:    Indicator
  embedded: false>

Tried to search in mongo console, still not works (nothing in the result)
    > db.indicators.find({"title": /.*Production.*/})
    >

Model : Indicator.rb
class Indicator
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic
  # include Mongoid::Search
  field :id, type: String
  field :name, type: String
  field :category, type: String
  field :tags, type: String
  # search_in :tags, :category
end

Answer: The shell query
db.indicators.find({ "title" : /.*Production.*/ })

won't find any documents because there is no title field, according to your sample documents. Is a text index defined?
db.indicators.ensureIndex({ "name" : "text", "categories" : "text", "tags" : "text" })

Additionally, tags is a string that resembles an array of strings - is that what you want? Or do you want n array of strings? I'd think you want
"tags" : ["iron", "metals", "nber", "production", "monthly", "nation", "usa", "nsa"]

rather than
"tags" : "[\"iron\", \"metals\", \"nber\", \"production\", \"monthly\", \"nation\", \"usa\", \"nsa\"]"


Erro ao conectar no banco de dados

Question: Tento fazer a conexão no meu bd, mas fica dando o erro "Falha ao conectar!"
Os dados que estão no meu bd sao:
Base de Dados: teste
Tabela: clientes
to tentando conectar por PHP
<code>    <?php

$conn = @mysqli_connect("localhost", "root", "", "teste") or die("Falha ao conectar!");

?>
</code>
e a validação:
<code><?php

require_once "conexao.php";

$email = $_GET['idemail'];
$cpf = $_GET['cpf'];
$query = "SELECT * FROM clientes WHERE cpf = '$cpf' AND email = '$email'";
$querySelect = mysqli_query($conn,$query);

if(mysqli_num_rows($querySelect) <=0){
    echo"<script type='text/javascript'>alert('Email ou cpf incorretos');window.location.href='index.html';</script>";
    die();
}else{
    setcookie("login", $cpf);
    header("Location:Postagem.html");
}
</code>
Mas sempre que coloco os dados corretos ou incorretos que estão no meu bd, da o mesmo erro de "Falha ao conectar!"
Comment: o problema esta no arquivo da conexao, retire o '@', ele está suprimindo os erros. mude para or die("Falha ao conectar!".mysqli_connect_error());
Comment: cheque se você realmente tem um banco com uma database teste, usuário root e senha vazia. ou mude sua mensagem de erro para escrever qual erro que deu, e não apenas que falhou
Comment: Eu mudei a mensagem de erro e quando vou testar, dá a mesma mensagem anterior
Comment: continua dando o mesmo erro
Comment: mas e a informação adicional? nada? nenhuma mensagem a mais? se você retirou o @ e colocou o mysqli_connect_error() no log, e ainda assim nao mudou nada, devo perguntar, você salvou o arquivo?
Comment: Né pra mudar pra : $conn = ("localhost", "root", "", "teste") or die("Falha ao conectar!".mysqli_connect_error());
e nao mudou nada, e eu salvei
Answer: se essa mudança trazer uma mensagem de erro, edito a resposta para lhe ajudar a corrigir:
<code>// cria conexao
$conn = new mysqli("localhost", "root", "", "teste");
// exibe motivo da falha, caso haja alguma
if ($conn->connect_error) {
    die("Falha ao conectar!, Motivo: " . $conn->connect_error);
}
</code>

Erro ao conectar no banco de dados


Solve $(z+2) /( z-3i) = 4+2i$ for $z$ in complex numbers

Question: I'm having some trouble trying to isolate $z$. Can I multiply $(4+2i)$ by $(z-3i)$ without changing $z$ into standard form?
Comment: yes you can....
Comment: how do you solve $\frac{x+2}{x-3} = 4?$
Comment: Algebra (addition, subtraction, multiplication, division) in the complex numbers works exactly like algebra in the real numbers, except that you have the additional relation $i^2 = -1$.  You can add, subtract, multiply whatever you want; you can divide as long as you're not dividing by $0$.
Answer: $$(z+2)=(4+2i)(z-3i)=(4+2i)z-12i+6\\z+2=4z+2iz-12i+6\\3z+2iz=12i-4\\z=\frac{12i-4}{3+2i}=...=\frac {12} {13}+\frac {44} {13} i$$
Comment: How did you go from 4z to 2z and from 2iz to 6iz?
Comment: @Filip maybe a typo, edited


Does JRE has diagnostics tools?

Question: Does anyone know if JRE (not JDK) has diagnostics tools, such as jps, jstack, jhat and so on?
Or these tools only present in JDK?
Thanks.
Answer: These files are all you have in the jre (jre1.6.0_20 linux):
<code>rwxrwxrwx 1 bob bob     10 2010-05-12 19:40 ControlPanel -> ./jcontrol
-rwxr-xr-x 1 bob bob  47308 2010-04-12 22:36 java
-rwxr-xr-x 1 bob bob  25634 2010-04-12 22:39 java_vm
-rwxr-xr-x 1 bob bob  84970 2010-04-12 22:39 javaws
-rwxr-xr-x 1 bob bob   6347 2010-04-12 22:39 jcontrol
-rwxr-xr-x 1 bob bob  47447 2010-04-12 22:36 keytool
-rwxr-xr-x 1 bob bob  47679 2010-04-12 22:36 orbd
-rwxr-xr-x 1 bob bob  47515 2010-04-12 22:36 pack200
-rwxr-xr-x 1 bob bob  47807 2010-04-12 22:36 policytool
-rwxr-xr-x 1 bob bob  47447 2010-04-12 22:36 rmid
-rwxr-xr-x 1 bob bob  47447 2010-04-12 22:36 rmiregistry
-rwxr-xr-x 1 bob bob  47475 2010-04-12 22:36 servertool
-rwxr-xr-x 1 bob bob  47679 2010-04-12 22:36 tnameserv
-rwxr-xr-x 1 bob bob 189274 2010-04-12 22:36 unpack200
</code>
So, the answer is that they are only present in the JDK.
Comment: You can get the stack trace with kill -QUIT . and you can start the jvm with JMX: ``/jre1.6.0_20/bin/java -Dcom.sun.management.jmxremote -jar jpws-0-5-0.jar``

As long as you do that and enable it to be managed from another machine then no you would not need to put the JDK on every machine.
Comment: So this means I need to install them on every server...

Or maybe there is another way to get diagnostic info locally?
Comment: You can start the jvm with JMX: ``/jre1.6.0_20/bin/java -Dcom.sun.management.jmxremote -jar jpws-0-5-0.jar``

As long as you do that and enable it to be managed from another machine then no you would not need to put the JDK on every machine

Does JRE has diagnostics tools?


Number of paths in complete graph.

Question: Lets consider complete graph $K_{4}$ and one of its vertices $a$. $A$ is adjacency matrix of $K_{4}$
The length of a path is a number of how many times we crossed some edge.
I call special path if it has length equal to $4$

How many there are closed special paths including $a$ in $K_{4}$?

I am asking because i wrote by hand all the possibilities and i get $13$ but on the other hand using knowledge from link below all the values of a $A^{4}$ on main diagonal equal to $21$. A contradiction.
https://en.wikipedia.org/wiki/Adjacency_matrix
I am looking for someone who explain me how it schould work.
Comment: The most likely case is you probably just didn't actually write down all of the possibilities right?
Comment: @79037662:  But if the path is closed maybe we don't care where it starts.  Then there are only $3!=6$
Comment: If the graph is complete, can't any permutation of the vertices be a closed special path? That would give an answer of $4!=24$.
Comment: @79037662 Can't it visit the same vertex more than once?
Comment: @saulspatz Normally a "path" in a graph can't visit the same vertex twice by definition.
Comment: @79037662 I think don't think the terminology is standardized.  A lot of authors call that a "simple path".
Comment: @RossMillikan That's true but I assumed if OP counted 13 they probably did care where it starts.
Comment: @saulspatz Wikipedia says "most definitions" of path specify distinct vertices https://en.wikipedia.org/wiki/Path_(graph_theory). But you're right, it's not standard.
Comment: The paths included in the $21$ counted by the diagonal entries of $A^4$ include paths where the same edge is traversed more than once, even twice in succession.  You perhaps didn't count such paths.  In the Wiki article linked by $79037662$ these are called "walks."
Comment: No matter how creative I become, I don't get $13$. I think it's most likely you counted $12$ (a multiple of both $3$ and $4$) and overcounted once.
Answer: Here's where the $21$ paths (or walks) come from.  You can compare to your work to see where the difference lies.  If we start at vertex $a$ and go to $b$, we can either proceed to a third vertex $c\neq a$ or we can return to $a$.  In the second case, the only way to get back to $a$ in two steps is to go to some vertex $d$ and then return to $a$.  We have $3$ choices for $b$ and $3$ for $d$, so there are $9$ paths of this type.
In the second case (where we have gone $a-b-c$) we again gave two choices: we can return to $b$ or we can go the the fourth vertex $d$.  In either case, we have then to return to $a$.  Reasoning as above, we see that there $6$ paths of each of these types, and $$9+6+6=21$$ paths in all.
Note that not all of these paths pass through every vertex, so we are only counting the closed walks of length $4$ that pass through $a$.

Number of paths in complete graph.


Evaluating a seemingly simple limit, using continuity of the partial derivative

Question: I am stuck with a seemingly easy problem. I have a function $f(x,y)$ which has continuous first derivatives. Now, I want to show that: $$ \lim_{h \to 0}\dfrac{f(a+hu,b+hv)-f(a,b+hv)}{hu} =f_x(a,b)$$
This is what I have thought: Since the derivatives are continuous, we know that, for each $\epsilon > 0$, there is a $\delta > 0$ such that it is:
$$0 < ((x-a)^2 + (y-b)^2)^{1/2} < \delta \implies |f_x(x,y) - f_x(a,b) | = \left|\lim_{h \to 0}\dfrac{f(x+h,y)-f(x,y)}{h} - \lim_{h \to 0}\dfrac{f(a+h,b)-f(a,b)}{h} \right| < \epsilon$$
My plan was to relate the first expression to this definition of the continuity of partial derivative. But the $hv$ which is added to $b$ spoils this idea. I think I am missing something very obvious here, but annoyingly I can't figure what. How should I proceed?
Comment: How do you interpret this when they are both $0$?
Comment: You haven't said what $u,v$ are.
Comment: Use the mean value theorem.
Comment: $u,v$ are simple real numbers.
Comment: @copper.hat How about that: With mean value theorem, it is $\dfrac{f(a+hu,b+hv)-f(a,b+hv)}{hu} = f_x(a + h',b+hv)$ where $ 0 < h' < hu$. Since $f_x$ continuous this is valid at each $(x,y)$. Then $f_x(a + h',b +hv) \to f_x(a,b)$ as $h \to 0$ since $ 0 < h' < hu$. Is this correct?
Comment: @UfukCanBiçici: Yes, I have formalised this below.
Answer: You need a little care with the value of $u$. You need $u \neq 0$ for the quotient to be defined. I will avoid this by multiplying through by the fixed
quantity $u$.
Using the mean value theorem we have
$f(a+hu, b+hv) -f(a, b+hv) = f_x'(a+t_h hu, b+hv)hu$ for some $t_h \in (0,1)$.
Let $\epsilon >0$, and choose $\delta>0$ such that
$|f_x'(c,d)-f_x'(a,b) | < \epsilon$ for all $\|(c,d)-(a,b)\| < \delta$.
Now suppose $|h| \|(u,v)\| < \delta$ and let $t_h$ be the value above, then
\begin{eqnarray}
|{f(a+hu, b+hv) -f(a, b+hv) \over h} - f_x'(a,b) u| &=& |f_x'(a+t_h hu, b+hv)u - f_x'(a,b) u| \\
&=& |f_x'(a+t_h hu, b+hv) - f_x'(a,b)| | u| \\
&\le& \epsilon |u|
\end{eqnarray}
It follows that
$\lim_{h \to 0} {f(a+hu, b+hv) -f(a, b+hv) \over h} = f_x'(a,b) u$.
Answer: Observe that by MVT: $f(a+hu,b+hv) - f(a+hu,b) = hv\cdot \dfrac{\partial f}{\partial y}(a+hu,c)$, and $f(a,b+hv) - f(a,b) = hv\cdot \dfrac{\partial f}{\partial y}(a,d)$. Thus we can write:
$\dfrac{f(a+hu,b+hv) - f(a,b+hv)}{hu} = \dfrac{f(a+hu,b) + hv\cdot \dfrac{\partial f}{\partial y}(a+hu,c) - f(a,b) - hv\cdot \dfrac{\partial f}{\partial y}(a,d)}{hu} = \dfrac{f(a+hu,b) - f(a,b)}{hu} + \dfrac{v}{u}\cdot \left(\dfrac{\partial f}{\partial y}(a+hu,c) - \dfrac{\partial f}{\partial y}(a,d)\right) \to f_x(a,b) + 0 = f_x(a,b)$ since when $u \neq 0, hu \to 0 \to h \to 0 \to c,d \to b$


Como remover pontilhado sob um link

Question: Estou editando um theme de tumblr e inseri 3 links no header. Porém ao inserir esse links apareceu uma linha pontilhada abaixo e não consigo remover. Como eu poderia removê-las no CSS?
Comment: Poste o CSS. Somente com a imagem não temos como ajudar.
Comment: "3 links no header". Você colocou três novos CSSs na sua página?
Comment: 5 negativos. Nem perguntas piores tem 5 negativos.
Answer: Se não for border pode ser text-decoration, coloque o valor de none ou transparent para ele que pode resolver.
Comment: Realmente isso @PyMaria, parabéns pela ajuda a comunidade.
Answer: Pelo visto isso é uma borda. Apenas faça isso no CSS no elemento correto:
<code>border: none;
</code>
Comment: Cara, a unica explicação que cabe aqui é a tradução de `border` e `none`, por que é óbvio o que eles fazem, rsrs,
Comment: Depois vocês me banem por eu negativar sem dar explicações. Qual a explicação desse negativo ? Vocês estão mutilando de negativos a pergunta, mas nem sequer ajuda o usuário a melhorá-la.

Como remover pontilhado sob um link


Property of closure of set

Question: I have difficulties with this problem and I have no idea how to solve it:

Suppose $A$ is a subset of $\Bbb R^2$ with this property: if $(x, y)$ belongs to $A$ then $(\|x\|-1,\|y\|^2)$ belongs to $A$. How can I demonstrate that the closure of $A$ has the same property? And the interior part?
Answer: The claim is not true: $A = \mathbb{R}^2$ has the given property, and the interior of $\mathbb{R}^2$ also has.
Regarding the closures, define $f : \mathbb{R}^2 \to \mathbb{R}^2$ by $f(x, y) = (\lVert x \rVert -1, \lVert y \rVert^2)$. Then $f$ is continuous, and by assumption, $f(A) \subseteq A$. Now, one characterization of continuity is that for every subset of $\mathbb{R}^2$, the image of the closure is contained in the closure of the image, so $f(\overline{A}) \subseteq \overline{f(A)} \subset \overline{A}$, which shows that $\overline{A}$ has the desired property.
Comment: Sorry I edited my question
Comment: The claim is still not true after the edit: if $A = [-1, \infty) \times \mathbb{R}$, then $A$ has the desired property, but the interior of $A$ does not (since $(0, 0)$ belongs to the interior, but $f(0, 0) = (-1, 0)$ does not).

Property of closure of set


how to prvent specific pages from being cached in squid?

Question: I have drupal based website and i am using squid as a caching level.
now, the homepage keeps getting un-updated content (old contents) and by running curl -I on my website i got this:

HTTP/1.0 200 OK
Date: Mon, 21 Mar 2011 11:52:15 GMT
Server: Apache
Last-Modified: Thu, 17 Mar 2011 17:44:47 GMT
Accept-Ranges: bytes
Content-Length: 77428
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Content-Type: text/html; charset=utf-8
X-Cache: MISS from Servername.MyWebsite.com
X-Cache-Lookup: MISS from Servername.MyWebsite.com:80
X-Cache: MISS from Admin
Connection: close

although it shows X-Cache:MISS in curl but it keeps giving old content.
now the question is: how can i configure squid to NOT cache my homepage or specific pages??
Thanks for your help
Comment: Don't those headers show that Squid is NOT serving cached content. I believe Squid inserts the x-Cache HTTP headers. The others, for example Last-Modified are coming from Apache. I would look elsewhere for the problem - What does your Apache logs say for this request?
Comment: nothing in apache access log !!
Answer: I'm not sure if you can block a certain file, but you could block a domain.
<code>acl no_cache_mydomain dstdomain .mydomain.com
cache deny no_cache_mydomain
</code>
Comment: the problem is in homepage only, other pages come correctly!! :((
Answer: By default squid will not cache non-cacheable content - which this obviously is. If you're getting a cache miss but seeing old content, then you've got more caching happenning deeper in your stack.
Comment: so, what shall i do to overcome this issue?


How to refresh DIV with AJAX when image is replaced?

Question: I have a online radio station and i wanted to show a album image for every song.Since I have the ability to automatically upload an image of a current playing song (artwork.png) to a web server via ftp, i made a script to display the image on html page..
My Code:

function refresh() {
  setTimeout (function() {
    var timestamp = new Date().getTime();
    $('#auto').html('');

    refresh();
  }, 1000);
}

$('#artwork').attr('src', 'artwork.png?timestamp=' + new Date().getTime());

Everything works great except auto refresh, so i have to manually refresh the page to load a new replaced image. But i want whenever a new image is uploaded to do one refresh on div and that's it. Where is the problem here with refresh();
Answer: First on all, the method refresh() wasn't invoked anywhere in your snippet, so you need to call it first.
Second, it's best practice to use setInterval Instead of setTimeout
There is no need to recall refresh() method in setTimeout as it will re attach setTimeout method every time it calls it-self, although it doesn't harm you programmer but if you want to call a piece of program every second then you should go for setInterval
Also I have bit simplified your code.

function refresh() {
  setInterval(function() {
    var timestamp = new Date().getTime();
    var newImage = 'https://picsum.photos/200?timestamp=' + new Date().getTime();
    $('#artwork').attr('src', newImage);
  }, 2000);
}
refresh();

Comment: So OP will have 2 intervals after 5 seconds, 4 intervals after 10 seconds, 8 intervals after 15 seconds, 16 intervals after 20 seconds, ... - Why should this be useful?
Comment: @Andreas yeah, thank you, I was already editing my answer for the same
Comment: There's still no real reason for `setInterval`. `refresh()` calling itself with `setTimeout` does the same as your `setInterval` version.
Comment: I know, the problem was the uninvoked function, but as you said calling the same method bind setTimeout many times, so it's  better practice is use to interval, that's what interval is made for, right?
Comment: _"It's best practice..."_ - No, as it totally depends on the use case: [setTimeout or setInterval?](https://stackoverflow.com/questions/729921/settimeout-or-setinterval)
Answer: There is issue with your code, you have created refresh() which when called should invoke a function to refresh the image every second, so you should use setInterval() instead. Plus, you never invoked refresh(). So, it won't work, try this:-

So, refresh() is defined, and invoked when page is loaded. refresh() then executes the setInterval() which executes the anonymous function every second to update the image. There are other optimizations possible like clearing the interval on page unload and so on, but this will get the job done. Hope it helps!!!
Comment: `refresh()`, that starts the interval, calls itself. Maybe you should reconsider your answe
Comment: Sorry, forgot to remove the refresh() call from initial code snippet
Answer: try your existing code with one more line added to it
function refresh() {
  setTimeout (function() {
    var timestamp = new Date().getTime();
    $('#auto').html('');
    refresh();
  }, 1000);
}
refresh(); // new added line
$('#artwork').attr('src', 'artwork.png?timestamp=' + new Date().getTime());


Accessing variable_get when loading bootstrap from an external file

Question: I am loading the core drupal 7 components through an external file by loading bootstrap. While the core drupal functions work properly, when I try to access variable_get I keep getting the default value. The variable_get works properly when accessed from within a module. Any ideas?
require_once dirname(__FILE__).'/scripts/encrypt.php';

//Include drupal
$currdir=getcwd();
define('DRUPAL_ROOT',$_SERVER['DOCUMENT_ROOT']);
chdir(DRUPAL_ROOT);
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
global $base_url;
$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

print_r(variable_get('var_name',DEFAULT_VAR_NAME));

This always returns
DEFAULT_VAR_NAME

Answer: Why not write a proper Drupal module and include your intended code in there? You miss out on so many of Drupal's nice features if you use it your way, including the issue you are asking about here, but also lots of security and sanity checks. Just sayin'
Comment: The problem with that is that it needs to be an a file that is accessible from ajax without loading all of Drupals core themes and pages. Do you know of any examples where I can do this?
Comment: Based on your suggestion it worked by using the following hook_menu:                              $items['page/update'] = array(
    'page callback' => 'data_update',
    'access arguments' => array('Update the list'),
    'type' => MENU_CALLBACK,
  );


How to solve this heat equation with fourier method

Question: Solve this via Fourier method:

$$u_t-u_{xx}=0 \quad\quad 0< x<\pi, \quad t >0, $$
$$u(0,t)=u_x(\pi,t)=0, \quad\quad t \ge 0$$
$$u(x,0)=2\sin\left(\frac{3x}{2}\right) \, \cos{2x},\quad\quad   0\leq x\leq\pi$$

I guess it is heat equation with insulated ends. what does it say with method of Fourier? do we use $u(x, t) =X(x)T(t)$? or
$$u(x,t)=\sum_{n=1}^{\infty}u_n(x,t)=\sum_{n=1}^{\infty}b_ne^{4n^2t}\sin(nx) $$
$u(x,0)=f(x)=\sum_{n=1}^{\infty}b_n\sin(nx)$
should I expand like $f(x)=2\sin(\frac{3x}{2})\cos2x=\sin(\frac{7x}{2})-\sin(\frac{x}2)=b_1\sin x+b_2\sin2x+b_3\sin3x....$
or finding
$$\frac2\pi\int_0^L(\sin(\frac{7x}{2})-\sin(\frac{x}2))\sin(nx)dx = $$
$$ = \frac2\pi\int_0^L\frac{\left(-\cos(x(\frac72+n))+\cos(x(\frac72-n)+\cos(x(\frac12+n))-\cos(x(\frac12-n)\right)}{2} = $$
$$= \frac2\pi \left(\frac{\frac{-\sin(x(\frac72+n))}{\frac72+n}+\frac{\sin(x(\frac72-n)}{\frac72-n}+\frac{-\sin(x(\frac12+n))}{\frac12+n}+\frac{\sin(x(\frac12-n))}{\frac12-n}}{2}\right)\Bigg|^\pi_0.$$
Answer: Try this:
$u(x,t) = \sum _{-\infty}^{\infty} c_k(t)e^{2\pi ikx} $. Period of $x$ is $\pi$.
Place this in the differential equation (and then manipulate), and then use the boundary methods.


How to calculate the exponential ratio between a few numbers?

Question: If I go onto Wolfram alpha and type 2 **x == 56 I see that x is around 5.8. What is a formula I can use to find the exact number (given use of a calculator)?
For example I have the following two times which are runtimes of a computation:
a = 0.005689493999852857
b = 151.89659522200054

I want to find the value of x such that a^x = b
So tried log a (b) which gave me -0.9717681977154843
My hunch is that since a is less than one, it needs to be given a negative exponent. However I'm not sure how to use this negative value, as opposed to a positive one. Should I just add one to both a and b before doing the logarithm, to ensure it's a positive exponent?
Comment: Have you studied logarithms?
Comment: You need to use a logarithm, but exact numbers are going to be hard to come by.
Comment: @EthanBolker I have. I was up to multivariable calculus in college before I stopped. I just haven't done it for a little while.
Answer: If
$$
2^x = 56
$$
then
$$
x = \log_2 (56).
$$
Your calculator probably has a $\log$ key, but that will give you the base $10$ logarithm.
You can look up the formula for changing the base of a logarithm. (Search for
log change base does the job.)
Answer: Taking logarithms of both sides will convert this to a linear equation which is easily solved:
$$2^x=56$$
$$\log(2^x)= \log 56 \tag{take $\log$ of both sides}$$
$$x\log 2 = \log 56\tag{property of logarithms}$$
$$x=\frac{\log 56}{\log 2}\tag{solve linear equation}$$
This works for any base of the logarithm. Calculators typically have $\log_{10}$ or $\log_e$ (often denoted "LOG" and "LN", respectively). Using the latter, I get the approximation
$$x \approx \frac{4.02434}{0.69315}\approx \boxed{5.80735}$$
The property of logarithms we used in the third line was $\log a^b=b\log a$.
Comment: if the base for some inputs is less than one, then those results will be negative exponents. Is there a way I could compare these with other inputs that produce a positive exponent?
Comment: @maxpleaner I'm not entirely sure what you're getting at, but perhaps you might be interested to note that $\ln \frac{1}{a}=\ln a^{-1}=-\ln a$, so if $\ln a$ was negative, $\ln \frac{1}{a}$ would be positive instead.  That is, instead of asking what exponent $x$ is needed to make $0.5^x=16$, you can instead look at what exponent $x$ is needed to make $(\frac{1}{0.5})^x=16$ and then multiply by negative one to make it the answer to the original question.


Complex numbers confusion

Question: I am a little bit confused trying to understand complex numbers. I read Richard Feynman lectures on physics and in chapter about complex numbers he says:
10^is = x + iy | i - imaginary, s - real number
First of all how is it possible that real number multiplied by itself (i*s times) gives complex number (x+iy) ? Why it is complex number, how we know that ?
Second, why we choose exponential function e^i0, to represent complex numbers ? Why e not 10 or any other number ?
Thanks ;)
Comment: Complex numbers are sums of imaginary and real numbers. All real numbers are complex numbers by default, reals are a subset of complex numbers.
Answer: Suppose you were interested in developing a useful for an expression like $10^{is}$. First, you would want to make is consistent with the rules of exponents, like $10^{is}=e^{is\ln(10)}$, and you would probably also want to make it follow the rules of calculus like $$\frac{d}{ds}10^{i s}=i\ln(10)10^{is}.$$ This means that if you tried to derive the Taylor series for $10^{is}$, you would get $$10^{is}=1+is\ln(10)+\frac{(is\ln(10)^2}{2!}+\frac{(is\ln(10))^3}{3!}+\frac{(is\ln(10))^4}{4!}.$$ Since Taylor series converge absolutely, you could rearrange this sum as: $$\left(1-\frac{(s\ln(10))^2}{2}+\frac{(s\ln(10))^4}{4!}+...\right)+i\left(s\ln(10)-\frac{(s\ln(10))^3}{3!}+\frac{(s\ln(10))^5}{5!}+...\right).$$ Notice that the terms inside the brackets are all real. At this point, you might recognize the two series inside the brackets as $\cos(s\ln(10))$ and $\sin(s\ln(10))$ respectively. Thus, $$10^{is}=\cos(s\ln(10))+i\sin(s\ln(10)).$$ Thus, $10^{is}$ being a complex number is the only way to make it consistent with the math on the real numbers which we have already put in place.
Answer: What is the meaning of power?
$3^n$ where $n \in \mathbb{N}$ means $3 \times 3 \times \dots \times 3 $ for $n$ times.
However when we expand the meaning of power to rational power
$$ a ^ \frac{m}{n}=\sqrt[n]{a^m}$$
The previous concept does not work. The meaning of power is redefined. But in special case where the power is an natural number, the result is the same as before.
The negative power is defined too. It does not give you any sense about how many times multiplication we well have.
Then definition of power is extended to real numbers. Here, root square cannot help you. You need a more powerful definition for power
$$a^r=\exp(r \times \log a)$$
This re-definition is fantastic for real numbers and it does not contradict the previous definitions.
For complex numbers, we follow the same principle. We do nothing except for expansion of $\exp$ and $\log$ for complex numbers. $\exp$ and $\log$ for complex numbers are equal to the value of their Tylor expantion when you put a complex number in them. So, previous definitions of power are still preserved for real number.
Hence, the concept of multiplying $n$ times is just good for natural numbers.

Why do we choose exponential for showing complex numbers?

Not always. One problem with complex numbers is that each complex number contains information two times as much as a real number. It can be shown in both ways
$$z=x+i y$$
$$z=r \exp(i \theta)= r \angle \theta$$
A complex number is a dot in 2D while a real number is a dot in 1D.
So you can show a dot with its $x$ and $y$. Alternatively, you can show it with magnitude ($r$) and angle($\theta$). Working with magnitude and angle gives you better view about how big a number is. In electrical engineering, a complex number can show an AC voltage. The magnitude shows the voltage while the angle shows the phase of sinusoidal waveform compared to an origin which is not such important in many cases. But why exponential? Just because of the following formula:
$$\exp(i \theta)=\cos(\theta)+i \sin(\theta)$$
$\exp(i \theta)$ is a unit vector ($sin^2+cos^2=1$). However it shows a direction. Combined with a magnitude ($r \exp(i \theta)$), it can show any complex number (or any 2D vector).
Update
$$\exp(i \theta)=1+(i\theta)+\frac{(i\theta)^2}{2!}+\frac{(i\theta)^3}{3!}+\frac{(i\theta)^4}{4!}+\frac{(i\theta)^5}{5!}+\frac{(i\theta)^6}{6!}+\dots=1+i\theta+\frac{-1 \theta^2}{2!}+\frac{-i \theta^3}{3!}+\frac{+ \theta^4}{2!}+\frac{i \theta^5}{5!}+\frac{-1 \theta^6}{6!}+\dots=(1+\frac{-1 \theta^2}{2!}+\frac{+ \theta^4}{2!}+\frac{-1 \theta^6}{6!}+\dots)+i(+\theta+\frac{-1 \theta^3}{3!}+\frac{ \theta^5}{5!}+\dots)=\cos(\theta)+i \sin(\theta)$$
Comment: Thanks. The formula: exp(iθ)=cos(θ)+isin(θ) was discovered by power series (Taylor series) or something else, what is the genesis of it ?
Comment: write the power series of exp and replace x with $i \theta$ and replace $i^2$ with $-1$. You see that it is equal to two parts. terms with odd and even powers of $\theta$. If you separate them, power series of sin and cos appears. The proof is very simple.
Answer: For the first question, $10^{is} = x+ iy$, we can do this because this lets us find suitable values of $x$ and $y$, and if "a real number multiplies by itself $i$ times" is not a complex number, then we will find $y$ to be $0$, giving you a real number.
So, basically, letting $\text{something} = x+ iy$ does not mean that we are saying that $\text{something}$ should be a complex number, rather it can be one. This is because the real numbers form a subset of the complex numbers.

Complex numbers confusion


Doubt regarding assumption of domain when one isn't given

Question:
Calculate $f(x)=\dfrac{49}{x^2}+x^2$ at the points where $\dfrac{7}{x}+x=3$.

Now if $D_f\subseteq \mathbb R$, then this has no solutions since $\dfrac{7}{x}+x=3$ has no solution in $\mathbb R$. But if $D_f=\mathbb C$, then this equation yields solution:
$\dfrac{49}{x^2}+x^2=\Big(\dfrac{7}{x}+x\Big)^2-14=9-14=-5$ (obviously here $x\notin \mathbb R$)
Now my doubt may be silly (I apologize for that), but until now at the high school level, we have been advised to assume the domain of function to be $\mathbb R$ except when given otherwise. But here the domain must obviously be assumed to be $\mathbb C$ to yield a solution. So what should be assumed as the domain of any function in general when any specific domain isn't mentioned?
Comment: You've gone too deep. I can't tell you how many times in the 9th class book(this is Selina ICSE I speak of, I am helping a few people using that book) I saw something like this, where you have to assume that $x$ satisfies an equation that no real $x$ can satisfy, then you have to find some other function of $x$ (All this comes in that expansions chapter). I would ask you to bring this up with your teacher, but there's no problem (at *that* level) in proceeding without acknowledging the domain. (Of course, rigorously speaking the question is unclear, since without the domain you cannot proceed)
Comment: @TeresaLisbon I disagree. OP did not go too deep. OP actually thought about the problem, rather than performing the robotic work of manipulating one expression to get another. Instead, OP actually thought about the problem, and realised it is not well formed. It's not that the OP went too deep. The problem authors didn't go deep enough.
Comment: @5xum Correction, I will put it this way : the authors did not expect him to go so deep. Big difference, thank you for pointing it out.
Comment: @TeresaLisbon Ah, now we agree. I just don't want OP to feel bad for doing the right thing :)
Comment: @5xum Thanks. My father went to Slovenia about $10$ years ago. He's been to Lake Bled and eaten at an Indian restaurant in Ljubljana. We have some nice pictures at home!
Answer:
So what should be assumed as the domain of any function in general when any specific domain isn't mentioned?

Nothing. There is no "general function domain". If the domain of a function is not implicitly clear from the context, then the text must explicitly mention that domain, otherwise, it is unclear.
Comment: So, should I assume that the question mentioned in the text was unclear?
Comment: @DevanshKamra It's a bit unclear, yes. Not tragically so, as the solution still stands, but it is a good example of how one must be careful when putting together "simple" questions.
Comment: Thanks for the help (+1).


Howto configure Raid on IBM x3500 m3

Question: I have recently acquired an old IBM x3500 m3 and I'm struggling to find the raid configuration. I've checked out everything in the uefi and post doesn't show any key combinations to access ServeRaid. I've disabled the "show boot logo" setting.
This guy used a boot cd to configure the raid controller. After searching i found a ServeRaid Support CD that might do the trick. I'm running Ubuntu Server 14.04.
Does anybody know how to do this ?
As a bonus question, the server has 6 250 GB drives but i only see 2 virtual drives.
That leaves me with the assumption one of the virtual drives might be a Raid 10 (or they are not configured at all). Is it possible to grow to a Raid 5 (or 6) without data loss ?
Since it's just a lab setup data loss would not be to tragic but I would not mind if I could skip reinstalling the system.
Thanks in advance!
Answer: Using the boot CD seems to be the only possibility.
Download the IBM ServeRaid Support CD form here.
Boot from the CD and hit ctrl + m.
Raid migration eg. from Raid 1 to 5 is possible.
The raid configuration was 3x Raid 1 with one degraded array.

Howto configure Raid on IBM x3500 m3


Show that $m = \pm 2$ or $m = \pm 3.$

Question: Let $$R = \left\{\frac{a + b\sqrt{-19}}{2}:a,b \in \mathbb{Z}, a \equiv b \mod 2 \right\} = \mathbb{Z} \left[\dfrac{1+\sqrt{-19}}{2} \right] = \mathbb{Z}[\alpha].$$
and define $d:R \setminus \{0\} \to \mathbb{Z}^{>0}$ to be a function satisfying: $a,b \in R$ with $a \ne 0$, and there exists $q,r \in R$ such that $b = aq + r$ with $r = 0$ or $d(r) < d(a).$

Let $m \in R$ be an element with $d(m)$ minimal, subject to the condition that $m \ne 0$ and $m$ is $\textbf{not a unit}.$ By definition of euclidean domain, there exist $q,r \in R$ such that $$2 = mq + r, \hspace{1mm} r = 0 \text{ or } d(r) < d(m).$$
Conclude from these conditions on $r$ and the definition of $m$ that $r = 0$ or $r = \pm 1$. By exploring these cases, show that $m = \pm 2$ or $m = \pm 3.$

I can see how $r = -1$ or $r = 0$ but not $r = 1.$ If $r = 1,$ then $2 = mq + 1 \Longleftrightarrow 1 = mq.$ Wouldn't this mean that $m$ $\textbf{is a unit}$?
Answer: You are correct in noting that the case $r= 1$ is impossible because $m$ was assumed to not be a unit.  The point is that the condition $r= 0$ or $d(r) < d(m)$ restrict $r$ to be $0$, $1$, or $-1$, and only two of these cases are possible by our assumption on $m$.

Show that $m = \pm 2$ or $m = \pm 3.$


Div toggled onKeyup and stays visible Javascript and JQuery

Question: here is my problem :
I am currently designing a JavaScript function destined to verify the safety level of a password. Once the password is typed, I use jQuery to toggle the display of a div (which is invisible by default) which contains the sentence "Your password is" + the given level of safety.
Everything works fine, except that I use the onKeyUp event in the password-input to trigger my div appearing. However, naturally, every key pressed toggles the visibility of my div. Result: with every first key pressed in the password input, my div appears, with the next key pressed, it disappears again. Is there a way to toggle the div once with the first key pressed and prevent it from disappearing with pressing of the next key ?
Here is the code :
function password1Security()

{
    var pwd1 = document.getElementById("password1");
    var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
    var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
    var pwdsft = document.getElementById("passwordSafetyLevel1");
    {
        if (strongRegex.test(pwd1.value))
        {
            pwdsft.innerHTML = 'Safe'
        }
        else if (mediumRegex.test(pwd1.value))
        {
            pwdsft.innerHTML = 'Quite Safe'
        }
        else
        {
            pwdsft.innerHTML = 'Unsafe'
        };
    }
};

<input name="password1"
        id="password1"
        type="password"
        size="15"
        maxlength="20"
        style="width:500px; height:30px;"
        onKeyUp="showPassSafety1()" />

Your password is .

Comment: Code indentation is your friend :)
Answer: You can use jQuery .one() event handler.
http://api.jquery.com/one/
Comment: Hi, thank you for the quick response. I am a novice in jQuery and I have trouble figuring out how to write the code with the one() method. Would it be something like $("password1").one("onKeyUp",showPassSafety1()); ?
Comment: It should be `$("#password1").one("keyup",showPassSafety1());`, where `password1` is the element where the user enters password, and `showPassSafety1()` is your function to show the invisible element. Don't forget, you must use jQuery selectors - it's not `$("password1")`, but `$("#password1")`.
Answer: I believe you are setting somewhere the visibility of your passwordSafety1 span.
When you do that you should check the length of your document.getElementById("password1").value and set it visible or not depending on this length for instance; avoid switching between none and block.