Expand a list of variables for each combination of the variables' values

Question: I have variables and the values of the variables as per the table below.

I would like to write code that produces the desired output below. I.e. a single row for each combination of values.
I need code that works for a variable number of variables. In this case there are 3 variables but I need something that works when the user specifies the number of variables and the name/values of each variable.
Comment: 1. can you show us what you tried by yourself? Even where and how you searched for... Then, I cannot understand the logic you try expressing in the example suggesting what you need. What 0 and 1 should be on the "Smoker" variable (which does not have any one between its values - in the definition table). Can you better explain **in words** what you try accomplishing and **based on what logic**? Please, clarify this aspect.
Comment: I don't know where to start. My only idea is to loop through each variable but as I said there will be a a variable number of variables. I can't do a variable number of loops.

I want to produce output for each COMBINATION of the input values. Does the "Desired Output" not explain what I need? Don't worry about the name of the 3 variables - they could be A, B and C.
Comment: You appear to be trying to replicate a "cross-join" or "Cartesian Product". This starting point might help https://superuser.com/questions/106156/how-can-i-create-a-cross-join-in-excel
Comment: Previously: https://stackoverflow.com/questions/19780016/vba-write-all-possible-combinations-of-4-columns-of-data/19780307#19780307
Answer: Please, test the next code and send some feedback. It uses arrays and should be fast enough for reasonable range to be processed. It is able to process as columns you need, up to the CPU processing limitation:
Sub combinations()
  Dim ws As Worksheet, rng As Range, arr2D1(1 To 1, 1 To 1)
  Dim arrCol, arrNo, arrFin, countR As Long, i As Long, j As Long, k As Long

  Set ws = ActiveSheet
  Set rng = ws.Range("B2:D5") 'it may contain a bigger (variable)  number of columns...

  ReDim arrCol(rng.Columns.count - 1)
  ReDim arrNo(UBound(arrCol))

  For i = 1 To rng.Columns.count
    'place each column content as a 2D array, in an array:
    If Application.CountA(rng.Columns(i)) = 1 Then 'for only one value in the column first cell:
        arr2D1(1, 1) = rng.Columns(i).cells(1).Value: arrCol(i - 1) = arr2D1
        arrNo(i - 1) = 1
    Else
        arrCol(i - 1) = ws.Range(rng.Columns(i).cells(1), rng.Columns(i).cells(1).End(xlDown)).Value
        arrNo(i - 1) = UBound(arrCol(i - 1))  'place in another array each column number of rows
    End If

    countR = IIf(countR = 0, arrNo(i - 1), countR * arrNo(i - 1)) 'calculate the necessary total number of rows of the array to return
  Next i

  ReDim arrFin(1 To countR, 1 To rng.Columns.count) 'redim the array to return

  Dim noRep As Long        'number of each value repeating per each column
  Dim multipliedNo As Long 'cummulated previous columns numbers to repeat
  Dim cummulatedNo As Long 'cummulated previous columns arrays elements
  Dim m As Long, c As Long, ii As Long

        j = 1  'initialize the columns variable
        For j = 1 To UBound(arrCol) + 1 'Iterate between the 2D array elements of arrCol
                multipliedNo = 1: cummulatedNo = 0 '(re)initialize the variables
                For m = 1 To UBound(arrFin, 2) 'iterate between the columns
                    multipliedNo = multipliedNo * arrNo(m - 1) 'multiplies the number of arrays/columns elements UP TO the processed column
                    noRep = countR / multipliedNo              'number of repetition for each element of the processed column
                    If m > 1 Then cummulatedNo = IIf(cummulatedNo = 0, arrNo(m - 2), cummulatedNo * arrNo(m - 2)) 'number of global repetition per column
                    If m = j Then Exit For 'cummulate only up to the present column...
                Next m

                c = 1 'initialize the final array rows variable
                For ii = 1 To IIf(j = 1, 1, cummulatedNo)     'global repetitions
                    For i = 1 To UBound(arrCol(j - 1))        'iterate between the column (array) elements
                        For k = 1 To noRep                    'repeat the same element from noRep times
                            arrFin(c, j) = arrCol(j - 1)(i, 1)'place the necessary value on processed column
                            c = c + 1
                        Next k
                    Next i
                Next ii
        Next j

        'drop the process result array, at once:
        Range("I2").Resize(UBound(arrFin), UBound(arrFin, 2)).Value = arrFin

End Sub

I think (now) it is not prepared for the case of only one element per column, which will not be placed in an array, but this can be solved after you confirm that it works as you need.
Please, send some feedback after testing it.
Comment: Thanks! I don't really know how, but this seems to do the job for my data.
Comment: @Zain Glad I could help! Yes, it does not follow the classic algorithm of calculating the combinations on rows. It calculates the necessary repetitions of each column element, of each group and so on. I will place a version better commented...
Comment: @Zain Adapted the code to also process the columns containing only one value in the first cell of the column...
Answer: I realised that the need to cater for a variable number of variables would make this quite complicated, so I had a go at it in my lunch break.
The following is a complete solution - but it is not tidy!! It also cannot be re-run - if you want to re-run it you have to convert all the tables back to Ranges and delete the Power Queries that have been created.
I've included a couple of my standard helper functions too.
Public Sub SetUpTablesForCrossJoin()

    Dim lastColumn As Long, thisColumn As Long, lastRowNo As Long
    Dim rng As Range, rng1 As Range
    lastColumn = lastCol(shtUserData)

    'I used your data, so 1st Column just says "Values" and 1st Row is "Variable Name"

    For thisColumn = 2 To lastColumn
        Set rng = shtUserData.Columns(thisColumn)
        lastRowNo = lastRow(rng)
        Set rng1 = Range(rng.Cells(1), rng.Cells(lastRowNo))

        'Turn each of the data sets into Excel Tables
        shtUserData.ListObjects.Add(xlSrcRange, rng1, , xlYes).Name = "Table" & CStr(thisColumn - 1)
    Next

    'Now turn each of those tables into a Power Query
    Dim PQName As String, colHeader As String
    For thisColumn = 2 To lastColumn
        PQName = "Table" & CStr(thisColumn - 1)
        colHeader = shtUserData.ListObjects(PQName).HeaderRowRange(1, 1)

        ThisWorkbook.Queries.Add Name:=PQName, Formula:= _
            "let Source = Excel.CurrentWorkbook(){[Name=" & Chr(34) & PQName & Chr(34) & "]}[Content], #""Changed Type"" = " & _
                    "Table.TransformColumnTypes(Source,{{""" & colHeader & """, type text}}) in #""Changed Type"""
        ThisWorkbook.Connections.Add2 "Query - " & PQName, _
            "Connection to the '" & PQName & "' query in the workbook.", _
            "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & PQName & ";Extended Properties=""""" _
            , "SELECT * FROM [" & PQName & "]", 2
    Next

    'Now use Power Query to Cross join them all
    Dim lfcr As String: lfcr = lfcr
    Dim queryFormula As String, addTable As String, expandTable As String

    queryFormula = "let" & lfcr & "    Source = Table1" & lfcr
    addTable = "    ,#""Added Custom%s"" = Table.AddColumn(%s, ""Custom"", each %s)"
    expandTable = "    ,#""Expanded Custom%s"" = Table.ExpandTableColumn(#""%s"", ""Custom"", {""%s""}, {""%s""})"

    Dim prevstep As String, prevstep1 As String
    For thisColumn = 2 To lastColumn - 1    'N.B. We've already captured Table1
        PQName = "Table" & CStr(thisColumn)
        colHeader = shtUserData.ListObjects(PQName).HeaderRowRange(1, 1)
        prevstep = IIf(thisColumn = 2, "Source", sPrintf("#""Expanded Custom%s""", thisColumn - 2))
        prevstep1 = sPrintf("Added Custom%s", thisColumn - 1)

        queryFormula = queryFormula & sPrintf(addTable, thisColumn - 1, prevstep, PQName) & _
                lfcr & sPrintf(expandTable, thisColumn - 1, prevstep1, colHeader, colHeader) & lfcr
    Next
    queryFormula = queryFormula & " in" & lfcr & sPrintf("    #""Expanded Custom%s""", thisColumn - 2)
    ThisWorkbook.Queries.Add Name:="CrossJoin", Formula:=queryFormula

    With shtCrossJoin.ListObjects.Add(SourceType:=0, Source:= _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=CrossJoin;Extended Properties=""""" _
        , Destination:=Range("CrossJoin!$A$1")).QueryTable
        .CommandType = xlCmdSql
        .CommandText = Array("SELECT * FROM [CrossJoin]")
        .ListObject.DisplayName = "CrossJoin"
        .Refresh BackgroundQuery:=False
    End With

End Sub
Public Function lastCol(rg As Variant) As Long
'Find the last column used in a worksheet - regardless of where the data starts and ends
'and regardless of whether the data is contiguous or jagged
'Note use of Variant for the input range parameter
'This allows both worksheets and ranges to passed into the function
    On Error Resume Next
    Dim lc As Long
    lc = rg.Cells.Find(What:="*" _
                    , After:=rg.Cells(1, 1) _
                    , LookAt:=xlPart _
                    , LookIn:=xlFormulas _
                    , SearchOrder:=xlByColumns _
                    , SearchDirection:=xlPrevious).Column

    If Err.Number <> 0 Then
        lc = 1  'cater for a completely empty sheet
    End If
    On Error GoTo 0
    lastCol = lc
End Function
Public Function lastRow(rg As Variant) As Long
'Find the last row used in a worksheet - regardless of where the data starts and ends
'and regardless of whether the data is contiguous or jagged
'Note use of Variant for the input range parameter
'This allows both worksheets and ranges to passed into the function
    On Error Resume Next
    Dim lr As Long
    lr = rg.Cells.Find(What:="*" _
                    , LookAt:=xlPart _
                    , LookIn:=xlFormulas _
                    , SearchOrder:=xlByRows _
                    , SearchDirection:=xlPrevious).Row
    If Err.Number <> 0 Then
        lr = 1  'cater for a completely empty sheet
    End If
    On Error GoTo 0
    lastRow = lr
End Function
Public Function sPrintf(ByVal inputStr As String, ParamArray replaceStrs() As Variant)
'Mimic the C++ sprintf function, replace place holders in a string with an array of values
'This version can handle input strings with %s - the array must be in the correct order
'It also handles the more flexible %1, %2 etc in which case the correct array cell will be used
'Don't be tempted to call this with sPrintf(inputStr, Array("a", "b")) as this will fail.
'Use a single dimension array with sPrintf(inputStr, "a", "b")

    Dim i As Long, res As String, bOld As Boolean, sRep As String

    bOld = IIf(InStr(1, inputStr, "%s", vbBinaryCompare) > 0, True, False)

    res = inputStr

    For i = LBound(replaceStrs) To UBound(replaceStrs)
        sRep = IIf(bOld, "%s", "%" & CStr(i + 1))
        res = Replace(res, sRep, replaceStrs(i), 1, 1, vbBinaryCompare)
    Next

    sPrintf = res

End Function

Basically the code is converting your data into Excel tables so they can be easily queried with Power Query.
It then creates one Connection-only Power Query for each of those tables (aka Variables)
Then it builds a Cross Join power query "on the fly" to merge all of the table queries into one big cartesian product. That bit could definitely do with a tidy up!
Answer: With the Sub below you can create combinations with the column values of any range. Empty cells are not considered valid values, and a column without any valid cells is not considered when creating combinations. I also considered it reasonable that the values of each column should be unique in the column and during preprocessing I create an array of arrays that have unique values. In my example the value "AA" in the first column is considered only once. If you need any further clarification, ask me.
Private Sub CommandButton1_Click()
   Call createCombinations(Me.Range("C5:F9"), Me.Range("G5"))
End Sub

Public Sub createCombinations(source As Range, destCell As Range)
   Dim colArr() As Variant, nrow() As Variant, ipos() As Long, clen() As Long
   Dim clcnt As Long, cntrws As Long, c As Long, nrcntr As Long, cc As Long
   Dim tmp  As Variant, tlb As Long, tub As Long, tclcnt As Long

   clcnt = source.Columns.CountLarge
   ReDim colArr(0 To clcnt - 1)
   ReDim ipos(0 To clcnt - 1)
   ReDim clen(0 To clcnt - 1)
   cntrws = 1

   ' CREATE AN ARRAY OF ARRAYS
   For c = 0 To clcnt - 1
      ' unique data of one column in array
      tmp = ColToUniq1DArray(source.Columns(c + 1))
      tlb = LBound(tmp):  tub = UBound(tmp)
      ' ONLY IF HAVE DATA CONSIDER IN COMBINATION
      If tub >= tlb Then
         ipos(tclcnt) = 0
         colArr(tclcnt) = tmp
         clen(tclcnt) = tub - tlb + 1
         cntrws = cntrws * (clen(tclcnt))
         tclcnt = tclcnt + 1
      End If
   Next
   ' The resulting combinations are the product of the cells in each column
   If tclcnt = 0 Then
      MsgBox ("There is no data to create combinations")
      Exit Sub
   End If
   'Debug.Print "Created rows> " & cntrws & "  Created columns> " & tclcnt

   ' create the output array to hold combinations
   ReDim nrow(1 To cntrws, 1 To tclcnt)
   Do
      ' write combination in array
      nrcntr = nrcntr + 1
      For c = 0 To tclcnt - 1
         nrow(nrcntr, c + 1) = colArr(c)(ipos(c))
      Next

      ' Here is the heart of the algorithm
      ' Increment the index of column by one, AND
      ' reset all indexes of columns to the right to zero
      For c = tclcnt - 1 To 0 Step -1
         If ipos(c) < clen(c) - 1 Then
            ipos(c) = ipos(c) + 1
            For cc = c + 1 To tclcnt - 1
               ipos(cc) = 0
            Next
            GoTo Lnext
         End If
      Next
      ' END OF COMBINATIONs WHEN NO ONE INDEX CAN INCREMENT BY ONE
      Exit Do
Lnext:
   Loop
   If Not destCell Is Nothing Then
      destCell.Resize(UBound(nrow, 1), UBound(nrow, 2)).Value2 = nrow
   End If
End Sub

' HELPER FUNCTION TRANFORM COLUMN TO UNIQUE ARRAY OF VALUES
Public Function ColToUniq1DArray(columnRange As Range) As Variant
   Dim d As Scripting.Dictionary, i As Long, ub As Long, myArray As Variant
   With columnRange
      myArray = Range(columnRange(1), columnRange(.Cells(.rows.CountLarge, columnRange(1).Column).End(xlUp).row)).Value2
   End With
   Set d = CreateObject("Scripting.Dictionary")
   ub = UBound(myArray, 1)
   For i = LBound(myArray, 1) To ub
      If myArray(i, 1) <> vbNullString Then
         d(myArray(i, 1)) = False
      End If
   Next i
   ColToUniq1DArray = d.Keys
   'Set d = Nothing
End Function


Laravel post contact form giving me error 419

Question: I've been trying to get a contact form to display as /contact when using the form, and after submitting the form. I'm getting Error 419 no matter what I seem to try.
I created a resource controller called ContactController to get this to work, but if I use Route::resource I'd be stuck using /contact/create as the actual form.
Here are my contact Routes for now:
//Route::resource('contact', 'ContactController');

Route::post('/contact', 'ContactController@store');

Route::get('/contact', 'ContactController@create');

Here is my contact form:
<form class="form" method="POST">
    @error('name')

{{ $message }}

    @enderror

        Name
        <input type="text" name="name" id="name" class="form-control @error('name') is-invalid @enderror" placeholder="Enter Your Name....">

    @error('email')

{{ $message }}

    @enderror

        Email
        <input type="text" id="email" name="email" class="form-control @error('email') is-invalid @enderror" placeholder="firstname.lastname@example.com">

    @error('subject')

{{ $message }}

    @enderror

        Subject
        <input type="text" id="subject" name="subject" class="form-control @error('subject') is-invalid @enderror" placeholder="What is it you need?">

    @error('content')

{{ $message }}

    @enderror

        Content
        <textarea class="form-control  @error('content') is-invalid @enderror" name="content" id="content" rows="3" placeholder="Tell me more..."></textarea>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

I'm sure there's something I'm doing wrong, so what could it be?
Answer: To prevent cross-site request forgery attacks, Laravel requires CSRF "tokens" to be present in your forms. Change
<form class="form" method="POST">

to
<form class="form" method="POST">
    @csrf

to include a hidden CSRF token field in the form.
https://laravel.com/docs/7.x/csrf
Comment: Love how I checked many different questions, now realizing that somehow I forgot to add it. Thank you.


Derivation of equations in kriging

Question: I have some confusion regarding some derivations of the equations for kriging in the wiki article.  $\newcommand{\Var}{\rm Var}$
It says that kriging error is given by:
\begin{align}
\Sigma_k^2(x_0) &= \Var\big(\hat{Z}(x_0)-Z(x_0)\big)    \tag{1}  \\
                &= E\left(\left(Z(x_0) - \hat{Z}(x_0)\right)^2\right)  \tag{2}  \\
                &= \sum_{i=1}^n\sum_{j=1}^nw_i(x_0)w_j(x_0)c(x_i,x_j) + \Var\big(Z(x_0)\big) - \\
                &\quad\ 2\sum_{i=1}^{n}w_i(x_0)c(x_i,x_0)  \tag{3}
\end{align}
I am confused how the equivalent expression $(3)$ from $(2)$ was derived.
Comment: The exposition in that article is in a logically reversed sequence. If you look further down you will see that the expectation of $\hat{Z}(x_0) - Z(x_0)$ is constrained to $0$, whence the variance (on the right of your first equation) reduces to the expectation of $(\hat{Z}(x_0) - Z(x_0))^2$. At this point, the closely related thread at http://stats.stackexchange.com/questions/30643 should fully answer your question.
Comment: I got it thanks. But my question was how the expression 1 was derived. I mean referring to your article that's fine but how come you get the summations in the expression. I want to know how it is derived
Comment: Well, "derived" means starting from something and proceeding by logical steps. Given that *some* derivation is shown on the Wikipedia page and that (essentially the same) derivation is shown in my answer to that other thread, it's really hard to figure out what kind of answer would be useful to you.  Why don't you indicate (1) where you want to start from and (2) at what step you begin not to follow.  Then we might be able to help you out.
Comment: ok I have mentioned how was expression 3 was derived from 2
Comment: Yes, and I directed you to a step-by-step derivation of expression 3 from expression 2 in an answer to a related question.  At what point in that answer would you like some clarification?
Comment: I found this in your post This, again, is a computation. It relies on the bilinearity and symmetry of covariance, whose application is responsible for the summations in the second line: Actually, I didn't get how the summation part came  when we calculated the expectation of the square of the difference between the predicted and actual value of Z0
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/4094/discussion-between-whuber-and-user34790)
Answer: I read that you are confused about how to arrive at $(3)$ from $(2)$. It is convenient to think in terms of vectors. That is, the Kriging weights $w_i$ can be represented as vector $\mathbf{w}$ and the Kriging estimate can be represented as
$$
\newcommand{\Cov}{\rm Cov}
\newcommand{\E}{\rm E}
\hat{Z}(x_0)=\mathbf{w}^T\mathbf{Z}
$$
where $\mathbf{Z}$ is a vector of observed values and the Kriging weights are defined as $\mathbf{w}^T=\mathbf{\Sigma_0}^T\mathbf{\Sigma}^{-1}$ where $\mathbf{\Sigma}=\Cov[\mathbf{Z},\mathbf{Z}]$ and
$\mathbf{\Sigma_0}=\Cov[\mathbf{Z},Z(x_0)]$. Then, assuming we have a covariance model $$\Cov[Z(x_1),Z(x_2)]=C(\|x_1-x_2\|)=C(r)$$
We can derive the Kriging uncertainty as follows:
\begin{align*}
\E[(Z(x_0)-\hat{Z}(x_0))^2]&=\E[(Z(x_0)-\mathbf{w}^T\mathbf{Z})^2]\\
&=\Cov[Z(x_0)-\mathbf{w}^T\mathbf{Z},Z(x_0)-\mathbf{w}^T\mathbf{Z}]\\
&=\Cov[Z(x_0),Z(x_0)]-2\Cov[\mathbf{w}^T\mathbf{Z},Z(x_0)]+\Cov[\mathbf{w}^T\mathbf{Z},\mathbf{w}^T\mathbf{Z}]\\
&=C(0)-2\mathbf{w}^T\Cov[\mathbf{Z},Z(x_0)]+\mathbf{w}^T\Cov[\mathbf{Z},\mathbf{Z}]\mathbf{w}\\
&=C(0)-2\mathbf{w}^T\mathbf{\Sigma_0}+\mathbf{w}^T\mathbf{\Sigma}\mathbf{w}
\end{align*}
The trickery is in pulling the Kriging weights out of the covariances (look up properties of covariances if those steps are not clear). What you are seeing on Wikipedia is the sum notation for the matrix operations presented above.

Derivation of equations in kriging


Problems Running Cherokee Web Server Admin - config_reader.c:249 - Parsing error

Question: I'm running Cherokee web server 0.99.30 on (Ubuntu Hardy) and I have been having some issues getting the admin to run property.
When I run sudo cherokee-admin -b
Login:
  User:              admin
  One-time Password: {password}

Web Interface:
  URL:               http://localhost:9090/

[20/11/2009 22:57:29.733] (error) config_reader.c:249 - Parsing error
Cherokee Web Server 0.99.30 (Nov 20 2009): Listening on port ALL:9090, TLS
disabled, IPv6 disabled, using epoll, 4096 fds system limit, max. 2041
connections, caching I/O, single thread

When I go to the admin page I get a 503 Service Unavailable error page.
Any idea about how I could fix this?
Thanks
Comment: Does anyone have a real answer to this? Python is already installed.
Answer: It's not documented but the solution is this simple:
apt-get install python
and it'll work.
Answer: Look like you hit a bug. I'd recommend you to recompile the server adding the --enable-trace --enable-backtraces parameters to ./configure and make CFLAGS="-ggdb -O0".
Once you did that, you'd have to execute:

CHEROKEE_TRACE=all cherokee-admin -b

It will print a handful of debug lines then. That's the information the Cherokee web server team would need in order to fix it up. (Additionally, you could send it directly to me, and I'd also take care of it as well.)


C# - how can a constructor be created that takes variables before they are declared?

Question: Based on my question - take the following code:
class Nevermore60Customer: GenericCustomer
{
  public Nevermore60Customer(string name, string referrerName)
  : base (name)
  {
      this.referrerName = referrerName;
  }
  private string referrerName;
  private uint highCostMinutesUsed;

To me, it appears the variable "referrrerName" is being initialized "after" it is being referenced as a passed parameter in the constructor.
public Nevermore60Customer(string name, string referrerName)

Am I worng, and if so how?  Or if I am right and it is being initialized after it is being referenced in the constructor, how is it possible?
Thanks
Answer: The position of the variable declaration compared with the constructor is irrelevant to C#.
It would make this easier to discuss if you had different names for the parameter and field though:
class Test
{
    public Test(string parameter)
    {
        this.field = parameter;
    }

    private string field;
}

Basically the field "exists" before the constructor is called. If the field is declared with an initializer, like this:
private string field = "default value";

then that initializer is run before the constructor, even though it may come after it within the source code.
Comment: Putting a break point on the code that declares your "NeverMore60Customer" class and stepping in using F11 may  help illustrate what's happening here
Answer: The constructor argument is not an alias for the field.  It hides the field name, this code won't work:
public Nevermore60Customer(string name, string referrerName) : base (name)
  {
      referrerName = referrerName;    // bad
  }

By using the "this." prefix, you can tell the compiler to assign the argument value to the field.  It is a very common pattern, avoids having to come up with another name for the argument.  Or do something awkward like prefixing the field name with, say, an underscore.
Answer: Not sure I understand the question. Your constructor has a strign parameter, referrerName, that you are assigning TO a private class variable, also called referrerName. I don't see where this.referrerName is referenced before its initialization?
Answer: this.referrerName refers to the class member declared as private string referrerName;
The referrerName to the right of the = is the parameter to the constructor.
Answer: It doesn't matter how you order the private members of the class and the constructor, the private members will always be initialized first.
Answer: C# is an object oriented language and you seem to confuse plain C procedural language concepts with C#. Unlike C, in C# the order of declaration does not matter as long as the instance is initialized before accessing and is within the scope.
Comment: Well, the order of declaration *can* matter. In particular, initializers are executed in textual order... which becomes ill-defined when you've got a partial class. It's almost always a bug to depend on this of course, but it can make a difference. The position of *methods* (or constructors, or properties etc) makes no defined difference that I'm aware of.
Comment: But they are all initialized and available before the constructor.


Move checkbox label to left on bootstrap custom checkbox

Question: I have a checkbox

   <input type="checkbox"  id="location"  v-model="checkedLocations"   value="location" name="customRadioInline1" class="custom-control-input">
    Option 1

How do I move the label to display on the left? I have tried changing the order but it just breaks the checkbox functionlity.

          Option 2
        <input type="checkbox"  id="location2"  value="location2" name="custom2" class="custom-control-input">

CODEPEN Link to show both examples
Answer: The answers don't seem to work with custom-switch. Here's a working example.
CSS
div.custom-control-right {
    padding-right: 24px;
    padding-left: 0;
    margin-left: 0;
    margin-right: 0;
}
div.custom-control-right .custom-control-label::after{
    right: -1.5rem;
    left: auto;
}
div.custom-control-right .custom-control-label::before {
    right: -2.35rem;
    left: auto;
}

HTML

    <input type="checkbox" class="custom-control-input" disabled id="customSwitch2">
    Right switch element

JsFiddle
https://jsfiddle.net/2cmbq9r0/
Edit: changed left:initial to left:auto to make it work with IE11.
Answer: The checkbox is not the actual <input> (that's hidden). This is done in order to style it consistently cross-browser, cross-device, as that's not currently possible for <input type="checkbox">.
Instead, the ::before pseudo-element of the  is used.
Therefore, you should place a custom class on the wrapper (custom-control-right in the example below) and add some CSS that overrides the default:

div.custom-control-right {
  padding-right: 24px;
  padding-left: 0;
  margin-left: 16px;
  margin-right: 0;
}
div.custom-control-right .custom-control-label::before,
div.custom-control-right .custom-control-label::after{
  right: -1.5rem;
  left: initial;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

        <input type="checkbox"  id="location"     value="location" name="custom1" class="custom-control-input">
        Option 1

         <input type="checkbox"  id="location2"  value="location2" name="custom2" class="custom-control-input">
         Option 2

Note: you can replace div.custom-control-right selector with .custom-control-right, if this code is parsed after you load Bootstrap css. However, on SO, the linked resources are loaded after the code in CSS panel and I had to overqualify the selector in order for it to work.
Comment: My bad, I only tested it on the label text, not on the box. I updated with required selector.
Comment: There is a small space between the checkbox and the label that doesn't trigger a change. But that's intentional and it's how the original one works too. It's intended so that the label text can be selected without triggering a change on it. I decided to keep that. If you don't want it, you need to add some `padding-right` and an equally negative margin to the ``, so it covers the checkbox.
Answer: Try it: Fiddle

    <input type="checkbox" id="location" value="location" name="custom1" class="custom-control-input">
     Option 1

    <input type="checkbox" id="location2" value="location2" name="custom2" class="custom-control-input">
     Option 2

css:
.custom-checkbox {
  padding-left: 0;
}

label.custom-control-label {
  padding-right: 1.5rem;
}

.custom-control-label::before,
.custom-control-label::after {
  right: 0;
  left: auto;
}

Comment: Note this will change all the `custom-checkbox` instances. Note there are specific classes for specific cases (i.e.: `custom-control-inline`). The best approach is to leave the default functionality untouched, so it still works as intended and add new functionality using a custom class, so you can apply it where needed.
Comment: You can create a new class and put the above CSS in it. so that you can use it if needed. example: https://jsfiddle.net/abhineetV/mhrgvkbj/3/


Facebook login/logout/check users in PHP Class powered by PHP-SDK

Question: I have PHP-Class to work with Facebook API:
<code>class Social {
   private $name;
   private $context;
   private $tocken;

   public function check(){
     $this->tocken = $this->context->getAccessToken(); // get current tocken
     if (isset($_SESSION['fb_tocken']) AND !empty($_SESSION['fb_tocken'])){
        // session tocken not null
        if ($_SESSION['fb_tocken'] == $this->tocken){
           // session tocken = current tocken
           // update last active
           return true;
        } elseif ($this->tocken == APPLICATION_TOCKEN) {
          // current tocken == default tocken
          $this->logout();
        } else {
          // current tocken <> default tocken
          $this->logout();
        }
     } else {
        // session tocken is null
        if ($this->tocken == APPLICATION_TOCKEN){
          // current tocken is default
          return false;
        } else {
          // current tocken is not default
          if ($this->getUserInfo()){
             // user registered - login action
             if ($this->login())
                return true;
             else
                return false;
          } else {
             // register new user
             if ($this->register()){
                if ($this->login()){
                   return true;
                } else
                   return false;
             } else
                return false;
          }
        }
  }
   }
   // ...
};
</code>
If user used alogritm:
1 - Login in facebook
2 - Login in application
3 - Logout from facebook
4 - Login in facebook
5 - Open application
Application Problem:
after fifth step my app can't authorize a user. But if user press 'refresh' he become authorized.
Comment: @Roddie I'am modify this class, now it works. But there is a problem -  IE x - not saved cookie from Iframe.How to overcome this behavior?
Answer: That is the correct behviour - but impossible to confirm without the rest of your code (i.e. the bit that grabs the token).
What happens is that when a user logs out, the current token (that you have stored in your session) becomes invalid. The user logs back into Facebook, you need to get the new token, and that's not going to happen automtically - but when you do a refresh, I presume your code getAccessToken() (not shown above) will grab the new token.
The simplest fix is to add a listener in Javascript for logging in and out. You can find the details here and you need the auth.login handler. When you have that triggered, simply refresh the page.
There are other options using Javascript tot pump the new token to a PHP listener that can update your session behind the scenes.
Comment: Robbie $this->tocken = $this->context->getAccessToken(); // get current tocken
Comment: You'll need to debug the rest of your code then - this works just fine in IE so you have something else that's stopping Javascript scripts from running, probably, or your refresh instruction is wrong. But we can't say more than that without seeing code.
Comment: all scenario worked. Not worked registration user if the user from canvas.

application goes crazy in this scenario.
Comment: This approach will work in canvas too, Sri it sounds like to have a looping redirect. Impossible to say though without seeing code. Id you're still stuck, create a new question and upload the code you have regarding the redirects.


Array compared to a variable method call

Question: Beginner programmer here, I currently have a program written up that takes an array and a variable and compares the two, if the variable declared is within the array, the array will print out all the numbers within the array besides the number contained in the variable. This is working and functioning properly. Furthermore, what I would like to do now is take the code I've written up and put it in a functioning method for reuse but I am currently kind of stuck on doing so. The end result would be having the a new smaller array displayed that does not contain the number 17 anymore.
Here is my code example.
public class arrayTest
{
   public static void main(String [] args)
   {
      int[]arrayA = {2,4,8,19,32,17,17,18,25,17};

      int varB = 17;

      for(int B = 0; B < arrayA.length; B++)
      {
         if(arrayA[B] != varB)
         {
            System.out.print(arrayA[B] + " ");
         }

      }
   }

      public static int newSmallerArray( int[] A, int b )
      {

      }
}

Comment: Do you want to return the smaller array, or only print it? Also your IDE has a refactor option to "extract method", probably
Comment: why do you have a return type of int? shouldn't it just print it like you've done within the main method? in other words a return type of void would be suitable or returning an array.
Comment: please refer this post [link] (http://stackoverflow.com/questions/5098540/delete-element-from-array) Its same as your question.
Comment: Clark do any of the answers address your question?
Answer: Ok, at this point
  int[]arrayA = {2,4,8,19,32,17,17,18,25,17};
  int varB = 17;

you can call
 newSmallerArray(arrayA, varB);

and then, in this method you would have the same looping code, but the variables names have changed
  for(int B = 0; B < A.length; B++)
  {
     if(A[B] != b)
     {
        System.out.print(A[B] + " ");
     }
  }

now the trouble is, you have declared this method as returning an int but there is nothing to return so maybe make it return void
public static void newSmallerArray( int[] A, int b )

next, I would also stick to java naming conventions
Full code sample returning a subset of the input array
using better names
public static void main(String[] args) throws SocketException {

    int[]arrayA = {2,4,8,19,32,17,17,18,25,17};
    int varB = 17;

    int [] na = newSmallerArray(arrayA, varB);
    // test
    System.out.println();
    for(int b = 0; na != null && b < na.length; b++)
    {
        System.out.print(na[b] + " ");
    }
}

private static int[] newSmallerArray(int[] a, int b) {

    int count = 0;
    for(int x = 0; x  0) {
        int[] newArray = new int [count];
        count = 0;
        for(int x = 0; x < a.length; x++)
        {
            if(a[x] != b)
            {
                newArray[count++] = a[x];
            }
        }

        return newArray;
    }

    return null;

}

Comment: I would like it to return the array without 17 in the array anymore
Comment: @Clark1776 you need to update your post with the comment you've just written.
Comment: looks good but very sophisticated for the program that I am trying to achieve
Comment: My original answer did not include this  *I would like it to return the array without 17 in the array anymore* but this is what you requested.  The answer you accepted did not include this.
Answer: I would like it to return the array without 17 in the array anymore
Then, assuming you are using Java 8+, use an IntStream and filter out b values. Like,
public static int[] newSmallerArray(int[] arr, int b) {
    return IntStream.of(arr).filter(x -> x != b).toArray();
}

If you want to do it without Java 8 features, you could count the occurrences of the value to exclude. Like,
private static int countValue(int[] arr, int b) {
    int count = 0;
    for (int value : arr) {
        if (value == b) {
            count++;
        }
    }
    return count;
}

And use that to correctly size a new array, and then copy the values. Like,
public static int[] newSmallerArray(int[] arr, int b) {
    int[] ret = new int[arr.length - countValue(arr, b)];
    for (int i = 0, p = 0; i < arr.length; i++) {
        if (arr[i] != b) {
            ret[p++] = arr[i];
        }
    }
    return ret;
}

Answer: Just refactor your code that contains the main logic and move it to method. It would be easy to do with an IDE. Else, you have to copy the code to a new method and pass necessary arguments.
public class arrayTest
{
   public static void main(String [] args)
   {
      int[] arrayA = {2,4,8,19,32,17,17,18,25,17};
      int varB = 17;
      // Call with the array and variable you need to find.
      newSmallerArray(arrayA, varB);
   }

   public static void newSmallerArray( int[] arrayA, int varB)
   {
      for(int B = 0; B < arrayA.length; B++)
      {
         if(arrayA[B] != varB)
         {
            System.out.print(arrayA[B] + " ");
         }
      }
   }
}

Comment: As @scary-wombat suggested, you need to follow the java naming conventions.


jax-rs jersey: Exception Mapping for Enum bound FormParam

Question: I am building a REST application, which is running on Glassfish 3, and having trouble handling the case when a parameter is bound to an enum:
<code> @FormParam("state") final State state
</code>
So, State is just an enum, which contains different types of states.
In case a value is submitted, that can not be parsed, a http 400 is returned. This basically is fine. However, I need to intercept that exception and return a custom response, which provides additional information to the client. (e.g. a json object containing a description: "state invalid"). I have bound parameters to my own classes and have been able to address the exception handling properly, but I  couldn't find any information on how to handle this case when using an enum. I guess I can use a dedicated class for that as well, but I would like to avoid that, if it is possible to keep the enum.
Answer: The way that I handled this was to first have a suitable deserializer in my enum:
<code>@JsonCreator
public static Type fromString(final String state)
{
  checkNotNull(state, "State is required");
  try
  {
    // You might need to change this depending on your enum instances
    return valueOf(state.toUpperCase(Locale.ENGLISH));
  }
  catch (IllegalArgumentException iae)
  {
    // N.B. we don't pass the iae as the cause of this exception because
    // this happens during invocation, and in that case the enum handler
    // will report the root cause exception rather than the one we throw.
    throw new MyException("A state supplied is invalid");
  }
}
</code>
And then write an exception mapper that will allow you to catch this exception and return a suitable response:
<code>@Provider
public class MyExceptionMapper implements ExceptionMapper<MyException>
{
  @Override
  public Response toResponse(final MyException exception)
  {
    return Response.status(exception.getResponse().getStatus())
                   .entity("")
                   .type(MediaType.APPLICATION_JSON)
                   .build();
  }
}
</code>
Comment: Thank you. I wasn't aware that an enum is parsed via fromString() as well. The documentation is kind of vague on that. I actually never tried that because it seemed kind of weird.
Answer: Hint: It is necessary that MyException extends WebApplicationException. Other exceptions (like an IllegalArgumentException for example) are not handled by any provider in that scope (when parsing the reqest).


Transposition (Permutations)

Question: I have a definition in my notes that states a transposition is a permutation which interchanges two symbols and leaves all the others fixed. Thus, if $T$ is a transposition, then $\operatorname{sgn}(T)= -1$.
I understood transposition to be disjoint cycles of length 2. What does it mean when it says interchanges two symbols?
Comment: The wording of your last paragraph could be improved, but since it tells what you "understood" I'm hesitant to edit it for you. *A transposition* (singular) corresponds to a "cycle of length 2" (singular).  To speak of *disjoint* cycles requires having more than one cycle (the point being that two cycles are disjoint when there is no common symbol shared by them).
Comment: Thank you for this!
Answer: It means that all but two symbols are fixed under the action of the transposition. "Symbols" here means elements of the set being acted on (conventionally $\{1,2,\ldots, n\}$ for elements of $S_n$).
For example, $(12)\in S_4$ would be a transposition, because it only interchanges the symbols $1$ and $2$, while leaving the symbols $3$ and $4$ fixed. On the other hand, $(12)(34)\in S_4$ would not be a transposition, because it interchanges $1$ and $2$ but also interchanges $3$ and $4$.
Comment: Thank you so much, makes so much sense. Sorry for my ignorance but what does sign(T)=-1 mean?
Comment: See here: [Parity of a permutation](https://en.wikipedia.org/wiki/Parity_of_a_permutation). $\operatorname{sgn}$ is a function that sends even parity permutations to $1$ and odd parity permutations to $-1$.
Comment: Also, if you had a larger set, i.e: n=10. Could (12)(34) exist in {1,2...10} ?As this would interchange 1 and 2, and 3 and 4, but the rest of the elements would be fixed?
Comment: Yes, that's right.
Comment: Great! Thank you! (Learning the whole of my linear algebra module in 2 days.)
Comment: No problem, good luck.

Transposition (Permutations)


Show that $\lim\limits_{n \to \infty}\sin n^2$ does not exist.

Question: Problem
Show that $\lim\limits_{n \to \infty}\sin n^2$ does not exist, where $n=1,2,\cdots.$
Proof
Assume that $\lim\limits_{n \to \infty}\sin n^2$ exists, then since $\cos (2n^2)=1-2\sin^2 n^2,$ $\lim\limits_{n \to \infty}\cos(2n^2)$ also exists.
It's easy to know $\lim\limits_{n \to \infty}\sin n^2 \neq 0$, even though the limit exists. Hence, $$\lim\limits_{n \to \infty}\sin (2n)^2=\lim\limits_{n \to \infty}\sin n^2 \neq 0.\tag1$$
Since $$\sin(2n)^2=\sin 2(2n^2)=2\sin(2n^2)\cos(2n^2),\tag2$$
hence $\lim\limits_{n \to \infty}\cos (2n^2) \neq 0.$ Otherwise, if $\lim\limits_{n \to \infty}\cos (2n^2) =0,$ then according to $(2)$, we may obtain $\lim\limits_{n \to \infty}\sin(2n^2) = 0,$ which contradicts $(1)$.
Now, notice that $\sin (2n^2)=\dfrac{\sin(2n)^2}{2\cos(2n^2)}$, for the reason that $\lim\limits_{n \to \infty}\sin n^2 \neq 0$ and $\lim\limits_{n \to \infty}\cos (2n^2) \neq 0$, we may claim that $\lim\limits_{n \to \infty}\sin (2n^2) $ exists but dose not equal $0$.
Since $\sin (2n^2)=2\sin n^2\cos n^2$, hence $\cos n^2=\dfrac{\sin(2n^2)}{2\sin n^2}.$ But we have known that $\lim\limits_{n \to \infty}\sin (2n^2) $ and $\lim\limits_{n \to \infty}\sin n^2 $ both exist and $\lim\limits_{n \to \infty}\sin n^2 \neq 0 $. Thus, $\lim\limits_{n \to \infty} \cos n^2$ exists. Therefore, $\lim\limits_{n \to \infty} \sin (n+1)^2$ and $\lim\limits_{n \to \infty} \cos (n+1)^2$ both exist as well.
Since $\sin(2n+1)=\sin[(n+1)^2-n^2]=\sin(n+1)^2\cos n^2-\cos(n+1)^2\sin n^2$,hence $\lim\limits_{ n \to \infty}\sin(2n+1)$ exists, which is absurd.
As a result, the assumption at the beginning that $\lim\limits_{n \to \infty}\sin n^2$ exists is false. We are done.
NOTE
Among the proof above, we apply two facts that $\lim\limits_{n \to \infty} \neq 0,$ and $\lim\limits_{n \to \infty}\sin (2n+1)$ does not exist, which has not been proven. If necessary, I'm pleased to complement the proofs of them.
Lemma 1

$\lim\limits_{n \to \infty}\sin(2n+1)\neq 0.$

Proof
Assume that $\lim\limits_{n \to \infty}\sin (2n+1)=0.$ Then $\lim\limits_{n \to \infty}|\sin (2n+1)|=0$ and $\lim\limits_{n \to \infty}|\cos (2n+1)|=1.$ Thus,
\begin{align*}
 \lim\limits_{n \to \infty}|\sin (2n+1)|&=\lim\limits_{n \to \infty}|\sin (2n+3)|\\
&\geq  \lim\limits_{n \to \infty}|\cos (2n+1)\sin 2|- \lim\limits_{n \to \infty}|\sin (2n+1)\cos 2|\\
&= \lim\limits_{n \to \infty}|\cos(2n+1)\sin 2|\\
&=\sin2 \neq 0,
\end{align*}
which contradicts.
Lemma 2

$\lim\limits_{n \to \infty}\sin (2n+1)$ does not exist.

Proof
Assume that $\lim\limits_{n \to \infty}\sin (2n+1)$ exists. Take two arcs with the middle points $\dfrac{\pi}{2},\dfrac{3\pi}{2}$ respectively and the length $\dfrac{2\pi}{3}$ from the unit circle. Notice the common difference of $\{2n+1\}$ is $2$, which is smaller than $\dfrac{2\pi}{3}$. Hence, there are infinitely many terms locating on the arc with the middle point $\dfrac{\pi}{2}$ and the length $\dfrac{2\pi}{3}$. For such terms $\{2n_k+1\}$, we have $$\sin(2n_k+1) \geq \sin \left(\frac{\pi}{2}-\frac{\pi}{3}\right)=\sin\frac{\pi}{6}=\frac{1}{2}.$$ Therefore, $$\lim\limits_{n \to \infty}\sin (2n+1)=\lim\limits_{n \to \infty}\sin (2n_k+1)\geq \frac{1}{2}.\tag3$$
Similarily, there also exists another subsequence $\{2m_k+1\}$ locating on the arc with the middle point $\dfrac{3\pi}{2}$ and the length $\dfrac{2\pi}{3}$. Notice that $$\sin(2m_k+1) \leq \sin \left(\frac{3\pi}{2}+\frac{\pi}{3}\right)=\sin\frac{11\pi}{6}=-\frac{1}{2}.$$ Therefore, $$\lim\limits_{n \to \infty}\sin (2n+1)=\lim\limits_{n \to \infty}\sin (2m_k+1)\leq -\frac{1}{2}.\tag4$$ As a result, $(3)$ and $(4)$ contradict each other.
Lemma 3

$\lim\limits_{n \to \infty} \sin n^2 \neq 0.$

Proof
Assume that $\lim\limits_{n \to \infty} \sin n^2 = 0.$ Notice that $\sin(n\pi)=0$ for all $n=1,2,\cdots.$ and the continuity of $y=\sin x$. Thus, for any given $\varepsilon>0$, there exists a $N \in \mathbb{N_+}$, when $k \geq N$, we may choose a positive integer $n_k$ such that $$|k^2-n_k\pi|<\frac{\varepsilon}{2}.$$ Without loss of generality, we may assume $\{n_k\}$ is rigorously increasing. Then
$$|(2k+1)-(n_{k+1}-n_k)\pi|=|(k+1)^2-n_{k+1}\pi-(k^2-n_k\pi)|<\varepsilon.$$ Thus, $$\lim_{k \to \infty}\sin(2k+1)=\lim_{k \to \infty}\sin(n_{k+1}-n_k)\pi=0,$$
which contradicts Lemma 1.
PLEASE CORRECT ME IF I'M WRONG! HOPE TO SEE MORE ELEGANT SOLUTIONS!
Comment: How is it easy to see that $\lim_{n\to\infty}\sin(n^2)\ne0?$
Comment: Possibly helpful https://math.stackexchange.com/questions/2373322/sin-n2-diverges
Comment: I (and I guess everyone) guess that here $n$ is an integer... but you should clarify that.
Comment: Caution: when I read $\sin(2n)^2$, I think of $\big(\sin(2n)\big)^2$ and not $\sin\big((2n)^2\big)$ as you meant...
Comment: Why is it absurd that the limit of $\sin(2 n + 1)$ does not exist? (I mean I would prove that particular question in a similar way to what you need to prove.)
Comment: @CharlesMadeline: Surely $\left(\sin(2n)\right)^2$ would be written simply $\sin^2 2n$?
Comment: If $L:=\lim_{n\to\infty}\sin n^2$ then $$L=\lim_{n\to\infty}\sin 4n^2=\lim_{n\to\infty}4\sin n^2\cos n^2(1-2\sin^2 n^2)=4L(1-2L^2)\sqrt{1-L^2},$$so if $L\ne 0$ we have $\frac{1}{16}=(1-L^2)(1-2L^2)^2$. This implies $L^2\in\{\frac{3}{4},\,\frac{5\pm\sqrt{5}}{8}\}$.
Answer: Suppose
$\lim_{n \to \infty} \sin(n^2)
$
exists with value $L$.
$\sin((n+1)^2)
=\sin(n^2+2n+1)
=\sin(n^2)\cos(2n+1)+\cos(n^2)\sin(2n+1)
$
so
$L \approx L\cos(2n+1)\pm\sqrt{1-L^2}\sin(2n+1)
$
or
$L(1-  \cos(2n+1))\approx\pm\sqrt{1-L^2}\sin(2n+1)
$
or
$L(2\sin^2(n+1/2))
\approx\pm\sqrt{1-L^2}\sin(2n+1)
=\pm\sqrt{1-L^2}2\sin(n+1/2)\cos(n+1/2)
$
or
$L\sin(n+1/2)
\approx\pm\sqrt{1-L^2}\cos(n+1/2)
$.
$L = 0$
implies that
$\cos(n+1/2) \to 0$,
which is false.
Therefore $L \ne 0$.
Therefore
$\tan(n+1/2)
\approx \dfrac{\pm\sqrt{1-L^2}}{L}
$.
This means that
$\tan(n+1/2)$
can have at most
two accumulation points.
Since
$\pi$ is irrational,
$\{(n+1/2)/\pi\}$
(fractional part)
is dense in
$[0, 1]$,
so
$\tan(n+1/2)
=\tan(\pi\{\frac{n+1/2}{\pi}\})
$
has many accumulation points.
Therefore
the limit can not exist.


Buscar nome do diretório de um arquivo .bat

Question: Eu tenho um arquivo .bat que faz algumas iterações via cmd em vários diretórios.
Meu problema é o seguinte:

Preciso conseguir pegar o diretório do próprio arquivo .bat para estar sempre voltando ao mesmo para fazer outras iterações.

um exemplo seria:
:exemplo
set file=C:\nome-do-diretorio\
for /f "tokens=*" %%A in (%file%) do ( cd %%A)

Até aqui ok, mas depois preciso que o cmd consiga ser apontado para o diretório do próprio arquivo bat.
Comment: No powershell é `(Get-Location).Path`!
Answer: Você pode usar %cd%, isso irá retornar o path atual onde o batch está sendo executado.
Pode testar com echo %cd%
Comment: Já faço algumas automatizações em batch a algum tempo e não sabia dessa variável. Obrigado.
Comment: É Justamente esta variável que estou utilizando e foi onde descobri o problema. A variável %CD%  pega o diretório atual pra onde esta apontado o cmd. Não queria fazer uma pesquisa em cima do nome do arquivo, pois pode ficar demorado.
Comment: *"mas depois preciso que o cmd consiga ser apontado para o diretório do próprio arquivo bat."* não entendi isso ficou confuso pra mim, você quer o diretório do arquivo bat?
Answer: Pode usar %~dp0
@echo off
echo "%~dp0"

Answer:

Você pode usar as variáveis e também as suas expansões de valores/atributos/propriedades.
No código abaixo tens algumas variáveis que são fixas e tens outras que são alteradas conforme as ações do bat, como exemplo nas trocas de diretórios.

@echo off & cd /d "%~dpn0"

for %%i in ("%windir%" "%appdata%" "%ALLUSERSPROFILE%")do cls & cd /d "%%~i" & call :^)
goto :eof

:^)
echo/ ----------------------------------------------------------------
echo/ variaveis nao alteram seus valores
echo/ ----------------------------------------------------------------
echo/ %%~d0              = %~d0
echo/ %%~p0              = %~p0
echo/ %%~dp0             = %~dp0
echo/ %%~f0              = %~f0
echo/ %%~dpnx0           = %~dpnx0
echo/ ----------------------------------------------------------------
echo/ pasta atual: %__CD__%
echo/ ----------------------------------------------------------------
echo/ variaveis alteram seus valores para pasta atual
echo/ ----------------------------------------------------------------
echo/ %%CD%%              = %cd%
echo/ %%__CD__%%          = %CD%
echo/ ----------------------------------------------------------------
timeout -t 5 & exit /b

Obs.: 1) Mais informações sobre as expansões de variáveis você tens na ajudo co comando for /?
Obs.: 2) Você pode setar uma variável para usar quando for retornar ao diretório onde o bat inicialmente foi executado dessa forma:

set "_pasta_bat=%~dp0"

rem :: retornando para a pasta do bat ::

cd /d "%_pasta_bat%"

rem :: ou apenas ::

cd /d "=%~dp0"


Find databasetype ( SQlite, Mysql, PostgreSQL ) from dbapi in python

Question: I need to find out what kind of database I am working against based on data from an dbapi cursor instance. Have not found any clues on how to do this in the dbapi docs. Can it be done?
Answer: It isn't part of the dbapi 2.0, at least to my knowledge.  However, you can implement a function to obtain the module name from a given database object (cursor, connection) and map that to a well-known string for your application to use:
<code>_DBNAME_MAP = {
    'psycopg2': 'postgres',
    'MySQLdb': 'mysql',
    'sqlite3': 'sqlite',
    'sqlite': 'sqlite'
    }

def get_dbname(dbobj):
    mod = dbobj.__class__.__module__.split('.', 1)[0]
    return _DBNAME_MAP.get(mod)
</code>
Examples:
<code>>>> s_conn = sqlite3.connect('foo.db')
>>> get_dbname(s_conn)
'sqlite'
>>> get_dbname(s_conn.cursor())
'sqlite'

>>> p_conn = psycopg2.connect('host=localhost user=postgres')
>>> get_dbname(p_conn)
'postgres'
>>> get_dbname(p_conn.cursor())
'postgres'
</code>


Output Path to File Content in Views

Question: In a view I would like to output just the path to the piece of content where the file is referenced like the below:
http://www.example.org/file/1

I DO NOT want to link directly to the file itself.
I thought it would be a simple task but most of the fields are adding html (like View).
I am filtering by a file type of "Video".  I have tried adding the below with no success:
File: Download Link
File: Edit link
File: Link
File: Path

And have also tried using a relationship:
Content: Link
Content: Path

I have been able to get it working by rewriting the File: File ID field and hard-coding the url with the [fid] as a token, but that's a horrible solution.
Answer: Please try to locate another relationship named "File Usage: File"
After that you should be able to add a field type "File: Path". In the field options you can decide how the output is formatted: as server-path (public://yourpath) or as download path.
Comment: I don't want to link directly to the file, I want to link to the piece of content where the file is referenced.

Output Path to File Content in Views


Show that if $A \in M_{nxn}(k)$ and $det A \neq 0$ then for each matrix $B \in M_{nxn}(k)$: $AB$ and $BA$ are similar

Question:
Show that if $A \in M_{nxn}(k)$ and $det A \neq 0$ then for each matrix $B  \in M_{nxn}(k)$:  $AB$ and $BA$ are similar. Give an example $A,B$ for which $AB$ and $BA$ are not similar.

If $AB$ and $BA$ are similar then I have matrix $C$ for which $AB=C^{-1}(BA)C$. However I don't know how to prove that this matrix exist if I know only that $det A  \neq 0$. I thought also about a fact that $tr(AB)=tr(BA)$ but I think it laso is unhelpfull for me.Can you get me some tips which facts are helpful for me to do this task?
Answer: Hint: Note that
$$
A(BA)A^{-1}=AB.
$$
For the second part, we should choose both $A$ and $B$ as non-invertible. (Because if one of them is invertible, then above statement shows that $AB$ is similar to $BA$.) A hint is to find $A,B$ such that $AB=O$, $BA\ne O$.
Comment: @MP3129 I've added some part explaining that. I hope this will help to find $A,B$.
Comment: Ok, thanks. In that case, in the second part of the task you just need to take matrix $ A $ for which $ det A = 0 $ and any matrix $ B $?


How can I programatically change the color of node title in views results?

Question: I want to change the color of the node titles from a view (fields on table).
My first ides was to alter the title and add a span with inline css.
function views_titles_views_pre_render(&$view) {
if ($view->name == 'documents' && $view->current_display == 'page') {
    $span_open  = '';
    $span_close = '';
    $view->style_plugin->render_fields($view->result);
    foreach ($view->style_plugin->rendered_fields as $index => &$rendered_result) {
      // Add HTML markup icon on rendered title field
      $rendered_result['title'] = $span_open . $rendered_result['title'].$span_close;
    }
  }
}

Although my attempt was a success, I managed to alter the title the css rule did not alter the color of the a tag. I figured out that I should go deeper into the title. As far I can tel the dpm of the views_pre_render does not show more options.
I have experience with drupal site building, but I am not in any way a php developer.
Can someone help me figure this out?
ps: I know there other more easy ways to achieve that but I want to do it with a module.
Comment: If you want to do it with a module, you can do it by simply adding a css files in a module.
Answer: An easier (and more maintainable) way to achieve this would be to set a class in your span, instead of hardcoding the style. Something like the following:
$span_open = '"';

You can then add a CSS file to your module, so that you can better specify the color, also overriding the a tag. For instance:
.my-title, .my-title a {
  color: green;
}

For more details about adding CSS to your module, see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_css/7.x


Circumventing Drupal's Cache for New Content

Question: We like to post updates to Facebook and Twitter when publishing new content. We are running into a problem, however, in that anonymous users will get the "Access Denied" page until the cache recycles to show them the new content.
Currently, we're caching pages for anonymous users for three minutes. How do we keep our cache, yet allow anonymous users to see new content immediately as it's published?
For what it's worth, we are not using Memcache, Varnish or anything outside of the standard Drupal page caching.
Comment: clearing cache after adding new content is consider an option for you?
Comment: Yes, that's certainly an option for us.
Answer: 403 "Access Denied" on a cache miss seems odd to me. One thing to try is http://drupal.org/project/adbc as it makes the Dupal cache operate like one expects.
Answer: I'm not sure why you're getting "Access Denied" when you view new content as anonymous user. New content shouldn't be cached yet.
As a solution for your issue, you can clear all Drupal cache or only Drupal page cache after adding new content.
The following code will clear page cache after inserting new content:
<code>   function MODULE_NAME_nodeapi(&$node, $op, $teaser, $page) {
      switch ($op) {
        case 'insert':
          cache_clear_all('*', 'cache_page', TRUE);
          break;
      }
    }
</code>
Note: This code will not work on Drupal 7
Comment: It's puzzling to us as well, but the cache is the only thing we can think it could be as the new content is available to anonymous users after a minute or two (and it's available to authenticated users right away).
Comment: Do have any node access modules installed on your Drupal project?
Comment: No, pretty vanilla. I think your approach will serve us best. Thank you.


Momentarily ignore values from Observable when another Observable provides a value

Question: I need to ignore Observable values for a period of time  when another Observable provides a value.
Currently, my implementation uses a variable to control blocking (or ignoring).
bool block = false;

var blocker = observable1.Do(_ => block = true )
                         .Throttle( _ => Observable.Timer(_timeToBlock)
                         .Subscribe( _ => block = false ));

var receiver = observable2.Where( i => !block && SomeCondition(i) )
                          .Subscribe( i=> EvenMoreStuff(i) );

Is there a more Rx way to do this, by combining these two observables?
EDIT: small change to blocker subscription
Answer: The first task is to express your block variables as an observable.
IObservable<bool> blockObservable = observable1
    .Select(x => Observable.Concat(
        Observable.Return(true),
        Observable.Return(false).Delay(_timeToBlock)))
    .Switch()
    .DistinctUntilChanged();

Each time observable1 emits a value, we select an observable that emits true, waits _timeToBlock, then emits false. The Switch just always switches to the most recent of those observables.
Here's a marble diagram.  Let's assume that _timeToBlock is 3 characters long.
observable1      -----x--xx-x-----x-----
select0               T--F
select1                  T--F
select2                   T--F
select3                     T--F
select4                           T--F
switch           -----T--TT-T--F--T--F--
blockObservable  -----T--------F--T--F--

Now we can Zip your sequence of values with the MostRecent value of the blockObservable.
var receiverObservable = observable2
    .Zip(blockObservable.MostRecent(false), (value, block) => new { value, block })
    .Where(x => !x.block)
    .Select(x => x.value);

Comment: Looks good. Of course the solution is to replace `bool` with `Observable` ! I need to wrap my head around the syntax and do some tests with it...
Comment: @supertopi Did this "browser code" work without any adjustment?
Comment: At least my unit tests passed. Are there any hidden side-effects I should know of? :)
Comment: @supertopi No it should be fine.
Answer: As an alternative using disposables you could create a small extension method:
public static IObservable<TResult> Suppress<TResult, TOther>(
                                    this IObservable<TResult> source,
                                         IObservable<TOther> other,
                                         TimeSpan delayFor)
{
  return Observable.Create<TResult>(observer => {
    var published = source.Publish();
    var connected = new SerialDisposable();
    Func<IDisposable> connect = () => published.Subscribe(observer);
    var suppressor = other.Select(_ => Observable.Timer(delayFor)
                                .Select(_2 => connect())
                                .StartWith(Disposable.Empty))
    .Switch();

    return new CompositeDisposable(
                connected,
                suppressor.StartWith(connect())
                          .Subscribe(d => connected.Disposable = d),
                published.Connect());
  });
}

This will convert the source observable into a ConnectableObservable, then every time the other source emits it will dispose of its subscription, then reconnect when the timer expires.
Comment: Thanks. It might be best practice to write your own extension methods, but I find this harder to read than Timothy's solution.


How to Get Custom Field Label Translation

Question: I'm using Internationalization module and in my custom entity type, I have my custom field. Since this entity is going to be usable for all enabled languages, I have added translation to my custom field's label.
In node.tpl.php file in my custom template, I am calling this field values like this:
$field = field_info_instance('node', 'field_custom', 'custom_entity');

And I render the field's label like this:
echo t($field['label']);

However, even though I've added translation for the label, it remains same string for all languages. I'm surely missing something here, how can I implement this?
Thanks in advance.
Comment: I had the same issue almost a week ago, latest i18n module release has alot of bugs with fields label translation, use the latest dev version and it works
Comment: I thought it was something about my way, but if bugs are that obvious, I will give it a try and update the question if this is why. Thank you.
Answer: You cannot use variables in t() function, it accepts only strings and placeholders with an array.
The i18n module has Field Translation module shipped with it, be sure you have enabled it as well.
There is also a good information on the following link about getting title fields translated as well.
Drupal 7 – Translate the title field label of content types
Comment: That's what I get confused about. If you use t('Home'), it translates. No array, just string: 'Home'. Isn't it relevant to string translations? I thought when you pass a string to t() function, it checks if there is a translated string and render it instead. P.S. I have enabled Field Translation already, otherwise I couldn't get to translate field properties that I mention in the question :-)
Answer: OK, here's how I solved the problem.
Internatinalization module renders the content according to translated strings before node.tpl.php gets rendered. Thus, the $content variable in node.tpl.php contains the latest version of rendered page.
Since I was not using the <?php print render($content); ?> because I was creating a custom template, I have used the field properties inside this $content variable. And they contain the translated versions of labels.
Here's how you can get a translated label of a custom field:
echo $content['custom_field']['#title'];

P.S. If you want to get a field property from $content variable, you must set that field to visible in content type's manage display section.
Comment: This does work, unless you want to get the label of a field that doesn't have a value assigned.  In that case the `$content` variable doesn't contain any info for the field (because it isn't actually part of that node's content).


SQL field data addition

Question: I am just wondering if it is possible to do something and as I cannot find any information about it:
let's say I have a field that I want to concatenate values to it:
For example
table 'test'
id |  name            |  surname
01 |  georges         |  Michael

and I am trying to add information about this field like :
table 'test'
id |  name             |  surname
01 |  georges, rick    |  Michael

Do I need to update, insert or alter this 'test'.'name' with a second value(in this case 'rick')? Is it even possible to do that or will I need to create another related table in order to link 'rick' with 'georges'?
I know that if it is possible I will have to "insert" the comma as well but I do not know how.
Comment: Do not store multiple values in a single row.  Use a junction table instead.
Comment: Is `rick` also coming from another column ?
Comment: Doing this potentially fails Database Normal Forms.  IT will make scaling, querying and doing things related this name field much more difficult.  Are you sure this is the correct approach "`Concatenating`" an name to an existing record?
Comment: Any time you want to change the data in one or more columns of an existing row of data, you need to do an `UPDATE`.  I'm not sure exactly what part of this you "cannot find any information about" though.  I think you are letting the concatenation aspect confuse you.
Comment: Which DBMS are you using?
Comment: no 'rick' would be a new dynamic variable. I am using Mysql server. To Gordon Linoff and xbert : Do you guys think this way of doing is not ACID compliant ?
Answer: SQL Server:
UPDATE test SET name = name + ', Rick' WHERE id = '01'

If you need to pull Rick from another table, you could do something like this:
UPDATE t
SET t.name = t.name + ', ' + o.othername
FROM test t
JOIN othername o ON t.id = o.id
WHERE t.id = '01'

And if you were looking for further posts/info on the topic, I'd suggest googling sql server string concatenation
Comment: Note `+` for string concatenation is not valid standard SQL and **only** applies to SQL Server. The same is true for the `FROM` clause in the `UPDATE` statement
Comment: Good point, thanks. I could swear I saw a sql_server tag on this originally! I must admit I remember seeing a mysql tag as well, hence my specification of SQL Server.

SQL field data addition


Not all values objects can be viewed with XCode Watch and Debug console

Question: For example, for some reason in initWithNibName:bundle: I can't see the value of self.view.bounds.size.width, have to stop the program and use NSLog.
When I type self.view.bounds.size.width into the watch, I get "Enter expression" message on the right.
When I type print self.view.bounds.size.width into the debug console, I get the following errors:
error: unsupported expression with unknown type
error: 1 errors parsing expression

Is there any way to see ALL the values I can see using NSLog?
EDIT: By @Abizern's suggestion tried p self.view.bounds.size.width and po self.view.bounds.size.width - same result.
Answer: try
p self.view.bounds.size.width

or alternatively:
po self.view

p is a simple print which works for values
po is for print object which essentially give the same result as an NSLog
Comment: Also, because bounds is a CGRect; a struct, not an object. If you want to use po with it try `po NSStringFromCGRect(self.view.bounds)`
Comment: Or even `p self.view.bounds` which works in recent versions of Xcode.
Comment: Tried both "po self.view.frame.bounds" and "p self.view.frame.bounds" - didn't work, still get the "unsupported expression with unknown type" error.
Comment: Are you setting the breakpoint in the scope of these variables?
Comment: Yes. To make sure I even set them right before and right after I use or assign this value and still get the same result.
Comment: Worked, thanks! "print self.view" that I tried before just gave the pointer value, "po" output is much more valuable. Still, why can't I use "po self.view.frame.bounds"?
Comment: because self.view.frame doesn't have a `bounds` attribute. you want self.view.frame, or self.view.bounds.
Answer: See this answer: https://stackoverflow.com/a/18923064/201828
Basically, bounds is not actually a member of UIView, but rather the layer. So just do:
p self.view.layer.bounds

This was driving me crazy, too :-(


Node.js Remove route while server is running

Question: Currently I am trying to remove the route of a
 Node.js server application on runtime.
for (k in self.app.routes.get) {
  if (self.app.routes.get[k].path + "" === route + "") {
    delete self.app.routes.get[k];
    break;
  }
}

After this method is called there is no longer the route in the self.app.routes object. But after I try to access the currently removed route I get the following error:

TypeError: Cannot call method 'match' of undefined
      at Router.matchRequest (/var/lib/root/runtime/repo/node_modules/express/lib/router/index.js:205:17)

Due to the documentation of express.js this must be the correct way of doing it.

The app.routes object houses all of the routes defined mapped by the associated HTTP verb. This object may be used for introspection capabilities, for example Express uses this internally not only for routing but to provide default OPTIONS behaviour unless app.options() is used. Your application or framework may also remove routes by simply by removing them from this object.

Does any body know how to correctly remove a route on runtime in Node.js?
Thanks a lot!
Comment: Can you confirm your version of Express?
Comment: Sorry for that. My version is: "3.1.0"
Answer: The error you are getting is because the route is still there. delete won't remove the element, it will only set the element as undefined. To remove use splice(k,n) (from kth element ,remove n items)
for (k in self.app.routes.get) {
  if (self.app.routes.get[k].path + "" === route + "") {
    self.app.routes.get.splice(k,1);
    break;
  }
}

Still your route function should handle this (choose which path/url to accept), which would be better.


Why SQL Alchemy async engine does not persist database setting change

Question: I am trying to update the timezone of a database using SQLAlchemy with psycopg async driver. However, the timezone is not reflected as being changed in the code, even though in the database it looks like is changed, code bellow and its output.
At this point the database timezone is set to Europe/Bucharest and I want to change it to Europe/Amsterdam.
import asyncio
from contextlib import asynccontextmanager
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import text
from sqlalchemy.ext.asyncio import (
    create_async_engine,
    AsyncSession,
)

db_uri = "postgresql+psycopg://bigbrother:email@example.com:5432/bigbrother"
db_engine = create_async_engine(db_uri, max_overflow=1, pool_size=2)

@asynccontextmanager
async def db_session_manager(a_db_engine):
    session = sessionmaker(a_db_engine, expire_on_commit=False, class_=AsyncSession)()
    try:
        yield session
        await session.commit()
    except Exception as ex:
        await session.rollback()
        raise ex
    finally:
        await session.close()

async def update_timezone():
    async with db_session_manager(db_engine) as session:
        await session.execute(
            text(
                """
            ALTER DATABASE "bigbrother"
            SET timezone TO 'Europe/Amsterdam'
        """
            )
        )

async def get_timezone():
    async with db_session_manager(db_engine) as session:
        current_timezone = (
            (
                await session.execute(
                    text(
                        """
                SELECT
                    name, abbrev, utc_offset, is_dst
                FROM pg_timezone_names
                WHERE name = current_setting('TIMEZONE')
            """
                    )
                )
            )
            .mappings()
            .one()
        )
        print(current_timezone)

print("timezone before")
asyncio.run(get_timezone())
asyncio.run(update_timezone())
print("timezone after update")
asyncio.run(get_timezone())

And this code is providing the following output:
timezone before
{'name': 'Europe/Bucharest', 'abbrev': 'EEST', 'utc_offset': datetime.timedelta(seconds=10800), 'is_dst': True}
timezone after update
{'name': 'Europe/Bucharest', 'abbrev': 'EEST', 'utc_offset': datetime.timedelta(seconds=10800), 'is_dst': True}
This output reflects that the engine still sees the old timezone, but If I check the database properties, the timezone seems change, which makes me think that this is related to caching.
If I run it again, thus recreating the engine, it provides the following output:
timezone before
{'name': 'Europe/Amsterdam', 'abbrev': 'CEST', 'utc_offset': datetime.timedelta(seconds=7200), 'is_dst': True}
timezone after update
{'name': 'Europe/Amsterdam', 'abbrev': 'CEST', 'utc_offset': datetime.timedelta(seconds=7200), 'is_dst': True}
What I would like to do is to get the timezone changed without recreating the engine, or remove the caching from the engine or refresh the engine somehow so it sees my modification. That would mean that, if the current database timezone is Europe/Bucharest and the desired one is Europe/Amsterdam, I want my code to provide the following output:
timezone before
{'name': 'Europe/Bucharest', 'abbrev': 'EEST', 'utc_offset': datetime.timedelta(seconds=10800), 'is_dst': True}
timezone after update
{'name': 'Europe/Amsterdam', 'abbrev': 'CEST', 'utc_offset': datetime.timedelta(seconds=7200), 'is_dst': True}
Versions that I use:
python==3.8.13 backports.zoneinfo==0.2.1 greenlet==2.0.2 pendulum==2.1.2 psycopg==3.1.9 python-dateutil==2.8.2 pytzdata==2020.1 six==1.16.0 SQLAlchemy==2.0.19 typing_extensions==4.7.1
Answer: This has nothing to-do with sqlalchemy, nor with asyncio, that's how postgresql works. Even if you'll do this in psql session, you'll get the same result. Here's psql sample session that should explain:
> select current_setting('timezone'); -- check current session timezone
 Europe/Kiev

> select setrole, setconfig from pg_db_role_setting
  inner join pg_database on pg_database.oid = pg_db_role_setting.setdatabase
  where pg_database.datname = 'testing'; -- select default database settings

setrole |          setconfig
---------+-----------------------------
       0 | {TimeZone=Europe/Kiev}

> alter database testing set timezone to 'Europe/Amsterdam'; -- alter database timzone

> select current_setting('timezone'); -- current session timezone is still the same
 Europe/Kiev

> select setrole, setconfig from pg_db_role_setting
  inner join pg_database on pg_database.oid = pg_db_role_setting.setdatabase
  where pg_database.datname = 'testing'; -- default database settings have changed

 setrole |          setconfig
---------+-----------------------------
       0 | {TimeZone=Europe/Amsterdam}

As you can see, doing alter database <DB> set timezone changes default database parameters and not the current one. When you create a new session, it uses these default values, so your new session has a different value for the timezone. The easiest fix would be to change current values as well with set, like this:
> select current_setting('TIMEZONE');
Europe/Kiev
> set timezone to 'Europe/Amsterdam';
> select current_setting('TIMEZONE');
 Europe/Amsterdam

so you need to update update_timezone function and add set timezone to 'Europe/Amsterdam', and the result of the script would be like this:
timezone before
{'name': 'Europe/Kiev', 'abbrev': 'EEST', 'utc_offset': datetime.timedelta(seconds=10800), 'is_dst': True}
timezone after update
{'name': 'Europe/Amsterdam', 'abbrev': 'CEST', 'utc_offset': datetime.timedelta(seconds=7200), 'is_dst': True}

However, this is most likely not what you want to do,  since this will change timezone only in one connection (that did set timezone), since sqlalchemy uses connection pooling, another connection (that could exist), will still have another value for timezone.
One option would be just executing set timezone to 'Europe/Amsterdam' as the first SQL expression that you execute, in that case all connections will have this timezone from the start.
Another option, is to provide timezone in a db_uri:
db_uri = "postgresql+psycopg://bigbrother:firstname.lastname@example.com:5432/bigbrother?options=-c TIMEZONE=Europe/Amsterdam"

You can use this URL in order to check what options are available.
Comment: Thank you for your response! Is really helpful


Data export limit in Sql Developer for excel file

Question: I am facing an issue which is quite strange while exporting data into and .xlsx file from the SQL Developer result set. I ran the same query on SQL Developer and on Dbeaver. When I export data from SQL Developer to a .xlsx file the number of rows exported into the sheet were 47519 and when I exported the same data into a .xlsx file via Dbeaver the number of rows was 87936.
I am now confused either the limit is being exceeded here for SQL Developer or some other issue. Well, I tried another result set and then the number of rows exported by SQL Developer jumped to 49916 and in Dbeaver the rows were around 87534.
It's causing so much trouble because from the past few weeks I've relied on the data files exported via SQL Developer.
I just want to know what possible issue I could be facing here.
Comment: Are you 100% sure you are connecting to the same database with the same user in both tools?
Comment: Do you know exact number of rows to be exported? Did you check it by `select count(*) from (your current query goes here)`?
Comment: @a_horse_with_no_name Well there's only 1 database so yes. And I have make sure by extracting data for 1 particular item and it is returning data fine it just messes up with large amount of data
Comment: @Littlefoot I haven't checked the count but let me check
Answer: I think you're running into a bug with version 19.2 of SQL Developer
Set your output type to CSV, or upgrade to version 19.4 where this is fixed.
Or, remove the DATE columns from your query.
This is the Bug description mentioned in the 19.4 release notes for bug fixes.
"Excel export limited to 32k, null dates truncate output"
Comment: Having the same issue... looking at my version...19.2... shit...
Thx for saving me another houre of debugging...
Answer: To handle the xls limit, SQLDeveloper will create one or more new sheets within the file for the additional rows. When you open your worksheet, you should see a tab at the bottom for each sheet created.
.CSV then convert it to Excel

second solution :

You could try the version 3.1EA2 which is able to write .xlsx
. That one can hold more than 65535 rows.
Answer: As @thatjeffsmith explained that the issue consists in null dates causing the truncation, I tried the following trick as a workaround:

NVL ( TO_CHAR ( < MY_DATE > ) , 'XXX' )

In this way I succeeded in exporting to Excel the entire query result.
By the way, I didn't have inside my table any null dates from the start. How come the original result, without the aforementioned workaround, have been truncated, @thatjeffsmith?
Answer: I do not recommend using SQL Developer for this task - I was bitten by it several times with most simple export actions not working without errors - the export feature of this tool is not something you want to rely on! Also csv exports are broken e.g. when result sets contain numbers with comma as delimiter it is not properly escaped or quoted what leads to invalid data - take care!
Comment: Welcome to Stack Overflow!  This information would be more helpful as a comment to the original question instead of an answer.


Extract command from process (using PID)

Question: I am implementig simple shell emulator in C. It should support running command in background (ex. sleep 5s &). So I run this command using fork() -> exec() sequence and wait for finish of that command using SIGCHLD signal handler. My question is, if there is any possibility to get process command (name), that was specified in exec() call. I give you example:
<code>//SIGCHLD signal handler (use for notification, when background process ends)
void sighandler(int sig) {
    int status;
    int pid = waitpid(-1, &status, WNOHANG);

    if (WIFEXITED(status)) {
        if (pid != -1 && pid != 0) {
            printf("\n[%d] Done: \n> ", (int) pid); //also need to provide user name (command) of exited process (ex. [PID] Done: sleep)
            fflush(stdout);
        }
    }
}

pid_t fork_pid = fork()

if (fork_pid == 0) { //child
    execl("sleep", "sleep", "5s");
} else { //parent
    ....
}
</code>
What I need, is somehow access name of command, that was specified in exec() call (see execl("sleep", "sleep", "5s");) in signal handler (see signalhandler(int sig)) to output something like [PID] Done: sleep.
I cannot use simple global variable of last runned command, because after running some command in background, more new command in foreground can appear and will rewrite that global variable. Example:
<code>> sleep 1m & //background command - variable is "sleep"
[PID of sleep process] Running in background
> ls //foreground command - variable is "ls"
> cat output //foreground command - variable is "cat"
.
.
.
[PID of sleep process] Done: sleep
>
</code>
Any way of doing this? Thanks a lot!
Comment: `/prod//cmdline` or `/proc/self/cmdline`? :S
Answer: You can create a list to associate pids with commands:
<code>void sighandler(int sig) {
            ...
            char *cmd = task_list.get(pid);
            printf("\n[%d] %s, Done: \n> ", (int) pid, cmd);
            ...
}

...

pid_t fork_pid = fork();
char command[1024] = "sleep";
if (fork_pid == 0) { //child
      execl(command, command, "5s");
} else { //parent
      task_list.insert(pid, command);
}
</code>


Dimension of $\operatorname{Hom}(V, W)$

Question: What is the dimension of $\operatorname{Hom}(V, W)$ if at least one of the two vector spaces $V, W$ is infinite dimensional? In the sense of cardinal numbers.
Thanks
Comment: I tend to believe $\infty$ is a good enough answer.
Comment: What is the cardinality was what I meant.
Answer: It depends ;-). If either of $V$ or $W$ is zero-dimensional, we will have $\def\Hom{\mathop{\mathrm{Hom}}}\Hom(V,W) = 0$, regardless of the dimension of the other space. If both of $V$ and $W$ are at least one-dimensional, and one of them is infinite dimensional, $\Hom(V,W)$ is infinite dimensional also:
So suppose $\dim V = \infty$, and $\dim W  \ge 1$ first, let $\{v_n \mid n \in \mathbb N\}$ be a linear independent set in $V$, $w_0 \in W \setminus \{0\}$. Then there are linear maps $f_n \in \Hom(V,W)$ such that
$$ f_n(v_m) = \delta_{nm}w_0, \quad n,m \in \mathbb N $$
Then $\{f_n \mid n \in \mathbb N\}$ is linear independent, as: Suppose $\sum\alpha_n f_n  = 0$ with only finitely many $ \alpha_n\ne 0$. Applying this to $v_m$ gives
$$ \alpha_m = \sum \alpha_n f_n(v_m) = 0(v_m) = 0. $$
So $\dim\Hom(V,W) = \infty$.
Suppose now $\dim V \ge 1$, $\dim W = \infty$, let $v_0 \in V \setminus \{0\}$, and $\{w_n \mid n \in \mathbb N\}$ be linear independent in $W$. There are linear maps $g_n \in \Hom(V,W)$ such that
$$ g_n(v_0) = w_n, \quad n \in \mathbb N $$
Then $\{g_n \mid n \in \mathbb N\}$ is linear independent: Suppose $\sum\alpha_n g_n = 0$. Applying this to $v_0$ gives
$$ 0 = 0(v_0) = \sum\alpha_n g_n(v_0) = \sum \alpha_n w_n $$
as the $w_n$ are independent, we have $\alpha_n = 0$ for all $n$. So $\dim\Hom(V,W) = \infty$.
Comment: :) My question was, what is the dimension in the sense of cardinal numbers... In the finite dimensional case it is dim(V)dim(W), but it must be much larger otherwise I suspect.
Comment: @NicolasBourbaki Ok, perhaps you should add the tag (cardinals) then, to attract the set theory guys :).
Answer: I have proof for the following in PDF. It's quite lengthy and if I can find a good place to upload it I'll add a link. Here's the answer with an outline.

If $\dim (V) = 0$ or $\dim (W) = 0$ then $\dim (\hom (V, W)) = 0$ This follows as $\hom (V, W)$ only contains the zero transform in either case.
If $\dim (V)$ is finite then $\dim (\hom (V, W)) = \dim (V).\dim (W)$, whether $\dim (W)$ is finite or infinite. To prove this first establish that $\hom (F, W)$ is isomorphic to $W$, then that $\hom (V, W)$ is isomorphic to $\oplus_{\dim (V)}\hom (F, W)$
If $\dim (V)$ is infinite and $\dim (W) \ne 0$ then $\dim (\hom (V, W)) = |W|^{\dim (V)}$ (This has a simple corollary that for the dual $V^* = \hom (V, F)$ that $\dim (V^*) = |F|^{dim (V)}$ which confirms for an infinite dimensional space $\dim (V^*) > \dim (V)$). The proof is circuitous. (a) establish for any infinite dimensional space $U$ that $|U| = |F|.\dim (U)$. (b) Establish that $\dim (\hom (V, W))$ is infinite. (c) Establish  for any (non-zero dimensional) $V, W$ that $|\hom (V, W)| = |W|^{\dim (V)}$. (d) Establish that $\dim (\hom (V, W)) \ge |F|$. (e) put all that together so that $|\hom (V, W)| = |W|^{\dim (V)} = |F|.\dim (\hom (V, W)) = \dim (\hom (V, W)$

Dimension of $\operatorname{Hom}(V, W)$


Why do eligibility traces assign higher values to recently/frequently visited states?

Question: For me the evolution of TD Algorithms looks like this:
1-step TD: problematic with sparse rewards => Inefficient use of experience
n-step TD: better than 1-step, but what is the best n? (nobody knows without trying)
n-step TD(lambda): combine all n-step returns and build a weighted average over all returns => Q/V function can only be updated at the end of an episode
n-step TD(lambda) with eligibility traces: elegibility traces allow the Q/V function to be updated online/on the fly without waiting till an episode is over
What I don't understand is why we need an eligibility trace at all?
I think we could just ignore the eligibility trace because states which weren't visited frequently will have a small TD error so they won't be updated much anyway.
Update rule:
$Q(s_t,a_t)=Q(s_t,a_t)+\alpha \delta(s_t,a_t) et(s_t,a_t))$
TD error:
$\delta (s_t,a_t)=R_t+ \gamma Q(s_{t+1},a_{t+1})−Q(s_t,a_t)$
Comment: Could you clarify why you think that "states which weren't visited frequently will have a small TD error"? In general, I would expect the opposite, since estimates for the current value of those rare states are likely to have higher standard error, due to low sample number. I don't think frequency of state/action pairs is relevant here anyway, and putting an answer together.
Answer:
What I don't understand is why we need an eligibility trace at all?

It specifically calculates an equivalent to the n-step return that can be applied immediately to all previous visited states.
Without the eligibility trace, you would be left with two possibilities (depending on how you intend to remove it):

If you only apply corrections to most recent state/action value, effectively single-step returns (same as $\lambda = 0$)
If you remember all previous state/action pairs in the trajectory and update them all, very similar to Monte Carlo (same as $\lambda = 1, \gamma = 1$), but with updates applied immediately based on best bootstrapped estimate so far.

Why do eligibility traces assign higher values to recently/frequently visited states?

This is a direct consequence of the weighting of the different n-step returns that sum into a full $\lambda$ return, and the same thing happens in the forward view without eligibility traces (just the sums and updates occur in a different order).
The most recently-visited state is being adjusted for the n=1 term, plus an estimate of all remaining terms that will be cancelled out over time depending on value of $\lambda$. When $\lambda = 0$, then you only ever use the n=1 term, it has all the weight, since the eligibility trace for the current state goes to zero on next iteration. When $\lambda = 1$, effectively the previous estimate is continuously over-written with the next one, as the eligibility trace doesn't reset.
When the same state appears multiple times in a single trajectory (say it occurs twice, $k$ steps apart), then an $x$ steps after the second occurrence must update for the n-step return for $n=x$ and $n=x+k$. So the extra weighting is is not due to frequency of occurring so much as actually occurring on the trajectory that is being updated - there are literally two returns to calculate and sum into the estimate when a state happens twice.

I think we could just ignore the eligibility trace because states which weren't visited frequently will have a small TD error so they won't be updated much anyway.

Eligibility traces do not correct for frequencies of anything (maybe you are thinking of importance sampling here?). Instead, they effectively calculate [a correction for] $\lambda$ return, the weighted sum of 1..n step return, that can be shown to be an estimate of that same $\lambda$ return taken at the end of an episode. The actual trajectory taken matters, irrespective of the probability of it happening.
Corrections for frequency of states and actions occur in the long term due to sampling, and are not directly related to what the trace is doing. One way to see this: Provided there are no cycles going back to earlier states (where the eligibility-trace version may have updated the policy already), you can suppose that an agent interacting with the same policy and environment and same RNG seed would behave the same and collect the same raw data of rewards and successor states for making updates. At the end of an episode, the goal for eligibility trace version is, given these same trajectories, that its updates are the same numerically as the version without eligibility trace where all the updates are calculated at the end. You can see this number does not take frequencies of states directly into account (they have an effect on the long-term value function, but not on the current set of updates).
In Q($\lambda$) the probabilities of the policy do matter - trajectories that include exploratory actions have their eligibility trace (and thus estimates of long-term return) reset when taking non-maximising actions, so as not to feed back later non-maximising returns to earlier states.


Valores inteiros no terminal

Question: Preciso fazer a soma dos números ímpares entre 2 valores. Em compiladores online o código funciona como previsto, somando quaisquer valores impares de entrada e dando a saída esperada, porém no meu terminal (4.15.0-34-generic) ao colocar, por exemplo, 6 e -5, o resultado sai algo em torno de 32655, como se tivesse chegado ao limite do int, que eu chequei na internet e não é nem próximo de -5 o limite negativo do int.
    #include <iostream>

using namespace std;

int main() {

    int x,y,r;
    cin>>x>>y;
    if(x<y) {
        for (x; x<y ; x++){
            if(x%2 == 0) {
                continue;
            }
            else {
                r += x;
            }
        }
        }
    else {
            for (y; y<x ; y++){
                if(y%2 == 0) {
                    continue;
                }
                else {
                    r += y;
                }
        }

    }

    cout<<r<<endl;

    return 0; }

O código é este, está em C++.
Answer: Você esqueceu de inicializar o r!
Então, a valor de r é sempre indeterminada e depende do que tem na memoria ao momento da sua alocação.
Muda sua inicialização:
int x,y,r;

em:
int x,y,r=0;

Comment: Acabei descobrindo por acaso isto, mas muito obrigado mesmo assim por compartilhar o conhecimento.
Answer: Provavelmente o problema é que não inicializou a variável r com 0. Então pega lixo na memória. Como os compiladores online precisam de ambientes controlados eles tem grande chance de ter o 0 na memória e funciona por coincidência. Não programe para funcionar, programe para estar certo. Espero que isto lhe ensine que não pode confiar no resultado apresentado, porque ele pode estar certo só por coincidência. Temos muitos programas rodando por aí que "param de funcionar do nada", por a coincidência deixou de existir. programar não é ver se funciona, é provar que funciona sempre, em todas situações. Organizando e simplificando o código ficaria assim:
#include <iostream>
using namespace std;

int main() {
    int x, y, r = 0;
    cin >> x >> y;
    if (x < y) {
        for (; x < y; x++) if (x % 2 != 0) r += x;
    } else {
        for (; y < x; y++) if (y % 2 != 0) r += y;
    }
    cout << r << endl;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Dá para simplificar mais, mas provavelmente teria perda de performance, e alguns achariam menos legível.
Comment: Muito obrigado meu nobre, essa ideia de inicializar a variável eu desconhecia por completo.

Valores inteiros no terminal


Adding same datastore to two Esxi 4.1 servers

Question: I have installed Winodws 7 on it Vmware workstation 7 into it I have created two Esxi 4.1 virtual machines and a 2003 64 bit machine for vCenter.
I have 500 GB HDD on which all these components are installed.
Now I want to practice for VCP exam and want to know how to add my local logical drive on that physical disk as a common datastore for these two ESXi 4.1 VMs?
One option may be that creating a 2003 VM installing NFS on it and presenting it to these ESX VMs.
Is there any option else?
Answer: You could use Openfiler to present iSCSI storage to your ESXi hosts. They have a VMware Virtual Appliance that would get you up and running pretty quickly.
Comment: +1, this is probably the best way, Tushar probably needs to work with block storage for at least part of his training and OpenFiler can do NFS too, there's no FC option in this kind of setup. Good luck too Tushar, VCP's not too tough but I'm doing VCAP right now and it's...challenging :)


Find largest image

Question: I am using the following to find the image within .content and apply it's width to the .project parent width.
    $('.content').find('img').each(function () {
         var $this = $(this), width = $this.width();
         {
            $(this).closest('.project').css("width", width);
        }
    });

My problem is that it doesn't find the largest image in the .content and sometimes applies a width that is smaller than the largest image and is creating problems with my layout.
Any help would be great. Thanks.

Edit
Woops, detail is wrong, the answers are great! I just need to apply the max width the parent project div.
Building off Sudhir's answer.
This doesn't work, should it work?
 $(document).ready(function() {
var max_width = 0;
$('.content').find('img').each(function(){
        var this_width = $(this).width();
        if (this_width > max_width) max_width = this_width;
});
$(this).closest('.project').css('width', max_width + 'px');
});

Example of the layout. There are many projects.

Other content here.

Other content here.

Comment: I'm having trouble picturing what the layout of the Div's is on your site. Do you have lots of .content divs each with their own .project div? Or is there one .content div with .project divs inside it each with images inside them? Could you post an example of the HTML layout please.
Comment: Yep each .content div has it's own parent .project div as well. Hows that @Tim I hope that makes sense, many .projects within a larger container.
Answer: You can't do this on document ready event. You have to do this on window load because all images must be loaded to get the dimensions.
$(window).load(function(){
    $('.project').each(function(){
        var maxWidth = 0;
        $(this).find('.content img').each(function(){
            var w = $(this).width();
            if (w > maxWidth) {
              maxWidth = w;
            }
        });
        if (maxWidth) {
          $(this).css({width:maxWidth});
        }
    });
});

Comment: Thats great @kitgui.com . My only problem is that if there is no image found it defaults to 0px. Which breaks the layout again. But should I write an additional script to look for projects without images.
Comment: right, my point was to show you it was window load as the main issue, not anything else. you can fix as you need. this is for demonstration purposes. I'll put a boolean for you if you just for shtz and giggles
Comment: Thank you very much, do you know if there is a way to avoid the window load issue?
Comment: Yes, you could put a load event for each image individually and give it context of its ".project" and "maxWidth" by using the data property. This becomes a little tricky if images are cached and don't fire as Chrome sometimes does. The less headache way is to rely on window load but it can seem slower. You could also result to putting divs wrapped around the images and use overflow hidden and give it an expected average dimension. Then you can adjust on load. At least users won't notice as much.
Comment: @kitgui.com If I remember right, you cannot have 'load' events on images in older MSIE versions
Comment: @yunzen  man you gotta see this -> http://code.google.com/p/ie7-js/  it basically fixes IE   see the IE9 one. This is amazing man. John Resig refers to this guy for inspiration. He's that good.
Answer: Do you mean something like this:

var max_width = 0;
$('.content').find('img').each(function(){
        var this_width = $(this).width();
        if (this_width > max_width) max_width = this_width;
});
$('.project').css('width', max_width + 'px');

Hope it helps
Comment: This works well, except it's applying the same width to each `.project`. Rather than finding the largest image within the project and applying the largest with to that project. Like how `.closest` worked before.
Answer: To get maximum width of something just iterate with this function:
var getMaxWidth = function ($elms) {
    var maxWidth = 0;
    $elms.each(function () {
        var width = $(this).width();
        if (width > maxWidth) {
            maxWidth = width;
        }
    });
    return maxWidth;
};

Comment: You forgot to initialise the `width` variable. :-)
Answer: The example in the jQuery plugin authoring guide is very similar to what you're looking for:
$.fn.maxWidth = function() {
  var max = 0;

  this.each(function() {
    max = Math.max(max, $(this).width());
  });

  return max;
};

Use it like so:
var maxWidth = $('.content img').maxWidth();

Answer: This works, I don't know if you want it super compressed though:
function findmax() {
    max=Math.max(max,parseInt($(this).css('width'))); }
function sum() {
    max=0;
    $(this).children('img').each(findmax);
    $(this).parent().css('width',max+'px'); }
var max;
$('.content').each(sum);

Answer: You're looping through all images, so the width of your container will always be the same as your last image.  You should check the width of the current image and compare it to the width of the widest image found at that point and adjust the width accordingly.
Edit
Try this:
$('.content').each(function () {
    var max_width = 0;
    $(this).find('img').each(function () {
        if ($(this).width() > max_width) {
            max_width = $(this).width();
        }
    });

    $(this).width(max_width);

});

Crazy with the nested $(this)'s but I think it should work.

Find largest image