how to avoid windows crash screen

Question: We have UnhandledExceptionEventHandler in place and unexpected exceptions were caught by that handler. But why we still see the following screen? I thought if we handled the exception, it will not go up to the OS. If no exception reach the system level, why that screen still show up?
Comment: Are you using more than one AppDomain?
Comment: You can't handle that exception.  Not calling Environment.Exit() still buys you this window.  You'll also get it if it bombs before you can set the event handler.
Answer: Registering an UnhandledExceptionEventHandler with AppDomain.UnhandledException does not mean that unhandled exceptions become handled.  Instead, it is a mechanism to be able to log the exception and relevant program state to aid in later debugging.  The exception will remain unhandled and Windows Error Reporting will be invoked.
In reality, when this event is invoked it's "too late" for the the exception to be handled.  Assuming you could tell the runtime to continue execution, where would execution unwind to?  Not a single frame on the call stack wanted to handle the exception.  At best, the executing thread could be terminated; but what if it's on the only foreground thread?  Better to propagate the unhandled exception to the operating system's default unhandled exception filter and let it invoke Windows Error Reporting.
Edit with some additional comments:
Now, certain applications you want to design to be crash-resistant, such as long-running service processes.  It may make sense to add "catch-all"* exception handlers in some cases, such as a job queue that executes jobs and it doesn't matter if an individual job fails with an unhandled exception; we log the problem and move on to the next job.  However, a root catch-all handler in something like Main makes little sense: your entire application is now in an unknown state.  You could log the exception and terminate, but you'd be missing out on the benefits of Windows Error Reporting: post-mortem minidumps and an easy button (the "Debug" button on that dialog) to invoke the registered JIT debugger that will take you directly to the problem.  For most software, my advice is to simply let your software crash; in-your-face bugs with minidumps are usually some of the easiest to fix.
*Some exceptions are inherently "uncatchable", such as a StackOverflowException.  Others, such as an AccessViolationException are catchable, but are inherently indicative of a serious program state incongruity (couldn't read or write from an expected memory location).  It is never a good idea to attempt recovery from such exceptions.
Answer: Click the Debug button to see where the exception comes from.
If you don't see it immediately, start your application in Visual Studio, go to the Debug,Exceptions dialog, and check all exceptions.  Then rerun your application, investigate the code every time the debugger tells you that a first-chance exception has been encountered, and pass the exception to the application if Visual Studio asks you whether to do this.
This should help you finding the source of the problem.
Answer: That's because your unhandled exception occurs in the main thread, and there is almost nothing to do about it. Check this article: What!? A .NET Application Can Die?
Almost nothing, yes, because you can still catch that exception on the Application.Run level. At this point your application is dead anyway, but at least you can "avoid windows crash screen" and implement your own crash screen instead:
    static void Main()
    {
        try
        {
            Application.Run(new Form1());
        }
        catch (Exception ex)
        {
            MessageBox.Show("Oops! Can I has " + ex.Message + "?");
        }
    }

Answer: There are cases when unhadled exceptions will not be handled by UnhandledExceptionEventHandler. For example System.Timers.Timer is swallowing exceptions, so they are not propagated to UnhandledExceptionEventHandler.

how to avoid windows crash screen


Compile Error in VBA

Question: I am new to VBA so apologies if I am not clear in my question.
I have code which is included below with a number of loops and I am getting a Compile Error "next without For" at line 165 "Next counter".
However I have the "For counter = " at line 121. So in my ignorance I am baffled.
Sorry if this code is too amateur but it is the best I can do.
Sub Macro9()

Dim cardtype, drcr, sheetname, wbkname, merchant As String
Dim counter, prd As Integer
Dim row1, row2, row3, row4, row5 As Integer
Dim col1, col2, col3, col4, col5 As Integer
Dim val1, val2, val3, val4, NFile As Long
Dim rng As Range
Dim wks As Worksheet
Dim WorkBk As Workbook
Dim FolderPath, FileName As String
Dim SelectedFiles() As Variant

prd = InputBox("Input the Period number")

FolderPath = "C:\My Files\Reports\Statements\"

ChDrive FolderPath
ChDir FolderPath

SelectedFiles = Application.GetOpenFilename( _
    filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)

For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)

    FileName = SelectedFiles(NFile)

    Set WorkBk = Workbooks.Open(FileName)

    sheetname = ActiveSheet.name
    wbkname = ActiveWorkbook.name
    merchant = Left(wbkname, 7)

    Cells.Select
    Selection.Find(What:="Trans Value", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

col1 = ActiveCell.Column

Cells.Select
Selection.Find(What:="Quantity", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

col2 = ActiveCell.Column

Cells.Select
Selection.Find(What:="charge Desc", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

col3 = ActiveCell.Column

ActiveCell.Offset(1, 0).Range("A1:A200").Select
Selection.SpecialCells(xlCellTypeConstants, 2).Select

row1 = ActiveCell.row

Cells.Select
Selection.Find(What:="Cr/Dr Trans Flag", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

col4 = ActiveCell.Column

Cells.Select
Selection.Find(What:="Balance from last month", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

row2 = ActiveCell.row - 1

Cells.Select
Selection.Find(What:="charge ($)", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

col4 = ActiveCell.Column

ActiveCell.Offset(1, 0).Range("A1:A200").Select
Selection.SpecialCells(xlCellTypeConstants, 1).Select

row4 = ActiveCell.row

Cells.Select
Selection.Find(What:="Store1 Credit", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
ActiveCell.FormulaR1C1 = "Web1 Credit"

Cells.Select
Selection.Find(What:="Store2 Credit", After:=ActiveCell, LookIn:=xlFormulas _
    , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
ActiveCell.FormulaR1C1 = "Web2 Credit"

For Each wks In Worksheets

Set rng = wks.Cells.Find("Store Refund")
If Not rng Is Nothing Then
rng = "Web Refund"
Exit Sub

End If
Next wks

For counter = row1 To row2

Rows(counter).Columns(col3).Select
cardtype = ActiveCell.Value
row3 = ActiveCell.row
drcr = Rows(counter).Columns(col4).Value
val1 = Rows(counter).Columns(col2).Value

If drcr = CR Then
val2 = -Rows(counter).Columns(col1).Value
Else
val2 = Rows(counter).Columns(col1).Value
End If

Windows("Stores 2013.xlsm").Activate

ActiveWorkbook.sheets(prd).Select

Columns("B:B").Select
Selection.Find(What:=cardtype, After:=ActiveCell, _
    LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate

If merchant = 1234567 Then
ActiveCell.Offset(0, 4).Select
val3 = ActiveCell.Value
Else
If merchant = 7654321 Then
ActiveCell.Offset(0, 8).Select
val3 = ActiveCell.Value
Else
If merchant = 1122334 Then
ActiveCell.Offset(0, 12).Select
val3 = ActiveCell.Value
End If

ActiveCell.FormulaR1C1 = val1 + val3
ActiveCell.Offset(0, 1).Select
val4 = ActiveCell.Value
ActiveCell.FormulaR1C1 = val2 + val4

Windows(wbkname).Activate

Next counter

Windows("Stores 2013.xlsm").Activate

ActiveWorkbook.sheets(prd).Select

Columns("B:B").Select
Selection.Find(What:="Total $", After:=ActiveCell, _
    LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate

If merchant = 1234567 Then
ActiveCell.Offset(0, 6).Select
Else
If merchant = 7654321 Then
ActiveCell.Offset(0, 10).Select
Else
If merchant = 1122334 Then
ActiveCell.Offset(0, 14).Select
End If

ActiveCell.FormulaR1C1 = "='[wbkname]" & sheetname & "'!R" & row4 & "C" & col4

WorkBk.Close savechanges:=False

Next NFile

End Sub

THanks in advance
Comment: Debug when you receive the error. It's possible the value of the current position is different to the rest, causing it to fail.
Comment: @t.thielemans Thanks for responding. Unfortunately, I do not get the debug option. I get the pop up Compile Error "next without For" and the highlighter goes straight to line 165 where "Next counter" appears in the code above
Answer: Else
If

is not the same as
ElseIf

Try this:
Sub Macro9()

Dim cardtype, drcr, sheetname, wbkname, merchant As String
Dim counter, prd As Integer
Dim row1, row2, row3, row4, row5 As Integer
Dim col1, col2, col3, col4, col5 As Integer
Dim val1, val2, val3, val4, NFile As Long
Dim rng As Range
Dim wks As Worksheet
Dim WorkBk As Workbook
Dim FolderPath, FileName As String
Dim SelectedFiles() As Variant

prd = InputBox("Input the Period number")

FolderPath = "C:\My Files\Reports\Statements\"

ChDrive FolderPath
ChDir FolderPath

SelectedFiles = Application.GetOpenFilename( _
    filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)

For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)

        FileName = SelectedFiles(NFile)

        Set WorkBk = Workbooks.Open(FileName)

        sheetname = ActiveSheet.Name
        wbkname = ActiveWorkbook.Name
        merchant = Left(wbkname, 7)

        Cells.Find(What:="Trans Value", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate

    col1 = ActiveCell.Column

    Cells.Find(What:="Quantity", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate

    col2 = ActiveCell.Column

    Cells.Find(What:="charge Desc", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate

    col3 = ActiveCell.Column

    ActiveCell.Offset(1, 0).Range("A1:A200").SpecialCells(xlCellTypeConstants, 2).Select

    row1 = ActiveCell.Row

    Cells.Find(What:="Cr/Dr Trans Flag", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate

    col4 = ActiveCell.Column

    Cells.Find(What:="Balance from last month", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate

    row2 = ActiveCell.Row - 1

    Cells.Find(What:="charge ($)", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate

    col4 = ActiveCell.Column

    ActiveCell.Offset(1, 0).Range("A1:A200").SpecialCells(xlCellTypeConstants, 1).Select

    row4 = ActiveCell.Row

    Cells.Find(What:="Store1 Credit", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.Select
    ActiveCell.FormulaR1C1 = "Web1 Credit"

    Cells.Find(What:="Store2 Credit", After:=ActiveCell, LookIn:=xlFormulas _
        , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.Select
    ActiveCell.FormulaR1C1 = "Web2 Credit"

    For Each wks In Worksheets

        Set rng = wks.Cells.Find("Store Refund")
        If Not rng Is Nothing Then
        rng = "Web Refund"
        Exit Sub

        End If
    Next wks

    For counter = row1 To row2

        Rows(counter).Columns(col3).Select
        cardtype = ActiveCell.Value
        row3 = ActiveCell.Row
        drcr = Rows(counter).Columns(col4).Value
        val1 = Rows(counter).Columns(col2).Value

        If drcr = CR Then
        val2 = -Rows(counter).Columns(col1).Value
        Else
        val2 = Rows(counter).Columns(col1).Value
        End If

        Windows("Stores 2013.xlsm").Activate

        ActiveWorkbook.Sheets(prd).Select

        Columns("B:B").Find(What:=cardtype, After:=ActiveCell, _
            LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate

        If merchant = 1234567 Then
            ActiveCell.Offset(0, 4).Select
            val3 = ActiveCell.Value
        ElseIf merchant = 7654321 Then
            ActiveCell.Offset(0, 8).Select
            val3 = ActiveCell.Value
        ElseIf merchant = 1122334 Then
            ActiveCell.Offset(0, 12).Select
            val3 = ActiveCell.Value
        End If

        ActiveCell.FormulaR1C1 = val1 + val3
        ActiveCell.Offset(0, 1).Select
        val4 = ActiveCell.Value
        ActiveCell.FormulaR1C1 = val2 + val4

        Windows(wbkname).Activate

    Next counter

    Windows("Stores 2013.xlsm").Activate

    ActiveWorkbook.Sheets(prd).Select

    Columns("B:B").Find(What:="Total $", After:=ActiveCell, _
        LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate

    If merchant = 1234567 Then
    ActiveCell.Offset(0, 6).Select
    ElseIf merchant = 7654321 Then
    ActiveCell.Offset(0, 10).Select
    ElseIf merchant = 1122334 Then
    ActiveCell.Offset(0, 14).Select
    End If

    ActiveCell.FormulaR1C1 = "='[wbkname]" & sheetname & "'!R" & row4 & "C" & col4

    WorkBk.Close savechanges:=False

Next NFile

End Sub

Also, there is a lot to be cleaned up in your code.  Have a read here: How to avoid using Select in Excel VBA macros
Comment: Brilliant! That seems to have sorted it out. I know I need to stop using select. Thanks for the link.
Comment: Great, glad it helped!  And as a matter of pure preference, I prefer Select Case over ElseIf Statements (http://msdn.microsoft.com/en-us/library/office/gg278454.aspx).  I find them easier to read.

Compile Error in VBA


Django 1.4 serving media files works, but not static

Question: I am using Django 1.4 and for some reason i am able to serve media files, but not the static ones...
Here is my code:
settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'

urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
                    (r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),

base.html:
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
<link href="{{ MEDIA_URL }}css/bootstrap-colorpicker.css" rel="stylesheet">

i get a 404 http not found... what am i doing wrong? An i did create the static folder in my project right next to media

http://mysite.com:8000/static/css/bootstrap.css
Comment: Do you have `django.contrib.staticfiles` in your INSTALLED_APPS and is this a development site with DEBUG=True?
Comment: yes to both questions... by the way in production should i put DEBUG to false??
Comment: Would this be of any help?  http://stackoverflow.com/questions/14799835/django-static-files-results-in-404/14800489#14800489
Comment: tried it with no luck
Comment: ADMIN_MEDIA_PREFIX is deprecated in Django 1.4. Also instead os STATIC_URL is recommended to use {% static "css/bootstrap.css" %}
Answer: Your static folder should be under one app that you use it for.
For example, I have a project named my_project and an application named my_app, I have some static files used in my_app so I put them under ~/project_path/my_project/my_app/static
NB: my_app must be in INSTALLED_APPS. See STATICFILES_FINDERS documentation.
Edit:
As a best practice, you should have a global static folder in one app (the main one), for example a static folder how contains your html template basic resources as jquery, bootstrap, your global style.
And for the static files how's required only for one app, for example app foo, these files should be under foo/static folder
Comment: yeah it use only one file, like @Andrew S say, we have used collectstatic to test if Django find or not the static folder, but it's used only for production(for example for apache). If in the future you would to delete one apps, it can't infect your others apps because any apps is static folder is independant from each other, that's the trick !
Comment: what if i need the same static file for 2 or more apps?? i duplicate the file or collect-static automatically detects and only uses 1?
Answer: I suggest removing the explicit media and static views and allowing the staticfiles app to create them (when DEBUG is True under development).
Check the default finders are present in your settings.py
https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_FINDERS
Either add your project static directory to STATICFILES_DIRS (https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS) or place app specific static folders under each app. The app needs to be listed in the INSTALLED_APPS for the finders to locate the static content.
Do not place static files into STATIC_ROOT yourself. This directory is managed by the collectstatic command. See https://docs.djangoproject.com/en/dev/howto/static-files/#deployment
Comment: default finders are present. i tried adding os.path.join(BASE_DIR, 'static/'), to STATICFILES_DIRS with no luck.. is that what you are suggesting? i want to keep my static files in one place only like the projects directory not inside the apps because i have some common resources
Comment: im not sure i understood.. i don't have a view for /static.. only the routing in urls and the rest in my settings.py
Comment: Remove the static entry from urls.py.  Also, 'STATIC_ROOT' should not be where your project static files are kept. The 'STATIC_ROOT' directory is where the 'collectstatic' command will place all static content for serving in production.
Comment: i did that and it only creates the admin static files.. it seems like it does not recognize my other static files for some reason
Comment: What is the full path to the root of the project's static files? That is the path you add to STATICFILES_DIRS. It should **not** be the same as STATIC_ROOT. As this is a directory outside of an app you don't need to add it to INSTALLED_APPS. Running collectstatic will copy all known static content to the STATIC_ROOT so it's a good test to see what is being found as static content. During development you don't serve files from the STATIC_ROOT and should use the staticfiles app to serve them automatically. There's no need to add the static URL to urls.py.
Answer: Here is how i define my media url in settings.py:
import os
ABSOLUTE_PATH           = os.path.dirname(__file__)
MEDIA_ROOT              = os.path.join(ABSOLUTE_PATH, '../media')
MEDIA_URL               = '/media/'
STATIC_ROOT             = os.path.join(ABSOLUTE_PATH, '../static')
STATIC_URL              = "/static/"

So like you see the difference is ../media and ../static
Is mysite in your installed apps ? Django look inside your installed apps and check if there's a static folder there.
Comment: Where is the location of your static folder ?
Comment: /home/username/git/mysite/mysite/static
Comment: Is your settings.py here /home/username/git/mysite/mysite/settings.py ? and /home/username/git/mysite your project folder ?
Comment: Another think, verify that you have this in your settings file:
`STATICFILES_FINDERS     = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )`
Comment: its here /home/username/git/mysite/mysite/settings.py
Comment: and yes i have the staticfiles_finder like that
Comment: Run this command `./manage.py collectstatic` and check if your files are copied here /home/username/git/mysite/static/
Comment: only the admin static files were copied to /home/username/git/mysite/mysite/static/
Comment: So Django doesn't know that you have a static files there.
Is mysite in your installed apps ?
Comment: No its not, only the apps.. but i tried adding now and it gives Error: No module named mysite
Comment: It's the error, Django look inside your installed apps and check if there's a static folder there. So could you post your settings.py and check if you have a `__init__.py` file inside  /home/username/git/mysite/mysite
Comment: yes i have __init__.py there.. i could put my static files under my apps, but at this point i have them all together in one folder and its being shared accross multiple apps


Go Git - Recurse Submodules

Question: I have a project which contains submodules as shown here.
[submodule "repo-a"]
    path = repo-a
    url = https://example.com/scm/repo-a.git
[submodule "repo-b"]
    path = repo-b
    url = https://example.com/scm/repo-b.git
[submodule "repo-c"]
    path = repo-c
    url = https://example.com/scm/repo-c.git

I am using go-git pkg and trying to clone with options as shown here,
cloneOpts := &git.CloneOptions{
      URL:               url,
      RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
}

It does not recursively pull the submodules. I see only empty directories. Am I missing something?
Comment: Yes, this needs a [mcve].
Comment: The go-git implementation doesn't use Git, so this is a pure go-git question.
Comment: I cannot reproduce this, the `PlainClone` method correctly clones the submodules of a repo that I tested it with.
Comment: @OliverTale-Yazdi My parent module contains nothing but `.gitmodule` which is the above file. Do you have anything else?
Comment: @torek So what happens when you clone this [example repo](https://github.com/githubtraining/example-dependency)? Is the content of the `js` folder present? Otherwise I would need to see the code to help you better.
Comment: @OliverTale-Yazdi: using plain (not go-) Git, I get: `git submodule status` => `-c3c588713233609f5bbbb2d9e7f3fb4a660f3f72 js`. The current branch (as recommended by https://github.com/githubtraining/example-dependency) is `master` and its tip commit contains a gitlink named `js` pointing to that commit; the `.gitmodules` file has instructions for cloning the submodule. A subsequent `git submodule update --init` clones the submodule and does a detached-HEAD checkout of that commit, as one might expect. What does `go-git` do when one provides the remaining MRE? Where is that remaining MRE?
Answer: Even after your comments, I have no idea how you are currently using go-git; so please provide your source code.
I am now answering your original question of "how to clone a repo and its submodules" in go-git:
package main

import (
    "os"

    "github.com/go-git/go-git/v5"
)

func main() {
    repoURL := "https://github.com/githubtraining/example-dependency"
    clonePath := "example-repo"

    _, err := git.PlainClone(clonePath, false, &git.CloneOptions{
        URL:      repoURL,
        Progress: os.Stdout,
        // Enable submodule cloning.
        RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
    })

    if err != nil {
        panic(err)
    }

    println("Have a look at example-repo/js to see a cloned sub-module")
}

As you can see after running this, example-repo/js contains the cloned submodule.
Comment: It works man. Sorry it was my fault. But i do appreciate you for taking time to create repo and show a working sample.
Comment: @RamPrakash No worries, I'm happy to help

Go Git - Recurse Submodules


Daemon clean up itself when get killed

Question: I'm try to create a daemon application by following the example :
Creating a daemon in Linux
In the example, there is no operations about the daemon stop.
Therefore, I'm curious about :

How to send stop signal to the daemon ? Or just kill PID directly ?
If the daemon only can stop on killed, should the daemon itself do the cleaning up operations on killed ? Just like close file descriptors, saving parameters, etc.

Thanks in advance.
Comment: Nowadays, in the systemd world, i think you just begin graceful shutdown when you receive the `SIGTERM` signal (which can be send by `kill` indeed). This information might be of use too : https://www.freedesktop.org/software/systemd/man/systemd.kill.html#KillMode=
Comment: Daemons often create a so-called pid file in /var/run or /run typically named ".pid" into which their pid is stored. This can be used to retrieve the pid of the daemon from its name and send a SIGTERM signal to make it finish gracefully.
Answer:
should the daemon itself do the cleaning up operations on killed ? Just like close file descriptors, saving parameters, etc.

Closing file descriptors is pointless -- they'll be automatically closed by the kernel when the process exits.
For "saving parameters", it depends on what you mean by "parameters". If you mean the command-line arguments, then no: when the daemon is restarted, it will get a fresh copy of these.
Comment: @whisper There are quite a few things you _may_ need to worry about, depending on what exactly your daemon is doing. SysV shared memory for example doesn't get cleaned up (which is also why you should avoid using it). Without knowing anything about your daemon, it's hard to guess what (if anything) you _may_ need to clean up.
Comment: Thanks a lot. Besides these, is there any other potential risks need to care about if no clean up action in the daemon ?
Comment: thanks, it's enough, I just start up test the daemon and do not have clear the idea what kind of resource may be token. I will keep it in mind with the program development going.

Daemon clean up itself when get killed


Place components at arbitrary (x,y) coordinates

Question: I want to place some buttons in a JPanel at random positions (x,y), and these layout classes are annoying.
Is this even possible in Swing?
Comment: It's better to learn about different [Layout Managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html).
Comment: No, you definitely _do not want_ to do any swing layout manually. And no, there's nothing annoying about layoutManagers - except you think learning is annoying in itself ;-)
Comment: why is everybody second-guessing the op? maybe he just needs complete control over the buttons positions (like for example in some kind of game where they move around and the user has to hit them).
Comment: @fortran *"complete control over the buttons"*  If you have the logic needed to maintain that 'control' in a logical sense - put it in a custom layout manager.
Comment: @AndrewThompson why? If I just want to shake them randomly (for example), what is the advantage of putting it in a custom layout manager?
Comment: Post an actual (working*) example on a separate question & I might be willing to discuss it further.  * And by 'working' I mean works for a variety of components & PLAFs in a resizable GUI.
Answer: You can set the coordinates if you use a null layout:
panel.setLayout(null);
Button b = new Button(....);
panel.add(b);
b.setSize(width, height);
b.setLocation(x,y);

But it is strongly recommended to use layouts. Layout classes are not "annoying", they are your friend if you understand them properly.
I propose reading a tutorial about GridBagLayout, it is easy to understand (kinda html tables) and very powerful.
Comment: +1 for recommending LayoutManagers, -0.5 for doing manual layout incompletely (hach, nicely prooving the usefulness of managers ... :-)
Answer: use null as "Layout Manager":
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Comment: that is what I wrote before editing, but then I realised that someone might try to look for a class called like that ^_^
Comment: no problem at all, it's simple wrong to propagate usage of null layout :-)
Comment: See [setLayout(null) is never necessary. Ever!](https://forums.oracle.com/forums/thread.jspa?threadID=1351374) for more discussion on the matter.
Comment: @kleopatra what kind of problem do you have?
Comment: @AndrewThompson creating a custom LayoutManager that does the same as the null layout when you really need to place components "manually" seems too add unnecessary layers and complexity
Comment: Try it (and make it work for `null` layout across the range of circumstances outlined in the linked thread) to find out different.


send string from C# app to php page

Question: i want send string to my php page and i used one of answers in this site
C# code:
 try
        {
            string url = "http://localhost:8080/test.php";
            string str = "test";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            string Data = "message=" + str;
            byte[] postBytes = Encoding.ASCII.GetBytes(Data);
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = postBytes.Length;
            Stream requestStream = req.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            Stream resStream = response.GetResponseStream();

            var sr = new StreamReader(response.GetResponseStream());
            string responseText = sr.ReadToEnd();

        }
        catch (WebException)
        {

            MessageBox.Show("Please Check Your Internet Connection");
        }

and php code:
 if (isset($_POST['message']))
{
    $msg = $_POST['message'];
    echo $msg;
}

but its just a blank page.
can anybody tell me what is wrong????
thank you.
Answer: I'm not sure setting "message=" + data will create an item in the post array called message: it may just create an unnammed item with content "message=blahblahblajh".
You can test this theory by doing this in your php:
foreach($_POST as $pdata)
echo " *-* ".  $pdata." *-*
 ";

I've not used the HttpWebRequest for this, but you could try using the webclient class:
    string url = "http://localhost:8080/test.php";
    string str = "test";
    WebClient webClient = new WebClient();
    NameValueCollection formData = new NameValueCollection();
    formData["message"] = str;
    byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
    string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
    webClient.Dispose();

Alas, I'm not in a position to try this out at the moment, so this is from memory and google!
Comment: which library i should use for namevaluecllection??
Comment: System.Collections.Specialized
Comment: thank you for replying but its still just a blank page
Comment: strange, have you changed your php to echo all the contents of the $_POST array? Then at least you would see if anything is getting to PHP
Answer: If you're going to the webpage from a browser after running the code, you would get a blank page, because your browser is not sending a post request, your application is, in order to view your response, just show the response text in a messagebox or a textbox. i.e.
MessageBox.Show(responseText);

send string from C# app to php page


Prove that for $\forall m \ge 2$, $\dfrac{1}{2}(a^4 + b^4 + c^4) \mid [(ab)^{2^m} + (bc)^{2^m} + (ca)^{2^m}]$.

Question:
Let $(a, b, c)$ be a Pythagorean triple. Prove that for $\forall m \ge 2$, $$\large \dfrac{1}{2}(a^4 + b^4 + c^4) \mid \left[(ab)^{2^m} + (bc)^{2^m} + (ca)^{2^m}\right]$$

Let $P_{n} = a^{2^n} + b^{2^n} + c^{2^n}$, we have that $$4(abc)^{2^k}P_{m} + P^2_{m + 1} - P_{m + 2}$$
$$ = 4(abc)^{2^m} \cdot \left(a^{2^m} + b^{2^m} + c^{2^m}\right) + \left(a^{2^{m + 1}} + b^{2^{m + 1}} + c^{2^{m + 1}}\right)^2 - \left(a^{2^{m + 2}} + b^{2^{m + 2}} + c^{2^{m + 2}}\right)$$
$$ = 4 \cdot \left[(ab)^{2^m} + (bc)^{2^m} + (ca)^{2^m}\right] + 2 \cdot \left[(ab)^{2^{m + 1}} + (bc)^{2^{m + 1}} + (ca)^{2^{m + 1}} \right]$$
$$ = 2 \cdot \left[(ab)^{2^m} + (bc)^{2^m} + (ca)^{2^m} \right]^2$$
So now we need to prove that $\dfrac{1}{2}(a^4 + b^4 + c^4) \mid 2 \cdot \left[(ab)^{2^m} + (bc)^{2^m} + (ca)^{2^m} \right]^2$
$\iff \dfrac{1}{2}(a^4 + b^4 + c^4) \mid 4(abc)^{2^k}P_{m} + P^2_{m + 1} - P_{m + 2}$. But I don't know about whether it is sufficient to prove that $\dfrac{1}{2}(a^4 + b^4 + c^4) \mid P_{n}$ for $\forall n \ge 2$.
And why does $(a, b, c)$ have to be a Pythagorean triple?
Comment: In the first equation chain, the step from line 3 to line 4 seems dubious. You are saying that $4[x+y+z]+2[x^2+y^2+z^2]=2[x+y+z]^2$. This would assume that $x+y+z=xy+yz+zx$. Even with $x=AB$, $A=a^{2^m}$ etc. this gives $AB+BC+CA=(ABC)(A+B+C)$ or $\frac1A+\frac1B+\frac1C=A+B+C$, which seems unreasonable.
Answer: As you did, this answer uses $P_m$ where
$$P_m=a^{2^m}+b^{2^m}+c^{2^m}$$
We may suppose that $c^2=a^2+b^2$.
Let $$Q_m=(ab)^{2^m}+(bc)^{2^m}+(ca)^{2^m},\qquad R=\frac{a^4+b^4+c^4}{2}$$
Now, let us prove by induction on $m$ that $R\mid P_m$ and $R\mid Q_m$.
We see that $R\mid P_2$ and $R\mid Q_2$ since
$$Q_2=(a^4+a^2b^2+b^4)^2\qquad\text{and}\qquad R=a^4+a^2b^2+b^4$$
Suppose that
$$R\mid P_m\qquad\text{and}\qquad R\mid Q_m$$
Then, since
$$Q_{m+1}=Q_m^2-2a^{2^m}b^{2^m}c^{2^m}P_m\qquad \text{and}\qquad P_{m+1}=P_m^2-2Q_m$$
we get
$$R\mid P_{m+1}\qquad\text{and}\qquad R\mid Q_{m+1}\qquad\blacksquare$$
Answer: HINT.-Given that $a, b, c$ are Pythagorean triples, we can deduce that the problem is equivalent to demonstrating that for every pair of integers $a, b$ the quotient
$$\frac{(a^{2^m}+b^{2^m})(a^2+b^2)^{2^{m-1}}+a^{2^m}b^{2^m}}{(a^2+b^2)^2-a^2b^2}$$ is always an integer for $m\ge2$ (which can be verified numerically).
Trying to apply induction we have for the minimum value $m=2$ the verification (where the numerator is exactly the square of the denominator)
$$\frac{(a^{4}+b^{4})(a^2+b^2)^{2}+a^{4}b^{4}}{(a^2+b^2)^2-a^2b^2}=(a^2+b^2)^2-a^2b^2$$
I cannot for now (lack of time) complete the inductive demonstration so I invite someone who wishes to do so.


android sqlight invoked from class

Question: I am using Gamelogic class which implements no one (just object to be honest )
I want from him to set a database where the game screen ask the logic questions and the last ask the sql question without all the Context usage , just to keep it simple .
is it possible ? if not what is the alternative?
Can someone show me little example?  I am lost and the notepad example does not help
thanks, yoav.
Answer: You HAVE to use a Context in that case. But you are lucky, all activities are Contexts so what you have to do is passing a reference of your activity to the Gamelogic class. For instance, you can pass it as an argument to its constructor:
public class Gamelogic{
    private Context context;
    public Gamelogic(Context context){
        this.context = context;
        // do what ever you want with the context object
    }
    // more complex logic here
}

On your activity:
public class YourActivity extends Activity{

    // foo bar baz blablablabla

    public void someWhereOnYourActitity(){
        new Gamelogic(YourActivity.this);
    }
}

Comment: does it makes a difference if i send

1.this.getApplicationContext()

OR

2.YourActivity.this

?
Comment: Actually no... they reference the same context.

android sqlight invoked from class


Conversão de charset

Question: Tenho um site para desenvolver para um cliente e o banco de dados MySQL dele está assim:

Database Properties: Character set: latin1--cp1252 West European; Collation: latin1_general_ci
Já as tabelas estão todas assim: Character set: utf8--UTF-8 Unicode; Collation: utf8_general_ci

O novo banco será:

Database Properties: Character set: Character set: utf8--UTF-8 Unicode; Collation: utf8_general_ci
Já as tabelas estão todas assim: Character set: utf8--UTF-8 Unicode; Collation: utf8_general_ci

Esta diferença entre as propriedades do banco me forçarão a fazer alguma conversão dos dados para não perder acentuação e caracteres especiais?
Comment: tem mais alguma dúvida? faça um comentário
Answer: Não terá problemas, o Database Properties define o "padrão" que será usado na "criação de tabela" quando esta não for setada um charset ele pega o default do Database.
Como você já tem as tabelas tudo em utf-8, e vai mandar para um Database onde tudo é utf-8 não precisa fazer nada além de um backup/restore normal.

Conversão de charset


How can I make the explosion affect only the x-axis and not the y-axis in unity

Question: this is the code
I add force but I want that the force Will be only on the x-axis and not on the y-axis
<code> Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, radius, Layertohit);

        foreach (Collider2D obj in objects)
        {
            Vector2 dir = obj.transform.position - transform.position;
            dir.y = 0;
            obj.GetComponent<Rigidbody2D>().AddForce(dir * force);
        }

        void OnDrawGizmosSelected()
        {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(transform.position, radius);
        }
</code>
Answer: You can freeze the y axis like
<code>foreach (Collider2D obj in objects)
    {
        Vector2 dir = obj.transform.position - transform.position;
        dir.y = 0;
        float y=obj.GetComponent<Rigidbody2D>().velocit.y
        obj.GetComponent<Rigidbody2D>().AddForce(dir * force);
        obj.GetComponent<Rigidbody2D>().velocity=new Vector2(obj.GetComponent<Rigidbody2D>().velocity.x,y)
    }
</code>


Writing streaming dataframe to kafka

Question: I am reading log lines from kafka topic through spark structured streaming,separating the fields of loglines, performing some manipulations on fields and storing storing it in dataframe with separate columns for every fields. I want to write this dataframe to kafka
Below is my sample dataframe and writestream for writing it to kafka
 val dfStructuredWrite = dfProcessedLogs.select(
    dfProcessedLogs("result").getItem("_1").as("col1"),
    dfProcessedLogs("result").getItem("_2").as("col2"),
    dfProcessedLogs("result").getItem("_17").as("col3"))

dfStructuredWrite
.writeStream
.format("kafka")
.option("kafka.bootstrap.servers", "host1:port1,host2:port2")
.option("topic", "topic1")
.start()

Above code gives me below error
Required attribute 'value' not found

I believe this is because I don't have my dataframe in key/value format.How can I write my existing dataframe to kafka in most efficient way?
Answer: The Dataframe being written to Kafka should have the following columns in schema:

key (optional) (type: string or binary)
value (required) (type: string or binary)
topic (optional) (type: string)

In your case there is no value column and the exception is thrown.
You have to modify it to add at least value column, ex:
import org.apache.spark.sql.functions.{concat, lit}

dfStructuredWrite.select(concat($"col1", lit(" "), $"col2", lit(" "), $"col3").alias("value"))

For more details you can check: https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html#writing-data-to-kafka

Writing streaming dataframe to kafka


Why udp has lower throughput than tcp?

Question: I am measuring the tcp and udp throughput by iperf3. I run iperf3 in virtual machines, one as server and the other as client. The VMs are connecting via 10 Gbps link. The results show that tcp get much higher throughput than udp. However, as we know TCP runs more algorithms and computation and it has three-way handshaking also, so why udp throughtput is less that tcp?is it something related to the buffer size of tcp and udp?  below are result of tcp and udp measurements. It is apparent that iperf sends more data for tcp rather than udp in a specific time, but why?
TCP: 8.88 Gbps
[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd
[  4]   0.00-1.00   sec   922 MBytes  7.73 Gbits/sec    1   3.04 MBytes
[  4]   1.00-2.00   sec  1.04 GBytes  8.92 Gbits/sec    0   3.04 MBytes
[  4]   2.00-3.00   sec  1.07 GBytes  9.15 Gbits/sec    0   3.04 MBytes
[  4]   3.00-4.00   sec  1.05 GBytes  8.99 Gbits/sec    0   3.04 MBytes
[  4]   4.00-5.00   sec  1.04 GBytes  8.91 Gbits/sec   80   2.17 MBytes
[  4]   5.00-6.00   sec  1.04 GBytes  8.91 Gbits/sec    0   2.35 MBytes
[  4]   6.00-7.00   sec  1.04 GBytes  8.98 Gbits/sec    0   2.54 MBytes
[  4]   7.00-8.00   sec  1.01 GBytes  8.69 Gbits/sec  176   1.88 MBytes
[  4]   8.00-9.00   sec  1.04 GBytes  8.97 Gbits/sec  208   1.42 MBytes
[  4]   9.00-10.00  sec  1.02 GBytes  8.80 Gbits/sec    0   1.48 MBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Retr
[  4]   0.00-10.00  sec  10.3 GBytes  8.80 Gbits/sec  465             sender
[  4]

UDP: 3.26 Gbps, packet length is default 8Kbytes
iperf3 -c "server address" -u -b 0

[  4] local 126.96.36.199 port 58375 connected to 126.96.36.199 port 5201
[ ID] Interval           Transfer     Bandwidth       Total Datagrams
[  4]   0.00-1.00   sec   375 MBytes  3.15 Gbits/sec  48035
[  4]   1.00-2.00   sec   394 MBytes  3.31 Gbits/sec  50457
[  4]   2.00-3.00   sec   352 MBytes  2.94 Gbits/sec  45114
[  4]   3.00-4.00   sec   391 MBytes  3.30 Gbits/sec  50092
[  4]   4.00-5.00   sec   403 MBytes  3.38 Gbits/sec  51566
[  4]   5.00-6.00   sec   403 MBytes  3.38 Gbits/sec  51599
[  4]   6.00-7.00   sec   418 MBytes  3.51 Gbits/sec  53493
[  4]   7.00-8.00   sec   372 MBytes  3.12 Gbits/sec  47651
[  4]   8.00-9.00   sec   444 MBytes  3.73 Gbits/sec  56892
[  4]   9.00-10.00  sec   399 MBytes  3.34 Gbits/sec  51033
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Jitter    Lost/Total Datagrams
[  4]   0.00-10.00  sec  3.86 GBytes  3.32 Gbits/sec  0.020 ms  354384/505931 (70%)

according to the packet length the throughput in udp is calculated based on the packets which are sent, regardless of the recieved ones!
Comment: The 57% percent lost UDP datagrams would be a logical explanation for having less than half the throughput of TCP ...
Comment: Thanks, I also noticed that, but why do we have UDP packet loss, as everything in the network is the same for udp and tcp?
Answer: TCP includes congestion control.  It will limit traffic to prevent packet loss.  UDP just sends all of the packets you request and hopes for the best.
https://www.geeksforgeeks.org/tcp-congestion-control/
Comment: Switches and cards have finite buffer sizes.
Comment: I understand we have packet loss in udp, but why? because the link is 10Gbps and no other traffic is on the link, so I think the link is not congested!
Answer: Even cheap hardware these days can exceed 10 Gb, especially with traffic generators like iperf. Buffers quickly fill up when link bandwith is exceeded, resulting in drops. No congestion control for UDP means it will keep sending packets through already saturated interfaces, which ruins goodput.
This is like a road half-clogged with crashes of speeding maniacs, with zero traffic management, and complaining that it doesn't hit the theoretical peak cars per hour.
Limit iperf's bandwith. TCP's 8.8 Gb is probably realistic, but let's be optimistic and try for Ethernet theoretical maximum: iperf -u -b 9750M
Comment: Thanks John, I tried udp with -b 9750M, but the result is the same!

Why udp has lower throughput than tcp?


Highest runs that a batsman can score in an over?

Question: Assuming there are no overthrows and no extras (like no-balls, wide balls, etc), what is the highest a batsman score in an over?
UPDATE:
If the ball first hits the bat, then the helmet and goes for a boundary, he will score 5+4 =9 runs/ball. So, in an over, 9*6 = 54 runs. Is this logic correct?
Comment: The 5 runs for hitting the helmet are penalty runs.  They don't go to the batsman's personal score.
Comment: I don't know if he gets 9 (5+4) runs in one ball. But if I am a captain, and if the ball touches the helmet back to back (or twice), I will send the helmet into the pavilion!
Comment: Penalty runs are also classed as extras, and as @PeterEisentraut points out, they do not count towards the batsman's score. Therefore 6*6 = 36 runs would be the maximum a batsman could score from a 6-ball over, without overthrows or running more than 6.
Comment: @hims056 hehe yeah...but it is possible..may be!
Comment: I don't 9 runs is possible.theoretically,consider this scenario, the batsmen has already ran 6 max possible(if ball not last) then the fielder throws the ball on to the helmet , the ball gets deflected and reaches the boundary then according to you the team would get 6+5+4=15 runs. I guess the ball will be called dead once it touches the helmet
Comment: @gout "_Assuming there are no overthrows and no extras (like no-balls, wide balls, etc)_" in the question.
Comment: without over throws you will still get 11 runs
Comment: i can say that jaques kallis hetted si sixes in one over
Comment: Farfiekld Sobers once scored 36 runs in a county match in England. He hit 6 sixes off an off spin bowler.
Answer: The number of runs you can score of a single delivery is in principle unlimited, because the batsmen can keep running forever.  This was especially possible before the introduction of current Lost Ball rule, for example when the ball got stuck in a tree.
Comment: I am not sure, I could follow you properly. How can a batsman get unlimited run of a single delivery?
Comment: @Mistu4u - there is no limit to the number of runs the batsmen can run between the wickets, as long as someone doesn't run them out - 6 is not a limit.  This was especially true before the Lost Ball rule - some grounds have trees within the boundary, where a ball could theoretically get lost in.  For most circumstances however 6 runs is the limit per ball.
Answer: If all balls are fair there will be 6 balls in the over. If one batter faces all of these and gets the maximum score possible each ball, which is 6 runs for hitting the ball on the full over the boundary, then they will score 36 runs in the over.
Comment: True, it is possible, though the exclusion of overthrows makes it even less likely. However I guess you're right, if all 11 players in the fielding side spontaneously break their legs running for the ball the batsmen could, in theory, keep running for ever....
Comment: I think the relevant rules are here http://www.lords.org/laws-and-spirit/laws-of-cricket/laws/law-18-scoring-runs,44,AR.html I can't see anything that limits the number of runs scored by running between wickets, so yes I think you're correct, you could in theory score more than 6 runs in a ball in this way.
Comment: If the ball does not cross the boundary, _however unlikely_, is it possible for the batsmen to run more than 6 runs off one delivery?
Comment: @Orangecrush see update
Comment: And yeah,not those kind of tricks,running forever and stuff..
Answer: i think so that there can be 48 made in a single over...four run by running nd while running the fourth run if filder overthrow nd it goes out for boundry then by ths way there is 8 runs per ball and 8*6=48
Comment: Thanks for your answer, but the question specifies that "there are no overthrows."


How to convert multiple rows into single row but with different column names in postgressql

Question: My resultant out is this using case when in postgres
id   name    amount1      amount2       amount3
1     abc    10           null          null
1     abc    null         5             null
1     abc    null         null          40

I want my output as:
id   name    amount1      amount2       amount3
1    abc     10           5             40
2    aaa     90           20            10

Comment: The input and output are having the same column name. I understand that the first record is an aggregate of abc with a sum of each corresponding field (sum(amount1) yields amount1), where the value defaults to 0 if it was `null`. Yet, I do not see how your input should yield the second record from your output, so I will assume in my answer that you are just not giving us your full input.
Answer: You can do it using group by and the aggregate function max() ( use sum() if you want to sum your data by id ) :
select id, max(name) as name, max(amount1) as amount1, max(amount2) as amount2, max(amount3) as amount3
from mytable
group by id

Answer: You can aggregate using group by and coalesce null values to 0:
select id, name, sum(coalesce(amount1, 0)) as amount1, sum(coalesce(amount2, 0)) as amount2, sum(coalesce(amount3, 0)) as amount3
from yourtable
group by id, name

I understand you have a case when and your input in the question is the result of that. Without knowing more about your tables, the best I can suggest is to replace yourtable in the query above with (<yourquery>) t and of course, you need to replace <yourquery> with your actual query.
See this fiddle: http://sqlfiddle.com/#!15/e568d0/6
Test DB:
create table yourtable(
    id int,
    name varchar(8),
    amount1 int,
    amount2 int,
    amount3 int
);

insert into yourtable(id, name, amount1, amount2, amount3)
values
(1, 'abc', 10, null, null),
(1, 'abc', null, 5, null),
(1, 'abc', null, null, 40),
(2, 'aaa', 90, 20, 10);


Bootstrap Date Picker End/Start Date Limit with Date Range

Question: I am using the Bootstrap Datepicker and I have 2 input fields  (start date and end date) that use the date range option (inputs:) which works really well. I am trying to get the start field to require picking a date past today's date (so only a date today or a date in the past).
Here is the jQuery I am using:
  $('.input-daterange').datepicker({
    format: 'mm-dd-yyyy',
    inputs: $('.date-control'),
    todayBtn: true,
    todayHighlight: true
  });

Here are the form fields:

      *Project Start Date

          Started

        <input type="text" class="form-control date-control start-daterange" name="date-start" id="date-start" value="" required="">

          Project Start Date is required.

      *Project End Date

          Finished

        <input type="text" class="form-control date-control" name="date-end" id="date-end" value="" required="">

          Project End Date is required.

I have already tried to use endDate: "0d"; to limit the start date field but if I do this it will also limit the end date field because they are being associated with the inputs: $('.date-control'). I saw in the documents that I could use <input type="text" class="form-control" data-date-end-date="0d"> but this does not work either, maybe because I am using the inputs option?
So my question is there an easy way to keep using the date range option and be able to limit the start date field to select today date and any date in the past?
I have viewed these other semi-related SO questions how to restrict bootstrap date picker from future date and How to have a dynamic maximum end date in Bootstrap Date Picker. Also I am using the latest version of bootstrap datepicker (v1.8).
Answer: It seems that the inputs option and the data-date-end-date attribute don't work well together. But there's a workaround and you'll get the same result. You can use the same class for both inputs and you can create the datepickers using that class. Besides that, you're gonna use the data-date-end-date attribute just in the start input, like this:
The Jquery code:
$('.date-control').datepicker({
  format: 'mm-dd-yyyy',
  todayBtn: true,
  todayHighlight: true
});

The form fields:

  *Project Start Date

      Started

    <input type="text" class="form-control date-control start-daterange" name="date-start" id="date-start" required="" data-date-end-date="0d">

      Project Start Date is required.

  *Project End Date

      Finished

    <input type="text" class="form-control date-control" name="date-end" id="date-end" required="">

      Project End Date is required.

ps: I've removed the value attribute from both inputs just to make it clear.
Comment: Thanks for responding. This works but it removes the association between the 2 fields which I need to keep intact which is why I am using `inputs: $('.date-control')`


Derivative of the Backshift Operator?

Question: Is there any meaningful sense in which the backshift operator can be said to have a derivative?
Here's my attempt at constructing one. Based on some helpful threads on this site, I represent the backshift operator $B$ as a matrix (showed here for an example time series of length $3$):
$$
\begin{pmatrix}
0 & 0 & 0\\
1 & 0 & 0\\
0 & 1 & 0
\end{pmatrix}
\begin{pmatrix}
y_1\\
y_2\\
y_3
\end{pmatrix} =
\begin{pmatrix}
0\\
y_1\\
y_2
\end{pmatrix}\ .
$$
I can take the derivative of the above equation with respect to $y_1$ and $y_2$ to obtain the vectors $(0, 1, 0)$ and $(0, 0, 1)$ respectively (the derivative w.r.t $y_3$ is undefined.) Extrapolating, and wishing to obtain an operator (instead of a vector) from the differentiation process, I conclude that the derivative of the backshift operator is a type of "shifted" indicator function $I_{t}$ which has a straightforward matrix representation. For example, I would write
$$
\frac{\partial B}{\partial y_1} = I_1 = \begin{pmatrix}
0 & 0 & 0\\
1/y_1 & 0 & 0\\
0 & 0 & 0
\end{pmatrix}\ .
$$
Does this calculation have any meaning, or are there some operator-space/common-sense rules which forbid some steps? References would be appreciated.
Comment: The derivative with respect to $y_3$ is certainly defined: it's the zero vector.
Comment: @GregMartin Thanks for the correction.
Answer: The backshift operator is a mapping (an "operator") between vector spaces, namely spaces of time series or sequences,
$$ B\colon \mathbb{R}^\mathbb{N} \to \mathbb{R}^\mathbb{N}, (y_i)\mapsto (y_{i-1}). $$
Here, $\mathbb{R}^\mathbb{N}$ is the space of mappings from $\mathbb{N}$ to $\mathbb{R}$, i.e., of real-valued sequences indexed by natural numbers. Time series that are not infinite can be accommodated by having only finitely many observations nonzero. The space $\mathbb{R}^\mathbb{N}$ is naturally a real vector space: we can add time series and multiply them by real scalars.
In functional analysis, there is a notion of differential of an operator between normed vector spaces. If an operator $f$ admits a "local linear approximation" $\varphi$ near a point $x$, then we say that $f$ is differentiable and that $\varphi$ is its differential at $x$ (see, e.g., Coleman, 2012, section 2.2). Note that this generalizes the familiar notion of differentiability of mappings between finite dimensional spaces: a function $f\colon\mathbb{R}^n\to\mathbb{R}^m$ is differentiable at a point $x$ if and only if it admits a well-defined tangential subspace (tangent line in the most familiar case of $n=m=1$) near $x$.
Now, we observe that $B$ is already linear:
$$ B\big(\lambda(y_i)\big) = \lambda B\big((y_i)\big)\quad\text{and}\quad
B\big((y_i)+(z_i)\big) = B\big((y_i)\big)+B\big((z_i)\big). $$
Thus, a (unique!) "best approximation" to $B$ is $B$ itself (see here at Math.SE). Therefore, the differential of $B$ at all "points" (i.e., sequences) is $B$ itself. Note that we don't even need to think about what norm we put on our space $\mathbb{R}^\mathbb{N}$.
Comment: For those looking for further intuition about why the derivative of a linear operator is the operator itself: https://math.stackexchange.com/a/1696767/49082

Derivative of the Backshift Operator?


How can I change the title of the node/add page of a specific content type?

Question: I want to change the title of the node/add page of a specific content type. Twig debug only shows me file names that would also change the titles of other content types. There was a module for this in D7, but unfortunately it was not ported to D8.
Comment: You could [alter the route](https://www.drupal.org/docs/drupal-apis/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones) and replace this title callback [NodeController::addPageTitle](https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Controller%21NodeController.php/function/NodeController%3A%3AaddPageTitle).
Answer: If you can hide the default page title using CSS, then you could create a custom block for the title and specify to have it show only on the content you want.
In the block configure visibility settings, set the page visibility to be restricted to your content type.
-- But, hiding the default page title block that will only work for you if the admin theme is using the same theme as the front-end site.
I think the admin page title is still passing through that Page title block (the default).. so maybe you can configure that block's visibility to hide on the edit pages where you want your custom block to appear?
Comment: The admin page doesn't matter, only the front end appearance is important
Answer: Simply use Metatag module. This is the no-code solution.
Use the metatags configuration for the specific content type. And then modyfy the Title field. With the Token module you have more power to modify the title.
Here  and here is some documentation about how to use metatgs.
Comment: Apparently this option only changes the text within the title tags?
Comment: @0711master yes. Otherwise - the question doesn't make sense, since you can edit the node title from the node edit form. If need automatically set the node title per content type - then use the module `autotitle`
Comment: Ah ok, I need to clarify: if you open any node/add page then the title you see directly above the node form is like "Add @type" with type being the name of the content type. This is the title I'm talking about.
Comment: Then - see the answer at the bottom of your question: You could alter the route and replace this title callback NodeController::addPageTitle.
Comment: Thank you and I hope you are safe!


Fatoração em JavaScript

Question: Como fatorar numeros nessa forma ?
26 | 2
13 | 3
1  |

Segue meu código ainda incompleto:
JSFIDDLE
Comment: Você quer os fatores primos ou outro tipo de fatoração?
Answer: NOTA: Eu não sei se você pôs seu exemplo errado, já que 13 não e
divisível por 3 ou se é aquilo mesmo que você quer que seja
exibido. Se for comente que eu atualizo minha resposta.
Vou escrever em C, já que não sei JS, mas deve ser bem parecido e,
mais importante, mais simples do que o código que você postou.
A primeira coisa é que você vai precisar de uma lista de números primos para fazer a fatoração. Se você não tiver a lista já em mãos, você pode usar um algoritmo para gerar essa lista pra você. Um jeito clássico, no sentido literal da palavra, já que foi
"inventado" por Erastosthenes uns 2000 anos atras, é o seguinte:

Estabelecemos um numero limite para encontrarmos primos ate ele (N).
Declaramos uma lista L contendo N valores true. Essa
   lista, ao final do algoritmo, vai obedecer à seguinte relação:

Se L[i] == true, se e somente se i é um numero primo.

Agora, procedemos da seguinte maneira:

Marcamos L[0] e L[1] como false, já que ambos 0 e
1 não são primos.
A partir do i = 2, se  i for primo (L[i] == true),
marcamos todos os seus múltiplos como não primos. Isto é, fazemos L[2*i] = false, L[3*i] = false, etc.

Isso, em C, pode ficar assim:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define N 1000 /* Nosso limite */

bool L[N + 1];

void peneira() {
    /* Primeiro marcamos todos como true */
    memset(L, true, sizeof(L));

    /* Agora o 0 e o 1 não são primos */
    L[0] = L[1] = false;

    /* A parte mágica */
    for (int i = 2; i <= N; ++i) {
        if (L[i]) {
            /* Se i é um numero primo, seus múltiplos não são */
            for(int k = i + i; k <= N; k += i){
                L[k] = false;
            }
        }
    }
}

int main() {
    peneira();
    for (int i = 0; i < 30; ++i) {
        if (L[i]) {
            printf("%d e primo\n", i);
        }
    }
    return 0;
}

Rodando isso, a saída e:
2 e primo
3 e primo
5 e primo
7 e primo
11 e primo
13 e primo
17 e primo
19 e primo
23 e primo
29 e primo

Ou seja, todos os primos ate 30.
Agora que temos todos os primos ate nosso limite N, podemos fatorar
qualquer numero:
void fatora(int num) {
    /* Vou calcular o numero de digitos de num para imprimirmos
     * bonitinho como no seu exemplo */
     int tamanho = floor(log10(num)) + 1;
     int primo = 2;
     while (num > 1) {
         /* Enqto num e divisivel por primo */
         while (num % primo == 0) {
             printf("%*d | %d\n", tamanho, num, primo);
             num /= primo;
         }
         /* Agora vamos para o proximo primo */
         ++primo;
         while (L[primo] == false) {
             ++primo;
         }
     }
     /* Imprimimos a ultima linha */
     printf("%*d | \n", tamanho, 1);
}

Finalmente, se rodarmos
int main() {
    peneira();
    fatora(26);
    return 0;
}

A saída vai ser:
26 | 2
13 | 13
1  |

Answer: Seguindo a lógica da fatoração cheguei a esta função:
function Calcular(nr) {
    var partes = [];
    while (nr > 1) {
        for (var i = 2; i <= nr; i++) {
            if (nr % i) continue;
            partes.push([nr, i]);
            nr = nr / i;
            break;
        }
    }
    partes.push([1, '']);
    return partes;
}

Alguns exemplos seriam:
Calcular(4); // "[[4,2],[2,2],[1,""]]"
Calcular(3); // "[[3,3],[1,""]]"
Calcular(5); // "[[5,5],[1,""]]"
Calcular(6); // "[[6,2],[3,3],[1,""]]"
Calcular(8); // "[[8,2],[4,2],[2,2],[1,""]]"

Depois montar o HTML depende de como quer o formato final. Supondo que usamos a mesma tabela aqui fica uma sugestão:
jsFiddle: http://jsfiddle.net/uLmxnm0q/
Answer: Achei na internet. Não testei, mas parece funcionar:
function fator(numero) {
   if (isNaN(numero) || !isFinite(numero) || numero%1!=0 || numero==0) return ''+numero;
   if (numero<0) return '-'+fator(-numero);
   var minFator = lFator(numero);
   if (numero==minFator) return ''+numero;
   return minFator+'*'+fator(numero/minFator);
}

function lFator(numero) {
   if (isNaN(numero) || !isFinite(numero)) return NaN;
   if (numero==0) return 0;
   if (numero%1 || numero*numero<2) return 1;
   if (numero%2==0) return 2;
   if (numero%3==0) return 3;
   if (numero%5==0) return 5;
   var m = Math.sqrt(numero);
   for (var i=7;i<=m;i+=30) {
      if (numero%i==0)      return i;
      if (numero%(i+4)==0)  return i+4;
      if (numero%(i+6)==0)  return i+6;
      if (numero%(i+10)==0) return i+10;
      if (numero%(i+12)==0) return i+12;
      if (numero%(i+16)==0) return i+16;
      if (numero%(i+22)==0) return i+22;
      if (numero%(i+24)==0) return i+24;
   }
   return numero;
}

Fonte: Javascriper
Answer: function fatoracao(aNumIn) {
var aRetorno = [
    [1, 1]
];
pFator = 1;
while (aNumIn != 1) {
    pFator++;
    pVezes = 0;
    while (aNumIn % pFator == 0) {
        pVezes += 1;
        aNumIn /= pFator;
    }
    if (pVezes) aRetorno.push([pFator, pVezes]);
}
return aRetorno;
}
let aIn = Math.pow(2, 5) * Math.pow(3, 2) * Math.pow(11, 1) * Math.pow(17, 2) * Math.pow(29, 1);
console.log(aIn, " >>>>  ", fatoracao(aIn));
// 26551008 ' >>>>  ' [ [ 1, 1 ], [ 2, 5 ], [ 3, 2 ], [ 11, 1 ], [ 17, 2 ], [ 29, 1 ] ]

Bem, o código acima retorna um vetor fatorado. Agora você poderá formatar a saída como desejar...

Fatoração em JavaScript


Prove Jensen's inequality?

Question: I was interested to see a proof for Jensen's inequality for the following variant:
Let $X$ be a discrete random variable with finite expected value and let $h:\mathbb{R} \to \mathbb{R}$ be a convex function. then:
$h(E[X])\leq E[h(X)]$
Please note, I'm interested in a proof for this variant with a discrete random variable. The proof in Wikipedia doesn't match my needs.
Comment: I suppose it could be extrapolated from the idea used in this : https://math.stackexchange.com/questions/1382006/could-someone-give-a-detailed-yet-elementary-proof-for-jensens-inequality/4019537#4019537
Comment: You are free to ask a proof different from the one in Wikipedia, but that proof also applies to the discrete case
Comment: @AitorIribarLopez wikipedia doesn't have proof for ℎ([])≤[ℎ()] for infinite case
Comment: @David yes, it does. Look at the "measure theoretical proof" and take $\mu$ to be the adecuate measure for the infinite case. I cannot help you if you don't know why measures generalize discrete and continuous probabilities
Comment: they proved it on finite n, still this is not what I asked about @AitorIribarLopez
Comment: Some hints: (1) it is sufficient to check the inequality in the case when $E[X]=0$ and when $h(0)=0$ (why?); (2) since $h$ is convex there is a real $c$ such that $h(x)\ge cx$ (why?); (3) taking expected values preserves inequalities.
Comment: @David no, I am not talking about that proof, I am talking about Proof 2 (measure-theoretical form). You should honestly think about it since it appears to me that you have a fixated idea in your head and won't listen to my advices
Answer: I believe you might be interested in the proof provided in Theorem 2.4 in Probability and Computing: Randomization and Probabilistic Techniques in Algorithms and data Analysis, Second Edition from M. Mitzenmacher and E. Upfal. The only assumption there is that $f$ has a Taylor expansion, so your random variable can be either discrete or continuous.

Let $\mu = \mathbb{E}[X]$. By Taylor's theorem there is a value $c$ such that
\begin{align}
f(x) &= f(\mu) + f^\prime(\mu)(x-\mu) + \frac{f^{\prime\prime}(c)(x-\mu)^2}{2}\\&\geq f(\mu) + f^\prime(\mu)(x-\mu),
\end{align}
since $f^{\prime\prime}(c) > 0$. Taking expectations of both sides and applying linearity of expectations and Lemma 2.2 yields the result:
\begin{align}
\mathbb{E}[f(x)] &\geq \mathbb{E}[f(\mu) + f^\prime(\mu)(x-\mu)]
\\&= \mathbb{E}[f(\mu)] + f^\prime(\mu)\mathbb{E}[(x-\mu)]
\\&= f(\mu) = f(\mathbb{E}[X])
\end{align}
Comment: You proof assumes that $f$ is of class $\mathcal C^2$, which is not necessary. To fix it, you can use that for a convex function and a point$x_0$ ($x_0=\mu$ in this case) there are $a$, $b$ such that $f(x) \geq ax+b$ with equality at $x=x_0$ ie there exists a "subtangent line". Also, for the OP, note that this proof applies wether $X$ is finite, countable, continuous or whatever you want

Prove Jensen's inequality?


ImageView exibe a imagem girada em 90 graus

Question: Quando faço o Upload de uma foto para o servidor e vou exibi-la utilizando
Picasso.with(getApplicationContext()).load(Caminhofoto).into(fotoalerta);

Se a foto foi tirada com o celular na vertical ela é carregada no horizontal teria como exibir ela corretamente. Tenho esse mesmo problema quando carregar ela do SDCARD mais estou utilizando esse código para exibir corretamente.
 public String getRealPathFromURI(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {

    try{
        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_NORMAL:
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.setScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-90);
                break;
            default:
                return bitmap;
        }
        try {
            Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            return bmRotated;
        }
        catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

Minha class de UPLOAD da imagem
public class classe_FTP
{
    FTPClient mFtp;
    private String TAG = "classeFTP";

public boolean MudarDiretorio(String Diretorio)
{
    try
    {
        mFtp.changeWorkingDirectory(Diretorio);
    }
    catch(Exception e)
    {
        Log.e(TAG, "Erro: não foi possível mudar o diretório para " + Diretorio);
    }
    return false;
}

public boolean Desconectar()
{
    try
    {
        mFtp.disconnect();
        mFtp = null;
        return true;
    }
    catch (Exception e)
    {
        Log.e(TAG, "Erro: ao desconectar. " + e.getMessage());
    }

    return false;
}

public boolean Conectar(String Host, String Usuario, String Senha, int Porta)
{
    try
    {
        mFtp = new FTPClient();

        mFtp.connect(Host, Porta);

        if (FTPReply.isPositiveCompletion(mFtp.getReplyCode()))
        {
            boolean status = mFtp.login(Usuario, Senha);

            mFtp.setFileType(FTP.BINARY_FILE_TYPE);
            mFtp.enterLocalPassiveMode();

            return status;
        }
    }
    catch(Exception e)
    {
        Log.e(TAG, "Erro: não foi possível conectar" + Host);
    }
    return false;
}

public boolean Upload(String diretorio, String nomeArquivo)
{
    boolean status = false;
    try
    {
        FileInputStream arqEnviar = new FileInputStream(Environment.getExternalStorageDirectory() + diretorio);
        mFtp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
        mFtp.setFileType(FTPClient.STREAM_TRANSFER_MODE);
        mFtp.storeFile("/patrulhar.com.br/imagens/"+nomeArquivo, arqEnviar);
        Desconectar();
        System.out.println("Upload win1 . ");
        return status;
    }
    catch (Exception e)
    {
        Log.e(TAG, "Erro: Falha ao efetuar Upload1. " + e.getMessage());
    }
    return status;
}

public boolean Upload2(String diretorio, String nomeArquivo)
{
    boolean status = false;
    try
    {
        FileInputStream arqEnviar = new FileInputStream(diretorio);
        mFtp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
        mFtp.setFileType(FTPClient.STREAM_TRANSFER_MODE);
        mFtp.storeFile("/patrulhar.com.br/imagens/"+nomeArquivo, arqEnviar);
        Desconectar();
        System.out.println("Upload win2 . ");
        return status;
    }
    catch (Exception e)
    {
        Log.e(TAG, "Erro: Falha ao efetuar Upload2. " + e.getMessage());
    }
    return status;
}
}

Comment: Se entendi bem então a solução passa por usar o método `rotateBitmap()` nessa situação também.
Comment: Mais tem como eu utilizar o rotateBitmap() utilizando o picasso ou como eu deveria fazer isso ?
Comment: Faça o *rotate* da imagem antes do *upload*
Comment: Faço o upload da imagem pelo caminho dela no celular como eu poderia fazer utilizando esse bitmap com ela certa?
Answer: Através da API Picasso é possível aceder ao Bitmap após o load recorrendo ao método transform() do RequestCreator.
Crie uma classe que implemente a interface Transformation:
public class ImageTransformation implements Transformation {
    @Override public Bitmap transform(Bitmap source) {

        //Faça aqui o que quiser com o bitmap e retorne-o.
    }

    @Override public String key() { return "square()"; }
}

Utilize desta forma:
ImageTransformation imageTransformation = new ImageTransformation();
Picasso.with(getApplicationContext())
       .load(Caminhofoto)
       .transform(imageTransformation)
       .into(fotoalerta);

No entanto, como o pretendido é apenas rodar a imagem, o RequestCreator disponibiliza o método rotate() para esse efeito:
Picasso.with(getApplicationContext())
       .load(Caminhofoto)
       .rotate(degrees)
       .into(fotoalerta);

ou
Picasso.with(getApplicationContext())
       .load(Caminhofoto)
       .rotate(degrees, pivotX, pivotY)
       .into(fotoalerta);


About the basis of a module

Question: Let $n\in \mathbb Z, n\ne 0$. Prove that $ \mathbb Z/n\mathbb Z$-module $\mathbb Z/n\mathbb Z$ has a basis, but $\mathbb Z$-module $\mathbb Z/n\mathbb Z$ hasn't any basis. Hope everyone help me with that. Thanks.
Answer: If you view $M = \mathbb Z / n \mathbb Z$ as module over $R = \mathbb Z / n \mathbb Z$ the element $1$ will form a basis: let $k \in \mathbb Z / n \mathbb Z$. Then $k  = k \cdot 1$.
On the other hand, if the ring acting on $M$ is $R = \mathbb Z$ then any subset of $\mathbb Z / n \mathbb Z$ will be linearly dependent, just multiply by $n$: for example, $1 \cdot n = 0$.
Comment: @user52523 From this answer you can see that basis elements for $\Bbb Z$ modules are in conflict with elements of finite order (torsion elements).

About the basis of a module


How to set the weights of an expert on a binary decision?

Question: Suppose that we have $n$ experts, each will give us a prediction $X_i$ on whether a binary event $E\in\{0,1\}$ will take place.
Suppose also that we know the probability that each of them will be correct (say, expert $i$ is correct w.p. $p_i\in(0,1/2)$), and that their predictions are independent of each other.
Our goal is to decide on weights $w_i,\ldots,w_n$ such that the prediction of the weighted majority is correct with the highest possible probability.
Namely, consider the event $E'=(\sum_i X_i\cdot w_i \ge 1/2\cdot \sum_i w_i)$, and we'd like to maximize the probability that $E=E'$.

What is the best way to set the weights if $w_i$ can only be defined using $P_i$?

What is the best way to set the weights if all weights can be based on all $P_i$'s?

I'm more interested in the first question :).
Comment: Have a look at the pretty extensive literature on ensemble learning.
Comment: @Aruralreader. Thanks for the pointer, but I'm not sure there's any `learning' here as I have a single binary events and the $p_i$'s are known in advance?
Comment: It sounds like you have a set of naive Bayes classifiers, or maybe something more sophisticated than that, and you want to figure out, based on data, how to weight the decision of each expert.
Answer: You are presenting a weighted experts problem as presented and explained (1) & (2)
Basically you choose probability based on weights variable, like for expert $i$ probability of being correct $p_i = {w_i\over \sum_i w_i}$
Initial weights can be taken equally as 1.
Then you have loss $m_i= 1$ if correctly predicted $x_i$, $0$ otherwise (basically $0 - \vert X - x_i \vert$) where $X$ is the realized event. Compute the expected (average) loss
$ E =$ m$\cdot$p
Repeat $t$ times and update weights assigned using factor $ \eta \in (0,1)$
$ w_{i}^{t+1} = (1-\eta m_{i}^{t})w_{i}^{t}$
$ \eta$ is like learning step & is a random value to be chosen, you can start with a value $ \ge 0.7$ & then in subsequent iterations choose a lower value.
Comment: @MA if you want to consider weights as $w$ same as $p$, $\sum_i w_i= 1$ & these are independent, then one way is to maximize $\prod w$. You can take the log of that to linearize. If $p$ are known & different from weights then maximize $\prod Pw$
Comment: Thanks a lot, but this seems to assume that there are multiple iterations of the process, while I am asssuming that the $p_i$'s are known, but there's a single-shot. Am I missing something?


Como transformar o espaço de um input text para %20?

Question: Como transformar o espaço de um input text para %20?
Gostaria de altera texto em questão para ser transportado em uma url
Estou gerado uma url para que as informações do site seja incluída no inicio da conversa ("text=sua%20mensagem")
exemplo:
https://api.whatsapp.com/send?phone=seunumerodetelefone&text=sua%20mensagem
Answer: Se esta em em um <input> somente a mensagem basta usar rawurlencode, assim no PHP:
<?php
if (!empty($_POST['message'])) {
    $message = rawurlencode($_POST['message']);

    $url = 'https://api.whatsapp.com/send?phone=seunumerodetelefone&text=' . $message;

    var_dump($url); //Somente para testar a URL
}

Supondo que o form esteja assim
<form action="pagina.php" method="POST">
<input type="text" name="message">
<button>Enviar</button>
</form>

Se for JavaScript pode usar encodeURIComponent:

var message = document.querySelector("#message"),
    testBtn = document.querySelector("#testar");

testBtn.onclick = function () {
    var url = 'https://api.whatsapp.com/send?phone=seunumerodetelefone&text=';
    var urlmessage = url + encodeURIComponent(message.value);

    console.log(urlmessage);
};
Digite algo: <input type="text" id="message" value="">

<button id="testar">Enviar</button>
Answer: Tente usar o str_replace:
str_replace(' ', '%20', 'https://api.whatsapp.com/send?phone=seunumerodetelefone&text=sua mensagem')


Nested objects' key is missing after it is formatted and rendered

Question: I have this object which I have been trying to print in my ejs template without object syntaxes. I followed an answer here in StackOverflow and was successful in printing it without the syntaxes but it doesn't print everything in the nested object. What I mean is there are two nested objects in data(f and g). So the properties(keys) in those nested objects like name, email, phone, country, car are missing from the output. How can I also render that with their respected values?
Here's the object and the code which I used to format it:
router.get("/", async(req, res) => {
    try{
        let data = {
                a: 'Tesla',
                b: 'Mclaren',
                c: 'Ferrari',
                d: 'Lamborghini',
                e: 'Lotus',
                'f':{
                    name: 'John',
                    'e-mail': 'email@example.com',
                    phone: '+12345678',
                    country: 'USA',
                    car: 'Toyota Prius'
                },
                'g':{
                    name: 'Sophie',
                    'e-mail': 'email@example.com',
                    phone: '+12345678',
                    country: 'UK',
                    car: 'Nissan Bluebird'
                },
                h: 'Volkswagen',
                i: 'Bugatti',
                j:[
                    '% mileage',
                    '% top speed',
                    '% suspension',
                    '% navigation',
                    '% horsepower',
                    '% 0-60s'
                ]
            }
            var result = Object.entries(data).reduce((result, [key, value]) => {
                key = key.replace(/([A-Z]|\d+)/g, ' $1').replace(/^(.)/, (unused, p1) => p1.toUpperCase());
                if (!['string', 'number', 'boolean'].includes(typeof value)) {
                    value = Object.entries(value).map(([key, value]) => (typeof value == 'boolean') ? (value ? key : undefined) : value).filter(v => v !== undefined).join(',');
                }
                result.push(`${key}: ${value}`);
                return result;
            }, []);
            var finalData = result.join('\n');
            res.render("data", {data: finalData});
    }catch(e){
        req.flash("error", "Unable to retrieve data. Please try again!");
        res.redirect("/");
    }
});

This is the result if I print it in the console:
A: Tesla
B: Mclaren
C: Ferrari
D: Lamborghini
E: Lotus
F: John,firstname.lastname@example.com,+12345678,USA,Toyota Prius
G: Sophie,email@example.com,+12345678,UK,Nissan Bluebird
H: Volkswagen
I: Bugatti
J: % mileage,% top speed,% suspension,% navigation,% horsepower,% 0-60s

This is the result after I render it in my ejs template:
A: Tesla B: Mclaren C: Ferrari D: Lamborghini E: Lotus F: John,email@example.com,+12345678,USA,Toyota Prius G: Sophie,email@example.com,+12345678,UK,Nissan Bluebird H: Volkswagen I: Bugatti J: % mileage,% top speed,% suspension,% navigation,% horsepower,% 0-60s

Expected result:
A: Tesla
B: Mclaren
C: Ferrari
D: Lamborghini
E: Lotus
F:
Name: John
Email: firstname.lastname@example.com
Phone: +12345678
Country: USA
Car: Toyota Prius
G:
Name: Sophie
Email: firstname.lastname@example.com
Phone: +12345678
Country: UK
Car: Nissan Bluebird
H: Volkswagen
I: Bugatti
J:
% mileage
% top speed
% suspension
% navigation
% horsepower
% 0-60s

Answer: This isn't pretty but should do the thing:
var result = Object.entries(data).reduce((result, [key, value]) => {
   key = key.toUpperCase();
   if (typeof value === 'object') {
     result.push(`${key}:`);
     if (Array.isArray(value)) {
       value.forEach(item => result.push(item));
     } else {
       Object.entries(value).forEach(([key, value]) => {
         key = key.charAt(0).toUpperCase() + key.slice(1)
         result.push(`${key}: ${value}`);
       })
    }
  } else {
    result.push(`${key}: ${value}`);
  }
  return result;
}, []);
var finalResult = result.join("\n");

Comment: Hi, I edited my answer to include 1 more line of code (for joining the array to a string), hope it helps :)
Comment: Hm, I'm afraid I'm not familiar with EJS. Is this any help? https://github.com/tj/ejs/issues/187 You might need to join the result array with `""` or something instead and then render the text as HTML.
Comment: I think I found the problem. I was rendering all the items in the array as simple texts. So they were wrapped in a single line. So i tried a loop in the template and used `````` for each item. And they are displayed in a list. I should thank you for the code. It's perfect. Thank you so much.
Comment: Sure - right now you have an array of strings, and what you need is an array of objects. So replace the `result.push(...)` with something like `result.push({ key, value })` and then you can handle the key and value separately in the frontend.
Comment: Hi. Thanks so much for helping me out. I tried your code and I could render it in my template but there's a slight issue. After rendering it on my template, all the items are wrapped in a couple of lines. Is there any way I could render each item on a new line?
Comment: I tried that already. The items are in new line in the terminal but not in the webpage. May be something need to be done in the frontend?
Comment: Hey mate, if you don't mind, I needed another help. Is it possible to get the same result but with good alignment? What I mean to say is I want all the colons to align perfectly. As key and value are 1 item in the array, I can't design the look of it from the frontend. So I was thinking if it's possible with js. It'd be a big help mate. If you want I can create another question here in stackoverflow.
Answer: Adding to the above answer use join to get the proper expected result.
let data = {
                a: 'Tesla',
                b: 'Mclaren',
                c: 'Ferrari',
                d: 'Lamborghini',
                e: 'Lotus',
                'f':{
                    name: 'John',
                    'e-mail': 'firstname.lastname@example.com',
                    phone: '+12345678',
                    country: 'USA',
                    car: 'Toyota Prius'
                },
                'g':{
                    name: 'Sophie',
                    'e-mail': 'firstname.lastname@example.com',
                    phone: '+12345678',
                    country: 'UK',
                    car: 'Nissan Bluebird'
                },
                h: 'Volkswagen',
                i: 'Bugatti',
                j:[
                    '% mileage',
                    '% top speed',
                    '% suspension',
                    '% navigation',
                    '% horsepower',
                    '% 0-60s'
                ]
            }
var result = Object.entries(data).reduce((result, [key, value]) => {
   key = key.toUpperCase();
   if (typeof value === 'object') {
     result.push(`${key}:`);
     if (Array.isArray(value)) {
       value.forEach(item => result.push(item));
     } else {
       Object.entries(value).forEach(([key, value]) => {
         key = key.charAt(0).toUpperCase() + key.slice(1)
         result.push(`${key}: ${value}`);
       })
    }
  } else {
    result.push(`${key}: ${value}`);
  }
  console.log(result.join("\n"))
  return result.join("\n");
}, []);

Comment: The `join()` shouldn't be called inside `reduce()`. After the function you can do `var finalData = result.join('\n');` like in your original example :)
Comment: Hi. Thanks so much for helping me out. I tried your code and I'm not getting any output. The template shows my error handler and the terminal only shows A: Tesla.


How do I find my compute engine path and how to set up the cron for a Google cloud deploy Mautic instance?

Question: I want to set cron jobs for my Mautic install, but I don't know what path to use ...
This is NOT for a Bitnami mautic install, I'm simply using examples below for reference, this is for a Google Cloud Deploy instance.
Mautic install is over here:
http://126.96.36.199/s/login

What is the path to my mautic installation
In what file should I put the cron code or where should I create a new file?
What path should I enter into the mautic cron job command

This the info and data I have now:
Siteground hosting:
15 * * * * /usr/local/bin/php /home/vuxi5632/public_html/brunovincent.net/mautic_yh/bin/console mautic:campaigns:update >/dev/null 2>&1

Bitnami Documentation
15 * * * * su daemon -s /bin/sh -c "installdir/php/bin/php installdir/apps/mautic/htdocs/app/console mautic:segments:update --env=prod"

Mautic forum post suggestion:
1 * * * * su daemon -s /bin/sh -c "/opt/bitnami/php/bin/php -q /opt/bitnami/apps/mautic/htdocs/app/console mautic:segments:update" #mautic-segments-cron

Google Cloud:
Not sure, but I have these 3 bits of information:
I ran this command in command prompt:
~# grep -i 'DocumentRoot' /etc/apache2/sites-available/000-default.conf

And I got this:
/var/www/html/mautic

My IP address is this:
http://126.96.36.199/s/dashboard

My Google cloud sign in comand is this:
gcloud beta compute ssh --zone "us-west1-a" "mautic-google-deploy-vm" --project "horizon-private-charters"

Command prompt path on my windows PC:
root@mautic-google-deploy-vm:~#

What is the EXACT code in need to input into the file?
Comment: Okay, let's try to follow the [guide](https://mauteam.org/mautic/mautic-admins/mautic-cron-jobs-for-dummies-marketers-too/) I mentioned in my answer and check your deployment. You've checked `DocumentRoot` and found path `/var/www/html/mautic` just as in the guide. Please check this path `/var/www/html/app/console` as well. To do it run `ls -l /var/www/html/app/` and update your question with a result. Also, please check configured cron jobs with command `sudo crontab -e` and add update your question with output.
Answer: Have a look at the Mautic documentation Cron jobs:

Mautic requires a few cron jobs to handle some maintenance tasks such
as updating contacts or campaigns, executing campaign actions, sending
emails, and more. You must manually add the required cron jobs to your
server.

and

If you're new to Linux or Cron Jobs, then the Apache Foundation has an
excellent guide which we would suggest that you read before asking
questions via the various support channels.

In case of Mautic Certified by Bitnami installed from Marketplace, you should follow steps below:

Install Mautic Certified by Bitnami (optional).

$ gcloud compute instances list
NAME         ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP    STATUS
mautic-1-vm  us-east4-a  f1-micro                   10.150.0.3   34.86.XX.181  RUNNING

Connect to the VM instance via SSH:

$ gcloud compute ssh mautic-1-vm --zone us-east4-a

Check Bitnami Mautic documentation Configure Scheduled Tasks:

Before running the commands shown on this page, you should load the
Bitnami stack environment by executing the installdir/use_APPNAME
script (Linux and MacOS) or by clicking the shortcut in the Start Menu
under "Start -> Bitnami APPNAME Stack -> Application console"
(Windows). On OS X VMs, the installation directory is /opt/bitnami and
OS X VM users can click the "Open Terminal" button to run commands.
Learn more about the Bitnami stack environment and about OS X VMs.

mautic-1-vm:~$ cd /opt/bitnami/
mautic-1-vm:/opt/bitnami$ sudo ./use_mautic

Edit Cron jobs:

bash-5.0# sudo crontab -e

I decided to use nano as an editor on this step:
1 * * * * su daemon -s /bin/sh -c "/opt/bitnami/php/bin/php -q /opt/bitnami/apps/mautic/htdocs/bin/console mautic:segments:update" #mautic-segments-cron
1 * * * * su daemon -s /bin/sh -c "/opt/bitnami/php/bin/php -q /opt/bitnami/apps/mautic/htdocs/bin/console mautic:campaigns:rebuild" #mautic-campaings-rebuild-cron
1 * * * * su daemon -s /bin/sh -c "/opt/bitnami/php/bin/php -q /opt/bitnami/apps/mautic/htdocs/bin/console mautic:campaigns:trigger" #mautic-campaigns-trigger-cron
1 * * * * su daemon -s /bin/sh -c "/opt/bitnami/php/bin/php -q /opt/bitnami/apps/mautic/htdocs/bin/console mautic:emails:send" #mautic-email-send-cron
1 * * * * su daemon -s /bin/sh -c "/opt/bitnami/php/bin/php -q /opt/bitnami/apps/mautic/htdocs/bin/console mautic:webhooks:process" #mautic-webhooks-cron

As I can see, Cron jobs were configured by Bitnami, but you can make some changes if needed (it looks like mautic:campaigns:update was missed, but other optional jobs were added)

In case of manual Mautic installation,  you can follow this 3rd party guide Mautic Cron Jobs – The Full Guide for 2020:

The path:
For servers running Debian, Ubuntu and Derivatives use:
grep -i 'DocumentRoot' /etc/apache2/sites-available/000-default.conf

For servers running CentOS, RHEL and Fedora Linux distributions, run:
$ grep -i 'DocumentRoot' /etc/httpd/conf/httpd.conf

This command will return something like:
DocumentRoot /var/www/html/mautic

and

So, let's say your path (DocumentRoot) is "/var/www/html/"
Then your cron jobs would be like this:
* * * * * php /var/www/html/app/console mautic:segments:update
* * * * * php /var/www/html/app/console mautic:campaigns:update
* * * * * php /var/www/html/app/console mautic:campaigns:trigger

Than you can use the same command sudo crontab -e to edit Cron jobs.

EDIT

What is the path to my mautic installation

It depends how you installed Mautic.

In what file should I put the cron code or where should I create a new file?

You should use command sudo crontab -e to open proper file.

What path should I enter into the mautic cron job command

Cron jobs for Mautic Certified by Bitnami configured "out of the box" (you can see path in my example),  path for manual installation you can find at web server configuration as it was described above.
Comment: Wow, thank you so much, but I'm such an idiot...this is NOT a mautic insall, it's a google cloud deploy, mautic is defective ,that's my whole problem..


Let $P,Q,R$ be subspaces of $\mathbb{R}^2$ such that $P+Q=P+R$, is it the case that $Q=R$?

Question: Effectively I'm trying to show that: $Q \subset R$  and  $R \subset Q$.
We know that $P+Q \subset P+R$ and that $P+R \subset P+Q$ and I'm really struggling to get from this to a solution. I have been staring at this problem for hours now, any hints would be greatly appreciated.
Comment: You need some assumptions.  If, say, $P=\mathbb R^2$ then any $Q,R$ will work.  Or, for general $P$, take $Q=P$ and $R=\{0\}$.
Comment: And other nontrivial cases are easy to obtain such as $P$ generated by $(1,0),$ $Q$ generated by $(0,1)$ and $R$ generated by $(1,1).$
Answer: It''s trivially false. Otherwise, it would mean that, say in $\mathbf R^2$, if two bases share a vector, the other vectors are collinear.


How to hide username displayed in code with Omega 3 theme

Question: Drupal 7 with Omega version 3 theme generates a username class for the article tag in the HTML code, something like :
class="node node-page node-published node-not-promoted node-not-sticky author-USERNAME odd clearfix".
I'd like to avoid having the username displayed in the code for security reasons.
After investigating, this comes from the code "omega_alpha_preprocess_node()" in the "sites/all/themes/omega/omega/template.php" where you find the following line:
"$vars['attributes_array']['class'][] = drupal_html_class('author-' . $vars['node']->name); "

I copied the code of "omega_alpha_preprocess_node()" to the "template.php" of my Omega subtheme, I renamed the "omega_alpha_preprocess_node()" to "MYTHEME_alpha_preprocess_node" and removed the line "$vars['attributes_array']['class']". Unfortunatly, it does not work.
As of today, the solution I found is to remove the line "$vars['attributes_array']['class']" from the initial Omega template.php file, which is not the best practice, but it works and the username output as a class of an article tag is no longer displayed.
Can someone help me find a more elegant solution, as I'm not a very experienced Omega developer and I need guidance? Thank you.
Answer: The theme function your trying to us is theme_preprocess_node, and you'r correct in replacing the Omega with [yourtheme].
The reason the function isn't getting called though is MYTHEME_alpha_preprocess_node should just be MYTHEME_preprocess_node. Alpha is part of the theme name, so if you remove it, the function should start working for you once you clear your cache.
EDIT ---------------------------------
Because drupal's template functions are still hooks, you can't just override the preprocess_node function, as omega's preprocess function is still going to run. However, what you can do is edit the $vars variable. Make sure you have the & in the param ( ie function (&$vars) ) so the vars is a reference.
From there, you should be able to modify the $vars['attributes_array']['class'] array and remove the unwanted class.
So if you put something like this in your code, that should get you close to where you might need to be.
function mytheme_preprocess_node (&$vars){
    $count = 0;
      foreach($vars['attributes_array']['class'] as $class){
        if(substr( $class, 0, 7 ) === "author-"){
          unset($vars['attributes_array']['class'][$count]);
        }
        $count += 1;
      }
}

EDIT 2 ============================
When I say remove the class from the var, I mean you should just be able to unset the variable (I updated my code snippet to show it inside the preprocess function).
You don't need to copy the whole of the omega_alpha_preprocess_node. What you actually are doing when you define your own theme_preprocess_node function is your telling drupal you would like to modify the variables for the node before it processes it. Because your working from a subtheme, the parent theme is still going to run it's own preprocess functions. So that class will always be added via omega. However, because your subtheme's preprocess function is downstream, it will get the &$vars reference with that class already added to it. So instead of rewriting the function, all that is needed is to simply remove the class from the $vars variable that you received in your params.
Comment: Hi Jance, here is what I did based on your input :

1. I pasted back the entire code of "omega_alpha_preprocess_node()" in the "template.php" of the omega/template.php file.

2.  I copied the "omega_alpha_preprocess_node()" to the "template.php" of my Omega subtheme and renamed it to "MYTHEME_preprocess_node".

3. I removed the "$vars['attributes_array']['class'][] " line from the "MYTHEME_preprocess_node".

4. I clerared all caches.

Unfortunatly, it still does not work and the username class for the article tag is displayed in the HTML code.
What did I do wrong ?
Thank you for your help.
Comment: @FL26, see my edit.
Comment: Thanks for your answer. When you say "edit the $vars variable", in which line? What I did is simply remove the lines "// Add a class to allow styling based on the node author.
  $vars['attributes_array']['class'][] = drupal_html_class('author-' . $vars['node']->name);" from the function MYTHEME_preprocess_node(&$vars).I suppose this is above my competence in Omega development. Thank you again.
Comment: @FL26, I updated my answer again, but the basic thing that's going on is the preprocess function is giving you the chance to modify the node &$vars before they are processed. Your not overriding any functions, rather adding your own logic. You can't just copy the function and remove the line you don't want (because the parent theme's function is still going to run) rather, you need to remove the class that you don't want from $vars when your function runs.
Comment: Thank you Jance, your explaination is cristal clear. I added your snippet code to the template.php file of my subtheme and it worked perfectly. Thanks to you, I now better understand how a theme and its subtheme work. FYI, in your snippet code, (&&vars) should be replaced by (&$vars). Thought you'd like to know.
Comment: Wopsie, good catch, I'll update that for posterity.