MySQL Error - Can't connect to local MySQL server through socket

Question: Sometimes on my VPS I get the error
Warning: mysql_pconnect(): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111) in /var/www/mysql.php on line 8

It can be solved by restarting MySQL several times, restating the sever or sometimes using mysqld command.
Using the mysqld command I get the following:
root@web:~# mysqld
130109 10:47:23 [Note] Plugin 'FEDERATED' is disabled.
130109 10:47:23 InnoDB: The InnoDB memory heap is disabled
130109 10:47:23 InnoDB: Mutexes and rw_locks use GCC atomic builtins
130109 10:47:23 InnoDB: Compressed tables use zlib 126.96.36.199
130109 10:47:23 InnoDB: Initializing buffer pool, size = 128.0M
130109 10:47:23 InnoDB: Completed initialization of buffer pool
130109 10:47:23 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
130109 10:47:23  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
130109 10:47:24  InnoDB: Waiting for the background threads to start
130109 10:47:25 InnoDB: 1.1.8 started; log sequence number 43428438
130109 10:47:25 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
130109 10:47:25 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
130109 10:47:25 [Note] Server socket created on IP: '0.0.0.0'.
130109 10:47:25 [Note] Event Scheduler: Loaded 0 events
130109 10:47:25 [Note] mysqld: ready for connections.
Version: '5.5.28-0ubuntu0.12.04.3'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  (Ubuntu)
130109 10:47:25 [ERROR] mysqld: Table './sever/table' is marked as crashed and should be repaired
130109 10:47:25 [ERROR] mysqld: Table './sever/table' is marked as crashed and should be repaired
130109 10:47:25 [ERROR] mysqld: Table './sever/table' is marked as crashed and should be repaired
130109 10:47:25 [Warning] Checking table:   './sever/table'

My get only 50 visitors a day and uses more than 3000 queries per hour.
My VPS is only 1 core with 256MB ram and runs on Ubuntu 64bit.
MySQL downtimes directly affect my website and I can't find a answer anywhere.
Thanks in Advance :)
Comment: This looks like the OOM-killer to me.  [Try this](http://serverfault.com/a/399838/26130)
Answer: Check your log, your table is crashing..
You should repair it before you continue.
See this link on how to do it
Also check the [hostname].err MySQL error log file. It could be in /var/lib/mysql either /var/log/syslog
Answer: You should have a look at the log (mysql error log, mysql query log, system logs) entries when the system is misbehaving not after you restart it.
It's likely that you are reaching the max connections limit.

only 50 visitors a day and uses more than 3000 queries per hour

erk, that's absurdly high, even if you are using Hibernate (but you made no mention of what's in between the webserver and MySQL).
I'd be looking to see what's happenning with the web traffic around this time - is it slowing down - are you swapping out too much stuff - exactly how many users are connected. Also check what's happenning with the mysqld process before you try to restart it - is the process still present?


Proper way to subclass from sklearn with * argument

Question: I am trying to subclass from sklearn.svm.LinearSVC and noticed the * argument in the signature. I'm not sure if this * refers to **kwargs or *args or something else. I am trying subclass the init function as follows. In this scenario I'm have added a single additional argument new_string_in_subclass the init function.
from sklearn.svm import LinearSVC
class LinearSVCSub(LinearSVC):
    def __init__(self, penalty='l2', loss='squared_hinge', *, dual=True, tol=0.0001, C=1.0, multi_class='ovr',
                 fit_intercept=True, intercept_scaling=1, class_weight=None, verbose=0, random_state=None,
                 max_iter=1000, sampler: new_string_in_subclass=None):

        super(LinearSVCSub, self).__init__(penalty=penalty, loss=loss, *, dual=dual, tol=tol,
                                            C=C, multi_class=multi_class, fit_intercept=fit_intercept,
                                                  intercept_scaling=intercept_scaling, class_weight=class_weight,
                                                  verbose=verbose, random_state=random_state, max_iter=max_iter)

        self.new_string_in_subclass = new_string_in_subclass

If I want to maintain the functionality of the LinearSVC class's other methods, do I need to pass the * argument to the super class's __init__ function? If so how do I do this? Right now I get a SyntaxError as below:
super(LinearSVCSub, self).init(penalty=penalty, loss=loss, *, dual=dual, tol=tol,
^
SyntaxError: invalid syntax
Comment: This `*` syntax is for keyword-only arguments. It was added in Python 3.8. See [Positional-only parameters](https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters) in the release notes.
Answer: A * only goes in the definition of a method, not in calls to that method.  The * indicates that all parameters after it can only be supplied by name, not by position.  Just leave it out when calling the super, and you should be fine.
Comment: I've posted [another question](https://stackoverflow.com/q/64430351/11542679) about another problem I ran into after this was sorted out. Appreciate if you could have a look. It's about using the above setup with sklearn `GridSearchCV `
Answer: The asterisk serves to separate keyword-only parameters: Bare asterisk in function arguments?  You should skip it when instantiating the sklearn class.


How to write a python function that will take a dataframe as input, normalize its columns with numeric data type and return the result

Question: This is my first question here, so I apologize in advance.
I want to write a function that takes dataframe name as argument and applies MinMaxScaler() on the dataframe columns that have numeric data type (int64). I looked it up in the internet and wrote the following code, which gave me the error, 'type' object is not iterable'
def standard(df):
        "Takes a dataframe and returns the dataframe with standardized numerical columns"
        from sklearn.preprocessing import MinMaxScaler
        scaler = MinMaxScaler()
        df = pd.DataFrame()
        int_column = []
        for column in pd.DataFrame:
            if 'int' in str(dtype(column)):
                int_column.append(column)
                df[int_column] = scaler.fit_transform(df[int_column])
                return (df)

Answer: Can you try the following:
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']

numeric_df = df.select_dtypes(include=numerics)

or with new version of pandas
numeric_df = df.select_dtypes('number')

So for your case
def standard(df):
    "Takes a dataframe and returns the dataframe with standardized numerical columns"
    from sklearn.preprocessing import MinMaxScaler
    scaler = MinMaxScaler()
    int_columns = df.select_dtypes('number').columns
    df[int_columns] = scaler.fit_transform(df[int_columns])
    return df

Comment: Thanks, the solution that you have provided after 'So for your case' worked. I have two follow up questions:
1) Does the word 'number' in the code line include all numeric data types by default (coz we are not defining it)?
`int_columns = df.select_dtypes('number').columns`
2) I tried replacing the word 'number' by int64 to apply scaler to only the column having int64 type (there are other columns that are numeric but are uint8 type (one hot encoded columns), however, it gave the following error when the dataframe was passed as argument:
ValueError: at least one array or dtype is required
Comment: can you try the first approach, where the dtypes are added into the list.
Comment: So, I tried the following code, but it did not scale any column, neither int64, nor any other dtype (the columns I want this function to scale are int64, while other one hot encoded columns are dtype uint8.

`def standard(df):
    "Takes a dataframe and returns the dataframe with standardized numerical columns"
    from sklearn.preprocessing import MinMaxScaler
    scaler = MinMaxScaler()
    numerics = ['int64']
    numeric_df = df.select_dtypes(include=numerics)
    df[numeric_df] = scaler.fit_transform(df[numeric_df])
    return df`
Comment: I guess you need to use `scaler.fit_transform(numeric_df)`


Moments and density tails

Question: Assume that the first $n$ moments $m_1,\dots\,m_n$ of a random variable $X\in\mathbb{R}$ are known, but not its probability density function $p(x)$.
Does there exist a methodology to characterize the tail behaviour of the p.d.f ?
For example whether $p(x)\sim |x|^{-\theta}$ or  $p(x)\sim e^{-\theta \, |x|^\gamma}$.
Comment: Did you look at truncated moment problems?
Answer: If two distributions $X$ and $Y$ have the same moments from 0 up to $n$, then the CDFs of the two functions differ asymptotically by less than $x^{-n}$. See this page for details and references.
Comment: That's interesting and useful, but does it tell us anything at all about the tails of either distribution?

Moments and density tails


For a $C^{\infty}$ function $f$ , if $|f(x)|\leq \exp(-\frac{1}{x^{2}})$ then is $f^{(n)}(0)=0$?

Question: Suppose $f\in C^{\infty}(\Bbb{R})$  . If $|f(x)|\leq \exp(-\frac{1}{x^{2}})$ for all $x\neq 0$ and $f(0)=0 $ . Does this imply $f^{(n)}(0)=0$
for all $n$ ?
I can see that $|\frac{f(h)}{h}|\leq \frac{1}{h}e^{\frac{-1}{h^{2}}}\to 0$ as $h\to 0$ which shows that $f'(0)=0$ .
But I am unsure about $n\geq 2$. Is it true for $n\geq 2$ ? If so, how can I prove this for $n\geq 2$?
I  tried to use Lagrange's Mean Value Theorem to see that $f'(ch)=\frac{f(h)}{h}$ for some $0<c<1$. But still, I cannot use this to get an approximation for all $f'(h)$ when $h$ is near $0$.
Can anyone help me with this problem?
Answer: You can use induction and l'Hôpital.

From you condition: $$\lim_{h\to 0} \frac{f(h)}{h^n} = 0$$

Using l'Hôpital:

$$\lim_{h\to 0} \frac{f(h)}{h^n} = \frac1{n!} f^{(n)}(0)$$
Can you finish from here?
Comment: Ofcourse thanks! . Why didn't I think of L'Hospital.


Why does creating a variable name for an exception raised in a Python function affect the reference count of an input variable to that function?

Question: I've defined two simple Python functions that take a single argument, raise an exception, and handle the raised exception. One function uses a variable to refer to the exception before raising/handling, the other does not:
def refcount_unchanged(x):
    try:
        raise Exception()
    except:
        pass

def refcount_increases(x):
    e = Exception()
    try:
        raise e
    except:
        pass

One of the resulting functions increases pythons refcount for its input argument, the other does not:
import sys

a = []
print(sys.getrefcount(a))
for i in range(3):
    refcount_unchanged(a)
    print(sys.getrefcount(a))
# prints: 2, 2, 2, 2

b = []
print(sys.getrefcount(b))
for i in range(3):
    refcount_increases(b)
    print(sys.getrefcount(b))
# prints: 2, 3, 4, 5

Can anyone explain why this happens?
Answer: It is a side effect of the "exception -> traceback -> stack frame -> exception" reference cycle from the __traceback__ attribute on exception instances introduced in PEP-344 (Python 2.5), and resolved in cases like refcount_unchanged in PEP-3110 (Python 3.0).
In refcount_increases, the reference cycle can be observed by printing this:
except:
    print(e.__traceback__.tb_frame.f_locals)  # {'x': [], 'e': Exception()}

which shows that x is also referenced in the frame's locals.
The reference cycle is resolved when the garbage collector runs, or if gc.collect() is called.
In refcount_unchanged, as per PEP-3110's Semantic Changes, Python 3 generates additional bytecode to delete the target, thus eliminating the reference cycle:
def refcount_unchanged(x):
    try:
        raise Exception()
    except:
        pass

gets translated to something like:
def refcount_unchanged(x):
    try:
        raise Exception()
    except Exception as e:
        try:
            pass
        finally:
            e = None
            del e

Resolving the reference cycle in refcount_increases
While not necessary (since the garbage collector will do its job), you can do something similar in refcount_increases by manually deleting the variable reference:
def refcount_increases(x):
    e = Exception()
    try:
        raise e
    except:
        pass
    finally:   # +
        del e  # +

Alternatively, you can overwrite the variable reference and let the implicit deletion work:
def refcount_increases(x):
    e = Exception()
    try:
        raise e
    # except:               # -
    except Exception as e:  # +
        pass

A little more about the reference cycle
The exception e and other local variables are actually referenced directly by e.__traceback__.tb_frame, presumably in C code.
This can be observed by printing this:
print(sys.getrefcount(b))
print(gc.get_referrers(b)[0])  # <frame at ...>

Accessing e.__traceback__.tb_frame.f_locals creates a dictionary cached on the frame (another reference cycle) and thwarts the proactive resolutions above.
print(sys.getrefcount(b))
print(gc.get_referrers(b)[0])  # {'x': [], 'e': Exception()}

However, this reference cycle will also be handled by the garbage collector.
Comment: This is a really excellent answer! Thank you for sharing your knowledge, I appreciate it.
Answer: It seems that writing out the question helped us realize part of the answer. If we garbage-collect after each call to refcount_increases, the refcount no longer increases. Interesting! I don't think this is a complete answer to our question, but it's certainly suggestive. Any further information would be welcome.
import gc
c = []
print(sys.getrefcount(c))
for i in range(3):
    refcount_increases(c)
    gc.collect()
    print(sys.getrefcount(c))
# prints: 2, 2, 2, 2


Is there a name for a beat/tempo that can be interpreted as being in two different times

Question: I am not a musician, I don't read music and I don't actually play any instruments. However (and sorry if this sounds stupid) I'm a very good dancer and believe I have a good ear and feeling for tempo and beat.
However, when I listen to certain songs, I notice that there is a beat/tempo that changes the moment another instrument joins in, or the vocalist starts to sing.
The two pieces of music I notice this on all of the time is the intro to 'All my life' by the Foo Fighters and the change over from the verse into the chorus section of 'Forever came today' by Diana Ross and the Supremes.
I have no idea how to describe it correctly (hence my posting here) but in the Diana Ross song, I can only describe it as a slow beat that doesn't change tempo as it goes into the chorus, but it suddenly sounds as though the tempo goes to the same speed as 'Can't hurry love' (also by Diana Ross (or Phil Collins)).
I'm not really expecting anything from the query, but it just sits in the back of my mind and somebody may also think about it, but know what it's called (if anything).
Thanks in advance,
Pete J.
Comment: Possibly a poly rhythm?  I can think on one easy to hear example, Breaking the Girl by the Chili Peppers.  It has a 2 over 3 or 3 over 2 groove.  The 3 is stringer but you can count it in either 2 or 3.  Also, what you are hearing might just be an example of syncopation.
Comment: Right at the start, the intro. They play 3 repetitive notes/chords and it's these 3 that is where it happens. It's only when Dave Grohl starts to sing that I realise I got the beat wrong.
Again, I don't know how to explain it. There is no different emphasis on any of the 3 notes/chords played, but I can interpret those 3 notes in two different ways.

Without singing it out to explain what I mean, I don't think I'm going to be able to explain it properly.
Comment: A polyrhythm is when two instruments actually play the different divisions, e.g. one instrument plays 3 notes while another plays 4 notes in the same amount of time. What you're describing could just be an ambiguous rhythm resulting from different instruments accenting different beats, e.g. one instrument stresses every 3rd note and another stresses every 4th note, without actually playing the notes at a different tempo. Listeners can then base their sense of the rhythm on one or the other instrument. I get that with Björk's *All Neon Like*.
Comment: Hi ggcg.

Thanks for answering. I just listened to the Chilli Peppers song and while I can hear what you mean, it isn't the same as I'm trying to describe. I also looked up the definition of syncopation and I don't think it is that as well.

Very difficult to explain what I'm hearing/feeling in words (funnily enough, one or two of my ex's have said the same sort of thing about me :)
Comment: For "All my life", at what phrase exactly do you experience the change in rhythm? I've read through the note sheet and couldn't find any abnormalities. It's actually pretty dull rhythmically.
Comment: Also listen to **Chasing Pirates** by _Norah Jones_ and **Ghost Story** by _Sting_.  There's lots of other possibilities. Both misdirect you rhythmically. After a while you realise that '1' is in a different place than you originally thought.
Answer: Hi and welcome to the music stack exchange. The term that best describes the phenomenon to which your question refers is misinterpretation.
Examining the songs that you reference, both the beat and the tempo are fairly straightforward... There is nothing out of the ordinary as far as how the beat or tempo can be quantified; at least according to music theory. There are simple time signatures with uniform tempos used throughout each of the respective songs, as is the most common rhythmic form used in almost all pop-music.
There is a term that refers to the usage of concurrent tempos in songs, Polytempo. This question here on the music stack exchange nicely describes the difference between this term and Polyrhythm and Polymeter... Also, see this question for a better understanding of the differences between beat, tempo and time signature.
It's worth stating here that it is potentially 'easy' to misinterpret the rhythms of songs that contain complex time signatures or mixed meters... or any song that doesn't conform to the most common duple/quadruple and triple meters. In the sense that these sort of rhythms do not tend to be 'dance-y' for the most part.
However, none of these terms fit the songs that you reference, after analysis.
Finally, perhaps it is easy to conflate beats or tempos when there is simply less to reference within a song... As you state in the comments, it isn't until the singing begins in the intro to 'All My Life' that the rhythm 'corrects itself' for you. In 'Forever Came Today,' the percussion drops-out a bit only to return with a big flourish to emphasize the dynamic change from the verse to the chorus.
Comment: I really like the idea of rhythmic _misdirection_. In "All My Life" the '1' of the measure occurs on the _second_ 16th note, not the first.
Comment: I follow you - the intro to "Eye of the Tiger" comes to mind... That wouldn't seem to apply to the "Forever Came Today" example in the question though.
Comment: Also the intro to "Life in the Fast Lane" by the Eagles...


Explicit construction of the transitive closure in the Boolean valued model

Question: Suppose $t\in M^B$ is an element of the Boolean valued model. Since $ZF\vdash\exists$x  x=TC({$Val_G(t)$}), there is $s\in M^B$ such that $1\Vdash Val_G(s)$=TC({$Val_G(t)$}). Is it possible to construct $s$ explicitly?
Comment: Do you know how to construct the union? I don't think this is significantly different.
Comment: John Bell's Boolean valued models book. In the part where it's shown the axiom of union holds in $M^B.$
Comment: @spaceisdarkgreen I'm not familiar with that, if you have any help or sources I could look at I'd really appreciate it
Answer: Let me give a possible construction for a name for the transitive closure although I will not give the precise proof for why it works.
We know that
$$\operatorname{TC}(a) = \textstyle \bigcup \{\bigcup^n a \mid n<\omega\}.$$
Let us mimic this definition with Boolean-valued names.
For a given $B$-name $\sigma$, let us consider the name $\mathsf{union}(\sigma)$ with the domain
$$\{\tau \mid \exists \upsilon \in \operatorname{dom} \sigma[\tau \in\operatorname{dom}\upsilon]\}$$
with the Boolean value
$$(\mathsf{union}(\sigma))(\tau) = \textstyle \sum \{\sigma(\upsilon)\cdot \upsilon(\tau) \mid \tau\in\operatorname{dom}\upsilon, \upsilon \in \operatorname{dom} \sigma\}.$$
You can see that
$$\| \mathsf{union}(\sigma)=\bigcup \sigma\|=1$$
for every $B$-name $\sigma$. Then consider the name $\mathsf{tc}(\sigma)$ given as follows:

The domain of $\mathsf{tc}(\sigma)$ is the union of all $\operatorname{dom}\mathsf{union}^n(\sigma)$ for all $n<\omega$, where $\mathsf{union}^n(\sigma)$ is the name obtained from $\sigma$ by applying $\mathsf{union}$ $n$ times.
For each $\tau\in\operatorname{dom}\mathsf{tc}(\sigma)$, define
$$(\mathsf{tc}(\sigma))(\tau) = \textstyle \sum \{\mathsf{union}^n(\tau) \mid \tau \in\operatorname{dom}\mathsf{union}^n(\sigma)\}.$$
Answer: The boolean-valued model satisfies $\sf ZFC$, so you can expect in some sense to perform set theoretical constructions inside the model. As for extracting a name to witness $\Vert \exists x \varphi(x)\Vert=1$, there is indeed some risk that choice is required (even if the proof of $\exists x\varphi(x)$ can be done in $\sf ZF$). However, when we have $\Vert \exists! x\varphi(x)\Vert = 1,$ it doesn't require any choice to extract a witness.
This is given as exercise 1.29 in John Bell's boolean-valued model book. The answer is given as a hint, with the proof left up to the reader: Say $\Vert \exists ! x\varphi(x)\Vert = 1$ and let $\alpha$ be the least ordinal such that $\bigvee_{x\in V^B_\alpha}\Vert\varphi(x)\Vert = 1.$ Then define $u\in V^B$ by $\operatorname{dom}(u)= V_\alpha^B$ and $u(z) = \Vert\exists y(\varphi(y)\land z\in y)\Vert.$ We have $\Vert\varphi(u)\Vert = 1.$
So, in the case like trcl (but much more generally), where we have a definable class function in $\sf ZF$ (i.e. $\sf ZF\vdash \forall x\exists!y\varphi(x,y)$), we know that $\Vert \forall x\exists! y\varphi(x,y)\Vert=1$, and a similar construction to the above shows (without using AC) that for any $u\in V^B$ there is a (canonically definable) $v\in V^B$ such that $\Vert \varphi(u,v)\Vert = 1.$


LINQ query to group data between two list collections, populating a nested object (VB.Net)

Question: I have these objects:
Public Class MakeInfo
  Public Property Name As String
  Public Property Description As String
  Public Property Stock As StockInfo
End Class

Public Class ModelInfo
  Public Property Make As String
  Public Property Name As String
  Public Property Description As String
  Public Property Stock As StockInfo
End Class

Public Class StockInfo
  Public Property Count As Integer
  Public Property MinPrice As Double
End Class

Using LINQ I need to take a List(Of MakeInfo) and a List(Of ModelInfo) and aggregate the StockInfo from ModelInfo into the List(Of MakeInfo).
So for each MakeInfo I will have a total count of all stock where MakeInfo.Name = ModelInfo.Make, and also a minimum price.
I think it's going to be something like this, but I'm having trouble accessing the nested object and not sure if it's going to be possible with a single query. I've tried a few variations, but here's where I'm up to:
newList = From ma In makeData _
          Group Join mo In modelData _
          On ma.Name Equals mo.Make _
          Into Group _
          Select New MakeInfo With {.Name = m.Name, _
                                    .Description = m.Description, _
                                    .Stock = ?}

Comment: Please show us what you've got thus far.
Answer: If you are actually trying to modify the original MakeInfo objects, you should stop the query with the group.  newList will have each make paired with the group of models of that make.  You can iterate through newList, and for each make, aggregate the models into the StockInfo for the make.
Dim newList = From ma In makeData _
              Group Join mo In modelData _
              On ma.Name Equals mo.Make _
              Into Group
For Each g In newList
    g.ma.Stock = g.Group.Aggregate(
                    New StockInfo() With {.MinPrice = Double.NaN},
                    Function(si, model)
                        Return New StockInfo With {
                                     .Count = si.Count + 1,
                                     .MinPrice = If(Double.IsNaN(si.MinPrice) OrElse
                                                    model.Stock.MinPrice < si.MinPrice,
                                                    model.Stock.MinPrice,
                                                    si.MinPrice)}
                    End Function)
Next

If you actually want new instances, just change the loop to create a new item instead of modifying the existing make.
Dim results As New List(Of MakeInfo)()
For Each g In newList
    Dim newMake As New MakeInfo()
    newMake.Name = g.ma.Name
    newMake.Description = g.ma.Description
    newMake.Stock = g.Group.Aggregate( same as before )
    results.Add(newMake)
Next

Comment: I thought there might be a way to do it without using a loop, perhaps I was being ridiculous (?). I've found LINQ to not perform much quicker than just doing the whole thing with a couple of loops and building the results up to a new collection. Having said that, I've used the second portion of code and got it working. Thanks for your help.
Comment: I found a better solution - I have added a new answer.
Answer: I eventually found the right way to do this and it doesn't require loop iteration:
Dim new_makes = From ma In makes
                Join mo In models On mo.Make Equals ma.Name
                Group By ma.Name, ma.Description
                Into TotalCount = Sum(mo.Stock.Count), LowestPrice = Min(mo.Stock.MinPrice)
                Select New MakeInfo With {.Name = Name, _
                                          .Description = Description, _
                                          .Stock = New StockInfo With {.Count = TotalCount, .MinPrice = LowestPrice}}

I was certain that it would be possible.


Drupal migrate - "--limit" option works only for first run?

Question: I have custom source plugin (imports from MongoDB) and when I run migration for the first time like:
<code>drush mim article --limit=10
</code>
it works well: 10 articles are being imported and process stops.
But if I repeat that command then only 1 article is imported.
And if I have like 10 imported articles and run again with limit=20 then 10 new ones are going to be imported.
And if I set limit smaller than current number of imported ones then only 1 new row will be imported.
Should command I specified import always 10 new rows (if there are available, unprocessed)?
Any hint is welcome!
(using drush 11.0.7 and Drupal 9.3.12) (edited)
Update:
So it looks like that code which is counting number of processed rows and checking if limit parameter is reached is not working well, that is, it counts also previously processed rows which should not be the case.
Comment: Looks like my source plugin is responsible for skipping processed row (answered by @mikelutz on slack).  So looks like in my case processed rows are not skipped, but counted again. But I didn't override next() method. Any example on how to do this?
Comment: next()  method (which I didn't override) of SourcePluginBase (which I'm using as a base class) should do the checking if row is processed already or not. But looks like it fails. I had an issue before with condition like that, when previously processed are always been processed again and it was resolved by updating drush.
Answer: I solved it this way:
Original next() of SourcePluginBase has checking if row processing is needed or not this way:
<code>  if (!$row->getIdMap() || $row->needsUpdate() || $this->aboveHighWater($row) || $this->rowChanged($row)) {
    $this->currentRow = $row->freezeSource();
  }
</code>
Now, in my class that inherits that SourcePluginBase I added to it prepareRow override:
<code>  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    if (!$row->getIdMap() || $row->needsUpdate() || $this->aboveHighWater($row)) {
      return parent::prepareRow($row);
    }
    return FALSE;
  }
</code>
I noticed that for previously imported rows condition $this->rowChanged($row) is true and for new rows that really needs to be processed $this->rowChanged($row) is true. So I removed first one and kept second one.
I'm aware that this is kind of workaround and that there is probably some incompatibility between drush and drupal, but this is the best solution I could do. If someone has better solution/explanation I will be glad to hear it.


Sorting an array alphabetically Javascript

Question: I'm trying to collect a list and put them into an array then sort via the first letter of each item in the array. So far i have:
var cityArray = [];
  $("#addresses_list ul li .name").each(function() { cityArray.push($(this).text().trim()) });
  var finalArray = ['"' + cityArray.join('", "') + '"'];
  finalArray.sort();
  alert(finalArray);

This is collecting correctly and grouping into an array but still not sorting. Any idea why it's not? Thanks in advance
Comment: Because `finalArray` has only one entry, the `cityArray` which you've turned into a string for some reason.
Comment: Possible duplicate of [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript)
Comment: yeah i changed to have the sort on cityarray and that worked. thanks
Answer: You need cityArray to sort before joining.
cityArray.sort();


How to check if latest Windows Updates are installed via PowerShell?

Question: I have an installation PowerShell script that installs Docker and other components onto Windows Server 2016.  I have learned (the hard way) that if the latest Windows Updates are not installed, sometimes Docker will get into a very wierd state and not function as expected.
Therefore, I would like to programmatically check in PowerShell if all available/latest Windows Updates are installed on the server and then show a warning to the user if there are available updates that are not installed.
So the question is, how to programmatically check if all available/latest Windows Updates are installed?
Any help would be greatly appreciated.
Comment: Look into the power shell module PSWindowsUpdate and Get-Windows Update. Resource: http://woshub.com/pswindowsupdate-module/
Comment: @LukasRäpple Thanks, this is awesome!  Do you know of a way to do this without using any third party software/scripts (only built-in Microsoft scripts)?
Comment: I am not sure that it is possible out of the box. The Module was created by MS MVP, thus, I think you can trust it. You can go through release notes here:
https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc
Answer: I suggest identifying exactly which updates are dependencies for Docker to work properly, and verifying those are installed specifically. It's surprisingly hard to emulate the "Check for Updates" button in PowerShell.
These are the built in commands, but they aren't documented and are just wrappers for WMI method calls.
Get-Command -Module WindowsUpdateProvider

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Get-WUAVersion                                     188.8.131.52    WindowsUpdateProvider
Function        Get-WUIsPendingReboot                              18.104.22.168    WindowsUpdateProvider
Function        Get-WULastInstallationDate                         126.96.36.199    WindowsUpdateProvider
Function        Get-WULastScanSuccessDate                          22.214.171.124    WindowsUpdateProvider
Function        Install-WUUpdates                                  22.214.171.124    WindowsUpdateProvider
Function        Start-WUScan                                       184.108.40.206    WindowsUpdateProvider

Documentation Team issue discussing lack of documentation https://github.com/MicrosoftDocs/windows-powershell-docs/issues/139
PowerShell Team issue discussing the broken functionality
https://github.com/PowerShell/PowerShell/issues/5718
This person seems to have figured out how to use the commands.
https://richardspowershellblog.wordpress.com/2017/11/17/windows-update-change-in-server-1709/
PS>  $au = Invoke-CimMethod -Namespace root/microsoft/windows/windowsupdate  -ClassName MSFT_WUOperations -MethodName  ScanForUpdates -Arguments @{SearchCriteria="IsInstalled=0"}

PS>  Invoke-CimMethod -Namespace root/microsoft/windows/windowsupdate  -ClassName MSFT_WUOperations -MethodName  InstallUpdates -Arguments @{Updates = $au.Updates}


String faltando caracteres(do banco de dados para o php)

Question: O que está acontecendo aqui é que uma string (varchar),vindo de uma consulta do banco de dados, está faltando caracteres quando vou passar pro php , o php ler até uma certa parte depois para. Quando faço uma consulta Utilizando o SQL Server Management Studio, a string está completa mas quando vou passar para o php, o php só ler ate uma certa parte.
SELECT Exemplo
from tableExemplo
where tableExemplo.Codigo = X

Fazendo isso  o SQL Server Management Studio a string apresentará o valor :
"VARIOS: COBRADO DA SEGURADORA EM 06/01/2020 E EM 22/01/2020 TODAS AS NFS 107909/1,111983/1,112375/1,112756/1,112793/1,112988/1,113117/1,113482/1,113580/1,114036/1,114039/1,114606/1,115956/1,116809/1,119221/1,120149/1121338/1,122063/1,122288/1,12454/1,125835/1,134878/1,142280/1,142282/1,145483/1,150156/1,152001/1,154225/1,154681/1,155069/1,161504/1,161690/1,"
No php o código está assim
function ExemploString($codigo){

return $this->db->query(" SELECT Exemplo
from tableExemplo
where tableExemplo.Codigo = $codigo";
}

$dataTeste = ExemploString(X);

echo"
";
print_r($dataTeste);
echo"
";

Ao executar o código acima
o echo e o print_r apresentará o resultado:
Array
(
    [0] => stdClass Object
        (

           [Exemplo] => VARIOS: COBRADO DA SEGURADORA EM 06/01/2020 E EM 22/01/2020 TODAS AS NFS 107909/1,111983/1,112375/1,112756/1,112793/1,112988/1,113117/1,113482/1,113580/1,114036/1,114039/1,114606

        )

)

Só está imprimindo uma parte do conteúdo.
já tentei o utf8_decode, utf8_encode, tira a quebra de linha no select mas mesmo assim continua imprimindo incompleto.
Comment: Você pode colocar a string de conexão na pergunta? Alguns drivers limitam a quantidade de caracteres enviados. Por exemplo o FreeTDS limita a 255 caracteres, e para conseguir o texto inteiro você precisa fazer um cast da coluna para text: `SELECT CAST(Exemplo as TEXT) FROM tableExemplo where...`
Comment: No seu print_r($dbData), não deveria ser print_r($dataTeste) ?
Comment: Corrigido,obrigado
Answer: A função print_r trunca uma string que possua mais de 1024 caracteres.
A solução é passar TRUE para o segundo parâmetro da função print_r
echo '
' . print_r ($bigArray, TRUE) . '
';


Send and Receive QStrings String through the Raspberry Pi serial port c++

Question: I am trying to write a string command to the serial port of my Raspberry Pi 2 B without success. I followed this http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart, but I need to send and receive QStrings (or arrays of bytes). Are there specific c++ functions that send and receive strings through the RPi Serial Port?
Could someone share some sample code?
Many thanks in advance!
Andrea
Answer: If you look at the QString docs you will see a number of methods that convert QString to other types. QString is just a wrapper around a character string.
To get at the underlying char buffer you can do something like this:
std::string stdStr = qString.toStdString();
char* buffer = stdStr.c_str();

Make sure that stdStr stays in scope as long as you wish to use buffer otherwise you will end up using a pointer that points to deallocated memory.
Comment: Thanks. Now, since I want to use the QSerialPort module, I install it with "sudo apt-get install libqt5serialport5-dev". Restart Qt, but when I add "QT += serialport" to my .pro file, the bild fails, saying: "Unknown module(s) in Qt: serialport". Did I miss something? Thank you.


Tutorial de usabilidade com transparência c#

Question: Estou trabalhando com c# e preciso fazer um tutorial de usabilidade, assim como em jogos que escurecem a tela, destacam um componente e exibem uma dica logo abaixo.
Até o momento fiz um Form em cima do outro, pois não consegui fazer uma layer sem que ela interferisse no sistema, pois alterei umas configurações do windows.
Enfim basicamente ficou assim acima do FormMain um form2 com 50% transparente (com 3 painéis que calculo a área de cada na mão para que destaquem um componente especifico que está no FormMain) e acima desse, um terceiro form com um painel contendo a tal dica. Achei essa forma muito ruim, mas não achei outra alternativa, pois não achei nenhuma API ou semelhante que realize esse procedimento.
Comment: estou fazendo um Form que atende a essa sua necessidade, a noite vou posta-lo pra você
Comment: Podes usar um tooltip, é mais simples.
Comment: @gato Se pudesse utilizaria, mas o cliente quer uma tela de tutorial...
Comment: No aguardo @RovannLinhalis !
Comment: Algum retorno @GabrielMonteirodeOliveira ?
Comment: @RovannLinhalis realizei alguns testes e parece funcionar, esqueci de comentar que esta dica em que precisamos exibir na verdade seria uma imagem .png ou .gif, e isto não parece funcionar muito bem, mas gostei da sua ideia de colocar um toolTip, vou sugerir está ideia...
Comment: é, não havia nada específicado sobre como a dica seria exibida, então fiz no tool tip, mas é fácil de colocar imagens, se quiser, podemos incrementar isso aí
Comment: @RovannLinhalis se for simples, por favor mostre como funciona ficarei muito grato!
Comment: @GabrielMonteirodeOliveira tem alguma imagem de exemplo que eu possa ter uma ídeia do q precisa ?
Comment: @RovannLinhalis seria algo como http://www.superdownloads.com.br/imagens/screenshots/9/0/90972,O.jpg agradeço pela sua ajuda!
Comment: vc vai ter um personagem e um balão como se ele estivesse falando, é isso ?
Comment: Isto mesmo @RovannLinhalis
Comment: Ok, assim que fizer posto aqui o resultado, mas se quiser se adiantar aí, o código vai ser praticamente o mesmo onde se cria o painelTransparente, porém colocando um PictureBox
Comment: @RovannLinhalis eu imaginei que fosse a mesma coisa, mas quando adiciono uma PictureBox no painelTransparente a imagem fica transparente e não sei como resolver...
Comment: Editei minha resposta. veja como ficou
Comment: @RovannLinhalis muito obrigado, isto vai atender muito bem as minhas necessidades!
Answer: Como havia comentado, estava desenvolvendo um Form que atende a sua necessidade.
Segue o código comentado:
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Testes
{
    //Form para destaques de controles
    //Utilizar para Condução do usuário, dicas, etc
    //Dev Rovann Linhalis - 22/06/2017
    public partial class FormHighlightControl : Form
    {
        //Controle que deve ser destacado
        Control ControleDestaque { get; set; }
        //Mensagem que será exibida
        string MensagemDica { get; set; }
        //Form Pai onde está o controle a ser exibido
        Form FormPai { get; set; }
        //Painel que será transparente
        Panel PainelTransparente { get; set; }

        ///
        /// Form de destaque de controles e exibição de dicas
        ///
        /// <param name="_parent">Form que será escurecido</param>
        /// <param name="_control">Controle que será destacado</param>
        /// <param name="_message">Mensagem de dica</param>
        /// <param name="_opacity">Transparencia do Form, 0=Invisivel, 1=Visivel, Recomendado 0.4</param>
        public FormHighlightControl(Form _parent, Control _control, string _message, double _opacity)
        {
            InitializeComponent();
            //Define a chave de transparencia do form
            this.TransparencyKey = Color.Magenta;
            //Define a cor do sombreamento do form
            this.BackColor = Color.Black;
            //Atribuição dos valores passados por parametro
            this.FormPai = _parent;
            this.Opacity = _opacity;
            this.ControleDestaque = _control;
            this.MensagemDica = _message;
            //Define visual do form
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.ShowInTaskbar = false;
            this.Size = this.FormPai.Size;
            this.Location = this.FormPai.Location;

            //Fechar com ESC
            this.KeyPreview = true;
            this.KeyDown += FormHighlightControl_KeyDown;
        }

        //Fechar com ESC
        void FormHighlightControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Escape)
                this.Close();
        }

        //Ao carregar o form, monta o painel transparente
        private void FormHighlightControl_Load(object sender, EventArgs e)
        {
            PainelTransparente = new Panel();
            PainelTransparente.Size = ControleDestaque.Size;
            PainelTransparente.BackColor = Color.Magenta;
            Rectangle r = FormPai.RectangleToScreen(FormPai.ClientRectangle);
            PainelTransparente.Location = new Point(ControleDestaque.Location.X + SystemInformation.SizingBorderWidth + r.Left - FormPai.Left, ControleDestaque.Location.Y + r.Top - FormPai.Top);
            PainelTransparente.Parent = this;
        }

        //Ao exibir o Form, Mostra a dica
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            if (!String.IsNullOrEmpty(this.MensagemDica))
            {
                toolTip1.ToolTipTitle = "Dica";
                toolTip1.ToolTipIcon = ToolTipIcon.Info;
                toolTip1.IsBalloon = true;
                toolTip1.OwnerDraw = true;
                toolTip1.SetToolTip(PainelTransparente, MensagemDica);
                toolTip1.Show(MensagemDica, PainelTransparente, PainelTransparente.Size.Width, PainelTransparente.Size.Height, 10000);
            }
        }
        //Fechar form ao clicar com o mouse em qlqr lugar
        private void FormHighlightControl_MouseClick(object sender, MouseEventArgs e)
        {
            this.Close();
        }

    }
}

Agora, sempre que quiser destacar um controle, e exibir um texto como dica, faça a chamada do Form assim:
        private void buttonOk_Click(object sender, EventArgs e)
        {
            FormHighlightControl form = new FormHighlightControl(this, buttonOk, "Este é o botão OK!", .4);
            form.ShowDialog();

        }

Resultado:

ps. Várias opções podem ser definidas pela interface do visual studio, preferi colocá-las dentro do construtor para melhor entendimento de quem utilizar o código.
Edit
Após pensar melhor nas necessidades, decidi criar uma classe para controlar as dicas que serão exibidas:
public class HighLightHint
{
    ///
    /// Título a ser exibido na dica
    ///
    public string Title { get; set; }
    ///
    /// Texto da dica
    ///
    public string Mensagem { get; set; }
    ///
    /// Controle ao qual a dica é atribuida
    ///
    public Control Control { get; set; }
}

Feito isso, agora no Form, você pode adicionar várias dicas, além de uma imagem de assistente. Segue código do Form:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace Testes
{
//Form para destaques de controles
//Utilizar para Condução do usuário, dicas, etc
//Dev Rovann Linhalis - 28/06/2017
public partial class FormHighlightControl : Form
{
    //Painel que será transparente
    Panel PainelTransparente { get; set; }
    //Form que será exibido o assistente
    Form PicAssistente { get; set; }
    //índice da dica exibida
    int HintIndex;
    //Form Pai onde está o controle a ser exibido
    public Form FormPai { get; set; }

    ToolTip toolTip1;

    ///
    /// Lista de Dicas
    ///
    public List<HighLightHint> Lista { get; set; }
    //Imagem do assistente (usar png com fundo transparente)
    public Image Assistente { get; set; }

    ///
    /// Form de destaque de controles e exibição de dicas
    ///
    /// <param name="_parent">Form que será escurecido</param>
    /// <param name="_control">Controle que será destacado</param>
    /// <param name="_message">Mensagem de dica</param>
    /// <param name="_opacity">Transparencia do Form, 0=Invisivel, 1=Visivel, Recomendado 0.4</param>
    public FormHighlightControl(Form _parent, double _opacity, List<HighLightHint> _lista)
    {
        InitializeComponent();

        HintIndex = -1;
        //Define a chave de transparencia do form
        this.TransparencyKey = Color.Magenta;
        //Define a cor do sombreamento do form
        this.AllowTransparency = true;
        this.BackColor =Color.Black;
        //Atribuição dos valores passados por parametro
        this.FormPai = _parent;
        this.Opacity = _opacity;

        //Define visual do form
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        this.ShowInTaskbar = false;
        this.Size = this.FormPai.Size;
        this.Location = this.FormPai.Location;
        this.Lista = _lista;
        //Fechar com ESC
        this.KeyPreview = true;
        this.KeyDown += FormHighlightControl_KeyDown;

    }

    public FormHighlightControl(Form _parent, double _opacity , List<HighLightHint> _lista, Image _assistente) : this(_parent, _opacity, _lista)
    {
        this.Assistente = _assistente;
    }

    //Fechar com ESC
    void FormHighlightControl_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.Escape)
        {
            this.Close();
            if (PicAssistente != null && !PicAssistente.IsDisposed)
                PicAssistente.Close();
        }
    }

    private void MostrarDica(int index)
    {
        if (this.Lista.Count > index)
        {
            this.Invalidate();

            if (toolTip1 != null)
                toolTip1.RemoveAll();

            toolTip1 = new ToolTip();

            if (PainelTransparente == null)
                PainelTransparente = new Panel();

            toolTip1.RemoveAll();
            if (PicAssistente != null && !PicAssistente.IsDisposed)
                PicAssistente.Close();

            Rectangle r = FormPai.RectangleToScreen(FormPai.ClientRectangle);
            Point newLocation = new Point(this.Lista[index].Control.Location.X + SystemInformation.SizingBorderWidth + r.Left - FormPai.Left, this.Lista[index].Control.Location.Y + r.Top - FormPai.Top);

            PainelTransparente.Size = this.Lista[index].Control.Size;
            PainelTransparente.BackColor = Color.Magenta;

            PainelTransparente.Location = newLocation;
            PainelTransparente.Parent = this;

            if (Assistente != null)
            {
                if (PicAssistente == null || PicAssistente.IsDisposed)
                {
                    PicAssistente = new Form();
                }

                PicAssistente.TopMost = true;
                PicAssistente.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                PicAssistente.ShowInTaskbar = false;
                PicAssistente.BackColor = Color.Magenta;
                PicAssistente.TransparencyKey = Color.Magenta;
                PicAssistente.AllowTransparency = true;
                PicAssistente.StartPosition = FormStartPosition.Manual;
                PicAssistente.Size = new Size(150, 200);

                if (newLocation.X > this.Width/2)
                {
                    if (newLocation.Y > this.Height / 2)
                    {
                        PicAssistente.Location = new Point(this.Location.X - this.Lista[index].Control.Width + this.Lista[index].Control.Location.X + SystemInformation.SizingBorderWidth + r.Left - FormPai.Left, this.Location.Y - PicAssistente.Height + this.Lista[index].Control.Location.Y + r.Top - FormPai.Top);
                    }
                    else
                    {
                        PicAssistente.Location = new Point(this.Location.X - this.Lista[index].Control.Width + this.Lista[index].Control.Location.X + SystemInformation.SizingBorderWidth + r.Left - FormPai.Left, this.Location.Y + this.Lista[index].Control.Location.Y + r.Top - FormPai.Top);
                    }
                }
                else
                {
                    if (newLocation.Y > this.Height / 2)
                    {
                        PicAssistente.Location = new Point(this.Location.X + this.Lista[index].Control.Width + this.Lista[index].Control.Location.X + SystemInformation.SizingBorderWidth + r.Left - FormPai.Left, this.Location.Y - PicAssistente.Height + this.Lista[index].Control.Location.Y + r.Top - FormPai.Top);
                    }
                    else
                    {
                        PicAssistente.Location = new Point(this.Location.X + this.Lista[index].Control.Width+ this.Lista[index].Control.Location.X + SystemInformation.SizingBorderWidth + r.Left - FormPai.Left, this.Location.Y + this.Lista[index].Control.Location.Y + r.Top - FormPai.Top);
                    }
                }

                PicAssistente.BackgroundImage = Assistente;
                //PicAssistente.BackColor = Color.FromArgb(100, 0, 0, 0);
                PicAssistente.BackgroundImageLayout = ImageLayout.Stretch;
                PicAssistente.Show();

            }

            if (!String.IsNullOrEmpty(this.Lista[index].Mensagem))
            {

                toolTip1.ToolTipTitle = this.Lista[index].Title;
                toolTip1.ToolTipIcon = ToolTipIcon.Info;
                toolTip1.IsBalloon = true;
                toolTip1.OwnerDraw = true;
                if (PicAssistente != null)
                {
                    toolTip1.SetToolTip(PicAssistente, this.Lista[index].Mensagem);
                    toolTip1.Show(this.Lista[index].Mensagem, PicAssistente, PicAssistente.Width/2, 0, 10000);
                }
                else
                {
                    toolTip1.SetToolTip(PainelTransparente, this.Lista[index].Mensagem);
                    toolTip1.Show(this.Lista[index].Mensagem, PainelTransparente, PainelTransparente.Size.Width, PainelTransparente.Size.Height, 10000);
                }
            }

        }
        else
        {
            this.Close();
            if (PicAssistente != null && !PicAssistente.IsDisposed)
                PicAssistente.Close();
        }
    }

    //Ao exibir o Form, Mostra a dica
    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        MostrarDica(++HintIndex);
    }
    //Fechar form ao clicar com o mouse em qlqr lugar
    private void FormHighlightControl_MouseClick(object sender, MouseEventArgs e)
    {
        MostrarDica(++HintIndex);
    }

}
}

E enfim, a chamada do Form:
 private void buttonOk_Click(object sender, EventArgs e)
 {
        List<HighLightHint > listaDicas = new List<HighLightHint>();
        listaDicas.Add(new HighLightHint() { Control = listBox1, Mensagem = "Este é o ListBox1!", Title = "Titulo dica 1" });
        listaDicas.Add(new HighLightHint() { Control = listBox2, Mensagem = "Este é o ListBox2!", Title = "Titulo dica 2" });
        listaDicas.Add(new HighLightHint() { Control = listBox3, Mensagem = "Este é o ListBox3!", Title = "Titulo dica 3" });
        listaDicas.Add(new HighLightHint() { Control = buttonOk, Mensagem = "Este é o buttonOK!", Title = "Titulo dica 4" });

        FormHighlightControl form = new FormHighlightControl(this,.4, listaDicas , global::Testes.Properties.Resources.wizard_magician_conjure_conjurer_icon_icons_com_53580);
        form.ShowDialog();

}

Não tenho muito tempo, mas achei bacana o proposito. Veja se te ajuda.


What is the definition of "sheet"?

Question: Here is a definition for evenly covered set.

Definition
Let $C,X$ be topological spaces and $p:C\rightarrow X$ is a continuous function.
Let $U$ be an open subset of $X$.
Then $U$ is said to be evenly covered by $p$ if there exists a family $\{V_i\}_{i\in I}$ of mutually disjoint open sets in $C$ such that $p^{-1}=\bigcup_{i\in I} V_i$ and $[\forall i\in I, p\upharpoonright V_i:V_i\rightarrow U$ is a homeomorphism.

I want to know what of below statements is the definition of "sheet".

Let $C,X$ be topological spaces and $p:C\rightarrow X$ be a continuous function.
Let $U$ be open in $X$ that is evenly covered by $p$.
Let $V$ be open in $C$.
Then (1)$V$ is said to be a sheet over $U$ if $V\cong U$.
(2) $V$ is said to be a sheet over $U$ if $p\upharpoonright V:V\rightarrow U$ is a homeomorphism.

What between (1)&(2) is the definition of "sheet"?
Also, should $V$ be required to be an open set?
Plus, if (2) is the correct definition, then is it okay to call $V$ as "a sheet over $U$ by $p$" to emphasize $p$?
Answer: In the first definition you have for what it means for $U$ to be evenly covered, the mutually disjoint open sets are your sheets.
$(1)$ and $(2)$ say the same thing, except for $(1)$, you would probably add "a sheet over $U$  via $p$" (or "by $p$", as you said) to emphasize that the homeomorphism is given by $p$ restricted to $V$.
Comment: How are they the same thing? Would you give me some details? If there is a homeomorphism $\phi:V\rightarrow U$, then why is $p|_V:V\rightarrow U$ a homeomorphism?
Comment: Yeah, that's why I said you would add "via $p$", so that you specifically state that the homeomorphism is given by $p$. My understanding is that saying "$V$ is a sheet over $U$ if $V \cong U$" is implicitly saying that the homeomorphism is given by $p$.
Comment: Thank you so much. I was in chaos dealing with this for a day.

What is the definition of "sheet"?


Weiner Process Markovian property

Question:
Wiener process definition:

$W(t) \sim \mathcal{N}(0, \sigma\sqrt{t})$
$W(t)$ is Markovian
$W(t+t')-W(t)$ and $W(t)$ are independent.

I don't know of a case where $2$ is true but $3$ is not & vice versa. From Markovian property definition, the future at $t+t'$ should depend on $t$. So the definition itself should mean $3$ is true. What am I missing here? Can you give examples for both cases?
Answer: 3 does not have to hold in order for 2 to hold. What the Markov property says is that $W(t+t')-W(t)$, conditional on the value of $W(t)$, does not depend on $W(s)$ for any $s<t$. It can still depend on $W(t)$ itself, but in the specific case of the Wiener process it doesn't. Basically for the Wiener process, you move the same way regardless of where you start; it is spatially homogeneous. So knowing $W(t)=x$ just translates the distribution of $W(t+t')$ to be centered at $x$ instead of $0$.
For an example where 2 holds and 3 does not, consider basically any SDE with coefficients depending on position, for instance $dX_t=X_t dW_t$.
I am less confident about whether 3 implies 2. What does imply 2 is $W(t_3)-W(t_2)$ being independent of $W(t_2)-W(t_1)$ whenever $t_1<t_2<t_3$. Maybe you can massage 3 into this but I would have to play with it.

Weiner Process Markovian property


Excel Conditional Formatting Using A Reference Range

Question: I have a watch range with certain cells highlighted yellow. For each of these cells, there is a corresponding reference value all located within one column.
I want to highlight all cells in my target range red for which the value in the corresponding reference cell matches the value in the target cells.
The code I've come up with is as follows, but there is some sort of a compile error I am unable to fix. Apparently the watch range can't consist of "multiple ranges".
Sub Highlight_pairAB()
Dim WatchRange As Range, Target As Range, cell As Range, ref As Range
Set Target = Range("Y3:Y274", "AC3:AC274") 'change column ref as required
Set WatchRange = Range("B3:B274", "E3:E274", "H3:H274", "K3:K274")
Set RefRange = Range("A3:A102")

For Each cell In Target.Cells
    If Application.WorksheetFunction.CountIf(WatchRange, cell.Value) > 0 Then
        cell.Interior.ColorIndex = 3
        For Each watchCell In WatchRange.Cells
            If watchCell.Interior.ColorIndex = 6 And RefRange.Value = Target.Value Then: targetCell.Interior.ColorIndex = 3
        Next watchCell
    Else: cell.Interior.ColorIndex = xlNone
    End If
Next cell
End Sub

Answer: Just in case this helps:
Change:
Set WatchRange = Range("B3:B274", "E3:E274", "H3:H274", "K3:K274")

To:
Set WatchRange = Range("B3:B274,E3:E274,H3:H274,K3:K274")

Answer: Another thing you could try would be to replace
For Each watchCell In WatchRange.Cells

with
For Each area In WatchRange.Areas
     For Each watchCell In area.Cells

edit: you also need two "Next" statements for it to match up. So be sure to make it
    Next watchCell
Next area

Comment: This looks promising but now I get an error of "Else without If" here: "Else: cell.Interior.ColorIndex = xlNone"


O que define uma classe de atributo no PHP 8?

Question: Estou usando atributos do PHP 8, a documentação desse recurso ainda é rudimentar, só contém exemplos de código e a api não está documentada então estou experimentando o uso do recurso.
class MeuAtributo {}

#[MeuAtributo]
class Teste {}

$reflection = new ReflectionClass(Teste::class);
$attributes = $reflection->getAttributes();
var_dump($attributes[0]->newInstance());

Ao executar esse código o seguinte erro ocorre na chamada de newInstance():
Attempting to use non-attribute class "MeuAtributo" as attribute in /code/index.php:10

O que é a classe de atributo mencionada na mensagem?
Como corrigir esse erro?
Comment: Geralmente, eu costumo fechar como **erro de digitação** perguntas que tenham algo parecido como "esqueci de colocar X" por desatenção ou ter deixado passar um detalhe despercebido  da documentação,  ou mesmo "erro de sintaxe". Aqui no stackoverflow é interessante que as perguntas estejam formuladas de maneira a ajudar não só a si próprio, mas também os demais usuários. Ao meu ver, faltou atenção na hora de implementar o Attribute.
Comment: Esqueci aquela hora de deixar o [link da documentação](https://www.php.net/manual/pt_BR/language.attributes.classes.php) para ajudar um pouco. Ainda está em inglês, somente.
Comment: Relacionada: [O que são atributos no PHP?](https://pt.stackoverflow.com/questions/484081) e [Como funcionam os atributos no PHP 8](https://pt.stackoverflow.com/q/487642/4995)
Comment: Esse recurso de Reflection é novo no PHP ou sempre teve? Se for que nem o do Java, é desnecessário em 99% dos casos, nem aconselho a aprender muito, só a saber que existe. A maioria dos casos que achar que dá pra usar vai ser melhor fazer sem. E se for que nem o do Java ainda por cima é lerdo. _Just saying_
Comment: @Piovezan Reflection do PHP existe desde 2004 com a versão 5. Não tenho informações sobre performance. mas sei que alguns frameworks usam (em injeção de dependências). Especificamente para a parte de atributos/annotations reflexão é a única forma de acessar esse recurso ([em C# também](https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/concepts/attributes/))
Comment: @PedroSanção Necessário ele é, senão não teria sido criado, mas em código de aplicações finais tende a ser mal utilizado. É o tipo de recurso para se ter em mente junto com herança múltipla, sobrecarga de operadores e coisas assim. Mas nesse caso dos atributos posso estar falando besteira porque não sei como é esse recurso de atributos no PHP, devem ser diferentes de campos como é o no conceitual, mas eu olhei por cima o código e interpretei como pegando campos do objeto (P.S.: Agora entendi, são tipo as annotations do Java mesmo. Bem, continuam sendo voltados mais p/ criar frameworks, não?).
Comment: @PedroSanção Cara, me desculpe, eu entrei na pergunta e comecei a falar tudo num nível hipotético e nem me toquei que você está usando atributos/reflection, achei que estivesse apenas tentando entender como funcionam. Não tive intenção de criticar esse uso em específico, que nem sei qual está sendo. Não entrei no mérito, só generalizei.
Comment: Tudo bem @Piovezan. Acho que annotation é o equivalente no Java sim
Comment: Bom, se for como no Java, a tendência é essa mesma que falei para reflection e annotations customizadas, saber que existem, ter noção de como funcionam, e deixar mais para os frameworks usarem: https://dzone.com/articles/creating-custom-annotations-in-java e https://stackoverflow.com/q/9222621/2241463 Em linguagens dinâmicas como no PHP reflection pode ter a vantagem extra de converter strings em campos de um objeto ou o oposto, e talvez também métodos, o que pode ser um pouco mais útil em alguns casos.
Answer: TD; DR:
Para definir uma classe de atributo classe adicione #[Attribute] antes da classe:
namespace App;

use Attribute;

#[Attribute]
class MeuAtributo {}

O use é necessário somente quando a classe usa namespace, como nesse exemplo.

Entendendo classe de atributos
A definição de classes de atributos está descrita nessa página do manual (sem tradução). Ainda assim acho útil fazer um paralelo com linguagens que já utilizam esse recurso, como C# por exemplo, pois falta descrição conceitual do recurso.
Os atributos fornecem um método eficiente de associação de metadados, ou informações declarativas, ao código (classes, métodos e propriedades, funções, constantes de classe, parâmetros). Após um atributo ser associado a uma entidade de programa, o atributo poderá ser consultado no tempo de execução usando uma técnica chamada reflexão.
Os atributos têm as seguintes propriedades:

Os atributos adicionam metadados ao seu programa. Os metadados são informações sobre os tipos definidos em um programa. Você pode adicionar atributos personalizados para especificar qualquer informação adicional necessária.
Você pode aplicar um ou mais atributos a classes, métodos e propriedades, etc.
Os atributos podem aceitar argumentos.
Seu programa pode examinar seus próprios metadados ou os metadados em outros programas usando reflexão.

Uma classe de atributo é uma classe que deriva direta ou indiretamente da classe Attribute, o que faz com que a identificação das definições de atributo nos metadados seja rápida e fácil. Suponha que você queira marcar tipos com o nome do programador que escreveu o tipo. Você pode definir uma classe de atributos Author personalizada.
Na prática
Attribute tem um parâmetro opcional para limitar onde essa classe de atributo pode ser utilizada, esse argumento aceita uma combinação das constantes usando | (operador de bit "OU"):
Attribute::TARGET_ALL;
Attribute::TARGET_CLASS;
Attribute::TARGET_CLASS_CONSTANT;
Attribute::TARGET_FUNCTION;
Attribute::TARGET_METHOD;
Attribute::TARGET_PARAMETER;
Attribute::TARGET_PROPERTY;

Por exemplo:
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class Exemplo {}

Permitirá que a classe de atributo Exemplo seja utilizada apenas como atributos de métodos e funções.
Sobre os erros
O erro destacado na verdade é uma exceção e pode ser capturada com try/catch. Ocorre quando há algum problema com a implementação, seja falta do atributo (o erro apontado na pergunta) ou uma restrição de uso (descrita acima).
Comment: Acho que faltou o `use Attribute;`, **se não me engano**, precisa dele
Comment: @Costamilam só precisaria do `use` se o arquivo usasse `namespace`, como nesse exemplo não foi usado ele não é necessário
Comment: Se quiser, pode adicionar isso a resposta, pra ficar mais completo


Can´t INSERT values with Foreign Key in MySQL

Question: I have a MySQL (5.1.42 on OsX) running.
I added a Foreign Key with this sql statement:
ALTER TABLE `Portal`.`Mitarbeiter_2_BlackBerry`
  ADD CONSTRAINT `fk_Blackberry`
  FOREIGN KEY (`id` )
  REFERENCES `Portal`.`Blackberry` (`id` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION
, ADD INDEX `fk_Blackberry` (`id` ASC)

But when i try to insert values in that table with this sql statement:
INSERT INTO Mitarbeiter_2_BlackBerry SET uebergabeAm = '2009-12-01 13:00:00', fk_Blackberry = (SELECT id FROM Blackberry WHERE id = '1')

I got the following Error:
Error Code: 1054
Unknown column 'fk_BlackBerry' in 'field list'
Anybody an idea what could be wrong?
Thanks for any hint :-)
Lars.
Answer: You need to put the value in the column id not the constraint fk_Blackerry. And if you know the value is 1, just insert 1- you don't need the subquery.
Answer: As per the Syntax Which you you can refer from here.
http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
fk_Blackerry is Symbol, not the column. Column on which foreign key constraint is id, So the updated query should be
INSERT INTO Mitarbeiter_2_BlackBerry SET uebergabeAm = '2009-12-01 13:00:00', id = (SELECT id FROM Blackberry WHERE id = '1')


Not sure if a gamma glm or glmm is needed?

Question: I am fitting a linear model for de CO2 dataset in R, I want to predict plant uptake (always positive) using Type, conc, and treatment, a quick look at the data gives me this relationship:

which is a saturation curve, it is clear that there is an effect by plant type, and that there is an interaction with treatment, also this are repeated measures from plants at different concentrations, so I thought random effects from plants make sense.
So I set up my linear models with and without random effects:
data(CO2)
library(lme4)

mod1 <- lm(uptake ~ Type*Treatment +
          I(log(conc)) + conc, data = CO2)

mod2 <- lmer(uptake ~ Type*Treatment +
           I(log(conc)) + conc + (1|Plant),
              data = CO2)

Now when I see the residuals of mod1

and mod2

I am not at all happy with the structure of the residuals, they seem to be heteroscedastic. which made me think I should go to glm or glmm, I am very familiar with the Poisson glm and binomial glm, but in this case, since it is a continuous positive I thought gamma family should be better. But when I read about it and see that the identity is inverse, I thought that it didn't make any sense to me to model the inverse of CO2 uptake.
I fitted these models anyway
mod3 <- glm(uptake ~ Type*Treatment +
  I(log(conc)) + conc, data = CO2, family =
   Gamma)

mod4 <- glmer(uptake ~ Type*Treatment +
  I(log(conc)) + conc + (1|Plant), data =
    CO2, family = Gamma)

mod4 failed altogether, and even when mod3 improved the residuals

I am not sure that I am using the family for the right reason.
Comment: How did you obtain the last plot? Have you tried other transformations other than log,  for ex. polynomials, splines? Your residuals appear to have a U shape (maybe).
Comment: For the last plot I used `broom::augment(mod3)` and then used ggplot to plot .fitted against . resid, I didn't try other transformations, since I used the log mostly to capture the saturation of CO2 Uptake, but I will try. Thanks
Comment: ... *But when I read about it and see that the identity is inverse*  you mean the default link function is inverse, but you could still choose some other link function!
Answer: The non-linear form of the residuals suggests that you may need to include non-linear effects in your model (e.g., quadratic effect, etc).
I don't necessarily think you need the gamma distribution; try other additions to your original model or you could model the data that are less than 230 (or wherever the point where you have that clumping) separately.
Comment: +1 indeed the curves don't look linear at all. However, instead of using quadratic effects it might be possibly better to use some realistic model based on first principles. It looks like these curves are some exponential function of concentration and that might have a physical explanation. In addition it seems like there are some random effects included. For the same class of points (treatment * type) we see subsets of points that follow, very closely, different curves. This might indicate that these points are from seperate experiments where parameters where slightly different.


Velocity decreasing and time increasing

Question: My question is in regards to forming linear relationships and solving through direct proportion. The question is as follows:

A ball is thrown vertically upwards with a velocity v of 12 m/s, which decreases by an amount proportional to t, the number of seconds where the ball moves upwards. After 0.5 seconds, the ball has slowed to a velocity of 7.1 m/s. How many seconds after it is thrown upwards will the ball start falling to the ground?

I tried solving through the basic v=kt l as in through direct proportion, but if I solve I get v=24t. And in that case, when v=0, that will only be when time is zero. So how do I get the formula right?
Comment: The velocity is not proportional to $t$. The **decrease** is.
Comment: @user296602 i could sense that but I got lost. How do I form the relation?
Answer: The velocity started at $12$ m/s, and after $0.5$ second, it was $7.1.$
The difference is $12 - 7.1 = 4.9,$
and this is the amount of the decrease in velocity in $0.5$ second.
In general, if we look at the ball after $t$ seconds, and it is moving at velocity $v,$ the decrease in velocity since it started moving upward is
$12 - v.$
We are given that the amount of decrease in the vertical velocity of the ball is directly proportional to how long it has been moving upward.
Since the decrease is directly proportional to $t$ there must be a constant $k$
such that
$$ 12 - v = kt. \tag1 $$
From the fact that the velocity was $v=7.1$ when the time was $t=0.5,$
by plugging those values into Equation $(1)$ we can solve for $k.$
Once we have $k,$ we can set $v = 0$ and solve for $t$ to find out the time when the ball has stopped moving upward.

Rather than speaking of the amount of decrease in velocity,
I think it is more usual to speak of the change in velocity
over a period of time.
So if the velocity starts at $v = 12$ at time $t = 0,$
we say that $12$ is the initial velocity, and we call this $v_0.$
If the velocity at a later time is $v,$ the change is
$v - v_0 = v - 12$; we always measure change by taking "final minus initial."
Since $v = 7.1$ when $t = 0.5,$ at that time the change in velocity has been
$$v - v_0 = 7.1 - 12 = -4.9.$$
It's a negative number because the velocity is decreasing and because a decrease is represented by a negative change.
Since the decrease is proportional to time, so is the change (which is just exactly the opposite value). So we have
$$ v - 12 = Kt. $$
You can proceed to solve this just like when we had a formula for the decrease; it just happens that now the value of $K$ will be negative.
Comment: (+1): This is a very nicely written answer that actually addresses the issue OP had without just using some kinematics formulae.
Answer: Acceleration is $(7.1-12)/0.5=-9.8$, so it takes $12/9.8=1.22$ seconds to reach $0$ velocity.
Answer: $\star)$: $v_f=v_i -at; $
$f:$ final; $i$:initial;
$a$: acceleration(constant).
1) $v_f= 7.1[m/s]$; $v_i= 12[m/s]$; $t=0.5 [s].$
Solve for $a$ in $\star)$.
2) Set
$v_f=0$(The ball reverses direction);
$v_i =12[m/s].$
Solve for $t$ in $\star).$
Answer: For $t=0$ the ball goes upwards with initial velocity $v_0= 12\,\mathrm{ms^{-1}}$. So we have that
$$
v(t)=v_0-at\qquad \Longrightarrow\qquad a=\frac{v_0-v(t)}{t}
$$
and after $t=t_1=0.5\,\mathrm s$ we have $v_1=v(t_1)=v(0.5)=7.1\mathrm{ms^{-1}}$
and then $a=9.8\mathrm{ms}^{-2}=g$ (i.e. $a=g$ is the acceleration due to gravity).
At the time $t=t^*$ when $v(t^*)=0$ the ball will stop and begin to fall down, that is
$$
v(t^*)=0=v_0-gt^*\qquad \Longrightarrow\qquad t^*=\frac{v_0}{g}\approx 1.22\mathrm s
$$

Velocity decreasing and time increasing


Profile 2, update separate database on submit?

Question: I want to know where and how to plug/hook into profile 2, so that when the user updates a specific profile ("new_profile"), that this then fires off a chunk of custom php code. The event must only be fired off IF validation passes. Which leads me to believe that I can't really just add another submit handler.
How would I be able to fire off this "second update" to a seperate database, if I only want to hook into the part after validation has passed?
Answer: Every module which exposes hooks are documented in module *.api.php file. In your case it's just hook_profile2_update .
<code>/**
* Respond to a profile being updated.
*
* This hook is invoked after the profile has been updated in the database.
*
* @param $profile
*   The $profile that is being updated.
*
* @see hook_entity_update()
*/
function hook_profile2_update($profile) {
  db_update('mytable')
    ->fields(array('extra' => $profile->extra))
    ->condition('pid', $profile->pid)
    ->execute();
}
</code>
Refer http://cgit.drupalcode.org/profile2/tree/profile2.api.php for more details.
Comment: This would work too, but I ended up adding an extra "submit" handler when the profile gets updated. Works just as well.


Retrieve file URL when upload form is submitted

Question: I have the following code in my form.
function video_subtitles_menu() {
  $items = array();

  $items['video_subtitles_test/upload'] = array(
    'title' => 'Upload Subtitle', //page title
    'description' => 'Uploading subtitle for videos',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_upload_subtitles_form'),
    'access callback' => TRUE
  );

  return $items;
}

function video_upload_subtitles_form($form, &$form_state) {
  $form = array('#attributes' => array('enctype' => 'multipart/form-data'));
  $form['video_name'] = array(
    '#title' => t('Name Of the video'),
    '#type' => 'textfield',
  );

  $form['sub_file'] = array(
    '#type' => 'file',
    '#title' => t('Upload video'),
    '#size' => 48,
    '#description' => t('Pick a video file to upload.'),
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function video_upload_subtitles_form_validate() {
  if (!file_check_upload('upload')) {
    form_set_error('upload', 'File missing for upload.');
  }
}

function video_upload_subtitles_form_submit($form, &$form_state) {
  $video_name = $form_state['values']['video_name'];
  $file = file_save_upload('sub_file', array());
  print "
";print_r($file);// no response here
  drupal_set_message(t('The form has been submitted.'));
}

On the submission handler, it only returns the text field. I don't get anything from file upload field, when I use file_save_upload().
This is the response which I get in Firebug. I tried uploading text and Excel files.

What I am trying to do is creating a block where users can upload a file; I then need to get to upload it to a CDN.
Comment: Have you looked at this comment in the file_save_upload API [discussion](https://api.drupal.org/comment/23883#comment-23883)?
Comment: `file_save_upload` returns _An object containing the file information if the upload succeeded, FALSE in the event of an error, or NULL if no file was uploaded._. So if you your result is `NULL`, it means no file was uploaded, and you should probably look into your server config. If it was `FALSE`, it means there was an error which you can find in your server logs or Drupal's watchdog (or both). 99 times out of 100 failures are due to permissions problems
Comment: this is the error stored in drupal log

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'H:\xampp\tmp\phpBBFD.tmp' to 'temporary://images.txt' in drupal_move_uploaded_file() (line 1607 of H:\xampp\htdocs\gemkt\trunk\includes\file.inc).
Answer: found the solution here.I am not sure what is the core issue but below is the solution
This was the comment in the above link where I found solution.

More than likely eveyone who is having a problem here has been
  developing on their local computer, then are tryng to migrate their
  system to a remote server. When you do this, you are probably moving
  your setting for directory paths along as well.
For example the temp path for your images is probably different than
  the image temp path on your host system.
I recommend this test in Drupal 6.14. goto /admin/settings/file-system
and look at your temporary directory... if its glaring red, then try
  renaming it to something like: /tmp. if that does not work, try
  renaming to just tmp ( no forward slash)
Next step to test this will be to upload an image or file. I tested it
  by uploading a new logo. But remember, that if you do a FULL DB dump
  from phpmyadmin from your local computer to the new host, you will
  probably see this problem again.

For Drupal 7 guys I just went to admin/config/media/file-system , so basically find out where the file system is in your config area and I change the '/tmp' to 'tmp'.
After changing it was able to print the file object :)
stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image [field_replacement] => stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image ) [fid] => 3102 )

Hope it help someone.


SetTimeout, fazer o texto sair depois de um tempo

Question:

        <input placeholder="Adicionar morador no 1° Andar" type="text" id="name1" style="margin-bottom: 40px;">

        <input type="button" value="Adicionar" onclick="adicionarMorador1(); confirmacao1();">

`

var andar1 = Array("Matheus")

        function adicionarMorador1() {
            var nome = document.getElementById("name1").value

            if (nome === "") {
                console.log("Insira um valor válido")
            } else {
                andar1.push(nome)
               // alert("Morador foi adicionado no 1° Andar")
                console.log(andar1)
            }
        }

        function confirmacao1 () {
            var x = "O morador foi adicionado no 1° andar";
            document.getElementById("confirma1").innerHTML = x;
            setTimeout(() => {
                x.close()
            }, 2000);
        }

        function ordenar1() {
            andar1.sort()
            console.log(andar1)
        }

Bom, tenho esses dois códigos, quando eu clico no botão adicionar ele dispara duas funções, uma ele joga no array andar1, e a outra manda um texto na página dizendo que o morador foi adicionado, porém eu queria que esse texto saísse depois de um tempo, usando o setTimeout, porém não consigo. Queria saber como eu faço o texto sair depois de um tempo determinado
Answer: Existem diversas formas de resolver esse problema!
Usando apenas CSS
#invisivel {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}

@keyframes cssAnimation {
    to {
        width: 0;
        height: 0;
        overflow: hidden;
    }
}

@-webkit-keyframes cssAnimation {
    to {
        width: 0;
        height: 0;
        visibility: hidden;
    }
}

https://jsfiddle.net/h10dkfqc/
Usando Vanilla Javascript
function confirmacao1() {
    var x = "
O morador foi adicionado no 1° andar
";
    document.getElementById("confirma1").innerHTML = x;
    setTimeout(() => {
        var elem = document.querySelector('#invisivel');
        elem.parentNode.removeChild(elem);
    }, 2000);
}

https://jsfiddle.net/ypo783rt/
Usando JQuery
function confirmacao1() {
    var x = "
O morador foi adicionado no 1° andar
";
    document.getElementById("confirma1").innerHTML = x;
    setTimeout(() => {
        $('#invisivel').remove();
    }, 2000);
}

https://jsfiddle.net/8newfhps/1/
Qualquer uma dessas soluções deve resolver o seu problema. Espero que ajude!


R function does not return anticipated vector

Question: I am trying to calculate the mean (as well as other calculations) based on two groupings (phylum and environment) and I would like to redirect to output to a file. I know that the below code works.
new_df = myDF[(myDF$Environment=='Water_MarineTreated') & (myDF$Phylum=='Acidobacteria'),]
print(mean(new_df$pH))

However, because there are so many environments and numerous phyla, I feel that a function containing loops is the best way to go. I have a function that takes the name of a vector and the name of the calculation (e.g. mean, sd, var, etc...) loops through each environment and each phylum, calculates the mean pH for each permutation, adds it to a vector, and the returns the vector. Unfortunately, the return value is "numeric(0)". While this is returning what I tell it to, it is not what I want.
I think the rule is one question per post so if someone can explain why there is an empty vector that is return rather than a vector filled with the pH means, I would appreciate it. And if the rule can be bent a bit and someone can answer why "eName = numeric()" does not work, I would appreciate that too. If I place a dummy print statement inside the inner loop, when I use eName = numeric(), nothing is printed where as if I initialize Water_MarineTreated = numeric(), the dummy statement in printed.
My function and the function call can be seen below.
    fileName = 'mini.txt'
    myDF = read.csv(fileName, header = TRUE, sep = ' ')
    environment = unique(unlist(myDF$Environment, use.names = FALSE))
    phyla = unique(unlist(myDF$Phylum, use.names = FALSE))

    Statistics = function(eName, funName)
    {
       #eName = numeric() #This approach does not work?!!
       for (i in environment)
       {
          for (j in phyla)
          {
             stats_df = myDF[(myDF$Environment==i) & (myDF$Phylum==j),]

             if (i == deparse(substitute(eName)))
             {
                #Water_MarineTreated == c(Water_MarineTreated, funName(as.numeric(stats_df$pH)))
                eName == c(eName, funName(as.numeric(stats_df$pH)))
                print('dummy_statement')
              }
          }
       }
       return(eName)
    }

    Water_MarineTreated = numeric()
    Water_MarineTreated = Statistics(Water_MarineTreated, mean)
    print(Water_MarineTreated)

A sample of the input looks like this:
Phylum pH Environment
Acidobacteria 5.4 Water_MarineTreated
Acidobacteria 6.1 Water_PondTreated
Acidobacteria 6.1 Water_MarineTreated
Acidobacteria 5.6 Water_MarineTreated
Acidobacteria 6.2 Water_MarineTreated
Deinococcus_Thermus 4.9 Water_MarineTreated
Firmicutes 5.1 Water_MarineTreated
Firmicutes 5.5 Water_MarineTreated

Answer: The data.table package offers (among other things) a very nice syntax for quickly calculating functions by groups.  Consider the following example:
library(data.table)

# Convert sample data to a data.table:
dt <- as.data.table(mtcars)

# Calculate the mean and median mpg by cyl and gear, where carb < 8:
dt[carb<8, # The "where clause"
   list(mpg.mean=mean(mpg), mpg.med=median(mpg)), # What you want to calculate
   by=list(cyl,gear)] # The groups go here
#   cyl gear mpg.mean mpg.med
#1:   6    4   19.750   20.10
#2:   4    4   26.925   25.85
#3:   6    3   19.750   19.75
#4:   8    3   15.050   15.20
#5:   4    3   21.500   21.50
#6:   4    5   28.200   28.20
#7:   8    5   15.800   15.80
#8:   6    5   19.700   19.70

Check out the documentation for more.
Comment: I am pretty new to R and I was not familiar with that package. I have it installed and it does exactly what I want with very little coding. Thank you.
Answer: Your solution can be obtained using plyr package:
library(plyr)
ddply(mtcars,.(mpg,cyl),colwise(mean))

For your data,if you are trying to find the mean of all columns other than Environment and Phylum (and assuming that these are numeric)
library(plyr)
 ddply(myDF,.(Environment,Phylum),colwise(mean))

Note: If you want sd, replace mean with sd.
Answer: You have in the middle of the loop the line:
eName == c(eName, funName(as.numeric(stats_df$pH)))

The double equal signs == means to compare and return a TRUE or FALSE, it does not do any assignment.  So eName starts off as an empty vector and never has anything assigned to it.  This is just one of the reasons that I prefer <- for assignment.
Even if you switch to an assignment, the way it is now you will overwrite the value each iteration and the return value will just be the final value, not all of them.  You need something more like:
eName[i] <- ...

or
eName[i,] <- ...

Though in either of those cases it is often simpler to use sapply instead of a loop.
Comment: I completely see the error (== != =). I changed it and it is returning a result. Your comment about overwriting is also correct. I will either amend my code or use other suggestions. Thank you.


Como faço para desabilitar o template stagehand ao criar um projeto flutter web?

Question: Já tentei desabilitar utilizando o comando pub global deactivate stagehand , porém não consigo criar nenhum projeto se este template não estiver habilitado. O VSCode pergunta se deseja ativá-lo usando o comando pub global activate stagehand.
Com este template habilitado, recebo a seguinte mensagem de erro :

Unable to execute Stagehand. Stagehand exited with code 65.
      stagehand 3.3.2 doesn't support Dart 2.3.0-dev.0.5.flutter-a1668566e5.

Ao executar o flutter doctor -v, recebo os dados abaixo:
[√] Flutter (Channel stable, v1.5.4-hotfix.2, on Microsoft Windows [versão 6.1.7601], locale pt-BR)
    • Flutter version 1.5.4-hotfix.2 at c:\flutter
    • Framework revision 7a4c33425d (10 weeks ago), 2019-04-29 11:05:24 -0700
    • Engine revision 52c7a1e849
    • Dart version 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)

[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at C:\Users\abel\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: C:\Program Files\Java\jdk1.8.0_211\bin\bin\java
    X Cannot execute C:\Program Files\Java\jdk1.8.0_211\bin\bin\java to determine the version

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/setup/#android-setup for detailed instructions).

[√] VS Code (version 1.36.0)
    • VS Code at C:\Users\abel\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.2.0

[!] Connected device
    ! No devices available

! Doctor found issues in 3 categories.

Alguma idéia ?
Comment: Eaí, Abel! Quando foi que você instalou o Flutter, já tem tempo ou foi hoje também?
Comment: Recentemente eu tive que remover o dart e também o VSCode.. mas o flutter havia sido instalado já há algum tempo sim.
Comment: Ah, sim. Chegou a dar uma olhada na minha resposta?
Comment: Dei sim George.. não tive como validá-la ainda.. mas vou testar ela ativando o stagehand para a versão que tenho do dart e ver se funciona. Funcionando te dou um Ok. Obrigado.
Answer: A mensagem erro diz que o Stagehand 3.3.2 não suporta a versão 2.3.0 do dart, que é a que você tem instalada. Olhando no GitHub a pubspec do Stagehand, vi que a versão mínima do Dart é 2.4.0.
Você poderia atualizar a versão do Dart com o comando:
flutter upgrade

Outra opção seria usar uma versão mais antiga do Stagehand com suporte à versão do Dart que você já tem instalada, que no caso poderia ser a 3.2.0. Para isso, pode usar o seguinte comando:
pub global activate stagehand 3.2.0

Comment: Infelizmente não deu certo.. Após tentar criar um novo projeto, o dart solicita a atualização para a versão mais recente. "Stagehand needs to be updated with 'pub global activate stagehand' to use this feature."
Comment: @AbelSouzaMagalhaes no caso, se você atualizar o flutter e o dart, você já pode usar a versão mais recente do stagehand, de acordo com os docs. (não cheguei a testar aqui ainda)
Comment: George, infelizmente não deu certo.. Atualizei o Dart para a versão 2.4 .. e depois para a versão 2.5 (dev) e mesmo assim apresenta o mesmo erro. Muito estrano a comunidade não estar relatando esse erro.


Does anyone know solution for adding pure javascript filter for View?

Question: As in queston. I was googling and searching forum, but found nothing useful.
I want to setup dynamic filter for a view. Eg. http://silverwareconsulting.com/index.cfm/2008/10/2/jquery-autofiltering-table. One difference is that I need to take filter value from textfield.
Maybe this functionality is built-in in Views, but I missed that?
Comment: Please add more information. What view is it? What filter value?
Comment: Any available filter. Eg. textfield for filtering results by selected view field, eg. first name. View format probably will be Table, but I found that similar solution is more flexible and exists in Drupal world
Answer: I'ld suggest you choose views format Table and then add your JS from hook_page_build().


Compare differences in dependent frequencies

Question: I would like to compare two error rates (proportion of incorrect answers in questions with dichotomous response-format) for two different items, and I am looking for some advice on how to do that.
Lets assume:
Control Group (CG) N = 100
Experimental Group (EG) N = 120
Item A: was answered incorrectly by 20 out of 100 participants in the CG (= 20%) and by 50 out of 120 participants in the EG (= 42%). --> I can calculate a chi-squared test whether the proportion of incorrect answers is higher in the EG than in the CG.
Item B: was answered incorrectly by 33 out of 100 participants in the CG (= 33%) and by 80 out of 120 participants in the EG (= 67%). --> Again, a chi-squared test can be calculated.
Question:
I would like to calculate whether the increase in the error rate is more pronounced for Item A (diff 33% to 67% = +34%) than for Item B (diff 20% to 42% = +22%).
EG and CG were manipulated between subjects; all items were answered by all participants, i.e., manipulated within subjects.
Reflections:
My idea is that I have to take into account the differences in the baseline errors (CG). So I thought about taking the baseline errors as 100% and compare the increase in the EG for Item A (+250%) to the one in Item B (+242%).
I'd be very grateful for any comments on whether this procedure is correct/makes sense in principle, and, if so, how the two values may be compared. I'm also unsure whether I still have to take into account that the data are kind of dependent as both items were answered by all participants?
Answer: I would not use either chi-squared tests or McNemar's tests.  The chi-squared does not take the dependency in the data into account, and neither incorporates information about both items into a proper, unified analysis.  Instead, I would use a generalized linear mixed effects model (GLMM).  You will have a logistic regression model with fixed effects for group and item, and a group X item interaction.  In addition, you will have random effects for the subjects to take their dependence into account.  At a minimum, you should have a random intercept; you may want to have a random slope as well, I'm not sure.  (If the model will fit, it probably wouldn't hurt.)  The test of the interaction is the critical test of your hypothesis: if it is significant, then the increases in the rates significantly differ.  The directionality of that estimate (i.e., a positive vs. negative coefficient) will tell you which is a larger decrement, but it will depend on which levels are taken as the reference levels of your variables.  At any rate, which is larger is clear enough from your summary statistics, all you need is a test of its significance.  One last thing to bear in mind is that you phrase your question in terms of raw risk differences, whereas the model will test odds ratios, you will need to be clear on that.
Comment: Thank you very much for your response. I also thought about using a GLMM, but was unsure whether it is the right method. Your answer gives me confidence to pursue this idea. It is clear to me why group and item are fixed effects. However, I am quite confused about the concept of mixed effects, random intercepts (this is not the same as the intercept inserted together with the fixed effects, or is it?), and random slopes. Would you mind explaining me (non-statistician) the basic idea of these concepts? I'd be especially interested in what function they have with respect to the dependent data.
Comment: Btw: Do I understand you right that even if the proportions of incorrect answers were corrected for the baseline error, they should not be tested against each other (e.g. with a z-test as proposed here: http://www.socscistatistics.com/tests/ztest/)?
Comment: For general info about fixed vs random effects, I have a couple recent answers [here](http://stats.stackexchange.com/a/125112/7290) & [here](http://stats.stackexchange.com/a/122587/7290) that may be helpful. [This](http://stats.stackexchange.com/a/68753/7290) is particularly good (I'm using the biostatistics version). Whether you should use random slopes is a substantive judgment: Do you think different people will be more or less affected by the items? I don't really follow your last question, but the test of the interaction in the GLMM is all you need; your suggested approach isn't valid.
Comment: Thank you @gung for [this](http://stats.stackexchange.com/questions/125093/how-to-use-a-linear-model-with-two-factors-and-repeated-measures/125112#125112) answer, which I think I understood best. I'd be also glad about further reading tips (books/book chapters), with some additional information on the topic (again understandable for a non-statistician). But else I'll just work through some more Q/A in this fantastic forum!
Comment: Spend some time reading through the existing threads on the site. If there is still something you don't understand afterwards, your best bet is to ask a new question.
Answer: If your question is solely about comparing the error rates between items A and B regardless of the groups, a 2x2 McNemar test for dependent responses could work (2 nominal variables, i.e. item A and item B with 2 levels each, i.e. correct/wrong).
If however you are interested in examining error rate differences between groups you could create a new variable assessing the decrease/increase in the errors for the both items. You could for example assign a 0 for unchanged responses (correct/wrong for both items) and a 1 to those participants who got it right for item B only. A Chi-Square will compute the actual and % change in the error rates between groups (they 're not dependent frequencies anymore). If it's significant, you could conclude that a significantly higher error rate was observed for the CG in comparison to the EG.
Comment: Many thanks for your answer! I thought about how to do a McNemar's test here and came up with the following solution: The 2x2 table would be CG and EG - Item A and Item B. With this procedure, I'm not sure whether the baseline error can be taken into account, however, because only the errors would be inserted into the table... Or did you think of another way of filling in the 2x2 table?
Comment: That's what I was thinking of. It won't be the errors that you will put have put in the Table, but the error rate (errors-baseline errors)
Comment: I see. Would that be a special type of McNemar's test? Because for the chi-square test you won't get the same result with percent compared to the actual number of cases, as this changes the N (unless your N is 100)... Or am I completely wrong?
Comment: I am not sure what you mean but after a bit more thinking I have edited my answer. I hope it makes things a bit clearer now


Running javascript function from a js file

Question: I have a Shopify website and I've added a .js file which holds few javascript functions, how can I tell a

And I want to run different functions on different pages when the page is loaded, for example, inside main-product.liquid I want to run only ".aone-slide" and on blog.liquid I want to run only ".ul.accordion", how is this possible?
I've tried to do something like that:

But I don't know how to continue because the name of the function or the trigger is a div/css class.
This is the file:
(function($) {
    $(".aone-slide").slick({
        dots: !0,
        infinite: !1,
        arrows: !1,
        speed: 300,
        slidesToShow: 2,
        slidesToScroll: 2,
    }), $("ul.accordion").accordion(), $(".slider-for").slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: !1,
        fade: !0,
        asNavFor: ".slider-nav"
    }), $(".slider-nav").slick({
        slidesToShow: 8,
        slidesToScroll: 1,
        asNavFor: ".slider-for",
        dots: !1,
        centerMode: !1,
        focusOnSelect: !0,
        responsive: [{
            breakpoint: 992,
            settings: {
                slidesToShow: 6,
                slidesToScroll: 1
            }
        }]
    })
})

Comment: If it's just a few pages, you could add an inline script to the foot of each page with a `window.onload` set to fire the function for that page. onload events can also be hard coded into element tags if you prefer. I can't understand any of your code but in core js it would also be fairly straight forward to extract a string from anywhere on the page (e.g. class name or id for a particular element) and use that to reference the function as a named property of the window object. `Window[functionName]()` where function name is a string or a variable holding a string value.
Answer: I think you're confusing what a Javascript function is.
In your .js file you have only one function. This particular function is applying a slider (using the slick library) to different html elements. And it is doing that automatically when jQuery ($) is ready.
For example the first .slick call is creating the slider on the elements with class aone-slide.
So the first problem is this, if the .js is loaded (and the code you're showing seems to be correct) it should already work. It should already create the sliders, on all the pages. If it doesn't there is something missing (but I don't have enough elements to tell).
If you want to run slick only on the selected pages you should create functions inside your .js file and call them in the pages.
So your .js would become something like this
function slickAone(){
   $(".aone-slide").slick({
    dots: !0,
    infinite: !1,
    arrows: !1,
    speed: 300,
    slidesToShow: 2,
    slidesToScroll: 2,
    });
}

(without function ($)...)
and then in your page yout put