Itens drag'n'drop dentro de tabela

Question: Boa tarde pessoal, estou querendo criar uma tabela com eventos interativos, semelhante ao FullCalendar,
queria saber se alguém conhece alguma biblioteca que permita a criação de quadrados/retângulos que tenha drag'n'drop como os do FullCalendar ou se é possivel configurar para que a categoria de eventos apareça no eixo y e as datas no eixo x.
Comment: **BOM DIA**.Seja bem vindo ao site, aconselho ver este link https://pt.stackoverflow.com/tour para utilizar o site adequadamente e satisfazer todas as suas dúvidas.
Comment: editei a pergunta pra melhor entendimento
Answer: Para drag and drop você poderá usar o Sortable do jQuery UI vê a documentação

$("table tbody").sortable({
  update: function(event, ui) {
    $(this).children().each(function(index) {
      $(this).find('td').last().html(index + 1)
    });
  }
});
table {
  border-collapse: collapse;
}

td,
th {
  background: #fff;
  border-width: 0;
  border-bottom: 1px solid #B8B8B8;
  font-weight: normal !important;
  padding: 15px;
  text-align: left;
  vertical-align: middle;
}

tr.even {
  td,
  th {
    background: #f1f1f1;
  }
}

thead,
tfoot {
  text-transform: uppercase;
  th {
    background: #ccc;
  }
}

body {
  color: #111;
  font-size: 16px;
  font-family: sans-serif;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

      Categoria
      Data
      Orden

    Festa Juninas
    24 junho
    1

    Natal
    25 dezembro
    2

Só não ficou muito claro para mim essa questão

"se é possivel configurar para que a categoria de eventos apareça no
  eixo y e as datas no eixo x."
Comment: Essa parte seria caso fosse usar o FullCalendar mesmo, ai queria que ficasse algo parecido com isso: https://i.imgur.com/IQDLrsT.png

;
No caso de utilizar o sortable do jQuery não daria certo por queria transformar a foto de cima em algo assim: https://i.imgur.com/y5bIMF7.png pra poder arrastar apenas os quadrados de um dia pro outro ou de um quarto pro outro.

Itens drag'n'drop dentro de tabela


Cannot modify association because the source reflection class is associated via :has_many

Question: My associations in a Rails 2 project are as follows:
<code>class Role < ActiveRecord::Base
  belongs_to :user
  has_many :attrs, :through => :user, :dependent => :destroy
end

class User < ActiveRecord::Base
  has_many :roles, :order => 'id DESC', :dependent => :destroy
  has_many :attr, :dependent => :destroy
end

class Attr < ActiveRecord::Base
  belongs_to :user
  has_many :roles, :through => :user
end
</code>
I am upgrading my project to rails 3. And while trying to delete user in rails 3, I get the following error:
Cannot modify association 'Role#attrs' because the source reflection class 'Attr' is associated to 'User' via :has_many.
But for the same thing, in rails 2 the users get deleted fine. I have never worked on rails 2 so I had to ask here.
What Can I do to fix this? I checked other answers but they don't seem to apply to my case.
Answer: In User Model
has_many :attr, :dependent => :destroy
It should be
has_many :attrs, :dependent => :destroy


Show $\max\{f-g,0\} + g=\max\{f,g\}$

Question: As stated in the title:

Show that for a given variable $x$ it holds $max\{(f-g)(x),0\}+g(x)=max\{f(x),g(x)\}$, where $f,g$ are functions.

I just came across the above stated expression and I am wondering if it is sufficient to check the two cases $f(x)\geq g(x)$ and $f(x)<g(x)$. Or do I have to use/verify further assumptions?
Comment: If $f$ and $g$ are functions, it is not true in general that either $f \geq g$ or $f < g$ (meaning that the inequality holds for any input $x$), so you should rather fix some input $x$ and check the cases $f(x) \geq g(x)$ and $f(x) < g(x)$
Comment: I disagree @frafour. Yes it is enough to check for those cases only, that is because max{f,g} is to mean max{f(x),g(x)} for some x. otherwise it has no other meaning.  assume $$ f(x) = 2*x $$ and  $$ g(x) = x*x $$ , what would be max{f,g} unless we are dealing with a particular value? hence max{f,g} gives a value and not a function.
Comment: @Babydesta: If $f$ and $g$ are functions then $\max ( f, g)$ is a function. Writing it out explicitly might use different expressions for different values of $x$, but that is a common and accepted way of defining a function. (For at least 100 years. Further back you could have an argument over whether a piece-wise defined function was really a function, but not these days.)
Comment: @JonathanZsupportsMonicaC, I understand what you mean, but you have to meet me halfway. A function in arithmetic has no meaning unless it has inputs and outputs. That is you define functions as relations from one set of values to another. now maximum has no meaning for functions, nor does addition of functions. when one says $f+g$ we know it means the function $h(x) = f(x)+g(x)$ and f(x) & g(x) are values. Basically every function operation is defined based on the input and output values. So we only define maximum of a function based on its output.
Comment: The process you're describing extends "maximum" and "addition" from being defined for numbers to being defined for functions. And, as you note, we (usually) do so "based on its output", which is usually described as "point-wise", i.e. we __define__ $f+g$ by $(f+g)(x) = f(x)+ g(x)$. Once we've done this, addition is defined for functions.
Answer: How is $\max \{f,g\}$ defined?
Remember that for any two numbers $x,y$: $$\max \{x,y\} ={x+y+|x-y|\over 2}$$
and this is easy to prove.

Show $\max\{f-g,0\} + g=\max\{f,g\}$


Question about the prime elements of $\mathbb{Z}[i]$.

Question: I am learning about gaussian integers and I have a few questions about the following argumentation.

What are the prime elements in $\mathbb{Z}[i]$? We remember that only
the units $+1,-1,+i,-i$ in $\mathbb{Z}[i]$ have Norm equal to one. We
will find the prime elements by using the norm. Let $\pi \in \mathbb{Z}[i]$ be prime. Since $N(\pi)=\pi \overline{\pi} \in$
$\mathbb{Z}$, $\pi$ divides a primenumber $p \in \mathbb{Z}$. Let $\pi z = p$, then $N(\pi)N(z)=N(p)=p^2$. So we either got $N(\pi)=p$ or $\pi u=p$ for a unit $u$.

Part 1:

Let $\pi \in \mathbb{Z}[i]$ be prime. Since $N(\pi)=\pi \overline{\pi} \in$ $\mathbb{Z}$, $\pi$ divides a primenumber $p \in \mathbb{Z}$

the above means that we start with a prime element $\pi$ in $\mathbb{Z}[i]$.
But why does $N(\pi)=\pi \overline{\pi}$ imply that $\pi$ divides a prime number $p \in \mathbb{Z}$? I did think about it but the only thing I could come up with is the following:
If $\pi$ is prime in $\mathbb{Z}[i]$, then for $r,s$ in $\mathbb{Z}[i]$ such that $\pi \mid rs$, then $\pi \mid r$ or $\pi \mid s$.
I know that if $a \mid b \in \mathbb{Z}$, then $N(a) \mid N(b) \in \mathbb{Z}$.
Thus we get that $N(\pi) \mid N(r)N(s)$, then $N(\pi) \mid N(r)$ or $N(\pi) \mid N(s)$. By this argumentation it follows that $N(\pi)$ is prime in $\mathbb{Z}$.
But that's not the same as in the quote above.
Question 1: So, why does $N(\pi)=\pi \overline{\pi} \in \mathbb{Z}$ imply that $\pi$ divides a prime $p\in\mathbb{Z}$?
Question 2: Does my argumentation work too?
Part 2:

Let $\pi z= p$, then $N(\pi)N(z)=N(p)=p^2$. So we either got
$N(\pi)=p$ or $\pi u=p$ for a unit $u$.

If $\pi z= p$ and $p \in \mathbb{Z}$, then
$N(\pi)N(z)=N(p)=p \overline{p}=p^2$.
I am not sure if I understand why  $N(\pi)N(z)=p^2$ does imply that $N(\pi)=p$ or $\pi=up$.
As far as I understand, if $N(\pi)N(z)=p^2$, we got the following cases:
Case 1: $N(\pi)=p$ and $N(z)=p$
Case 2: $N(\pi)=p^2$ and $N(z)=1$
Case one implies $N(\pi)=p$. And case two implies $N(z)=1 \Leftrightarrow z \in \mathbb{Z}[i]^{\times}$.
Question 3: Is my argumentation regarding part 2 correct?
Comment: Part 1 is, I think, pretty simple. Take a non-integer prime in $\mathbb{Z}[i], a+bi$. It necessarily has a complex conjugate $a-bi$. Since $(a+bi)(a-bi) = a^2 + b^2 \in \mathbb{Z}$, $a+bi$ divides some integer. And this is linked; $a+bi$ is a Gaussian prime iff $(a+bi)(a-bi)$ is an integer prime.
Comment: @EricSnyder I do understand why $a+bi$ should divide some integer in $\mathbb{Z}$. But why does it have to be a prime number? I do not really see why "$a+bi$ is gaussian prime iff $(a+bi)(a-bi)$ is an integer prime".
Comment: That last part is, as far as I know, simply part of the definition of Gaussian primes. [Here's an MSE link](https://math.stackexchange.com/questions/1640798/the-norm-of-a-gaussian-prime-is-a-prime-or-a-square-of-a-prime-in-mathbbz) that uses similar argumentation as yours.
Answer: It is maybe a good idea (for this answer) to always write in which ring an element divides an other one. We have a beautiful situation, both rings
$\Bbb Z$ and $\Bbb Z[i]$ have unique factorization (unit times prime factors to powers, and the uniqueness is up to reordering factors).
Note that $\Bbb Z[i]$ is the ring of integers in $\Bbb Q(i)$, in other words, an element of $\Bbb Q(i)$ is in this ring, iff it is a root of an irreducible monic polynomial with integer coefficients. The norm map is a multiplicative map (we are excluding zero from its domain)
$$
N:\Bbb Z[i]^\times \to\Bbb Z^\times\ ,
$$
the image is always positive. A maximal factorization in $\Bbb Z[i]^\times$ is mapped into a factorization in $\Bbb Z$, which can be or not maximal.
It may be good to have some examples to support the arguments.
Primes in $\Bbb Z$ are (up to units):

the two, which ramifies like $(1+i)^2=2i$, so $2$ (times a unit), seen in $\Bbb Z[i]$ has two factors / one factor of multiplicity two.
primes $p$ from $\Bbb Z$ of the shape $4k+3$, these are inert, when taken from $\Bbb   Z$ and suddenly seen in $\Bbb Z[i]$. For instance, $3,7,11,19,...$ cannot be decomposed in $\Bbb Z[i]$. Quadratic reciprocity. We have, seeing $p$ as $p+0i$, $N(p+0i)=(p+0i)(p-0i)=p^2$. So the norm does not (in general) map primes to primes. So Question 2...
primes $p$ from $\Bbb Z$ of the shape $4k+1$, these always decompose, when taken from $\Bbb Z$ and suddenly seen in $\Bbb Z[i]$, and the decomposition is of the shape $p=(a+bi)(a-bi)$, and these $a,b$ always exist. For instance, $5=(2+i)(2-i)$, $13=(3+2i)(3-2i)$, $17=(4+i)(4-i)$, $29=(5+2i)(5-2i)$, they can be (uniquely up to units) decomposed in $\Bbb Z[i]$, and the the pieces $(a\pm bi)$ are primes in $\Bbb Z[i]$. Quadratic reciprocity.
We have $N(a+ib)=p$. So the norm maps such primes in primes.

Start with $\pi=a+bi$, a prime in $\Bbb Z[i]$. Then $N(\pi)=(a+bi)(a-ib)$ is an integer, and it has a decomposition in prime factors $p_1p_2\dots p_r$. We can thus write:
$$
\pi=(a+bi)\text{ divides in $\Bbb Z[i]$ }(a+bi)(a-bi)=(p_1+0i)(p_2+0i)\dots(p_r+0i)\ .
$$
Since $\pi = (a+ib)$ is a prime, it divides at least one of the factors on the right side. That's all.

It remains to use that $\pi$ divides some $p+0i$ in $\Bbb Z[i]$ for some prime $p$ from $\Bbb Z$. Write $p=\pi z$ in $\Bbb Z[i]$. So $p^2 =N(\pi)N(z)$, and for the two norms, of $\pi$ and of $z$ there are two possibilities, parallel to factorizations of $p^2$ in positive integers.
We have $N(\pi)=N(z)=p$ or $N(\pi)=p^2$ and $N(z)=1$.
In the last case, $N(z)$ means $z$ is a unit, so an element among $\pm 1$, $\pm i$ only.
Comment: The downvoter may please kindly drop a short hint. Typing many lines often leads to errors, and it is not so simple to type them, then to see an error and press that downvote button. I understand it may be hard to drop this one-line comment pointing to the line with the error, or to the way i am missing the point of the question, or to the fact that i do not know that $7$ does not split in $\Bbb Z[i]$ at the point when the question is stated, so i cannot take it as an example, or... but please let me know somehow from which direction the wind blows and catches me off guard...


How a rows permutation affects the SVD of a matrix?

Question: Given a matrix with its Singular Value Decomposition:
$$
X = \begin{bmatrix}
       x_{1,1} & \dots & x_{1,m}          \\[0.3em]
       \dots & \dots           & \dots \\[0.3em]
      x_{n,1} & \dots & x_{n,m}
     \end{bmatrix} = U\Sigma V^T$$
If I build a new matrix, $X_{perm}$, whose rows are a permutation of the $X$ ones, e.g.
$$X_{perm1} = \begin{bmatrix}
       x_{n,1} & \dots & x_{n,m}          \\[0.3em]
       \dots & \dots           & \dots \\[0.3em]
      x_{1,1} & \dots & x_{1,m}
     \end{bmatrix}$$
(where the first and the last rows are exchanged), I thought that the $V$ matrix of the SVD won't change. Actually, computing it with some tools it changes.
Can you please briefly explain me why?
Answer: If $E$ is the elementary matrix that effects exchange of the first and last rows, then for $X = U \Sigma V^\ast$ an SVD of $X$, $X_{\mathrm{perm}} = (EU)\Sigma V^\ast$ ought to be a perfectly valid SVD of $X_{\mathrm{perm}} = EX$, since $E$ is a perfectly respectable real orthogonal matrix. But then again, SVD's aren't unique (only $\Sigma$ is, up to permutation of the diagonal entries), so it might just be an idiosyncrasy (but not an error) of your software package that it ends up computing different $V$'s for $X$ and $X_{\mathrm{perm}}$?


What filtering system is blocking my users?

Question: For automatic updates to an application I maintain, I have the app access a particular URL on our website, but I noticed from some logs that some users get some HTML instead, that begins with:
<code><HTML><HEAD><META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL=http://d14ii001:9017/authenticate?original_url=http%3A%2F%2Fdedicatedmicros
</code>
where dedicatedmicros is the start of the URL it checks for updates from.
Can anyone tell me what filter or proxy this looks like and ideally why dedicatedmicros.com might be filtered out.
The odd thing is that the request does seem to get through but the reply doesn't.
Comment: So what are you deliversing as reply? Can you give an example? if it is binary data -here is the reason.
Comment: 1.18.24 = http://dedicatedmicros.com/blahblah/somescript.php?fileid=1234
Answer: It's almost impossible to say exactly what proxy would cause that, as a lot of them do it.  I have a pair of BlueCoat ProxySG devices in my office that do exactly what you're seeing above, and have the same end behavior.
What's happening is the proxy is requiring the user be authenticated to use the service.  The request by the client is being sent, and you see it in the logs, but the proxy intercepts the response, and sends a message to the client saying that it has to redirect to a different page.  That page is where the client/end user is supposed to enter credentials to login.  A lot of times, especially when setup as a transparent proxy configuration, this authentication ties in with some network authentication, like NTLM, Kerberos or the likes. With the proxy being considered a trusted host as it is in the private network, most browsers can auto-send login information.
Once authenticated, the proxy server will most likely send back some cookie, and allow access to the original URL.  As you can see from the HTML code you have above, there is an argument being passed to the authentication script called "original_url".  This is so the page knows where to send the client.
If this is device is not on your network, and managed by somebody else, you should try talking with the folks that manage the network there, and discuss the possibilities of a special bypass for your application, or site.
Comment: Thank you for that answer.  I suppose I should try to log the IP address associated with the failure that this causes (the app uploads details of the failure too) and then work back to get an exception added for our application.
Comment: Or could you get your application to support authentication? A lot of places will consider that reasonable - I know our general application support policy where I work is that if you expect us to change our network to fit your application instead of being able to configure the application to fit the network as it is, then we just assume the vendor simply doesn't want us to use their app...
Comment: Is that authentication specced somewhere, or do I need to work it out for each network I want the application to work within?


how to make an if else statement for character length

Question: I'm trying to write a piece of code that will see if the text entry has 50 or more characters and if it does then to just show the 50 plus ellipsis (...)  or else if it has less than 50 characters then to just show the whole entry without the ellipsis.
My current code is:
from django.db import models

# Create your models here.

class Topic(models.Model):
    """A topic the user is learning about"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        """Return a string representation of the model"""
        return self.text

class Entry(models.Model):
    """Something specific learned about a topic"""
    topic = models.ForeignKey(Topic)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        if text.len() >= 50:
            """Return a string represerntation of the model"""
            return self.text[:50] + "..."
        else:
            return self.text

When I run this while using Python and Django I keep getting an error. How would i go about fixing this
Comment: Also in your last function, you need `len(self.text)`, not `text.len()`.
Comment: See my second comment above...
Comment: What is the error are you're getting?
Comment: Your last function needs to be indented, presumably...
Comment: currently gettings self
Error in formatting: NameError: name 'text' is not defined
Comment: `if text.len() >= 50:` -> `if self.text.len() >= 50:`
Comment: @allcaps: Does a Django TextField have a len  member function? (genuine question)
Comment: In Python len() returns the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). https://docs.python.org/3/library/functions.html#len
Answer: Use:
if len(self.text) >= 50:

instead of:
if text.len() >= 50:

Answer: from django.db import models

# Create your models here.

class Topic(models.Model):
    """A topic the user is learning about"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        """Return a string representation of the model"""
        return self.text

class Entry(models.Model):
    """Something specific learned about a topic"""
    topic = models.ForeignKey(Topic)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        if len(self.text) >= 50:
            """Return a string represerntation of the model"""
            return self.text[:50] + "..."
        else:
            return self.text

Comment: Code only answers are not ideal. Please review [answer] and tell us *why it didn't work* and *how this fixes it*.


Importing JSON file to access table

Question: I'm using this JSON library by omegastripes to import json files into an Access database. This post has a pretty good solution, but you need to know the field names ahead of time. I'm looking for a more generic sub to pull any flattened json object into a table (creating the table first if it doesn't exist), and I can create the table relationships later.
In most cases, I only need a portion of the json file I'm working with. For example, with the json below I can ignore the "meta", and the "phones" sections:
{
  "contacts": [
    {
      "id": 9785,
      "type": "Individual",
      "first_name": "John",
      "middle_name": "Jacob",
      "last_name": "Jingleheimer-Schmidt",
      "suffix": "Sr.",
      "company_name": null,
      "added_by": 337864,
      "phones": [
        {
          "id": 204,
          "number": "8884447777"
        }
      ]
    },
    {
      "id": 9887,
      "type": "Individual",
      "first_name": "John",
      "middle_name": "Jacob",
      "last_name": "Jingleheimer-Schmidt",
      "suffix": "Jr.",
      "company_name": null,
      "added_by": 337864,
      "phones": []
    },
    {
      "id": 8556,
      "type": "Business",
      "first_name": null,
      "middle_name": null,
      "last_name": null,
      "company_name": "J&J Construction",
      "added_by": null,
      "phones": [
        {
          "id": 13168,
          "number": "5557779999"
        },
        {
          "id": 13169,
          "number": "2224446666"
        }
      ]
    }
  ],
  "meta": {
    "total_records": 3,
    "total_pages": 1
  }
}

Comment: "I'm looking for a more generic sub to pull any flattened json object into a table (creating the table first if it doesn't exist)"  This will create random table-names, and random-table-fieldnames ?  And HOW ar you going to query those random (read: unknown table- or field- names?
Comment: That's kind of the point - I'm dealing with an API that can call many different "random" types of JSON files. Rather than build a function for each one, I wanted a function that could import any of them, [so I built it](https://stackoverflow.com/a/76132245/12735176). The table name is passed in as a parameter. The field names are pulled from the JSON file. Once the table exists, calling the function again will append new records.

Now I can build more specific functions that call this generic one first, and then query the data like any other table once it's been imported.
Answer: Ended up building the solution before I finished posting my question. Here's what I made! This will build a table from the parsed json object, OR any of its sub-objects/arrays. Copy the ToTable function into the JSON module...
Public Function ToTable(vJSON, tblName As String) As Long
    ' Input:
    ' vJSON - Array or Object which contains rows data
    ' tblName - the name of the access table to create / append to
    ' Output:  Returns 0 if successful. Otherwise returns an error code
    On Error GoTo Exit_Handler
    Dim db As Database, rs As Recordset, arr(), k, v

    Select Case varType(vJSON)
    Case Is >= vbArray
        If SizeOf(vJSON) = 0 Then Err.Raise 53, "JSON.ToTable", "The JSON object is empty"
        arr = vJSON
    Case vbObject   'place vJSON inside an array of 1 so the loops don't error out
        ReDim arr(0)
        Set arr(0) = vJSON
    End Select

    Set db = CurrentDb
    If IsNull(DLookup("Name", "MSysObjects", "Name='" & tblName & "'")) Then
        'if tblName doesn't already exist...
        Dim tblFields$, vType$

        For Each k In arr(0)    'get field type based on the first record in each field
            Select Case varType(arr(0)(k))
            Case vbBoolean
                tblFields = tblFields & ", [" & k & "] BIT"
            Case vbDouble
                tblFields = tblFields & ", [" & k & "] FLOAT"
            Case vbDate
                tblFields = tblFields & ", [" & k & "] DATETIME"
            Case Else
                If Len(k) Then tblFields = tblFields & ", [" & k & "] VARCHAR"
            End Select
        Next
        If Len(tblFields) = 0 Then Err.Raise 59, "JSON.ToTable", "There are no field names to add."
        'create new tbl
        db.Execute "CREATE TABLE [" & tblName & "](" & Mid(tblFields, 2) & ");"
    End If
    Set rs = db.OpenRecordset(tblName, dbOpenTable, dbAppendOnly)

    'add records to fields
    For i = LBound(arr) To UBound(arr)
        rs.AddNew
        For Each k In arr(i)
            If Len(k) Then
                Select Case varType(arr(i)(k))
                Case vbObject
                    rs.Fields(k) = "{...}"
                Case Is >= vbArray
                    rs.Fields(k) = "[...]"
                Case Else
                    rs.Fields(k) = arr(i)(k)
                End Select
            End If
        Next
        rs.Update
    Next

Exit_Handler:
    ToTable = Err
    If Err = 3265 Then
        MsgBox "Error 3265 - You are trying to import to a field that does not exist in the table: '" & tblName & "'. Try passing in a different tblName, or deleting this table.", , "JSON.ToTable Error"
    ElseIf Err Then
        MsgBox "Run time error #" & Err.Number & " " & Error$, , Err.Source
    End If
End Function

...and then run test_me to try it out:
Sub test_me()
    Const sJSON = "{""contacts"":[{""id"":9785,""type"":""Individual"",""first_name"":""John"",""middle_name"":""Jacob"",""last_name"":""Jingleheimer-Schmidt"",""suffix"":""Sr."",""company_name"":null,""added_by"":337864,""phones"":[{""id"":204,""number"":""8884447777""}]},{""id"":9887,""type"":""Individual"",""first_name"":""John"",""middle_name"":""Jacob"",""last_name"":""Jingleheimer-Schmidt"",""suffix"":""Jr."",""company_name"":null,""added_by"":337864,""phones"":[]},{""id"":8556,""type"":""Business"",""first_name"":null,""middle_name"":null,""last_name"":null,""company_name"":""J&J Construction"",""added_by"":null,""phones"":[{""id"":13168,""number"":""5557779999""},{""id"":13169,""number"":""2224446666""}]}],""meta"":{""total_records"":3,""total_pages"":1}}"
    Dim oJSON
    JSON.Parse sJSON, oJSON

'uncomment one of theses lines to import only a portion of the json object. You might want to change "yourTableName" to something else between runs:
'    oJSON = oJSON("contacts")   'import a sub-array
'    Set oJSON = oJSON("meta")   'import a sub-object

    JSON.ToTable oJSON, "yourTableName"
End Sub

Answer: Thank you for including your code. I believe this code needs the additional code for SizeOf(), which requires isEmpty() and isDefined() and a couple of constants.
Public Const SIZE_NOT_ARRAY As Long = -1
Public Const SIZE_EMPTY As Long = 0

Public Function SizeOf(ByVal values, Optional ByVal dimensionOneBased As Long = 1) As Long
    ' Return Value:
    '   -1 - Not an Array
    '    0 - Empty
    '   >0 - Defined
    Dim lngResult As Long: lngResult = SIZE_NOT_ARRAY 'Default to not an Array
    Dim lowerBound As Long
    Dim upperBound As Long
    On Error GoTo NormalExit
    If (IsArray(values) = True) Then
        lngResult = SIZE_EMPTY                          ' Move default to Empty
        lowerBound = LBound(values, dimensionOneBased)  ' Possibly generates error
        upperBound = UBound(values, dimensionOneBased)  ' Possibly generates error
        If (lowerBound < upperBound) Then
            lngResult = upperBound - lowerBound + 1     ' Size greater than 1
        Else
            If (lowerBound = upperBound) Then
                lngResult = 1                           ' Size equal to 1
            End If
        End If
    End If
NormalExit:
        SizeOf = lngResult

Public Function isEmpty(ByVal values As Variant, Optional ByVal dimensionOneBased As Long = 1) As Boolean
    isEmpty = SizeOf(values, dimensionOneBased) = 0

Public Function isDefined(ByVal values As Variant, Optional ByVal dimensionOneBased As Long = 1) As Boolean
    isDefined = SizeOf(values, dimensionOneBased) > 0

Importing JSON file to access table


Kube-apiserver crashing

Question: I am trying to create a kubernetes cluster on my local machine.
I created 3 vm's (two master and a slave).
I am using kubespray(v2.15.0) to create my cluster, But my kube-apiserver contianer keeps crashing with following error:
2021-03-03T10:33:06.41276414Z stderr F F0303 10:33:06.408597       1 sample_and_watermark.go:182] Time went backwards from 2021-03-03T10:33:06.408588954Z to 2021-03-03T10:33:06.408562115Z for labelValues=[]string{"executing", "readOnly"}

Can someone please help me diagnose this issue.
Here are the list of versions:

Vagrant : 2.2.14
Ubuntu : 18.04.5 LTS
Kubespray : 2.15.0
kubernetes : 1.19.7
Comment: Can you try to install latest version of Kubernetes 1.20.4? Make sure you have choose proper network plugin - Vagrant uses flannel. Check if all requirements are met - https://github.com/kubernetes-sigs/kubespray#requirements  https://github.com/kubernetes-sigs/kubespray/blob/master/docs/vagrant.md
Comment: Hi Vishak, welcome to S.F. [The issue](https://github.com/kubernetes/kubernetes/issues/96459) doesn't mention it, but that behavior _(which is happening to your kernel, and k8s is just the victim)_ is almost certainly caused by extremely high load on your host OS, screwing up the virtualization's clock. I see the fix was pulled into _some_ release of 1.19 but the changelog doesn't cite it, so ideally you'd heed Malgorzata's advice and use a modern version. Good luck!
Comment: @VishakVinod Did you manage solve problem using our tips ?
Comment: Sorry I didnt get time to run it with 1.20.4. I will try it soon and let u knw about the result
Comment: @Malgorzata thanks for the advice.. it worked.. I changed the version to 1.20.4 and it worked.. kubespray latest version(2.15.0) officially dosent upport 1.20.4 so had to do some manual changes to get it working
Answer: As  solution install newest version of Kubernetes - 1.20.4. Kubespray version officially support -   Kubernetes v1.19.7 so small changes should be done before applying to adjust to Kubernetes version 1.20.4.
Read: kubernetes, kubespray.
Comment: @VishakVinod Does this [answer your question](https://stackoverflow.com/help/someone-answers)?

Kube-apiserver crashing


Riemann sums for sequence of functions

Question: Let $f:[0,1]\rightarrow \mathbb{R}$ be a Riemann integrable function and let $p$ be a real number with $0<p<1$. Prove that
$$
\frac{1}{n}\,\sum_{j=0}^nf\left(\frac{j}{n}\right)\left(1-p^{j}\right)\rightarrow \int_0^1f\left(t\right)\,dt
$$
Comments Of course,  by Riemann integrability, we have that
$$
\frac{1}{n}\,\sum_{j=0}^nf\left(\frac{j}{n}\right)\rightarrow \int_0^1f\left(t\right)\,dt
$$
The idea is to define the sequence of functions
$$
g_n(t)=f(t)\,(1-p^{\left\lfloor t*n\right\rfloor}).
$$
so that $g_n(t)\rightarrow f(t)$ point-wise on $[0,1]$. However I cannot Prove that the convergence is uniform since
$$
\sup_{t\in[0,1]}\left|g_n(t)-f(t)\right| = \sup_{t\in[0,1]}p^{\left\lfloor t*n\right\rfloor}=1.
$$
Answer: We have
$$\frac{1}{n}\,\sum_{j=0}^nf\left(\frac{j}{n}\right)\left(1-p^{j}\right) = \frac{1}{n}\,\sum_{j=0}^nf\left(\frac{j}{n}\right)- \frac{1}{n}\,\sum_{j=0}^nf\left(\frac{j}{n}\right)p^{j},$$
and it is enough to show the second term converges to $0$.
Since $f$ is Riemann integrable and, hence, bounded,
$$\left|\frac{1}{n}\,\sum_{j=0}^nf\left(\frac{j}{n}\right)p^{j} \right| \leqslant \frac{1}{n}\sum_{j=0}^n\left|f\left(\frac{j}{n}\right)\right|p^{j} \\ \leqslant \frac{\sup_{x \in [0,1]} |f(x)|}{n}\frac{1- p^{n+1}}{1-p} \\ \leqslant
\frac{\sup_{x \in [0,1]} |f(x)|}{n(1-p)}\\ \longrightarrow_{n \to \infty} 0$$

Riemann sums for sequence of functions


Bootstrap datetimepicker moment format issue

Question: Alright I am having an issue with getting dates to display as intended when using the bootstrap datetimepicker.  I know it runs off moment.js for the formatting but it doesn't seem to be following the normal set of rules for moment (I am using the newest versions of both).
For example if I were to take a date and create a regular moment() object out of it and then format it with MMMM that would give me the full month name (February)
moment('02/24/2015')->format('MMMM'); // gives February
But if I am working with a datetimepicker object and set the format on it, it will end up outputting (FebruraryFebruary) and if I just want the full month name I need to go with MM.
$(input).datetimepicker({
    format: 'MM'
}) // gives February
Can anyone explain why it does not follow the correct moment formatting rules?  I find it odd (and difficult to get the result I want because I cannot find the rules I need to set to get what I am looking for) that I cannot just take my standard moment formatting rules and apply it to the datetimepicker and get the intended result.
halp!
Comment: Upgrade to latest version 'MMMM' on bootstrap datetimepicker and momentjs both give February
Comment: epic fail on my part. I had copied the new datetimepicker code into the file but it didn't upload.  Thanks
Answer: Moment format and BootStrap DatetimePicker format works differently.
Never set Momment format into Datetimepicker format.
Consider this:
datetimeformat MM/dd/yyyy HH:mm:ss PP for Bootstrap DatetimePicker AM format
and the equivalent in momment format is given below:
MM/DD/YYYY hh:mm:ss A

Check Momment.JS site for more information


Find the points of the surface defined by $-x_1^2 + x_2^2 - x_3^2 + 10x_1x_3 = 1$ closest to the origin

Question: For the surface
$$\{ (x_1, x_2, x_3) \in \mathbb R^3 \mid -x_1^2+x_2^2-x_3^2 + 10x_1x_3=1 \}$$
I want to find the points on it closest to the origin.  I know how to do a substantial part of this.  First I make the matrix
$$A = \begin{pmatrix}-1 & 0 & 5 \\ 0 & 1 & 0 \\ 5 & 0 & -1\end{pmatrix}$$
and then get the eigenvalues
$$|A-\lambda I| = \begin{vmatrix} -1-\lambda & 0 & 5 \\ 0 & 1-\lambda & 0 \\ 5 & 0 & -1-\lambda\end{vmatrix}$$
$$ = (-1-\lambda)(1-\lambda)(-1-\lambda) + 5(-5(1-\lambda))$$
$$= (1-\lambda)([-1-\lambda]^2-25)$$
$$= (1-\lambda)(-1-\lambda-5)(-1-\lambda+5)$$
$$= (1-\lambda)(-6-\lambda)(-4-\lambda) $$
$$= (1-\lambda)(6+\lambda)(4+\lambda)$$
So the eigenvalues are $\lambda = 1,-6,-4$ and therefore the quadratic form can be represented as
$$c_1^2 - 6c_2^2 - 4c_3^2=1$$

The part I don't get is how to find the point closest to the origin from here.  I've seen solutions to problems similar to this where they merely set two variables to 0 and out of all such choices of two variables, they pick the one with the least value for the third which satisfies the equation.
However, how do we know this process will select the point closest to the origin?  If coefficients were made suitably extreme, at least on the face of it, you'd think we might be able to engineer and example where picking some very small mixture of non-zero values of $c_1, c_2, c_3$ would satisfy the equation and be smaller than what you'd get for setting some two of them to 0.
In this particular case we could set $c_2=c_3=0$ so that $c_1=1$.  But what guarantee is there that we couldn't give $c_2$ just a little something, drastically reducing the amount we need to give to $c_1$?  Even if we couldn't do that here, what if the coefficient of $c_2$ were negative a million, so that you'd think just a little bit in $c_2$ goes a very long way to reducing what we need from $c_1$?
[Edit: As pointed out, I should have said that the characteristic equation was
$$(1-\lambda)(-6-\lambda)(4-\lambda)$$
so that the eigenvalues are 1, -6, and 4.  Then the quadratic can be expressed as
$$c_1^2-6c_2^2+4c_3^2=1$$]
Comment: You want to minimize $x^2+y^2+z^2$ subject to $-x^2+y^2-z^2+10xz-1=0$. Maybe use Lagrange multipliers, instead?
Comment: Or eliminate $y$: you want to minimize $2x^2-10xz+2z^2+1$.
Comment: Note that eigenvectors and eigenvalues of this matrix can be found by inspection: from the second column $(0,1,0)^T$ with eigenvalue $1$ is obvious, and the other two are obtained via sum and difference of the other two columns.
Comment: You've made a sign error: $-4$ is not an eigenvalue, but $4$ is.
Answer: It might be easier to see what's going on by switching to cylindrical coordinates. With $c_1=r\cos\phi$ and $c_3=r\sin\phi$, the transformed equation (with corrected sign) becomes $$r^2={1+6c_2^2 \over 1+3\sin^2\phi}.$$ The numerator has an absolute minimum of $1$ at $c_2=0$ and the denominator lies in the interval $[1,4]$. The minimum value of $r^2$ clearly occurs at $c_2=0$, $\phi = \pm\pi/2$, i.e., at $c_1=0$, $c_3=\pm1/2$.
Looking at this geometrically, the intersections of this surface with the planes $c_2=const$ are homothetic ellipses centered on the $c_2$-axis, with the smallest of the family occuring at $c_2=0$: making any changes to $c_1$, $c_2$ and $c_3$ that moves you off of this plane can only move you away from the minimum-distance point(s). On the other hand, if you hold $c_2$ fixed at zero, you can't change $c_1$ and $c_3$ arbitrarily. They are constrained by the minimal ellipse.
Answer: According to some theorem I forgot name of, you can get away with just finding points having gradient point to origo.
$$g(x_1,x_2,x_3) = -{x_1}^2+{x_2}^2-{x_3}^2+10x_1x_3 - 1$$
$$\nabla g = [-2x_1 + 10x_3, 2x_2, -2x_3 + 10x_1]^T$$
so $$ {\bf x} - \lambda (\nabla g ({\bf x})) = 0, \lambda \in \mathbb R$$
$$ [x_1 - \lambda(10x_3-2x_1), x_2 - \lambda(2x_2), x_3 - \lambda(10x_1-2x_3)] = \bf 0$$
We first see either $\lambda = 1/2$ or $x_2=0$ must hold for component $2$ to fulfill.
if $x_2\neq 0$:
This means for component 1: $x_1 - 1/2(10x_3-2x_1) = 0$ giving $5x_3 = 2x_1$
And component 3: that $5x_1 = 2x_3$
Only solution can then be along $[0,1,0]^T$
if $x_2=0$:
$$x_1-\lambda(10x_3-2x_1) = 0\\x_3-\lambda(10x_1-2x_3) = 0$$
from first: $\lambda = \frac{x_1}{10x_3-2x_1}$
$$x_3 - \frac{x_1(10x_1-2x_3)}{10x_3-2x_1} = 0$$
$$\frac{x_3(10x_3-2x_1)}{10x_3-2x_1} - \frac{x_1(10x_1-2x_3)}{10x_3-2x_1} = 0$$
simplification gives:
$$x_3^2 = x_1^2$$
so $$\lambda[\pm 1,0,\pm 1]$$ must be solution.

We can verify soundness by these Octave commands
<code>% First define level set:
g = @(a) -a(1).^2+a(2).^2-a(3).^2+10*a(1)*a(3) - 1;
% Now define cost function 1e3 factor indicates we want fit to manifold to be 1000 times more important than being close to origo:
f = @(a) 1e3*g(a).^2 + norm(a).^2;
% Now run Nelder-Mead numerical optimization algorithm:
x = fminsearch(f,randn(1,3))
</code>
This gives me: a typical solution
    [-3.5353e-01   1.5206e-05  -3.5353e-01]
which would indicate $x_1=x_3 \approx -0.3535, x_2 \approx 0$
Answer: If you start at $(c_1,c_2,c_3)=(1,0,0)$ and give a little something to $c_2$, then you would have to increase $c_1$ in order to keep $c_1^2 - 4 c_2^2 - 6 c_3^2$ equal to $1$.
(I'm not quite sure I understand your worries correctly, but you seem to think that $c_1$ can be decreased? If so, you've got it backwards.)
And any point $(c_1,c_2,c_3)$ with $c_1>1$ is farther from the origin than $(c_1,c_2,c_3)=(1,0,0)$, so $(1,0,0)$ is closest (together with $(-1,0,0)$).
Comment: Right, I did have it backwards.  Initially I was satisfied that, perhaps your logic was the intended solution.  However, as someone pointed out, I had a sign error (which I'll edit in the post in a minute) so that the eigenvalues were actually 1, 4, and -6.  So now it seems that $c_3$ can in fact be increased and thereby reduce what is needed from $c_1$.  I suppose a valid (if non-rigorous) logic would be: $c_3$ now does a better job of getting to 1 "faster" than $c_1$ does.  And due to the nature of the square, small values contribute little--so if $c_3$ is going to do anything, it should do
Comment: everything.  If the functions were different from mere sums of squares then we might need a more subtle calculation.
Comment: @Addem: Yes, in that case $(0,0,\pm \frac12)$ would be closest to the origin, which can be shown by a different argument based on the inequalities $$c_1^2+c_3^2 \le c_1^2 + 4 c_3^2 \le 4(c_1^2+c_3^2).$$


Prove, that graph $G$ has at least $\chi(G)(\chi(G)-1)/2$ edges.

Question: Can anybody give me any hints about how to prove that for any graph $G$ the number of edges in it is at least $\chi(G)(\chi(G)-1)/2$?  $\chi(G)$ is the minimal number of colors we need to use to color the graph (it's chromatic index in other words).
I tried induction but I'm stuck at an induction step.
I do the induction on the number of edges.
When $|E(G)|=0$ then obviously we can color the graph using only one color, so the theorem holds.
Now induction step from $n \Rightarrow n+1$ edges.
Let's erase any edge $e=\{v,u\}$ from $G$. Then $\chi(G-e)$ is either the same, or $\chi(G-e)<\chi(G)$, because we relaxed the graph an $v$ and $u$ no longer need to have different colors. From the first case the thesis is clear, because $G-e$ has more then $\chi(G)(\chi(G)-1)/2$ edges so with the one we erased it's still more. But from the second case we only know that $G \geq \chi'(G)(\chi'(G)-1)/2$ and $\chi'(G)(\chi'(G)-1)/2 \leq \chi(G)(\chi(G)-1)/2$ so that gives me nothing...
Answer: Given a coloring of $G$ with $\chi(G)$ colors, there must be an edge between every two color classes, because otherwise we could color them the same color.
Comment: Thank you :) Incredibly simple and sweet answer :) Looks like my long inductive proof was not a wise choice :P


Fatal error: Call to a member function getId() on string

Question: Não consigo encontrar o erro que está aparecendo no meu banco-produto. Alguém poderia me ajudar a encontrar? Agradeco de antemão.
 Fatal error: Call to a member function getId() on string in         C:\Bitnami\wampstack-5.6.19-0\apache2\htdocs\beladuquesa\sys\banco-produto.php on line 85

esta é a função alteraProduto:
    function alteraProduto($conexao, $produto) {

echo ("* inicio funcao alteraProduto * "); //Aviso de teste

81)$query = "update produtos set nome = '{$produto->getNome()}',
82)codigo = {$produto->getCodigo()},
83)preco = {$produto->getPreco()},
84)descricao = '{$produto->getDescricao()}',
85)categoria_id = {$produto->getCategoria()->getId()},
86)cor_id = {$produto->getCor()->getId()},
87)tamanho_id = {$produto->getTamanho()->getId()} where id = 88)'{$produto->getId()}'";**

return mysqli_query($this->conexao, $query);

echo ($query); //Aviso de teste
}

Este é o teste que fiz do que está vindo do altera-produto:
* inicio alteração * * Envia para Banco Produto * array(8) { ["id"]=> string(1) "1" ["codigo"]=> string(2) "12" ["nome"]=> string(13) "Vestido Paula" ["preco"]=> string(6) "100.00" ["descricao"]=> string(20) "Vestido em Tricoline" ["cor_id"]=> string(2) "20" ["tamanho_id"]=> string(1) "5" ["categoria_id"]=> string(1) "2" } * inicio funcao alteraProduto *

Este é o arquivo altera-produto:
    <?php
require_once 'conecta.php';
require_once 'banco-produto.php';
require_once 'banco-cor.php';
require_once 'banco-tamanho.php';
require_once 'banco-categoria.php';
require_once 'produto.php';
require_once 'cor.php';
require_once 'tamanho.php';
require_once 'categoria.php';

$produto = new Produto();
echo ("* inicio alteração * "); //Aviso de teste
$produto->setId( $_POST['id'] );
$produto->setCodigo( $_POST["codigo"]) ;
$produto->setNome( $_POST["nome"]);
$produto->setPreco( $_POST["preco"]);
$produto->setDescricao( $_POST["descricao"]);
$produto->setCor(new Cor());
$produto->setCor( $_POST["cor_id"]);
$produto->setTamanho(new Tamanho());
$produto->setTamanho( $_POST["tamanho_id"]);
$produto->setCategoria(new Categoria());
$produto->setCategoria( $_POST["categoria_id"]);
echo ("* Envia para Banco Produto * "); //Aviso de teste
var_dump($_POST);

Answer: Seu código está definindo duas vezes a categoria, uma como um objeto e outra como o conteúdo de $_POST["categoria_id"].
Tente mudar sua rotina de altera-produto para ficar assim:
$produto->setCategoria(new Categoria());
$produto->getCategoria()->setId( $_POST["categoria_id"]);
echo ("* Envia para Banco Produto * "); //Aviso de teste

Note que você tem esse mesmo problema com a propriedade Tamanho. Você cria um objeto e logo em seguida seta o conteúdo de $_POST["tamanho_id"].
Comment: Muito obrigado Hertel na mosca!!! Resolvido.
Comment: De nada. Se tiver mais problemas abra uma nova pergunta.


Avoiding click event on absolute positioned element below

Question: I have 2 elements a parent element and its child, and both are absolutely positioned.
I have a click handler for each element, although when I click the child element the parent element behind it also catches the click.
How do I prevent the parent element from receiving the click event?
Comment: Can you add a JS fiddle with your code please?
Answer: If you want a pure CSS solution, you could use pointer-events: none;. This will make sure your mouse ignores the parent element, for good, so be careful in your use of it.
Also note this is NOT SUPPORTED in IE or Opera. (Or at least, not on HTML elements, just SVG)
jQuery alternative is e.StopPropagation, more info can be found here
Answer: You can use JQuery and simple have a preventDefault or return false on the parent element:
$('#parent').click(function() {
    return false;
});

$('#child').click(function() {
    //do something
});

Comment: This doesn't prevent the parent from receiving a click event, it just doesn't do anything when such an event occurs. So if the OP needed to do something for a click on the parent that isn't directly on the child this wouldn't help.


Intent result, how to know who sent it?

Question: Is it possible to know which package or process sent the Intent result?
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);

I found a way to know which apps are capable of handling this intent, but I also want to know which one was selected, or rather, which one returned the result. Is this possible?
Comment: possible duplicate of [How to find Intent source in Android?](http://stackoverflow.com/questions/4789155/how-to-find-intent-source-in-android)
Answer: It depends on apps how they are developed.
Some apps returns an Intent object full of stuff, other empty or null.
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent i) {
         if (i!=null){
            i.getPackage();
            i.getExtras();
            i.getData();
            i.getScheme();
            i.getType();
           }
        }

Try to log/read all possible values inside Intent.
Answer: You can also try looking at the Logcat.It contains information about when the intent started and how.I have tried using it to know whether an intent starts or not.

Intent result, how to know who sent it?


How to show this integral equals 0?

Question: Problem: Suppose $h:S\to\mathbb{R}$ is integrable on the set $S\subset\mathbb{R}^n$. Also $h=0$ everywhere except on a set of measure 0. How to show that $\int_S h=0$?
Attempt: I am trying to prove that $\underset{P}\sup\left\{L(h,P)\right\}=\underset{P}\inf\left\{U(h,P)\right\}=0$. I want to prove this by showing that for all positive $\epsilon$, I can produce a partition $P$ such that either $L(h,P)>-\epsilon$ or $U(h,P)<\epsilon$. However, I have trouble justifying that such a partition exist. Any suggestions?
Comment: I know, but I am saying the proof that a function continuous except on a set of measure zero is integrable can be modified very slightly to give a proof of your statement
Comment: Have you seen the proof that a function continuous except on a set of measure zero is integrable? Almost the exact same proof works here.
Comment: I am already given that $h$ is integrable. I have trouble showing that the value of the integral is 0.
Answer: Note that $h$ vanishes everywhere in $S$ except on a set $E \subset S$ with measure $0$.
Take any partition $P$ of $S$.  If $R$ is any subrectangle, then $R$ is not a subset of $E$ since it has non-zero measure.  Hence, $h$ vanishes at some point in $R$ and $L(h,P) \leqslant 0 \leqslant U(h,P)$.
This is true for every partition $P$. Therefore,
$$\sup_{P}L(h,P) \leqslant 0 \leqslant \inf_{P} U(h,P).$$
Since the integral exists
$$\int_S h = \sup_{P}L(h,P) = \inf_{P} U(h,P)= 0.$$
Comment: Great argument, thanks!
Comment: @Letian: You're welcome. You were on the right track, but this is the most concise way to prove this for Riemann rather than Lebesgue integrals, as far as I know.

How to show this integral equals 0?


What is length of period of fibonacci number mod 1000033

Question: Can some explain me how the period of Fibonacci mod $1000033$ is $4684$.
As we know if $n$ mod $5$ is $2$
 or $3$ then period is $2n + 2$ so the period should me $2\times1000033 + 2$
 but why it is $4684$.
Thanks.
Comment: I think what we know is that the period *divides* $2n+2$, rather than always being equal to it.  (Also, I think this only holds when $n$ is prime.)
Comment: Note that $2000068=2^2\times 7 \times 61 \times 1171$ and $4684=2^2 \times 1171$
Comment: No, we don't. I am pretty sure that the period modulo $1$ is $1$, and $1$ is not $4$.
Comment: Sorry ( n mod 5)  is   2 or 3  thanks for your comment.
Comment: You must be mistaken. The period mod 8 is 12, the period mod 18 is 24, the period mod anything ending in 8 doesn't fit your pattern. Similarly, the period mod 33 is 40, and so on. Your assumed pattern is incorrect.
Comment: But if n=1000000007 then period is 2000000016 which is form of n mod 5 = 2 and period 2*1000000007+2 , If I am wrong can some one explain me how to find the period. Thanks.
Comment: See http://math.stackexchange.com/questions/217285/applications-of-abstract-algebra-to-elementary-mathematics/217289#217289
Comment: see also table of Pisano periods $\pmod n$ for all $n \leq 10000$ in text format at  http://oeis.org/A001175/b001175.txt
Answer: The period is actually $ \pi(n) = k\cdot\text{ord}_n(F_{k+1}) $ where k is the smallest positive integer such that $n\mid F_k$.
So first find the first Fibonacci number where 1000033 divides $F_k$, This happens at $F _{1171}$, so $F_{1171}/1000033$ does not give any remainder when dividing. Every fibonacci number before that does. Thus $k=1171$.
The second part: $\text{ord}_n(F_{k+1})$ is the multiplicative order. You can look that up yourself, but for fibonacci numbers its either 1, 2, or 4. In this case its 4.
(Wolfram Alpha proof: https://www.wolframalpha.com/input/?i=multiplicative+order%28fib%281172%29%2C1000033%29)
So: $1171*4=4684$
I think you are talking about $2*n+2$ with primes. That refers to the fact that all primes "land" on that, but there period can be shorter, meaning $F_{2*1000033+2}\equiv 0 \mod 1000033$. Thus for some primes $F_{2n+2}\equiv 0 \mod 1000033$.
"For p≡±1(mod5) and ±2(mod5) the periods for Fibonacci sequences modulo p divide p−1 and 2p+2 respectively."


Windows Server 2012 vs Windows Server 2008 on 1gb of ram

Question: I will be purchasing a vps soon and I there are two possible operating system that I can use, Windows Server 2012 Standard and Windows Server 2008. The vps will only have 1gb of ram. Memory wise what would be the better operating system.
Thanks,
Answer: Even though this may not be a very good question.  The clear answer without a doubt is Windows 2012.
Windows 2008 has no advantages over 2012 in terms of low-memory scenarios.
Windows 2012 on the other hand, was designed more than ever, especially with virtualization scenarios in mind where limited memory or hypervisor-enabled dynamic memory is available.
PS: Both operating systems will run with 750MB of RAM.
Comment: In my lab I squeezed a fully functional AD DC plus DNS into 512MB of RAM using Server Core 2012. I don't think that would have been possible on 2008 R2...
Comment: @MichaelHampton Indeed. If you enable Hyper-V dynamic mem. with a lower limit of 512MB, a Server 2012 server will page everything out until it consumes only 512MB of RAM... however, I've found in my own tests that you gain a lot of performance if you set the min. to 750MB just so that not as much data gets paged out to disk. Just setting the min. from 500MB to 750MB or 1GB gives noticeable gains in responsiveness in my experience.
Comment: Yeah, it was _functional_ at 512MB, with one user and one computer joined, but I wouldn't run it that way with any significant number of objects.
Comment: @MichaelHampton I think that may have something to do with why an "extra small" VM deployment in Windows Azure is given 750MB of RAM.
Comment: Yeah I currently have a Windows Server 2008 Vps with 512mb of ram and it's pretty slow.
Comment: Server 2012 refines previous versions of Server. It also comes with some great new features like IIS8 & more. So, I would suggest you to go with Windows Server 2012.
Comment: Go with Server 2012, as Server 2008R2 is EOL for support *soon*.
Comment: As an aside, I saw a presentation at a conference about a usable (barely :-) Windows Server 2008 core install file & print server with 160 MB of RAM.
Answer: Besides the operating system, other applications have to be taken into account when you consider RAM. Applications like:

Exchange (minimum: 8GB)
System Center Configuration Manager (minimum: 8GB)
System Center Service Manager (minimum: 2GB, also with at least two processor cores)

Also, if you're running Hyper-V, you will have to take into consideration the RAM consumed for each virtual machine. So it's not simply OS - it's also what you install on top of the OSes.


multiple records in one form - strong params issue

Question: I want to create a several records with a single form, but I'm not sure how to make it work with strong params. I can make the strong params accept an array of hashes, but I'm not sure how to make the form post that, and I can make the form post a hash with integer keys, but I'm not sure how to make the strong params accept that.
I have a Question model and an Answer model. This is a questionnaire page, which shows all the Questions and lets the user create Answers to them.

Questionnaire

<%= form_with url: questionnaire_path, local: true do |form| %>
  <% @questions.each_with_index do |question| %>
    <%= fields_for "answers[]", question do |af| %>

<%= question.body %>

      <% question.options&.each_with_index do |option, index| %>
        <%= af.check_box :options, {multiple: true }, index, nil %>
        <%= af.label :options, option %>
        <%= af.hidden_field :question_id, value: question.id %>
      <% end %>
    <% end %>
  <% end %>

<%= form.submit "Submit Answers" %>

<% end %>

I get back params that look like this:
"answers"=>{"0"=>{"options"=>["0"]}, "1"=>{"options"=>["0", "2"]}}

So I tried using this:
  def answer_params
    params.require(:answers).permit(:question_id, options: [])
  end

But then I get an error:
Unpermitted parameters: :1, :2

Answer: I don't like this solution, but the workaround I've found so far is to change my fields_for to include a scope outside of answers, called questionnaire:
<%= fields_for "questionnaire[answers][]", question do |af| %>

Then change answer_params to this awkwardness:
  def answer_params
    params.require(:questionnaire).permit(answers: [:question_id, options: []])[:answers].values
  end


Install and Configure XHProf (Ubuntu)

Question: Problem
I'm trying to use XHProf but I'm getting horrible php error every time it runs.
Warning: Invalid argument supplied for foreach() in xhprof_compute_inclusive_times() (line 1670 of /var/www/drupal/sites/all/modules/XHProf/xhprof.inc).
Warning: Invalid argument supplied for foreach() in xhprof_compute_flat_info() (line 1644 of /var/www/drupal/sites/all/modules/XHProf/xhprof.inc).
Warning: Invalid argument supplied for foreach() in theme_xhprof_overall_summary() (line 367 of /var/www/drupal/sites/all/modules/XHProf/xhprof.module).

The problem is solved here because the temporary folder doesn't exist, however mine does.
Set-Up Server Side
I'm running a fresh Ubuntu Server 13.04 with Drupal 7.
Install xhprof using pear following the instructions here.
I also added a temporary directory to php.ini, which I created manually.
extension=xhprof.so
xhprof.output_dir="/var/tmp/xhprof"

Drupal Set-Up
I have both the devel installed and I also installed the XHProf module.
In admin/config/development/xhprof, I enabled profiling of all page views and drush requests.
On following an xhprof link I get the error above.
Answer: Good god Batman. That was incredibly frustrating. Here's a guide to getting xhprof working. (Note: I am very new to Linux. I'm not sure if the permissions I use are safe, or whether there is a better way of doing it. I'd only do this on a test environment.)
IMPORTANT: It won't tell you anything about how to interpret it. I have no idea how to, I'm just happy it works.
Getting XHProf Working
1. What operating system are you running?
Mac or Linux?
It's possible.
Windows?
Probably not. To run xhprof on windows you have to have a compiled dll. There's a link to one in this thread, but I always had compatibility issues with it when I tried to use it on XAMPP.
I think it was compiled with a different version of Apache.
2. Getting it working on Ubuntu
It's possible on Mac. Here are two useful links:
http://www.lullabot.com/blog/article/installing-xhprof-mamp-and-php-52-mac-os-106-snow-leopard
http://www.midwesternmac.com/blogs/jeff-geerling/getting-xhprof-working-well
But I haven't done it. I managed to get it working on Ubuntu Server 13.04, although I think any recent version of Ubuntu Server would work.
I set-up my server on VirtualBox. VirtualBox is free but it might take a bit to learn how to set it up.
3.Installing XHProf
I'm going to assume we have a fully functioning Ubuntu Server.
First we need to install pear. We'll use this to install XHProf.
sudo apt-get install pear

We follow this up with phpdev which is also needed.
sudo apt-get install php5-dev

If these commands don't work and I've got them wrong, just go straight ahead with:
sudo pecl install -f xhprof

Ubuntu will tell you what you're missing and give you the prompt to install it. Once you've got all the dependencies install xhprof.
You might get an error on installing xhprof, it'll try to download the beta and fail. In that case try:
sudo pecl install -f xhprof-beta

Hopefully xhprof is now installed.
Now we need to configure it. Open your php.ini which is at /etc/php5/apache2/php.ini
and add the following two lines under the extensions section:
extension=xhprof.so
xhprof.output_dir="/var/tmp/xhprof"

The second line sets the output directory. If this folder doesn't exist you'll have to create it.When you've done that reboot apache using
sudo service apache2 restart

4. Checking if XHProf is running
Now we need to check if that worked.
Test 1:
Enter php -m
If you see xhprof in the list you're good to go. If not, don't worry, try this instead to check if it's working:
Go to your webroot /var/www/ and create a php file with only:
phpinfo();

Save it as phpinfo.php. Open this in your browser and you should see PHP information. Search for xhprof and if you see this then it's running.

5. Getting it working with Drupal
I couldn't get it working with the Drupal module. So instead I'm going to tell you how to get it working with the devel module.
First some config that I borrowed from here. I didn't really follow this part, but it works so gift horse and all that.
Create a new config file with the following command:
sudo nano /etc/apache2/conf.d/xhprof.conf

and insert the following code.
alias /xhprof_html "/usr/share/php/xhprof_html/"

Then we possibly need to create a symlink to our xhprof_html folder. So just in case set this:
ln -s /usr/share/php/xhprof_html /var/www/xhprof_html
This will create a folder in your webroot that points to the existing xhprof file. Then in your browser you can open http://mywebsitehere.com/xhprof to see all the runs you've made.
Then restart apache. Now it's time for a little devel config. Go to the devel settings, enable xhprof and set:
xhprof directory = /usr/share/php

XHProf URL = /xhprof_html

Now at the bottom of each page you should see a little link to xhprof.

And clicking it should take you to a page that looks like this. You're done. Congratulations!

If that didn't work and you're getting run errors it's probably because Drupal doesn't have permission to write to the tmp folder that we set earlier so enter:
sudo chown -R www-data /var/tmp/xhprof

And hopefully that works. We're done. Hoorah!
Unless you want graphing functions. Thankfully that's as easy as:
sudo apt-get install graphviz
sudo service apache2 restart

And now you should have graphing functions. Hopefully that helps!
Comment: Wow, impressive answer. For what it's worth, the permissions you've used seem sane.
Comment: Yeah there was some serious pain getting that to work. Hopefully it'll help someone else (and me in two months when I've forgotten).
Comment: Great answer, works perfectly, thanx to relieve the pain :-)
Comment: I don't have `/etc/apache2/conf.d` directory. I made   `sudo nano /etc/apache2/conf-enabled/xhprof.conf` and `a2enconf xhprof` instead
Comment: Thanks for the run-through.  On Ubuntu 14.04 I installed from the Ubuntu repositories rather than PEAR, and found I needed to execute `php5enmod xhprof` in order to create the priority symlink from the conf.d directory to the mods-available directory xhprof.ini file.  Another way to check if xhprof is enabled is to run `php5-fpm -i | grep xhprof`, replacing php5-fpm with whatever SAPI you're checking.
Comment: Just wanted to point out that the symlink command is misprinted in Dominic Woodman's answer. ls -s /usr/share/php/xhprof_html /var/www/xhprof should be: ln -s /usr/share/php/xhprof_html /var/www/xhprof_html i.e. replace "ls" with "ln" and "/var/www/xhprof" with "/var/www/xhprof_html" to be consistent with suggested Devel settings path.
Comment: adding entry in `/etc/php5/apache2/php.ini` and checking with `php -m` won't work on Ubuntu as you are checking with `cli` and have not made entry in `/etc/php5/cli/php.ini` - best to make both
Comment: Impressive answer (and interesting question)! There are people on Drupal.SE who don't like loooooooong / detailed answers, but "I" do like them ... PS: welcome also to the land of +1K ...
Comment: For which version of PHP did you install it? I have PHP 5.4 but it complains that the module was compiled for the earlier version. Any idea how to fix this?
`PHP Warning:  PHP Startup: xhprof: Unable to initialize module
Module compiled with module API=20090626
PHP    compiled with module API=20100525
`

Install and Configure XHProf (Ubuntu)


Using views to display complex content

Question: I am using Drupal 8 to build a little complex website. Here is an example of what the content is like:
Content Types: Books, Chapters, Paragraphs
For instance a book content type would contain fields to hold author, cover pic, etc. then the chapter will have a link to the related book, and paragraphs will have links to its related chapter and an ordering number.
Now I'd like to have the website to have pages as following:

/books - will show all books by cover photo with links to go to the contents
/books/<book-name> - will show info about a specific book with list of chapters each with a link to go to the content of that chapter
/books/<book-name>/<chapter-number> - Will show all paragraphs in that chapter

My question is can this be achieved just by the view module that is installed with d8 vanilla?
Can I achieve all of this with one view? If multiple views are needed, can they all use the same path structure (/books is common in that case)?
Answer: Yes this can be achieved by using views module. And the structure should go something like:
a. Content Type Book.
b. Content Type Chapter.
Now chapter CT will have node references field of CT Book.
Create a view of books content type which will show all books then create a page within same view with some changed filters to show /books/book-name.
Now create another view  with link /books/book-name/chapter-number where book-name will match the node reference field or /books/book-name/ from previous view to get book name.
Comment: Regarding the last sentence, create another view with link /books/book-name/chapter-number, does it mean to create a view for each book?
Comment: No it means create a single view dynamically by getting bookname from contextual filters and convert it to node id
Comment: How would Drupal pick the correct view/page when the url `/books` is requested? I mean I am yet to try it but just wondering
Comment: you have to define a path i.e. when you create a view with page option under page settings there is an option called path, where you can define your views path for ex; books, books/% where % is wildcard.

Using views to display complex content


Calculate the probability of observing n elements in m draws from an uneven frequency distribution, in order but consecutive or not

Question: I want to calculate the probability to observe a certain sequence of n elements in order, but not necessarily consecutively, after drawing m times from an uneven frequency distribution.
For example:
Frequency distribution:
A- 0.5 B- 0.4 C- 0.05 D-0.05
What's the probability to observe the sequence 'AAA' if you draw 10 times from this distribution? A good draw could have consecutive A's or not (AAACCCCCCC or ACCCCACCCA are both valid). What about ACB?
The goal is to filter out matches that are too common and short from sequence alignment. For example, aligning AAA with ABCABCACBCBC does not mean much as the A's are frequent in the distribution.
One extra problem is that simulation approaches are not possible here, as I have multiple millions of such comparisons to score.
Answer: You can write a dynamic program to compute these values in time proportional to the length of the probe string and the number of draws.
For a probe string $s=s_1s_2\cdots s_k$ where letter $s_i$ has probability $p_i$, let $f(s,m)$ be the desired probability. Drawing from the distribution, considering the chance that the first letter in the target matches $s_1$, and writing $s^\prime=s_2s_3\cdots s_k$ for the suffix, it is immediate that $$f(s,m)=p_1f(s^\prime,m-1)+(1-p_1)f(s,m-1).$$ For initial conditions use $f(s,0)=0$ for nonempty $s$ and $f(s, n)=1$ for empty $s$.
The calculations are rapid.
Examples: $f(AAA,10) = 121/128$ and $f(ABC,10)=1247150641/5120000000.$

Here is working R code to illustrate.
f <- function(p, n) {
  p <- rev(p)
  k <- length(p)
  a <- rbind(1, matrix(0, k, n+1))
  for (i in 1:k) {
    for (j in i:n+1)
      a[i+1, j] <- p[i] * a[i, j-1] + (1-p[i]) * a[i+1, j-1]
  }
  return(a[k+1, n+1])
}

For example,
a <- .5; b <- 0.4; c <- 0.05; d <- 0.05
f(c(a,a,a), 10)

[1] 0.9453125

print(f(c(a,c,b), 10), digits=16)

[1]  0.2435841095703125

For symbolic solutions, here is working Mathematica code:
f[x_, n_] := f[x, n] = Expand[x [[1]] f[Rest@x, n - 1] + (1 - x [[1]]) f[x, n - 1]];
f[x_, 0] /; Length[x] > 0 := 0;
f[{}, n_] /; n >= 0 = 1;

For example,
f[{a,b,c}, 5]

$a^3 b c+a^2 b^2 c+a^2 b c^2-5 a^2 b c+a b^3 c+a b^2 c^2-5 a b^2 c+a b c^3-5 a b c^2+10 a b c$

f[{a,b,c}, 10] //Length

120

(The general answer is a polynomial with 120 terms.)
f[{10, 8, 1}/20, 10]

$ \frac{1247150641}{5120000000}$

N[f[{10, 8, 1}/20, 10], 16]

$0.2435841095703125$

(This agrees with the R solution above.)


Formula to identify invisible sheets

Question: I have the following simple Excel spreadsheet:
        A
1    Sheet1    =MID(CELL("filename",Sheet1!K1),FIND("]",CELL("filename",Sheet1!K1))+1,255)
2    Sheet2    =MID(CELL("filename",Sheet2!K1),FIND("]",CELL("filename",Sheet2!K1))+1,255)
3    Sheet3    =MID(CELL("filename",Sheet3!K1),FIND("]",CELL("filename",Sheet3!K1))+1,255)
4    Sheet4    =MID(CELL("filename",Sheet4!K1),FIND("]",CELL("filename",Sheet4!K1))+1,255)
5    Sheet5    =MID(CELL("filename",Sheet5!K1),FIND("]",CELL("filename",Sheet5!K1))+1,255)
6
7

In Column A there is a list of all sheets in the Excel file.  I list the sheets using the formula that you can see next to it.
All this works fine so far.

Now it can happen that some sheets in my spreadsheet are invisible (hidden). In this case I want that those sheets do not appear in the list above. Therefore, I wonder if there is a formula that can identify if a sheet is visible or not. Something like this:
IF MID(CELL("filename",Sheet1!K1),FIND("]",CELL("filename",Sheet1!K1))+1,255) = Invisible THEN ""

Do you have any idea how to solve this issue?
Comment: Sounds like you need a pair of Workbook_SheetActivate and Workbook_SheetDeactivate sub procedures.
Answer: I don't really understand the purpose of this list... it seems like you're just duplicating the list of worksheet "tabs" shown at the bottom of the screen.
I sense something being made more complicated than necessary; either an XY Problem, or some duplicate data that you're trying to manage without reorganizing it. :-)
Regardless, based on my understanding of your question, there are no built-in functions to do what you need, but these VBA examples should give you some ideas:
This procedure lists all visible worksheets, in the Immediate Window (Hit Ctrl+G from VBA to view it):
Sub ListSheets()  'list in immediate window
    Dim sht As Worksheet
    For Each sht In Worksheets
        If sht.Visible = xlSheetVisible Then Debug.Print sht.Name
    Next sht
End Sub

This procedure is similar excep lists them on the active worksheet, leaving blanks for hidden sheets (like your example would imply):
Sub ListSheets()  'list on worksheet
    Dim sht As Worksheet
    For Each sht In Worksheets
        If sht.Visible = xlSheetVisible Then Range("A" & sht.Index) = sht.Name
    Next sht
End Sub

This function can be called from a worksheet formula and lists the name of the worksheet you specify by index number. It returns "" (empty string/nothing) if the worksheet is not set to Visible, or if it doesn't exist.
Function listSheet(shtNum As Long) As String
    On Error Resume Next
    If Sheets(shtNum).Visible = xlSheetVisible Then listSheet = Sheets(shtNum).Name
End Function

Related note:
There are three types of worksheet visibility.

More Info:

MSDN: Worksheet.Visible Property (Excel)
Comment: Hi ashleedawg, thanks a lot for help. Exactly, what I was looking for.

Formula to identify invisible sheets


Find maximum element in an RDD in Pyspark by using map/filter

Question: a = sc.parallelize((1,9,3,10))

I want to find the maximum element in a without using any max function.
I tried
    a.filter( lambda x,y: x if x>y else y)
I am not able to compare elements in the RDD. How do I use for loop or if else condition properly in the map/filter function. Is it possible?
Thank you.
I was trying to post a different question. But not able to.
a = sc.parallelize((11,7,20,10,1,7))

I want to sort the elements in increasing order without using sort() function.
I tried:
def srt(a,b):
if a>b:
    i=a
    a=b
    b=i

final=a.map(lambda x,y: srt(x,y))

I am not getting the required result.
I want to get
  (1,7,7,10,11,20)

thank you.
Answer: You cannot find the max/min using filters. You may achieve that using comparison in a reduce operation:
a = sc.parallelize([1,9,3,10])
max_val = a.reduce(lambda a, b: a if a > b else b)

The lambda just compares and returns the bigger of 2 values.
Comment: Would you please post that on a different question? That would help with search results.
Comment: Thank you.

I just have one more query. Is is possible to incorporate a for loop in the reduce/map/filter function
Comment: You can declare a function `func` that does whatever you want, and you can have any kind of control flow in it. Then you can replace the lambda expression above with the function name. In the case of this reduce, your function will have to take 2 parameters (just as the lambda does).
Comment: Thank you. If you don't mind, I have one more query. I have updated the question. I was trying to sort the elements in an RDD without using the sort() function. But its not working. Thank you.
Comment: Okay. Sorry. I will do that. Its just I have to wait for 90 minutes to post the next question. Thanks.


php - Simple HTML dom - elements between other elements

Question: I'm trying to write a php script to crawl a website and keep some elements in data base.
Here is my problem : A web page is written like this :

The title 1

 Some text

 Some interesting text

The title 2

 Some text

 Some interesting text

 Some different text

 Some other interesting text

The title 3

 Some text

 Some interesting text

I want to get only the h2 and p with interesting text, not the p class="one_class".
I tried this php code :
<?php
$numberP = 0;
foreach($html->find('p') as $p)
{
    $pIsOneClass = PIsOneClass($html, $p);

    if($pIsOneClass == false)
    {
        echo $p->outertext;
                $h2 = $html->find("h2", $numberP);
                echo $h2->outertext;
                $numberP++;
        }

}
?>

the function PIsOneClass($html, $p) is :
<?php
function PIsOneClass($html, $p)
{
foreach($html->find("p.one_class") as $p_one_class)
    {
        if($p ==  $p_one_class)
        {
            return true;
        }
    }
    return false;
}
?>

It doesn't work, i understand why but i don't know how to resolve it.
How can we say "I want every p without class who are between two h2 ?"
Thx a lot !
Comment: If they're all `p.one_class`, why not look for those `p` tags and remove them before outputting your result for save?
Comment: But how can I order the h2 and the p ? With this script, it print h2 p h2 p h2 p but i want something like h2 p p h2 p
Answer: From the  simpleHTML dom manual
[attribute=value]

Matches elements that have the specified attribute with a certain value.
or
[!attribute]

Matches elements that don't have the specified attribute.
Answer: This task is easier with XPath, since you're scraping more than one element and you want to keep the source in order. You can use PHP's DOM library, which includes DOMXPath, to find and filter the elements you want:
$html = '
The title 1

 Some text

 Some interesting text

The title 2

 Some text

 Some interesting text

 Some different text

 Some other interesting text

The title 3

 Some text

 Some interesting text
';

# create a new DOM document and load the html
$dom = new DOMDocument;
$dom->loadHTML($html);
# create a new DOMXPath object
$xp = new DOMXPath($dom);

# search for all h2 elements and all p elements that do not have the class 'one_class'
$interest = $xp->query('//h2 | //p[not(@class="one_class")]');

# iterate through the array of search results (h2 and p elements), printing out node
# names and values
foreach ($interest as $i) {
    echo "node " . $i->nodeName . ", value: " . $i->nodeValue . PHP_EOL;
}

Output:
node h2, value: The title 1
node p, value:  Some interesting text
node h2, value: The title 2
node p, value:  Some interesting text
node p, value:  Some other interesting text
node h2, value: The title 3
node p, value:  Some interesting text

As you can see, the source text stays in order, and it's easy to eliminate the nodes you don't want.
Comment: Thank you, i didn't know that exist. Is it possible to use Simple Html Dom at the same time or is it useless ?
Comment: You can't do XPath operations with Simple HTML DOM, but you could output the HTML from DOMDocument and then read it in with SHD. You should be able to do everything you want with DOM, though -- it's a very comprehensive library for handling XML. [Here's the manual](http://php.net/manual/en/book.dom.php).


SQL Data manipulation - window functions and complicated joins likely

Question: Streaming Video data (event type with timestamp) to source and target using device.

select
r1.customer_id,
'Play on ' || (r1.device) as source,
'Play on ' || lead(r2.device,1) OVER(PARTITION BY r2.customer_id ORDER BY
r2.time::timestamp ASC) as target
from streaming r1
left join streaming r2 on r1.customer_id=r2.customer_id

This query above is giving me 8*8 = 64 rows, but I need 8 (Like the pic above), any help would be appreciated
*using PostgreSQL
Answer: Why are you doing a self-join?  The results seem to only want lag():
select s.customer_id,
       lag(s.device) over (partition by s.customer_id order by s.time) as source,
       s.device as target,
from streaming s;

Comment: Thanks, this worked. I was thinking about a lesson from self join, how when data you're referring to is in the same dataset, you'd use self join
Comment: @Si_CPyR . . . Window functions are quite powerful and can often replace self-joins.


API Authentication using OAuth help needed

Question: Background: I am trying to create an SMS API service. The developers have a Dev ID, and an API secret key assigned to their developer account. The developers will be creating apps which will issue calls to my API. But the application issuing the call must be verified first.
Issue: The main issue i have is with authentication. I read up on OAuth and pretty much uderstood it. I read through this presentation (Slide 71-82). All OAuth articles talk about the OAuth 'dance' or the 'love triangle'. My problem seems to be, that i dont see a proper triangle in my case. Or, a better way to put it would be, the triangle doesn't seem to be complete.
What i mean by that is, in the case of lets say, LinkedIn, trying to make some app which helps users associate their LinkedIn acc with twitter, OAuth makes complete sense. Because LinkedIn needs to get resources from twitter ON THE USERS BEHALF (Cuz the user HAS A TWITTER ACCOUNT). In my case, only the consumer has a developer account registered with my service. The end-user doesn't have any credentials for the consumer to ask on behalf of. So how can i implement Oauth? So what will the consumer ask the provider? Will it only state that "watch out, here i come?". Cuz that seems pretty pointless unless its asking for a request token in exchange for an access token. But in this case since the end user doesnt even have an account, the steps seem useless.
So, i cant figure out how to go about this authentication issue. Ive tried thinking about using php sessions so it can help me associate a token with the particular client who is using the API. But the REST/OAUTH purists seem to disagree on the usage of sessions in authentication. They claim that OAuth is a standard which has proven itself and that is what I should use instead of coming up with my own obscure schemes.
Comment: sorry about adding the PHP in the title...
Answer: From your description it seem that you're in a two party scenario only (developers write code which accesses your API on their own behalf, not on behalf of an end-user), so that means indeed that doing the full 3-legged oAuth scenario isn't needed.
You could use pretty much any authentication scheme and that would work (API Keys, other oAuth grant types [see below] or even ID/Secret combinations. In the oAuth world:

Look at the other oAuth 2.0 Grant types: especially resource owner PW grants - https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-26#section-4.3. It's slightly better than username-password because the PW isn't passed across the channel all the time (it passes once though) and it assumes the developer writing the code is the owner of the credentials.

Look at oAuth v1.0: this different in various ways to v2.0 but one feature it does have which some people like is the way tokens are used - which is rather than being passed across the wire they are used to generate a hash in the client and then the hash is verified on the server side. It's more expensive and complex than checking a key but it's less prone to attack.

In the non-oAuth world, if it's primarily a server resource used by developers directly, an ID/Secret or API-Key pattern is probably more than sufficient and it's much easier to implement for your developers.
Re: oAuth - if you're doing any type of user auth then definitely stick with the standard - the stuff is complex and having libraries out there really helps. If it's developer-api you likely don't need to go that far.
If you want the API to be secure in an ideal world anything which requires the security token to pass across the gaps should be secured using SSL, especially if that client code could be running on a mobile device or laptop which might communicate over wireless. If this isn't the case, someone could jump in an copy a token from one of the devs.
The only one of the protocols above that avoids this is the oAuth 1.0 variation since the secret never leaves the client but is used to hash instead. But it's complex. Last one to look at is the Amazon AWS pattern which does hashing similar to oAuth 1.0 http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html and people emulate quite a bit.
Comment: thanks for the response! thats a lot to consider for me.. ill read up on wht youve mentioned and get back to you. Thanks again!


Can one compare Hazard Ratio and Average Hazard Ratio?

Question: I would like to compare three predictors of survival by comparing three cox regression models.
One model violates the PH assumption which brought me to weighted cox regression as implemented by coxphw package by Dunkler, Ploner, Schemper and Heinze (2018).
However, I was wondering whether one can compare Hazard Ratios from cox proportional hazard models and average Hazard Ratios from cox weighted hazard models (i.e. "predictor a was associated with a greater risk of ... (HR = ...) than predictor b (AHR = ...").
Edit:
Following the sugesstion of @EdM, I elaborate my plans.

The goal is to evaluate the predictive power of three predictors for occurence of a specific disease (i.e. baseline test A, a novel baseline test B and a combination of these C).
Three different models are to be set up in order to adjust for covariates. I would like to establish a statement like "Predictor C was associated with a greater risk of occurence of the disease than Predictor A and B (HR A = ; HR B = ...)".
However, one model does not meet the PH assumption (mainly due to predictor B, which is categorical), this led me to weighted cox regression and to the question whether one can just compare averaged HR with HR obtained by proportional hazards cox regression. Or is this like comparing apples and pears?
Comment: Could you please say more about what you mean by "comparing three Cox regression models"? Are you evaluating 3 predictors separately, or are you using the same predictors but including interactions, nonlinear transformations, etc differently among the models? Please provide that information by editing the question, as comments are easy to overlook and can get deleted.
Comment: @EdM, I edited my post, hope this can shed light on my question
Answer: This type of model comparison might actually be leading to your apparent loss of proportional hazards (PH).
There are problems when you omit any outcome-associated predictor from a Cox model, as there are in logistic regression. At the least, that can lead to bias in the coefficient estimates of the retained predictors. The situation can get exacerbated in Cox models evaluating events over time, particularly if predictors are correlated.
Say, for example, that your predictor A is associated with a faster development of disease than is predictor B while A and B are associated with each other. Then if you omit A from a model that still contains B, those with the A marker will preferentially develop disease at earlier times and be lost from the risk set at later times. So in a model that omits A it might seem that the association of B with outcome decreases over time as the higher-risk cases (marked by A) leave the risk set: an apparent loss of PH. If you keep A in your model, the model can take the A status into account and you might find that the combination of A and B maintains PH adequately.
In general, the more outcome-associated predictors you include in your model without overfitting, the better predictive performance will be. As your predictor C is the combination of A and B, one would expect the C model to be superior.
Comparing hazard ratios (HRs), however, is not the best way to compare models. HRs tell you how quickly the disease develops on average, but they don't necessarily demonstrate the model's overall ability to discriminate event times among cases or to reliably gauge the probability of disease development by any given time. You might, for example, have a predictor that works very well with a large HR on a small subset of cases but doesn't work well over the entire population of interest.
Provided that the models are fit to the same data set, overall model comparison can be done by anova() for nested models, or by the Akaike Information Criterion (AIC). There are tools for evaluating Cox model discrimination and calibration in, for example, the rms package in R.
If PH doesn't hold, then there aren't well-defined HRs in any event--they necessarily change over time. Without PH, comparisons among HRs thus make even less sense. The best way to proceed to to grapple directly with PH, as the lack of proportionality might be of substantive interest. For example, use time-varying coefficients, as explained in the R survival package time-dependence vignette. Something as simple as a step function could both solve the PH problem and indicate different associations of a marker with earlier versus later events. Or try an accelerated failure time model that doesn't follow PH, like a log-normal or log-logistic model.
If you nevertheless still want to compare HRs among Cox models that don't meet PH, then you have to choose what type of "average" HR you want to compare. Absent PH, the standard Cox model provides a type of event-averaged HR. That average thus depends on the distributions of event and censoring times. The weighting procedures in coxphw try to to provide more of a time-averaged HR less dependent on the specific event and censoring times. According to the article describing the package, the procedures

weight the contributions of each event time to the partial likelihood according to the product of the survivor function and the inverse cumulative probability of follow-up at that time.

Absent PH, however, those HR values from coxphw aren't time-constant HRs in the sense envisioned in a Cox model. Those HR values can be interpreted in terms of odds of concordance, a useful measure of a single model's performance, but concordance is not sensitive for distinguishing among models. That continues to argue against using HR values to compare among models.
Absent PH, comparing HRs between standard Cox models and those from coxphw is "comparing apples to pears," as you fear. So choose one or the other type of model for such comparisons. If all models are fit on the same data, my sense is that the coxphw correction will be similar for all models, so that inter-model comparisons should be similar with either standard or coxphw models even if the absolute HR values differ between those model types. One might argue that the coxphw approach for all models will be the most generally reliable, but I have no practical experience with it.
Comment: Thanks for your elaborate answer, @EdM. Since the violating variable does not change over time bc it refers to a baseline category (to be more exact, the df consists of one row per subject, i.e. one observation per subject) I applied a step function as described in the vignette by Therneau et al. This yielded convergence warnings, huge coefficients and NA values.  Applying accelerated failure time models (weibull dist) worked out but gave out higher AIC values in all 3 models than in Cox models (dif AIC ca. 80).  Would you suggest weighted cox regression for all is therefore the best choice?
Comment: @a.henrietty Look at the plot of smooth scaled Schoenfeld residuals over time from `cox.zph()`. Are the deviations from PH [large enough to matter](https://stats.stackexchange.com/a/61136/28500)?  If they are, try to match the shape over time with a step or a `tt()` function. Convergence warnings for a step model suggest that  data weren't reformatted properly with `survSplit()` to match the step time. Check that. I'm not sure that AIC values are comparable between Cox and AFT models. Examine model validation and calibration. I see weighted Cox as a last resort.
Comment: @a.henrietty Just noticed that you tried a Weibull for your AFT model. Weibull is the only distribution family that is both AFT and PH. So if PH isn't working for your Cox model it won't work for a Weibull parametric model either. Try non-PH AFT models like log-normal or log-logistic. For AIC comparison, see my [answer](https://stats.stackexchange.com/a/533694/28500) to your related question. I suspect that the AIC values from partial-likelihood Cox models can't be compared directly against those from full-likelihood parametric models, but I'm not completely sure.


Validating residual plot count data (different levels)

Question: I am studying the distribution of a marine species using the number of sightings as a dependent variable. When I am trying to validate the plots of the best model I am getting a non-usual pattern, and then I decided to get the null model with different distributions, and I don't know what is causing the different levels on the residuals vs fitted values.

null<-glm.nb(Sightings~offset(logEffortScale),data=l, link=log)

null<-glm.nb(Sightings~offset(logEffortScale),data=l, link=log)

plot(residuals(null)~predict(null))

Edit: correct residuals vs predicted plot
plot(residuals(null)~predict(null,type="response"))

m1 <- zeroinfl(Sightings ~ offset(logEffortScale), data = l)

m1b <- zeroinfl(Sightings ~ offset(logEffortScale), data = l, dist = "negbin")

m2 <- zeroinfl(Sightings ~ offset(logEffortScale), data = l, dist='poisson', link='logit')

Comment: What's the difficulty? Are you concerned about the curved lines in the residual plot? That's a natural consequence of the discrete data and the model you're fitting.
Comment: My doubt is if I can use this model output as a good model, and if this lines have any consequence on the final output. And if the negative binomial will be a good option for this type of data. Thanks
Comment: I am not sure how to be plainer. Try this: It looks pretty much like *exactly what you'd expect to see*, if the data were negative binomial. What did you think it should look like?
Comment: I wasn't sure if the lines of the residuals vs fitted values were correct. I added a plot residuals vs predicted values where I got the same lines with many negative predicted values, are these values correct? could I accept this? thanks!
Comment: With the one with negative predicted values *what was the actual model*? Can you show how this was obtained?
Comment: I updated the question; the actual model was the null model (null<-glm.nb(Sightings~offset(logEffortScale),data=l, link=log)) and the code for the plot was (plot(residuals(null)~predict(null)))
Comment: Ah. You're not getting what you imagine you're getting. See `?predict.glm` which explains that the default for the `type` argument is predictions on the scale of the linear predictor, not the observations. The linear predictor can easily be negative. Try `type="response"` in your call to `predict` ...
Comment: Thanks Glen_b, I didn't know that. I updated the final plot, and it looks much nicer.
Comment: The R package DHARMa will help you make more interpretable plots: https://cran.r-project.org/web/packages/DHARMa/index.html > The 'DHARMa' package uses a simulation-based approach to create
> readily interpretable scaled (quantile) residuals for fitted
> generalized linear mixed models.
Answer: This sort of pattern is to be expected with count data and log-links. The count data makes the residual vs fitted plot have "lines" diagonally across it (and gaps between), corresponding to counts of 0, 1, 2,... and the log-link makes those "lines" curved.
So you will expect to see this with Poisson and negative binomial regression and log links if the typical count is fairly small, in particular with simple models (such as say one continuous predictor, or one continuous predictor and a factor with few levels).
So nothing seems to be amiss, at least not from the appearance of the plots.


How to guide user through multiple unrelated forms

Question: I have a content type with a term reference field. I want to give user a convenient way of grouping multiple nodes of that type together. I see it like this:

The user creates a first node
When he goes to a node page, he sees a link "subjoin another document"
After pressing it the taxonomy term creation form is shown, user fills required fields
After saving the term he gets redirected to node creation form
Second node is created, taxonomy term fields of both nodes point to newly created taxonomy term

What puzzles me is how it's best to implement such a multiphase logic in Drupal, when we need to guide the user through several unrelated forms.
Answer: I'm not sure, but you might find References and Relation module useful for this.
Comment: Completely forgot about the relation module! Many thanks. I see there is great progress since last spring. Will try to adapt a relation-select module, it's demonstrated in this great screencast: http://dev.nodeone.se/en/relation-select
Answer: In the end I implemented this functionality in a custom module. Together with prepopulate it allows to conveniently link nodes together without manually creating taxonomy terms.

function mymodule_menu() {
  $items = array();
  $items['continue_with/%/%'] = array(
    'title' => 'Continue with',
    'description' => 'Creates new story and links existent material to it',
    'page callback' => 'vidsboku_custom_continue_with',
    'page arguments' => array(1,2),
    'access callback' => true,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_continue_with($content_type, $nid) {
  $existing = node_load($nid);

  if(!is_object($existing)) {
    drupal_goto("");
  }

  if (empty($existing->field_story)) {
    if (!node_access('update', $existing)  || !(user_access('administer taxonomy') || user_access('edit terms in 4'))) {
      drupal_set_message('Insufficient permissions','error');
      drupal_goto("");
      return;
    }

    $term = new stdClass();
    $term->vid = 4; // Vocabulary ID for Story
    $term->name = $existing->title; // Term Name

    taxonomy_term_save($term);
    $tid = $term->tid;

    $existing->field_story = array('und' => array(0 => array('tid' => $tid)));
    node_save($existing);
  } else
    $tid = $existing->field_story['und'][0]['tid'];

  drupal_goto('node/add/' . $content_type, array('query' =>
                                                  array('edit[field_story][und]' => $tid)));
}


How to animate a tabbarbutton image

Question: I have a toolBarItem which calls a save action on a database. I would really much like to change the image of the item (a cabinet) dynamically so that a drawer opens, a label is animated "inside" and then it closes. Very much like the trash item on the mail app animation.
I know how to make a UIView pop-up by scaling it up and down on an animation on a given times given in an array (together with an array of CT scale), so I'm guessing it could be done more or less the same way.
Does anyone know about an example of who to accomplish that?. Back on xcode 4.1 i was able to highlight the button while the label was moving, but I cannot do that anymore (somehow I did add a normal button on the toolbarItem, which I cannot do anymore).
Thanks in advance!
Answer: well, if somebody is having the same issue here is how it can be done:
<code>- (IBAction)barButtonAction:(UIBarButtonItem *)sender {

    NSArray *frameArray=[NSArray arrayWithObjects:[UIImage imageNamed:@"01-refresh.png"], [UIImage imageNamed:@"02-redo.png"], [UIImage imageNamed:@"03-loopback.png"], [UIImage imageNamed:@"03-loopback.png"],[UIImage imageNamed:@"03-loopback.png"],[UIImage imageNamed:@"03-loopback.png"],[UIImage imageNamed:@"03-loopback.png"],[UIImage imageNamed:@"03-loopback.png"], nil];

    self.button.image=[UIImage animatedImageWithImages:frameArray duration:10.0];

}
</code>

How to animate a tabbarbutton image


I have a message: ERROR 1241 (21000): Operand should contain 1 column(s) Mysql

Question:   SELECT *
  FROM tableA
  WHERE  (( typec = "red"
            AND cl = "1er", "2e", "3e", "4e"));

I have a message: ERROR 1241 (21000): Operand should contain 1 column(s) Mysql
Answer: The = operator compares two singular values. If you want to compare a list of values, you can use the in operator:
SELECT *
FROM   tableA
WHERE  typec = 'red' AND
       cl IN ('1er', '2e', '3e', '4e');
-- Here --^


How to configure remote access to SVN

Question: I've installed SVN on my Ubuntu 9.10 server - running on EC2.
What are the options for allowing access to SVN for a set of remote users? I was going down the path of svn+ssh but then does that mean that each user needs to have a user account on the box? If so, can I prevent them from logging onto the system interactively?
Is this any easier/different if I setup SVN access using webdav and apache?
Are there better options I haven't mentioned?
Answer: svn+ssh doesn't mean that everyone needs their own account (use key-based auth to a shared account) and yes, you can stop interactive login by means of the command option to the keys.
It's definitely different if you use webdav, but I wouldn't class it as definitely "easier".  There's some annoying niggles that have to be overcome with webdav, but if you're more familiar with Apache it is probably easier than working out the intricacies of SSH, if you're not familiar with SSH.
Answer: The main options are Apache or svn+ssh. svn+ssh does indeed require local users accounts. It also is more tricky to get permissions right.
I would definitely go the Apache way. With Apache's svn module and broad choice of authentication methods you'll have a flexible solution.
We're very happy with it. It performs well and was easy to set up.
Answer: Yes, svn+ssh requires local accounts but then you don't have to setup svn accounts. We do use svn+ssh with users that already have ssh access to the server so I'm not sure if you could prevent them from login on. If you decide to go that way, take a look here: http://penguinapple.blogspot.com/2010/11/installing-svn-over-ssh-on-debian-and.html. The last section about using keys instead of passwords is particularly important if you don't want your users to go crazy.

How to configure remote access to SVN