Winapi: Screenshot is not displayed on window

Question: I'm new with GUI programming on windows and came across some problems (using visual studio 2017).
I have a client and server application, client basically takes pictures of desktop and sends it to server which then displays it on the screen. As I decided to post a question here I created one project which creates a window(which is used to display screensots) takes the screenshot and displays it (I tried to use as minimal code as possible to reproduce the problem).
Here is the code:
// Onefile.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#define SECURITY_WIN32
#include <Windowsx.h>
#include <WinSock.h>
#include <Windows.h>
#include <WinBase.h>
#include <Stdio.h>
#include <Security.h>
#include <Sddl.h>
#include <Shlwapi.h>
#include <Shlobj.h>
#include <TlHelp32.h>
#include <Psapi.h>
#include <Wininet.h>
#include <Urlmon.h>

#pragma comment(lib,"WS2_32")

static BITMAPINFO g_bmpInfo;
static BYTE      *g_pixels = NULL;
HWND hWndClient;
HDC hDcBmpServer;
static const TCHAR *className = TEXT("ControlWindow");
static const TCHAR *titlePattern = TEXT("Desktop");

static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  switch (msg)
  {
  case WM_CREATE:
  {
    printf("WndProc: WM_CREATE\n");
    fflush(stdout);
    break;
  }
  case WM_SYSCOMMAND:
  {
    printf("WndProc: WM_SYSCOMMAND\n");
    fflush(stdout);
    return DefWindowProc(hWnd, msg, wParam, lParam);
  }
  case WM_PAINT:
  {
    printf("WndProc: WM_PAINT\n");
    fflush(stdout);

    PAINTSTRUCT ps;
    HDC         hDc = BeginPaint(hWnd, &ps);

    if (hDc == NULL)
    {
      printf("WM_PAINT: BeginPaint FAILED!\n");
      fflush(stdout);
    }

    RECT clientRect;
    if (GetClientRect(hWnd, &clientRect) == 0)
    {
      printf("WM_PAINT: GetClientRect FAILED %d\n", GetLastError());
      fflush(stdout);
    }

    RECT rect;
    HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0));

    if (hBrush == NULL)
    {
      printf("%d WM_PAINT: CreateSolidBrush FAILED %d\n", GetLastError());
      fflush(stdout);
    }

    rect.left = 0;
    rect.top = 0;
    rect.right = clientRect.right;
    rect.bottom = clientRect.bottom;

    rect.left = g_bmpInfo.bmiHeader.biWidth;

    if (FillRect(hDc, &rect, hBrush) == 0)
    {
      printf("WM_PAINT: FillRect 1.0 failed!\n");
      fflush(stdout);
    }

    rect.left = 0;
    rect.top = g_bmpInfo.bmiHeader.biHeight;

    if (FillRect(hDc, &rect, hBrush) == 0)
    {
      printf("WM_PAINT: FillRect 2.0 failed!\n");
      fflush(stdout);
    }
    DeleteObject(hBrush);

    if (BitBlt(hDc, 0, 0, g_bmpInfo.bmiHeader.biWidth, g_bmpInfo.bmiHeader.biHeight, hDcBmpServer, 0, 0, SRCCOPY) == 0)
    {
      printf("WM_PAINT: BitBlt failed!%d\n", GetLastError());
      fflush(stdout);
    }
    else
    {
      printf("WM_PAINT: BitBl SUCCESS!\n");
      fflush(stdout);
    }
    EndPaint(hWnd, &ps);
    break;
  }
  case WM_DESTROY:
  {
    PostQuitMessage(0);
    break;
  }
  case WM_ERASEBKGND:
    return TRUE;
  case WM_LBUTTONDOWN:
  case WM_LBUTTONUP:
  case WM_RBUTTONDOWN:
  case WM_RBUTTONUP:
  case WM_MBUTTONDOWN:
  case WM_MBUTTONUP:
  case WM_LBUTTONDBLCLK:
  case WM_RBUTTONDBLCLK:
  case WM_MBUTTONDBLCLK:
  case WM_MOUSEMOVE:
  case WM_MOUSEWHEEL:
  {
    printf("WndProc: Buttons\n");
    fflush(stdout);
    break;
  }
  case WM_CHAR:
  {
    printf("WndProc: WM_char\n");
    fflush(stdout);
    break;
  }
  case WM_KEYDOWN:
  case WM_KEYUP:
  {
    printf("WndProc: KEYUPm\n");
    fflush(stdout);
    switch (wParam)
    {
    case VK_UP:
    case VK_DOWN:
    case VK_RIGHT:
    case VK_LEFT:
    case VK_HOME:
    case VK_END:
    case VK_PRIOR:
    case VK_NEXT:
    case VK_INSERT:
    case VK_RETURN:
    case VK_DELETE:
    case VK_BACK:
      break;
    }
  }
  case WM_GETMINMAXINFO:
  {
    printf("WndProc: WM_GETMINMAXINFO\n");
    fflush(stdout);
    break;
  }
  default:
    return DefWindowProc(hWnd, msg, wParam, lParam);
  }
return 0;
}

//Register class
BOOL CW_Register(WNDPROC lpfnWndProc)
{
  WNDCLASSEX wndClass;
  wndClass.cbSize = sizeof(WNDCLASSEX);
  wndClass.style = CS_DBLCLKS;
  wndClass.lpfnWndProc = lpfnWndProc;
  wndClass.cbClsExtra = 0;
  wndClass.cbWndExtra = 0;
  wndClass.hInstance = NULL;
  wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
  wndClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
  wndClass.lpszMenuName = NULL;
  wndClass.lpszClassName = className;
  wndClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
  return RegisterClassEx(&wndClass);
}

//Create window which should display pictures
HWND CW_Create()
{
  printf("CW_Create: Creating Windows...\n");
  fflush(stdout);

  hWndClient = CreateWindow(className,
    titlePattern,
    WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SIZEBOX | WS_SYSMENU,
    CW_USEDEFAULT,
    CW_USEDEFAULT,
    800,
    600,
    NULL,
    NULL,
    GetModuleHandle(NULL),
    NULL);

  if (hWndClient == NULL)
  {
    printf("CW_Create:  ERROR! CreateWindow failed %d\n", GetLastError());
    fflush(stdout);
    return NULL;
  }

  if (ShowWindow(hWndClient, SW_SHOW) == 0)
  {
    printf("CW_Create: The window was previously hidden\n");
    fflush(stdout);
    return NULL;
  }
  else
  {
    printf("CW_Create: The window was previously shown\n");
    fflush(stdout);
  }
  printf("CW_Create: Exiting...\n");
  return hWndClient;
}

void CreateWindows()
{
  CW_Register(WndProc);
  CW_Create();
}

int main()
{
  CreateWindows();

  memset(&g_bmpInfo, 0, sizeof(g_bmpInfo));

  g_bmpInfo.bmiHeader.biSize = sizeof(g_bmpInfo.bmiHeader);
  g_bmpInfo.bmiHeader.biPlanes = 1;
  g_bmpInfo.bmiHeader.biBitCount = 24;
  g_bmpInfo.bmiHeader.biCompression = BI_RGB;
  g_bmpInfo.bmiHeader.biClrUsed = 0;
  g_bmpInfo.bmiHeader.biSizeImage = 800 * 3 * 600;

  //Client side which takes a picture of screen
  RECT rect;
  HWND hWndDesktop = GetDesktopWindow();
  GetWindowRect(hWndDesktop, &rect);

  HDC     hDc = GetDC(NULL);

  if(hDc == NULL)
  {
    printf("Client: hDc is NULL %d\n", GetLastError());
  }
  HDC     hDcScreen = CreateCompatibleDC(hDc);

  if (hDcScreen == NULL)
  {
    printf("Client: hDcScreen is NULL %d\n", GetLastError());
  }

  HBITMAP hBmpScreen = CreateCompatibleBitmap(hDc, rect.right - rect.left, rect.bottom - rect.top);

  if (hBmpScreen == NULL)
  {
    printf("Client: hBmpScreen is NULL %d\n", GetLastError());
  }

  //Resize the picture to 800x600 dimension
  HBITMAP hBmpScreenResized = CreateCompatibleBitmap(hDc, 800, 600);

  if (hBmpScreenResized == NULL)
  {
    printf("Client: hBmpScreenResized is NULL %d\n", GetLastError());
  }
  HDC     hDcScreenResized = CreateCompatibleDC(hDc);

  if (hDcScreenResized == NULL)
  {
    printf("Client: hDcScreenResized is NULL %d\n", GetLastError());
  }

  SelectObject(hDcScreenResized, hBmpScreenResized);

  SetStretchBltMode(hDcScreenResized, HALFTONE);
  if (StretchBlt(hDcScreenResized, 0, 0, 800, 600,
    hDcScreen, 0, 0, rect.right, rect.bottom, SRCCOPY) == 0)
  {
    printf("Client: StretchBlt is NULL %d\n", GetLastError());
  }

  DeleteObject(hBmpScreen);
  DeleteDC(hDcScreen);

  //Assign new values
  hBmpScreen = hBmpScreenResized;
  hDcScreen = hDcScreenResized;

  SelectObject(hDcScreen, hBmpScreen);

  free((HLOCAL)g_pixels);

  g_pixels = (BYTE *)malloc(g_bmpInfo.bmiHeader.biSizeImage);

  g_bmpInfo.bmiHeader.biWidth = 800;
  g_bmpInfo.bmiHeader.biHeight = 600;

  if (GetDIBits(hDcScreen, hBmpScreen, 0, 600, g_pixels, &g_bmpInfo, DIB_RGB_COLORS) == 0)
  {
    printf("Client: GetDIBits is NULL %d\n", GetLastError());
  }

  DeleteObject(hBmpScreen);
  ReleaseDC(NULL, hDc);
  DeleteDC(hDcScreen);

  //Server side which should take the pixels and paint them on the window
  HDC hDcServer = GetDC(NULL);
  if (hDcServer == NULL)
  {
    printf("Server: hDcServer is NULL %d\n", GetLastError());
  }

  hDcBmpServer = CreateCompatibleDC(hDcServer);
  HBITMAP hBmp;

  hBmp = CreateCompatibleBitmap(hDcServer, g_bmpInfo.bmiHeader.biWidth, g_bmpInfo.bmiHeader.biHeight);
  if (hBmp == NULL)
  {
    printf("Server: hBmp is NULL %d\n", GetLastError());
  }

  SelectObject(hDcBmpServer, hBmp);

  int ScanLines = SetDIBits(hDcBmpServer,
    hBmp,
    0,
    g_bmpInfo.bmiHeader.biHeight,
    g_pixels,
    &g_bmpInfo,
    DIB_RGB_COLORS);

  if (ScanLines == 0)
  {
    printf("Server: hBmp is NULL %d\n", GetLastError());
  }
  else
  {
    printf("Server: Scanned lines %d\n", ScanLines);
  }

  fflush(stdout);

  InvalidateRgn(hWndClient, NULL, TRUE);

  MSG msg;
  while (GetMessage(&msg, NULL, 0, 0) > 0)
  {
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
}

As you can see I'm creating a window using CreateWindows function, then try to take a screenshot, then I resize it to the proper window size
which in my case is 800x600 and then try to display it using InvalidateRgn function. I've deleted basically all code in WndProc in sake of this question and only left WM_PAINT part.
The problem I'm having is that the window which should be filled with the screenshot is black and nothing is displayed on it. I have no compiler or runtime errors but the screenshot is not displayed. I think I'm missing some information on how to do this properly. Hope you can help.
P.S
This is the source code of some project, I don't want to convert screenshot into .bmp and send it that way, I want to understand why this method doesn't work. thanks.
Comment: My bad, I changed it to `rect.left = clientRect.left;` since I use `GetClientRect(hWnd, &clientRect)` but I have same situation.
Comment: Your program has nothing to do with client/server. This is a stand alone program, it's a good start to get the functions right before moving to client/server. Please describe what you are trying to do within the context of a stand alone program. Note, `WndProc` should return 0 if `swich` statement break.
Comment: thanks for the note, I want to take a screenshot and display it on the window.
Answer: Create a memory device context and bitmap (HBITMAP handle). Select the bitmap in to memory dc. Then use BitBlt to copy from screen to memory dc. The bitmap will then contain the screen data.
You can then print the bitmap handle directly in WM_PAINT. This would be a DDB, it can't be transferred between programs. You need DIB, or so use GetDIBits to copy the content from bitmap in to a byte array (g_bmpInfo and g_pixels)
Note that the size of 24-bit bitmap is not always with * height * 3, you need a special formula to account for padding.
BITMAPINFO g_bmpInfo;
BYTE      *g_pixels = NULL;

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        auto hdc = BeginPaint(hWnd, &ps);

        RECT rc;
        GetClientRect(hWnd, &rc);

        int w = g_bmpInfo.bmiHeader.biWidth;
        int h = g_bmpInfo.bmiHeader.biHeight;
        if(g_pixels && w && h)
        {
            //print the bitmap on screen
            SetDIBitsToDevice(hdc, 0, 0, w, h, 0, 0, 0, h, g_pixels,
                 &g_bmpInfo, DIB_RGB_COLORS);
        }

        EndPaint(hWnd, &ps);
        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

int main()
{
    CreateWindows();

    RECT rect;
    HWND hWndDesktop = GetDesktopWindow();
    GetWindowRect(hWndDesktop, &rect);
    int width = rect.right - rect.left;
    int height = rect.bottom - rect.top;

    int bpp = 24; //24-bit
    int size = ((width * bpp + 31) / 32) * 4 * height;

    memset(&g_bmpInfo, 0, sizeof(g_bmpInfo));
    g_bmpInfo.bmiHeader.biSize = sizeof(g_bmpInfo.bmiHeader);
    g_bmpInfo.bmiHeader.biWidth = width;
    g_bmpInfo.bmiHeader.biHeight = height;
    g_bmpInfo.bmiHeader.biPlanes = 1;
    g_bmpInfo.bmiHeader.biBitCount = 24;
    g_bmpInfo.bmiHeader.biCompression = BI_RGB;
    g_bmpInfo.bmiHeader.biSizeImage = size;

    g_pixels = new BYTE[size];

    auto hdc = GetDC(HWND_DESKTOP);
    auto memdc = CreateCompatibleDC(hdc);
    auto hbitmap = CreateCompatibleBitmap(hdc, width, height);
    auto oldbmp = SelectObject(memdc, hbitmap);

    //copy from screen to memory
    BitBlt(memdc, 0, 0, width, height, hdc, 0, 0, SRCCOPY);

    //fill g_pixels array
    GetDIBits(hdc, hbitmap, 0, height, g_pixels, &g_bmpInfo, DIB_RGB_COLORS);

    MSG msg;
    while(GetMessage(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    //cleanup
    SelectObject(memdc, oldbmp);
    DeleteObject(hbitmap);
    DeleteDC(memdc);
    ReleaseDC(HWND_DESKTOP, hdc);

    delete[] g_pixels;

    return 0;
}

Comment: Thank you very much for explanaition. Just to be sure, sending `g_pixels` and `g_bmpInfo` from client to server, then calling `SetDIBitsToDevice` on server side should display the image right?
Comment: Yes, you should be able to send `g_pixels` and `&g_bmpInfo` as binary data.
Comment: and one more question please, We create bitmap of entire screen in here `CreateCompatibleBitmap(hdc, width, height);`,but it shrinks to window size(800x600), I added this code https://pastebin.com/MaFrbZVh but the image is same in the window. Should `StretchBlt` function "stretch" entire screen bitmap into `800x600` bitmap? P.S I'm trying to have whole screen image in the window not part of it.
Comment: Maybe system DPI settings is at 125% or higher. Call `SetProcessDPIAware()` at the start of the program. Ideally DPI awareness should be set in manifest file. See also [High DPI in Desktop apps](https://learn.microsoft.com/en-us/windows/desktop/hidpi/high-dpi-desktop-application-development-on-windows)


Arrange a matrix into unique rows and columns

Question: Say I have a vector,
vec <- c(rep(1,4),rep(2,4),rep(3,4),rep(4,4),rep(5,4),rep(6,4),rep(7,4),rep(8,4),rep(9,4))

that I arranged into a matrix 6x6.
mat <- matrix(vec,6,byrow=T)

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    1    1    2    2
[2,]    2    2    3    3    3    3
[3,]    4    4    4    4    5    5
[4,]    5    5    6    6    6    6
[5,]    7    7    7    7    8    8
[6,]    8    8    9    9    9    9

I would like to have the numbers shuffled around such that they are unique for each row and column. Or in other words, there must be no duplicates numbers in any row or column.
The length of the vector, the elements of the vector, the number of rows and columns of the matrix are all fixed. The only aspect that can be changed is the placement of the numbers.
How would I go about solving this computationally?
Below is one possible correct result (done manually). Note that no row or column has any duplicate number.
res <- matrix(c(3,1,2,5,7,8,6,8,5,2,9,4,8,6,7,4,3,5,2,9,3,1,6,7,1,4,9,7,5,6,4,2,1,9,8,3),nrow=6,byrow=T)

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    1    2    5    7    8
[2,]    6    8    5    2    9    4
[3,]    8    6    7    4    3    5
[4,]    2    9    3    1    6    7
[5,]    1    4    9    7    5    6
[6,]    4    2    1    9    8    3

table(res)

res
1 2 3 4 5 6 7 8 9
4 4 4 4 4 4 4 4 4

Comment: There are some odd quirks in people's opinions. 'How to get R to give permutations', & 'how to rearrange a matrix', are clearly coding questions, & not at all about statistics, IMO.
Comment: This is really more of an R coding question than a question about statistics. It is off topic here, but should be on topic on [SO]. If you wait a bit, we can migrate it for you.
Comment: Interesting. I posted this on SO. It was downvoted a lot saying the question was not clear, not a programming question etc and unsuitable for SO. So I posted it on CrossValidated, and now it has been migrated to SO again.
Answer: To start, there is a better way to get your vector.  This will entail less typing and make your code clearer:
vec <- rep(1:8, each=4)
mat <- matrix(vec, ncol=6, byrow=T)

Next, note that you are asking for unique orderings of the elements by rows.  That is, you want the permutations of your elements.  The number of unique permutations of N elements is N!.  We can compute that number in R thus:
factorial(length(unique(vec)))
# [1] 40320

That is way more orderings of your numbers than you need.  (it seems you just want 6.)  Assuming you would like to draw some random orderings, lets draw 6 numbers from the possible 40320:
set.seed(3931)  # this makes the example exactly reproducible
rows <- sample.int(40320, 6)
rows
# [1] 36601 24136  5713 23405 25328 32973

From here, to get the actual permutations, we will use the permute library in R.  Because the total number of permutations is large, we will have to set the maxperm argument to be larger than its default (9999, I gather):
library(permute)
out <- allPerms(unique(vec), control=how(maxperm=41000))[rows,]
out
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,]    8    2    7    1    3    4    6    5
# [2,]    5    7    4    1    6    8    2    3
# [3,]    2    1    8    6    3    4    7    5
# [4,]    5    6    4    1    2    8    7    3
# [5,]    6    1    3    2    5    7    4    8
# [6,]    7    4    6    5    8    2    3    1

My apologies for misreading the question.  The number of permutations of N elements, when you will only use r of them is N!/r!.  Here is a simple calculation:
factorial(length(unique(vec))) / factorial(length(unique(vec))-6)
# [1] 20160

It isn't clear to me how to get allPerms() to use fewer than all elements.  Here is a simple kludge to get around that:
library(permute)
out <- allPerms(unique(vec), control=how(maxperm=41000))[rows,1:6]
out
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    8    2    7    1    3    4
# [2,]    5    7    4    1    6    8
# [3,]    2    1    8    6    3    4
# [4,]    5    6    4    1    2    8
# [5,]    6    1    3    2    5    7
# [6,]    7    4    6    5    8    2

Comment: This is impressive. But, the `out` is a 8x6 matrix while it should be a 6x6 matrix. Also `table(as.vector(out))` returns 1:9 6 each. It must be 1:9 4 each. Anyhow this is a good place for me to start fiddling. Thanks a lot.
Comment: Hmmm, good point, I didn't look closely enough. I'll take another look when I get a chance. I'm pretty busy right now.


Computation of total space of fibration using Leray-Serre spectral sequence

Question: If  a Leray-Serre spectral sequence corresponding to fibration $F\hookrightarrow E\to B$ with $E_2^{2,t}=H^s(B;k)\otimes H^t(F;k)$ converges to $H^{*}(E;k)$ as an algebra then the generators of graded algebra  $H^{*}(E;k)$ comes only from edge homomorphisms? Can $E^{p,q}_{\infty},p,q\not=0$ give a generator of $H^{*}(E;k)$?
Answer: Suppose there are classes $b_1 \in E_2^{1,0}$, $b_2 \in E_2^{2,0}$ and $f \in E_2^{0,1}$, with $b_1 b_2 = 0$. Suppose further that there is a differential $d_2: f \mapsto b_2$. Then the class $b_1 \otimes f$ will survive and be an algebra generator.
Comment: If $E_{\infty}^{2,0}=E_{\infty}^{0,4}=0$ and $E^{0,2}_{\infty}=k$, where $k$ is a field, then can $E_{\infty}^{2,2}=k$ be? Is this situation is possible?
Comment: There are no algebraic obstacles: if $E_2^{0,1}=k=E_2^{0,2}$, and if $E_2^{2,0}=k$, there could be a differential $E_2^{0,1} \to E_2^{2,0}$. To actually verify that this is possible, you would need to find a fibration demonstrating this behavior.


disabling a deactivation guard when routing

Question: I have a route with the following flow : user navigates from Route A to Route B, these routes are in different modules and each has a activation and a deactivation guard.  The activation guard redirects the user to the last navigated point within the module (it's remembered in ngrx) the deactivation guard checks for any unsaved changes and prompts the user before navigating out.
route A -> Deactivate guard prompts Pending confirm, user clicks Yes, navigation proceeds
route B -> Activation guard kicks in, determines previous point exists, issues a router.navigateByUrl(previousUrlFromHistory) and returns false to cancel the current navigation.
The problem here is that in my Activation guard for route B when navigateByUrl executes it considers it a brand new navigation cycle FROM route A and this in turn triggers the deactivation guard all over again (cyclical).
So, for this invocation I need to temporarily route without any deactivation guards executing since it's a safe navigation issued by the redirect guard itself.
Is there a way to tell the router itself to navigate without guards?  for example: router.navigateByUrl(url, { checkDeactivate: false }); or something like that?
I could handle this manually using flags but would rather use a router option if it exists.. I couldn't find anything so far.
Answer: Answering my own question here.  I see Angular 7 now has route state that can be passed, so i'm going to pass it as route data and then query the flag in my deactivationGuard which should be simple enough. Thankfully we are transitioning to Angular 7.


How to pass image entry in atom rss feed. in rails 3.1

Question: every time people give tutorials on how to make atom rss templates, but my question here is how can i pass in and image in the rss format. for instance i have this code sample in rss
atom_feed :language => 'en-US' do |feed|
  feed.title @title
  feed.updated @updated

  @news_items.each do |item|
    next if item.updated_at.blank?

    feed.entry( item ) do |entry|
      entry.url news_item_url(item)
      entry.title item.title
      entry.content item.content, :type => 'html'

      # the strftime is needed to work with Google Reader.
      entry.updated(item.updated_at.strftime("%Y-%m-%dT%H:%M:%SZ"))

      entry.author do |author|
        author.name entry.author_name)
      end
    end
  end
end

where can i display the image of the article and how do i do it
Answer: The Atom format (http://www.atomenabled.org/developers/syndication/) supports an icon (square) and a logo (rectangular)... so in your block
entry.icon '/path/to/my/icon.png'
entry.logo '/path/to/my/logo.png'

EDIT: serves me right for not checking some code. Those elements are optional elements for the feed element, not the entry. Try:
feed.icon '/path/to/my/icon.png'

Comment: i did this in my block but the image is not being displayed `entry.icon image_tag story.image(:small)`
Comment: Don't use `image_tag`. This will create an HTML image tag. You need the `image_path` helper, and prepend it with your domain name.


How to prove this sequent by natural deduction?

Question: How do I prove
$$\forall x\forall y\forall z(S(x, y)\land S(y, z) \Rightarrow S(x, z)), \forall x\neg S(x, x) \vdash \forall x\forall y(S(x, y) \Rightarrow \neg S(y, x)).$$
by natural deduction?
1 $\quad \forall x\forall y\forall z(S(x, y)\land S(y, z) \Rightarrow S(x, z))\quad \text{premise}$
2 $\quad\forall x\neg S(x, x) \quad\text{premise}$
I don't know what's the next step, replace $x$ by some term?
I got it!!
Comment: What did you try?  What rules are you working with? (there are many different proof systems, each with their own set of rules ..)
Comment: by predicate natural deduction
Comment: That is not specific enough ... again, there are many different systems for 'predicate natural deduction' ... can you post those rules?  Or maybe have an online link?
Comment: I just added in the above
Comment: That helps ... how is your $\forall$ Intro defined?  (especially that one is defined differently between different systems ...) Do you have an example for that?
Comment: I've added some example (line 3), but I don't know whether this is correct or not.
Comment: Your first step is wrong.  Your first step should be to come up with any proof at all of the statement, before trying to convert that proof to natural deduction.  You have to have a reason for thinking it is true before you can make a proof.  This is not a guessing game.
Answer: Hint: Assume $S(x,y)$ and $S(y,x)$. Then $S(x,x)$ by the first premise, contradicting the second premise.
Comment: What is assume S(x, y) and S(y, x)? I haven't do the \forall eliminate yet.
Answer: HINT
It's always good to think about this informally, and then try to formalize that.  Thinking about it informally will clarify your all-important proof strategy.
OK, so you want to prove:
$$\forall x\forall y(S(x, y) \Rightarrow \neg S(y, x))$$
This means that you consider and $x$ and $y$, assume that $S(x,y)$, and then try to show $\neg S(y,x)$.
And for the latter, since it is a negation, probably a proof by contradiction will be good, i.e. assume that you do have $S(y,x)$, and show that that leads to a contradiction.
Comment: I can understand what you said, but this problem is still too complicated for me. Could you provide some further hint?
Comment: Like I said, don't get too caught up with the symbols and the rules initially: you want to see the forest through the trees!  The fact that you try and solve this problem 1 step at a time tells me that you're not really thinking about a strategy, but it is that strategy that is often key to solving these problems. So, before I provide any further hints, I want you to consider what I said in my post about a high-level proof strategy: can you see how that will work?
Comment: It's still too hard for me.. I don't know how to deal with those \forall correctly.
Comment: @walkcc  You have no example for that?  Are you using a book?
Comment: Yes, there are some examples. But how can I assume S(x, y) and S(y, x) then get contradiction thus get negation of S(y, x). I cannot operate these things without eliminate \forall.
Comment: I don't know "how can I assume S(x, y)."
Comment: @walkcc Without knowing the rules, I don't know either how you can do that in your system ... you really have no examples or a book title or some web link to your system?
Comment: The book is
Comment: By Huth and Ryan?
Comment: Yes, it's by Huth and Ryan.
Comment: @walkcc OK, cool. Well, I see that they have the rule for $\forall$ i (Intro) on page 110.  You'll also need to contradiction ($\bot$) rule to derive a contradiction, and the $\neg$ i rule to derive a negation once some assumption leads to a cpontradiction. Finally, you can make assumptions at any point in the proof, as long as you start that inside a new box.  I have to be offline for a while, but look at the rules, think about my strategy, and good luck!
Comment: Thx:) I'll do my best!
Comment: I thought I've got the point! I just updated myAns. Could you check it latter? Thank you very much!!!
Comment: @walkcc Eh, yes, that is totally correct .... Did you find this somewhere?  To be really honest ... that's a bit hard to believe you got all that given how lost you were earlier ... Typically students starting with this material take at least a few weeks to get up to speed with these proofs.
Comment: I've learned proposition logic last week, and I just studied the predicate logic now. All these stuff were written by myself honestly.
Comment: @walkcc  OK, well, well done then!!


Bayes' theorem in 1-d EM algorithm

Question: I'm watching a video on the EM algorithm,

When we use Bayes' Theorem to calculate $b_i$, how do I find $P(b)$ and $P(a)$ initially? It says we can estimate the priors $P(b)$ and $P(a)$ but that's once we have at least one value $b_i$. Should I simply let $P(b)$ and $P(a)$ be 1 to begin with?
Also, why does it say we could estimate the priors? Don't we have to in order to calculate $b_i$?
Answer: The beauty, and the potential danger, of the EM algorithm is that no matter where you start, you will always (for most problems) converge to a local mode.  It's always a good idea when running such a mode finding algorithm to initialize it with various starting values to make sure that you found the global mode, as opposed to a local mode.
For $p(a)= \tau$ and $p(b)= 1-\tau$, you have to start with starting values for $\tau$ just like the other parameters.  The parameter $\tau$ will be updated during each M-step of the EM algorithm and will not be fixed from the start as one would normally think of a prior.  See the gaussian mixture example here.
Comment: Good question.  There is no way to prove you have found the global mode unless you apply some other method.  But if you start your algorithm from enough different starting points, it would be reasonable to conclude that whichever mode corresponds to the largest observed data likelihood would be the global mode.  The observed data likelihood in this case corresponds to the mixture of two normals with parameters and weights equal to the mixture proportions estimated by EM.
Comment: How will I know when I've actually found the global mode?
Comment: Could I simply use $P(b) = (b_1 + b_2 + ... + b_n)/n$ and $P(a) = 1 - P(b)$ and update it every iteration? If so, what should I initialize the values to at the very beginning? It appears the other parameters can be picked pretty much at random, is that the case here?
Comment: You could start there, assuming you had starting guesses for $b_1$, $b_2$, ..., $b_n$.  Where you start determines where you finish, so if you have a good starting value, you could make it to the global mode.  In general, it can be difficult to select a starting value that will get you to the global mode as opposed to a local mode, which is why it would be better to run an EM algorithm from each of several different starting values.
Comment: But see there's the whole chicken and egg thing where I can't estimate my $b_i$'s without having my $P(b)$ and $P(a)$ and I'm not sure how to go about making good starting guesses. Perhaps I could assume the priors to be equal for the first few $b_i$ calculations? I will make sure to try several starting values for the parameters of the gaussians
Comment: Indeed, there's not really a great solution to how to initialize the parameters or the latent variables, the $b_i$'s.  This is precisely why you should run it from various starting points.  You should experiment with different starting values for $P(b)$ as well!

Bayes' theorem in 1-d EM algorithm


Where are the PHP directories on Mac OS X?

Question: I'm trying to configure PHP on Mac OS X (10.5.7) and am really confused as to where this program "lives".
Here's what I've found / not found:
php: /usr/bin/php
php.ini:  /etc/php.ini
extensions directory: /usr/lib/php/extensions
Are there other places where PHP components are located?
Answer: Have you tried:
locate php

Here is an article that may provide some guidance.
Another article: Working with PHP 5 in Mac OS X 10.5
One from php.org: Using the bundled PHP
Comment: that's somewhat helpful... finds anything with "php" in the filename, thanks (although i would rather hear where it's supposed to be located)
Comment: hmm, good enough, i guess!


Python nested dictionary append new key based on another list

Question: I have a nested dictionary and I want to push a new element on in based on the resulted list. My current code is working fine, but I want a generic solution of multilevel dictionary and multiple nested list elements. Basically, I want to make this portion dynamic based on the list path- N.B: The items on the list is dynamic
data['top_banner']['image']['global_image'] <---- path wil come from list element

Part of dictionary:
{
  "top_banner": {
    "image": {
      "global_image": {
        "alt": " ",
        "src": "path/to/file/5473cd34fadbb6a3-dine-1.jpg",
        "sizes": [
          {
            "src": "",
            "view": "100vw",
            "media": "(min-width:100px)",
            "intrinsicwidth": 0,
            "intrinsicheight": 0
          }
        ],
        "types": [
          "webp ",
          "jpg"
        ],
        "background": True,
        "intrinsicWidth": 2400,
        "intrinsicHeight": 2400
      }
    },
    "title": "Dine",
    "description": ""
  }
}

List path:
[['top_banner', 'image', 'global_image']]

Current code:
data['top_banner']['image']['global_image'].update({'intrinsicWidth': 200, 'intrinsicHeight': 300})

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this should be from the list

Answer: If I understood correctly, use functools.reduce to go down the nested path
from functools import reduce
import pprint

data = {
    "top_banner": {
        "image": {
            "global_image": {
                "alt": " ", "src": "path/to/file/5473cd34fadbb6a3-dine-1.jpg",
                "sizes": [
                    {
                        "src": "", "view": "100vw", "media": "(min-width:100px)",
                        "intrinsicwidth": 0, "intrinsicheight": 0
                    }
                ],
                "types": ["webp ", "jpg"],
                "background": True, "intrinsicWidth": 2400, "intrinsicHeight": 2400
            }
        },
        "title": "Dine", "description": ""
    }
}

path = ['top_banner', 'image', 'global_image']
reduce(lambda y, x: y[x], path, data).update({'intrinsicWidth': 200, 'intrinsicHeight': 300})
pprint.pprint(data)

Output
{'top_banner': {'description': '',
                'image': {'global_image': {'alt': ' ',
                                           'background': True,
                                           'intrinsicHeight': 300,
                                           'intrinsicWidth': 200,
                                           'sizes': [{'intrinsicheight': 0,
                                                      'intrinsicwidth': 0,
                                                      'media': '(min-width:100px)',
                                                      'src': '',
                                                      'view': '100vw'}],
                                           'src': 'path/to/file/5473cd34fadbb6a3-dine-1.jpg',
                                           'types': ['webp ', 'jpg']}},
                'title': 'Dine'}}

Comment: what if I have multiple path list e.g `[[],[],[],[]]` then reduce within another for will be good. I have added that on my edit. Please have a look
Comment: So what you are saying is that path is actually several paths?
Comment: Yes, because my nested dictionary is very large, I just added a portion of that. The soln is working fine but I am just curious that for multiple paths.
Comment: Could you add a concrete example with the given dictionary?
Answer: import types

data = {
    "top_banner": {
        "image": {
            "global_image": {
                "alt": " ",
                "src": "path/to/file/5473cd34fadbb6a3-dine-1.jpg",
                "sizes": [
                    {
                        "src": "",
                        "view": "100vw",
                        "media": "(min-width:100px)",
                        "intrinsicwidth": 0,
                        "intrinsicheight": 0,
                    }
                ],
                "types": ["webp ", "jpg"],
                "background": True,
                "intrinsicWidth": 2400,
                "intrinsicHeight": 2400,
            }
        },
        "title": "Dine",
        "description": "",
    }
}

paths = [["top_banner", "image", "global_image"]]

def recursive(data, path):
    if len(path) == 0:
        return data
    return recursive(data[path[0]], path[1:])

for path in paths:
    recursive(data, path).update({"intrinsicWidth": 200, "intrinsicHeight": 300})

print(data)

result :
{
    "top_banner": {
        "image": {
            "global_image": {
                "alt": " ",
                "src": "path/to/file/5473cd34fadbb6a3-dine-1.jpg",
                "sizes": [
                    {
                        "src": "",
                        "view": "100vw",
                        "media": "(min-width:100px)",
                        "intrinsicwidth": 0,
                        "intrinsicheight": 0,
                    }
                ],
                "types": ["webp ", "jpg"],
                "background": True,
                "intrinsicWidth": 200,
                "intrinsicHeight": 300,
            }
        },
        "title": "Dine",
        "description": "",
    }
}

Answer: you can use a recursive function:
def get_dict_element_by_path(dic, lst):
    if lst:
        return get_dict_element_by_path(dic[lst[0]], lst[1:])
    else:
        return dic

my_list = ['top_banner', 'image', 'global_image']
get_dict_element_by_path(data, my_list).update({'intrinsicWidth': 200, 'intrinsicHeight': 300})

Answer: Or you can do it this way whitout recursion
data = {
    "top_banner": {
        "image": {
            "global_image": {
                "alt": " ",
                "src": "path/to/file/5473cd34fadbb6a3-dine-1.jpg",
                "sizes": [
                    {
                        "src": "",
                        "view": "100vw",
                        "media": "(min-width:100px)",
                        "intrinsicwidth": 0,
                        "intrinsicheight": 0,
                    }
                ],
                "types": ["webp ", "jpg"],
                "background": True,
                "intrinsicWidth": 2400,
                "intrinsicHeight": 2400,
            }
        },
        "title": "Dine",
        "description": "",
    }
}

paths = [["top_banner", "image", "global_image"]]
res = data

for path in paths:
    for p in path:
        res = res[p]
    res.update({"intrinsicWidth": 200, "intrinsicHeight": 300})

print(data)

and this is the result
{
    "top_banner": {
        "image": {
            "global_image": {
                "alt": " ",
                "src": "path/to/file/5473cd34fadbb6a3-dine-1.jpg",
                "sizes": [
                    {
                        "src": "",
                        "view": "100vw",
                        "media": "(min-width:100px)",
                        "intrinsicwidth": 0,
                        "intrinsicheight": 0,
                    }
                ],
                "types": ["webp ", "jpg"],
                "background": True,
                "intrinsicWidth": 200,
                "intrinsicHeight": 300,
            }
        },
        "title": "Dine",
        "description": "",
    }
}

Answer: You could make a nestedDict class based on dict and override its get, getitem, and setitem methods to support indexing by paths.   This would make the indexing and manipulation more seamless:
class nestedDict(dict):

    def __getDictKey(self,index):
        parent,path = self,[index]
        while True:
            key = path.pop(0)
            if isinstance(key,(list,tuple)): path[:0] = key
            elif path: parent = parent[key]
            else: break
        return parent,key

    def __getitem__(self,index):
        d,k = self.__getDictKey(index)
        return dict.__getitem__(d,k)

    def get(self,index,default=None):
        try: return self[index]
        except KeyError: return default

    def __setitem__(self,index,value):
        d,k = self.__getDictKey(index)
        dict.__setitem__(d,k,value)

Example usage:
data = nestedDict(data)

# Indexing by path:

data['top_banner', 'image','global_image','src']
'path/to/file/5473cd34fadbb6a3-dine-1.jpg'

data['top_banner', 'image','global_image','background'] = False

# Indexing by dynamic paths:

path = ['top_banner', 'image','global_image']

data[path]
{'alt':' ', 'src':'path/to/file/5473cd34fadbb6a3-dine-1.jpg', 'sizes': ... }

data[path,"types"]
['webp ', 'jpg']

data[path].update({'intrinsicwidth': 200, 'intrinsicheight': 300})

data[path,"types"].append('pdf')

data[path,'background'] = False

# Indexing by composite paths:

pathParts = [['top_banner', 'image'],['global_image','types']]

data[pathParts]
['webp ', 'jpg']

To perform the same update on a list of different paths, you should use a loop:
paths   = [path1,path2,path3]
newSize = {'intrinsicwidth': 200, 'intrinsicheight': 300}
for path in paths:
    data[path,"global_image"].update(newSize)

Eventually, you may also want to override the keys, values and items method to allow iteration over paths of various lengths:
def keys(self,depth=1):
    if depth ==1 :
        yield from ([k] for k in dict.keys(self))
    else:
        for k,d in dict.items(self):
            if not isinstance(d,dict): continue
            yield from ([k]+p for p in nestedDict.keys(d,depth-1))

def values(self,depth=1):
    yield from (self[k] for k in self.keys(depth))

def items(self,depth=1):
    return zip(self.keys(depth),self.values(depth)))

Which will allow things such as:
# get all 2-part paths

for p in data.keys(2): print(p)

['top_banner', 'image']
['top_banner', 'title']
['top_banner', 'description']

# all level 4 paths and values

for k,v in data.items(4):print(k,":",v)

['top_banner', 'image', 'global_image', 'alt'] :
['top_banner', 'image', 'global_image', 'src'] : path/to/file/5473cd34fadbb6a3-dine-1.jpg
['top_banner', 'image', 'global_image', 'sizes'] : [{'src': '', 'view': '100vw', 'media': '(min-width:100px)', 'intrinsicwidth': 0, 'intrinsicheight': 0}]
['top_banner', 'image', 'global_image', 'types'] : ['webp ', 'jpg']
['top_banner', 'image', 'global_image', 'background'] : True
['top_banner', 'image', 'global_image', 'intrinsicWidth'] : 2400
['top_banner', 'image', 'global_image', 'intrinsicHeight'] : 2400

# All 'types' values (at level 3)

for v in data.values(3):print(v['types'])

['webp ', 'jpg']


A triple integration that need change of boundary

Question:
Evaluate Integral: (Without calculator, Just by hand)
$$\int_0^1\int_0^{1-x}\int_y^1\frac{\sin(\pi z)}{z(z-2)}\,dz\,dy\,dx$$

The answer of the problem uses a visualization of the boundary and change the order of integration such that $0\leq z\leq 1; ~~ 0\leq y\leq z ; ~~ 0\leq x\leq 1-y$ and changed the order to $dx\,dy\,dz$. And then it solves easily. I want to know is there any way to solve this change of boundaries without visualizing the shape? and by using only algebraic inequalities? How?

Note that I don't want to use this visualization. because sometimes for some planes that are not very well visualized, the answer gets a lot complicated. and I want a method to find a way to change order of integration. At least in problems involving intersection of planes and lines.
Answer: In my experience, changing the order of integration when the limits are variable is sometimes possible, but never intuitive. Plotting the region is one of those kinds of steps that I can't skip without getting something wrong, so I simply don't skip that step. Ever. It is, admittedly, even harder in 3D than in 2D, but I would still recommend plotting the region and visualizing each variable as functions of other variables. That may not be the answer you want to hear, but it's my answer. Naturally, if the limits are all constants, then it's much easier to change the order - your region is rectangular.
Comment: I would use traces to plot planes like those quickly: set variables equal to zero and see what happens with the rest of the equation.
Comment: I know that visualizing is the best way. But sometime plotting them is very difficult by hand for example for not very intuitive planes like $2x + 3y + 4z = 5$ , $x + y + 3z = 2$ , $-x+y+4z = 15$ (Just random numbers, Not sure what they actually make). And you must answer these question in only 15 minutes without any calculator or anything else.


Add output of loop to data frame within R

Question: I am looking to run tests on the speed it takes to perform database queries. I am looping a query X number of times and would like to store the sys.time calculated to execute from each query in a data frame. I have tested the loops and functions, which work, but when I attempt to store the calculated sys.time into the data frame is get the following error:
Error in `$<-.data.frame`(`*tmp*`, query_time, value = 0.359616041183472) : replacement has 1 row, data has 0

I am unsure of what my issue is, any help is appreciated. Below is the code I am using.
Empty data frame to store the query results
# Empty data frame to store query results
query_results <- data.frame(query_date = as.POSIXct(character()),
                query_type = character(),
                query_records = numeric(),
                query_time = as.POSIXct(character()))

Function to run database query
dbQueryTimes <- function(num_records){
  start_time <- Sys.time()
  fetch(dbSendQuery(con, "SELECT * FROM database_table"), n = num_records)
  end_time <- Sys.time()
  query_results$query_time <- end_time - start_time
}

Function to input number of iterations to run and number of records to return in query
funct_query_select_all <- function(num_iterations, num_records){
  for (i in 1:num_iterations) {
  dbQueryTimes(num_records)
}}

Running the query function
funct_query_select_all(5, 10000)

Comment: `query_results$query_time <- end_time - start_time` from inside a function is an anti-pattern to sound programming, imho. But it's also your bug. You are assigning a single `numeric` to an **empty** `POSIXt` column instead of trying to append it. I suggest you don't use this code you have here, instead use something like `bench::mark(dbSendQuery(...))` (or the `microbenchmark` package).
Comment: You are overwriting `xyz` each time in the `for` loop. Do you expect R to know you intend to append and do that instead?
Comment: Thank you, bench::mark works well, but I still have the same  issue, adding the results from a loop to a df.
for (i in 1:10) {
  xyz <- bench::mark(fetch(dbSendQuery(con, "SELECT * FROM PROD_DIA.GSC_REVENUE_HISTORY"), n = 1000))
}
Comment: I do not expect R to do anything other than run the code. What I am looking for is assistance from a community to help a non developer become better with coding in R, preferably in a useful way without any negativity
Comment: Okay Ryan. You are overwriting `xyz` each time, that does not seem like a useful thing to do. You can (1) assign to an index in a vector/list: `out <- list(); for (i in 1:10) out[[i]] <- bench::mark(..);`; or (2) use a more canonical R method, `out <- lapply(1:10, function(i) bench::mark(..))`. BTW, since you are repeating the same query, you might want to consider that the DBMS might recognize the query and use a pre-compiled version, in which case the first might be slower than the second and subsequent. It depends on the DBMS and the query (and tables).
Comment: Thank you for this info and the DBMS piece. I planned on running it once, but wanted the option to run it a few times to see if there was any variation based on internet loads, but something to take into consideration. Thanks again!
Answer: here is a minimal example that is something like what you're trying to do:
## empty dataframe to store results
query_results <- data.frame(query_date = as.POSIXct(character()),
                            query_type = character(),
                            query_records = numeric(),
                            query_time = as.POSIXct(character()))
## to make reproducible example
set.seed(4919)

## for 12 new "records"
for(i in 1:12){
  ## new results
  query_date <- Sys.Date()
  start_time <- Sys.time()
  query_type <- sample(LETTERS, size=1)
  query_records <- sample(0:99, size=1)
  end_time <- Sys.time()
  query_time <- end_time - start_time
  ## row bind results to existing dataframe
  query_results <- rbind(query_results,
                         data.frame(query_date, query_type,
                                    query_records, query_time))
}

output
   query_date query_type query_records        query_time
1  2021-03-22          P            44 3.838539e-05 secs
2  2021-03-22          A            55 2.694130e-05 secs
3  2021-03-22          J            79 3.147125e-05 secs
4  2021-03-22          D            84 2.264977e-05 secs
5  2021-03-22          U            38 2.312660e-05 secs
6  2021-03-22          K            13 2.384186e-05 secs
7  2021-03-22          T            72 2.527237e-05 secs
8  2021-03-22          M            55 2.479553e-05 secs
9  2021-03-22          N             9 2.527237e-05 secs
10 2021-03-22          X            64 2.598763e-05 secs
11 2021-03-22          B            91 2.574921e-05 secs
12 2021-03-22          Y            65 2.503395e-05 secs

there are likely more elegant ways to solve this problem, but the loop above makes a single row then rbinds that row to the existing dataframe. as pointed out in the comments, the way you added a single element in your example doesn't work.


C# - Alto consumo de memória ao chamar método

Question: Estou trabalhando com um Form principal e nele tem diversos Panels. Em um deles, o "panelGeral" eu utilizo para chamar as instâncias de novos formulários e mostrar nele utilizando o seguinte código da classe FormCall:
public void chamaFormulario(Form form)
{
        Form activeForm = frmMain.ActiveForm;
        foreach (Panel painel in activeForm.Controls )
        {
            if(painel.Name == "panelGeral")
            {
                painel.Controls.Clear();
                if(form != null)
                {
                    form.TopLevel = false;
                    painel.Controls.Add(form);
                    form.Show();
                }
            }
        }
}

Por exemplo, quando o programa abre eu chamo um Form de boas-vindas da seguinte maneira:
private void frmMain_Shown(object sender, EventArgs e)
    {
        frmInicio frm = new frmInicio();
        formCall = new FormCall();
        formCall.chamaFormulario(frm);
    }

Quando eu chamo o Form frmClientes e, ao abri-lo, ele possui um botão "Voltar" que tem o objetivo de voltar a tela de boas-vindas, que chama o seguinte método:
private void btVoltarClientes_Click(object sender, EventArgs e)
    {
        frmInicio frm = new frmInicio();
        FormCall form = new FormCall();
        form.chamaFormulario(frm);
    }

Mas observando o consumo de memória na ferramenta de diagnostico do VS2017 Community, o que estava consumindo 60MB sobre para 96MB, e caso eu abra novamente o form de clientes e aperte para voltar de novo, sobe para 136MB... E assim sucessivamente.
O que devo fazer para resolver este alto consumo memória?
Comment: Isto ocorre depois de você clicar no botão algumas vezes?
Comment: Maniero. Sim! Mas a solução do Rovann eu acho que resolveu o problema.
Answer: Tente ao remover os controles do painel (painel.Controls.Clear();) descartar os formulários:
painel.ControlRemoved += (ss, ee) => { ee.Control.Dispose(); };

Comment: Dei mais um porque soluciona o problema, mas isso é trágico, o ideal é rearquitetar pra não precisar mais fazer isso.
Comment: sim, você está colocando os formulários dentro do painel, e quando remove, eles ainda estão instânciados e em memória... o `Dispose` irá descartá-los
Comment: Nossa, meio que resolveu o problema. Agora ta consumindo por volta de 38~55MB, testei clicando e clicando varias vezes. Seria essa a solução mesmo hehe?
Comment: Obrigado Rovann. Deu certo e resolveu o problema


Naming audio plug-ins using JUCE framework

Question: I've been working on developing some audio plugins recently using the JUCE framework. I'm having an issue regarding naming the plugin. I've created separate projects for entirely different plugins. However when I load the plugin by starting Logic Pro X, I seem to only get the most recent plugin that I built, however, the plugin is always title as the very first plugin that I made. That is to say, It seems that when I make a new plugin, it takes on the name of my previous plugin and replaces it.
I've tried renaming the Plugin Code, but the AU validation tool recognizes the plugin as having the Plugin Code of the previous plugin.
Has anyone come across this problem or have any suggesting as to what might be causing it?
Additionally, I was using the WDL framework before using JUCE and had the same problem. This of course makes me think that the problem is not specific to JUCE or WDL.
Any input is appreciated, Thanks!
Comment: There's an audiounit cache you might try clearing: http://www.arturia.com/faq/utilization/how-do-i-clear-my-audio-unit-cache
Answer: Open the Introjucer with one of your projects and select the "Config" tab in the left panel. Then select your project at the top of the tree view.
In the right panel, you should see 2 fields called "Plugin Manufacturer Code" and "Plugin Code".
Your other project should have the same Plugin Manufacturer code, but a different Plugin Code to uniquely identify each plugin.


Improving one's calculation skills

Question: I am a first-year graduate student in mathematics. My undergraduate mathematics curriculum did not emphasize "calculating"; it was a theoretical curriculum in which even a traditional course in multivariable calculus was not "required" (a course in differential geometry sufficed).
I am training to be a "hands-on analyst", if that term makes any sense. For example, I know how to existence and uniqueness of solutions to PDE, but I haven't yet the "nose" to compute, to perform certain critical integration by parts, etc. I am starting to realize that theories are built on calculations and certain very interesting techniques in PDE--such as viscosity methods for example--arose from refining one's intuition while performing calculations. This is very inspiring for me and I want to learn to calculate!
Calculating has been an acquired taste for me, and as a "hands-on analyst", I would like to work in PDE and variational problems where one is interested in producing sharp bounds, etc. (this is vague, I know).
I am wondering if anyone can suggest any references/ workbooks where I can refine my "computation" skills. For example, I heard that the physicist Lev Landau gave his prospective students a preliminary test in integration. I suspect I will not pass such a test at this moment, but I would like to try to get myself to a stage where I can. Is there perhaps (a Russian?) text that emphasizes computation and serves as a good workbook for refining one's computation/calculation abilities.
Much thanks in advance!
Comment: You might find Schaum's 3,000 Solved Problems in Calculus a good review of calculus. It is mostly computational and the answers/explanations are given right after each problems.
Comment: I really like this question @user
Comment: Are you looking for applied books in PDE's, Numerical Methods and calculating in general? Regards
Comment: I think V.I. Arnold's Trivium (and it's follow-up) might be useful to you.
Answer: As suggested in the comments above: Schaum's 3,000 Solved Problems in Calculus seems to fit the bill! You can preview the table of contents and some sample pages at the link above.
Another such collection is entitled The Humongous Book of Calculus Problems by Michael Kelley, relatively inexpensive (as is the Schaum's book), and here, to, the link will take you to Amazon.com where you can preview the book.
Also Khan's Academy Calculus has great videos for review, and includes practice questions to work through.
In addition, you might want to check out Paul's Online Math Notes, click on the drop down menu for "class notes" and you'll find tutorials with practice problems for Calc I, II, and III.
Finally, this site: Math.SE, has loads of posted questions (many, many computational in nature) related to Calculus (and derivatives, integrals, etc), and most questions have one or more answers/hints to solutions. And if you find a problem somewhere that you can't seem to solve, your welcome to ask it here! (And you're welcome to use your refreshed, developing computational skills by answering questions, as well!)
Comment: +1 Reading Paul's Online Math Notes (and doing the exercises) was literally the way I learned multivariable calculus (Calc III).
Comment: @Jesse Madnick Did you solidify that knowledge with some other computational material apart from those notes? Also, what was your existing knowledge of the area like at that time?
Comment: @smokeypeat: Yes, after reading Paul's Math Notes, I read a multivariable calculus study guide book.  (I forget the title... maybe it was "How to Ace Multivariable Calculus" or something like that.) I had no prior knowledge of multivariable calculus other than single-variable calculus. These sources of self-study might not have been ideal -- they weren't rigorous textbooks -- but they helped build my intuition, and were good for a first pass at the subject.  I took an actual course in the subject about a year later.
Answer: Here's another perspective: Study some physics! Physics problems mostly deal with computing things and I can imagine you'd be able to pick up things very fast with a math background. And you won't be learning just calculations but you'll also be learning some very interesting things. If you pick up any book on Classical or Quantum Mechanics, or E&M, most involve interesting math and the problems involve lots of computations and tricks involved for those computations.
If you can do the problems in Stone and Goldbart's "Mathematics for Physics" book, I'd say your computation skills are pretty solid.
Answer: Polya & Szego "Problems and theorems in analysis", also translated to Russian.
These two volumes are full of problems that teach you to calculate, but it is also full of ideas and the extremely useful analytic folklore, which may be unknown to modern students. Everything is developed through series of problems, so it is a major undertaking to do the whole thing, but it is extremely rewarding.
The only bad thing about it is that its scope is mostly limited to 19th century single-variable function theory.
Answer: I'm in a similar position to you, insofar as I finished a math degree about 10 years ago, and I'm now preparing to switch careers and am preparing for professional exams.  I lost all my chops.
I've been using Calculus on the Web to strengthen those skills.  Temple University's math department uses it to automate homework, and it is open to the public.  It's pretty neat -- they break down problems into the essential steps in the first few problem sets on a topic, so you drill the procedure to do it right.
Also, I strongly suggest getting your hands on a flashcarding program like Anki and memorizing any derivatives or integrals (and any other computed values) you commonly see.  Being good at "hands on" analysis means being able to use experience and knowledge to solve problems quickly.  You can "fake" experience with knowledge. In short, you want the "common" facts at your fingertips, so you can get through problems using "slick" intuitive arguments based on "shortcuts".  (Compare to "elegance" in proofs)
Finally, do every solved problem you can get your hands on.

Improving one's calculation skills


How to implement a builder for a complex type?

Question: I have a very complex type. The type has multiple readonly properties and each property is a complex type:
public class FinalResult
{
    public ComplexType1 ComplexType1 {get;set;}

    public ComplexType2 ComplexType2 {get;set;}

    public ComplexType3 ComplexType3 {get;set;}

    public ComplexType4 ComplexType4 {get;set;}
}

Because ComplextTypeX is complex I have created a builder for each of them:
public class ComplexType1Builder
{
    public ComplexType1 Build(Dependency dep, OtherDependency otherDep)
    {
        // build / create the complex object

        return complexType1;
    }
}

public class ComplexType2Builder
{
    public ComplexType2 Build(Dependency dep, OtherDependency otherDep)
    {
        // build / create the complex object

        return complexType2;
    }
}

// same for ComplexType3 and ComplexType4

Finally I have FinalResultDirector which ties everything together:
public class FinalResultDirector
{

    private readonly ComplexType1Builder _builder1;
    private readonly ComplexType2Builder _builder2;
    private readonly ComplexType3Builder _builder3;
    private readonly ComplexType4Builder _builder4;

    public FinalResultDirector(
        ComplexType1Builder builder1,
        ComplexType2Builder builder2,
        ComplexType3Builder builder3,
        ComplexType4Builder builder4 )
    {
        _builder1 = builder1;
        _builder2 - builder2;
        _builder3 = builder3;
        _builder4 = builder4;
    }

    public FinalResult Build(Dependency dep, OtherDependency otherDep)
    {
        return new FinalResult
        {
            ComplexType1 => _builder1.Build(dep, otherDep),

            ComplexType2 => _builder2.Build(dep, otherDep),

            ComplexType3 => _builder3.Build(dep, otherDep),

            ComplexType4 => _builder4.Build(dep, otherDep),
        };
    }
}

This works, but my OO heart is crying. I know this can be solved much nicer, cleaner and more SOLID, but I haven't seen the solution.
I've tried using interfaces, but since each builder returns a different type, it doesn't have any additional value.
Another approach I've been thinking about is new up a FinalResult object and have each Build method accept this as a third parameter: public ComplexTypeX Build(Dependency dep, OtherDependency otherDep, FinalResult finalResult). And then return void. Now all the builders have the same method signature. The downside of this approach is that you get tempted to use properties on FinalResult that aren't set yet.
I'd love to hear how to solve this in a nice OO way.
Comment: Well, you've passing 4 builders with different types to director class, but assign them to 4 variables with the same type `ComplexType1Builder`. Why do you need 4 builders then? This line will not compile `_builder2 - builder2;` Did you try to build your sample at least? It can't be a real code, because it'll never run
Comment: If you have code that works but could be better (possibly not this code) [Code Review](https://codereview.stackexchange.com) is a better match. Do make sure you have actual working code before posting there, though.
Comment: Why do you need such complicated `FinalResult` class, with complex types inside? Have you thought about decoupling it? Does it always has all complex types all the time or it depends on some logic? Otherwise you may look at fluent builder
Comment: `FinalResult` won't compile, because properties must have a names, not the type only
Comment: Fixed the code. Yes, as far as I can see at the moment, I need al these complex types.
Comment: Properties setters still not accessible, all builders has the same `ComplexType1Builder` type. Please, post your actual code
Comment: This is a real representation of my code. I can't post the real code because it contains  confidential stuff.
Comment: You should assume builders need different dependencies as well as shared ones. It will help you thinking of a design that can accommodate such evolution.
Answer: You could use a single Builder class that builds all types. The general rule (to me) is that if you have lots of classes that each have only 1 method, then that is overdesigned and you should at least consider making fewer classes or even a single class with all those methods.
Now that we have one Builder class, it also becomes easier to try eliminating the FinalResultDirector class.
This + I added internal set; because you can't assign readonly properties except from the constructor or from an initializer inside the class.
Working code + dotnetfiddle:
using System;

public class Program
{
    public static void Main()
    {
        var director = new FinalResultDirector(new ComplexTypeBuilder());
        var result = director.Build(new Dependency(), new OtherDependency());

        Console.WriteLine(result);
    }
}

public class ComplexType1 {}
public class ComplexType2 {}
public class ComplexType3 {}
public class ComplexType4 {}

public class Dependency {}
public class OtherDependency{}

public class FinalResult
{
    public ComplexType1 ComplexType1 {get; internal set;}
    public ComplexType2 ComplexType2 {get; internal set;}
    public ComplexType3 ComplexType3 {get; internal set;}
    public ComplexType4 ComplexType4 {get; internal set;}
}

public class ComplexTypeBuilder
{
    public ComplexType1 Build1(Dependency dep, OtherDependency otherDep)
    {
        return new ComplexType1();
    }
    public ComplexType2 Build2(Dependency dep, OtherDependency otherDep)
    {
        return new ComplexType2();
    }
    public ComplexType3 Build3(Dependency dep, OtherDependency otherDep)
    {
        return new ComplexType3();
    }
    public ComplexType4 Build4(Dependency dep, OtherDependency otherDep)
    {
        return new ComplexType4();
    }
}

public class FinalResultDirector
{
    private readonly ComplexTypeBuilder _builder;

    public FinalResultDirector(ComplexTypeBuilder builder)
    {
        _builder = builder;
    }

    public FinalResult Build(Dependency dep, OtherDependency otherDep)
    {
        return new FinalResult
        {
            ComplexType1 = _builder.Build1(dep, otherDep),
            ComplexType2 = _builder.Build2(dep, otherDep),
            ComplexType3 = _builder.Build3(dep, otherDep),
            ComplexType4 = _builder.Build4(dep, otherDep)
        };
    }
}


How many cups of sugar do I need for these 5th grade problems?

Question: Problem 1a: If 4 glasses of a mixture needs 1 cup of sugar how many cups of sugar are needed for 5 glasses?
This one is easy and makes sense. It's just simply $\frac{1}{4}*5$ Now taking it a notch higher:
Problem 1b: If 4 glasses of a mixture needs 1 cup of sugar and 6 glasses need 2 cups, how cups of sugar are needed for 7 glasses?
Geometrically you can solve the problem by plotting a line between (4,1) and (6,2); calculate the slope/intercept and get the answer. But how can I do this (algebraically) from a 5th grader's perspective?
Problem 1c: (A variation) If 4 glasses need 1 cup sugar, 6 glasses need 2 and 8 glasses need 4 then how many cups of sugar do I need for 7 glasses?
Geometrically, you get a triangular region and there are two solutions to the problem! How could a 5th grader solve this variation algebraically? Geometrically it's easy, but since there are two answers, how can a 5th grader interpret the solution since there isn't a unique solution?
(Background: my nephew came to me with #2 and wasn't aware of slope/intercepts but was struggling with solving it using simple algebra. Maybe I'm overlooking something but it seems to be a bit tricky for a 5th grader. What are some good ways of approaching these sets of problems?)
Comment: Too much sugar and the kids will get hyperactive. You don't want that.
Comment: These are strange questions.  There isn't enough information to define a unique solution.  Why should we necessarily expect that the amount of sugar needed is modelled by a straight line, when for 1b that would mean we need no sugar for 2 glasses of mixture?
Comment: @TaraB - good point on zero cups for 2 glasses. Let's assume that the 'line passes through the origin' so you always have some sugar for some mixture. As for them being ill defined, that's the part I'm struggling with myself and hence the question :)
Answer: I'm not sure there is a good answer to 1b.  Probably the answer you give is the best available.  For a 5th grader, the last 2 glasses of water needed 1 cup, so one more glass will need 1/2 cup more for a total of 2 1/2.  For an algebra student you could fit a quadratic through (0,0), (4,1), and (6,2), which gives approximately (7,2.6264).
For 1c I would do the same and say 7 is halfway from 6 to 8, so I need halfway between 2 and 4 cups of sugar, getting 3.  But I'm not sure I believe that answer either.
Answer:
Problem 1b: If 4 glasses of a mixture needs 1 cup of sugar and 6 glasses need 2 cups, how cups of sugar are needed for 7 glasses?

One possible solution might be to argue that if 4 glasses of a mixture needs 1 cup of sugar, then $4 + 4 = 8$ glasses of mixture needs $1 + 1 = 2$ cups of sugar. And we know that $6$ glasses needs $2$ cups of sugar.
So $4 + 4 + 6 = 14$ glasses require $1 + 1 + 2 = 4$ cups of sugar. And so for $1/2(14) = 7$ glasses, we would then need $1/2(4) = 2$ cups of sugar.
But as noted, this question is too ill-defined (missing too much information) to arrive at a unique correct solution.
For example, the reasoning I used above would lead to two possible solutions to (c). The first would be, using the reasoning above, 2 cups of sugar. (Based on the information about 4 glasses and 6 glasses.  But one could argue similarly that $6 + 8 = 14$ glasses require $2 + 4 = 6$ cups sugar, which would seem to mean that $1/2(14) = 7$ glasses would require $1/2(6)$ = 3 cups of sugar.

Perhaps these questions are posed in order to challenge students to explore ways of approaching the problem, which may result in different solutions.  I've seed this pedagogical strategy before: more of a task in problem solving and understanding why one needs more information to arrive at one unique, correct solution, than a task of rote application of algebra manipulations. Certainly, at any rate, one could hardly expect 5th graders to have the sophistication and knowledge necessary to "fit a curve" other than that of a straight line.


Distributing an Android app outside Google Play and get it linked to it

Question: Suppose I have a wifi network with a walled garden that prevents users from accessing Internet unless an authentication procedure is performed via browser.
Suppose I have an application on Google Play that automates this process for inexperienced people. And suppose 95% of users are inexperienced and unwilling to perform SMS-OTP authentication on a site that is not optimized for mobile.
Scenario
A person asks a clerk how to connect to internet using Android. The clerk suggests the person to download the Android app, but the person responds he has no Internet access because he has no 3G data plan.
Possible workaround
The walled garden portal detects the device running Android by user agent and says: "Would you like to download an APK from our internal network without having to go to Google Play?". The user accepts, unlocks unknown sources and installs the app.
Question
In this scenario, if a user downloads an APK of a Google Play-available application, signed with same key, on his device, will the installed application be linked to Play and subject to updates? And I mean without using a Market linker app.
Comment: I think this question would work better if you deleted everything except the last two sentences. Focus specifically on the actual question; everything else is a distraction!
Comment: Why not allow access to Play for unauthorised users?
Comment: @alex because of a loooooooooooooooooooooooot of issues. Believe me, it's not an option. We may discuss them in chat but please not here :)
Comment: @GrahamBorland you are right but often people ask the OP details about the scenario, the context, or comment stupidly "why can't you just connect to Play?"
Answer: That's my old answer, don't read it, just skip to the edit portion:

Short answer is no!
I'm sure there're geeky ways around to link an app to its Google Play
  variant, but your scenario of non-geeky customers I reckon the best
  option is to program the network to allow Android mobile access
  (checking the user agent) to play.google.com (maybe even from the
  redirection website auto-launch the google play link direct to said
  app).

edit:
I'm thinking a bit more on this problem and I would like to change my answer to "I don't know" (what a horrible answer). But I would like to propose a test that you can do it yourself.
The reason I'm changing the answer is because I remember now apps like Titanium and they do link the app to the Play whenever restoring a backup. Of course, Titanium needs root, but that's because it's messing with other apps, not its own.
So in light of what I discusse I'll suggest you a simple test:

build an app, anything, Hello world!
Upload this app to Google Play and make it active
Wait a few hours for Google servers to make it available
Manually flash the same build version (with exact same signing key, etc) to a device.
Reboot the device (to be sure the system will read through installed applications and do communication with Google Play)
Go to Google Play on the device and check if it shows the app

It's possible that the app have the same package name and signed with the same key, the Google Play on the device itself will recognise it as the same and link it.
Comment: May the application link itself from code? Or does market linking require root which is not for that 95% of inexperienced?
Comment: I've changed my answer. Check it out.
Comment: I'd change the test a bit :) - Most importantly, after rebooting, publish an updated version to Play, just one that says "Hello world 2.0" and see if it updates automagically after a few hours!!!
Comment: so for a further change. Do both! Check if the original one is there. And then do the update and check for the updated. ;) And after the tests, let me know =]
Comment: no it wont update automatically but of course can do it manually without deleting the app as it has same signature -- wont do it automaticaly as you havent downloaded it from play and thus you havent checked the box update automatically


AttributeError: 'numpy.ndarray' object has no attribute 'assign_add'

Question: I'm trying to apply the attributes of an image to another image using Keras/Tensorflow and python but when I run my code I get the error shown above. The error comes specifically from:
x[..., 0].assign_add(103.939)
x[..., 1].assign_add(116.779)
x[..., 2].assign_add(123.68)

The rest of my code seems to work fine as it compiles, processes the images, etc, but at the end of the run, I get this error. Any help would be greatly appreciated.
Comment: Somehow your `keras` code has created `x` as a `numpy` array.  What is it supposed to be?
Answer: .assign_add is a tensorflow function, not a numpy function.
https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/assign_add?hl=gl
Can you try this?
tf.assign_add(x[..., 0],103.939)
Comment: I haven't imported tensorflow to my project so is there any way to do this through Keras? Because of this I get this error now: NameError: global name 'tf' is not defined
Comment: I am confused, ```add_assign``` is apparently a tensorflow function.


Função cálculo com cursor dinamico

Question: Eu estou tentando criar uma função de banco que ao receber um valor de parâmetro que contenha determinado valor ele crie um cursor com a tabela em específico.
Segue
DELIMITER $$

drop function if exists `fn_calculo_sla`;

CREATE FUNCTION `fn_calculo_sla`(
    `prm_id` int,
    `prm_entrada_registro` varchar(50)
)
RETURNS double
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
SQL SECURITY DEFINER
COMMENT ''
BEGIN

-- <inicio_declaracoes>

  -- declara variaveis de associação para usar no loop
  DECLARE var_id INT(11);
  DECLARE var_status INT(11);
  DECLARE var_data_acao DATE;
  DECLARE var_hora_acao TIME;

  -- declara variaveis de associação para utilizar para buscar o próximo registro com base no atual
  DECLARE var_id_next INT(11);
  DECLARE var_status_next INT(11);
  DECLARE var_data_acao_next DATE;
  DECLARE var_hora_acao_next TIME;

  -- declara variaveis de controle
  DECLARE done TINYINT(1) DEFAULT FALSE; -- para uso no CURSOR
  DECLARE tempo_trabalho DOUBLE DEFAULT 0;
  DECLARE tempo_livre DOUBLE DEFAULT 0; -- tempo livre ( exemplo: após horario de trabalho, finais de semana, feriados )

  DECLARE status_ocorrencia_nao_gera_sla  VARCHAR(200) DEFAULT '';
  DECLARE status_ocorrencia_fechada       VARCHAR(200) DEFAULT '';
  -- declara cursores

  IF(prm_entrada_registro = 'ocorrencia') THEN
      DECLARE dados_historico CURSOR FOR SELECT id, `status`, data_acao, hora_acao FROM ocorrencias_historico WHERE ocorrencia_id = prm_id order by data_acao, hora_acao;
  ELSEIF (prm_entrada_registro = 'tarefa') THEN
     DECLARE dados_historico CURSOR FOR SELECT id, `status`, data_acao, hora_acao FROM tarefas_historico WHERE tarefa_id = prm_id order by data_acao, hora_acao;
  END IF;

  -- outros
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; -- quando não tiver mais registros no CURSOR aberto a variavel 'done' recebe true

-- <fim_declaracoes>

  OPEN dados_historico; -- abre o CURSOR e seleciona os registros e associa

  select ifnull(encerra_ocorrencia,'') into status_ocorrencia_fechada
    from ( select group_concat( id ) as encerra_ocorrencia from status_ocorrencia where encerra_ocorrencia = 1) x limit 1;

  select ifnull(conta_tempo_sla,'') into status_ocorrencia_nao_gera_sla
    from ( select group_concat( id ) as conta_tempo_sla from status_ocorrencia where conta_tempo_sla = 0) x limit 1;

  FETCH dados_historico INTO var_id, var_status, var_data_acao, var_hora_acao; -- Associa a linha atual do registro nas variaveis, obedecer a ordem do SELECT

  read_loop: LOOP -- declara a região de LOOP para percorrer o cursor

     FETCH NEXT FROM dados_historico INTO var_id_next, var_status_next, var_data_acao_next, var_hora_acao_next;-- Associa a próxima linha do registro nas variaveis, obedecer a ordem do SELECT

     IF done THEN -- Verificar se ainda há registros na próxima posição

       IF ( FIND_IN_SET(var_status,status_ocorrencia_nao_gera_sla) = 0 AND FIND_IN_SET(var_status,status_ocorrencia_fechada) = 0 ) THEN

        set var_data_acao_next = CURDATE();
        set var_hora_acao_next = CURTIME();

        set tempo_trabalho = tempo_trabalho + TIMESTAMPDIFF(SECOND, CONCAT(var_data_acao,' ',var_hora_acao), CONCAT(var_data_acao_next,' ',var_hora_acao_next)); -- Calcula a diferença entre as duas datas

        set tempo_livre = tempo_livre + fn_calculo_tempo_livre(var_status,var_data_acao, var_hora_acao, var_data_acao_next, var_hora_acao_next, var_id);

       END IF;

        LEAVE read_loop; -- Sair do loop
     ELSE

        set tempo_trabalho = tempo_trabalho + TIMESTAMPDIFF(SECOND, CONCAT(var_data_acao,' ',var_hora_acao), CONCAT(var_data_acao_next,' ',var_hora_acao_next)); -- Calcula a diferença entre as duas datas

         set tempo_livre = tempo_livre + fn_calculo_tempo_livre(var_status, var_data_acao, var_hora_acao, var_data_acao_next, var_hora_acao_next, var_id);

     END IF;

     SET var_status    := var_status_next;
     SET var_data_acao := var_data_acao_next;
     SET var_hora_acao := var_hora_acao_next;
     set var_id          := var_id_next;

  END LOOP;

  CLOSE dados_historico;

  IF ( tempo_trabalho > 0 ) THEN
    SET tempo_trabalho = (tempo_trabalho - tempo_livre);
  END IF;

  RETURN tempo_trabalho;
END $$

DELIMITER ;

Gostaria que quando prm_entrada_registro for igual a ocorrencia busque a tabela ocorrencias_historico e caso prm_entrada_registro seja igual a tarefa busque da tabela tarefas_historico.
É possível?
Atualmente está gerando erro:

Erro SQL (1064) na estrutura #2: You have an error in your SQL syntax;
  check the manual that corresponds to your MySQL server version for the
  right syntax to use near 'DECLARE dados_historico CURSOR FOR SELECT
  id, status, data_acao, hora_acao FRO' at line 37
Answer: Até onde eu sei o MySQL tem algumas restrições com o DECLARE, Você não pode fazer DECLARE após algumas operações, sendo assim trabalhe dessa forma, Declare os 2 cursores e trabalhe com os IF's verificando onde usar o cursor 1 ou 2 no caso, algo assim:
DELIMITER $$

drop function if exists `fn_calculo_sla`;

CREATE FUNCTION `fn_calculo_sla`(
    `prm_id` int,
    `prm_entrada_registro` varchar(50)
)
RETURNS double
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
SQL SECURITY DEFINER
COMMENT ''
BEGIN

-- <inicio_declaracoes>

  -- declara variaveis de associação para usar no loop
  DECLARE var_id INT(11);
  DECLARE var_status INT(11);
  DECLARE var_data_acao DATE;
  DECLARE var_hora_acao TIME;

  -- declara variaveis de associação para utilizar para buscar o próximo registro com base no atual
  DECLARE var_id_next INT(11);
  DECLARE var_status_next INT(11);
  DECLARE var_data_acao_next DATE;
  DECLARE var_hora_acao_next TIME;

  -- declara variaveis de controle
  DECLARE done TINYINT(1) DEFAULT FALSE; -- para uso no CURSOR
  DECLARE tempo_trabalho DOUBLE DEFAULT 0;
  DECLARE tempo_livre DOUBLE DEFAULT 0; -- tempo livre ( exemplo: após horario de trabalho, finais de semana, feriados )

  DECLARE status_ocorrencia_nao_gera_sla  VARCHAR(200) DEFAULT '';
  DECLARE status_ocorrencia_fechada       VARCHAR(200) DEFAULT '';
  -- declara cursores

     DECLARE dados_historico1 CURSOR FOR SELECT id, `status`, data_acao, hora_acao FROM ocorrencias_historico WHERE ocorrencia_id = prm_id order by data_acao, hora_acao;

     DECLARE dados_historico2 CURSOR FOR SELECT id, `status`, data_acao, hora_acao FROM tarefas_historico WHERE tarefa_id = prm_id order by data_acao, hora_acao;

  -- outros
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; -- quando não tiver mais registros no CURSOR aberto a variavel 'done' recebe true

-- <fim_declaracoes>

  IF(prm_entrada_registro = 'ocorrencia') THEN
      OPEN dados_historico1;
  ELSEIF (prm_entrada_registro = 'tarefa') THEN
      OPEN dados_historico2;
  END IF; -- abre o CURSOR e seleciona os registros e associa

  select ifnull(encerra_ocorrencia,'') into status_ocorrencia_fechada
    from ( select group_concat( id ) as encerra_ocorrencia from status_ocorrencia where encerra_ocorrencia = 1) x limit 1;

  select ifnull(conta_tempo_sla,'') into status_ocorrencia_nao_gera_sla
    from ( select group_concat( id ) as conta_tempo_sla from status_ocorrencia where conta_tempo_sla = 0) x limit 1;

IF(prm_entrada_registro = 'ocorrencia') THEN
      FETCH dados_historico1 INTO var_id, var_status, var_data_acao, var_hora_acao; -- Associa a linha atual do registro nas variaveis, obedecer a ordem do SELECT
  ELSEIF (prm_entrada_registro = 'tarefa') THEN
      FETCH dados_historico2 INTO var_id, var_status, var_data_acao, var_hora_acao; -- Associa a linha atual do registro nas variaveis, obedecer a ordem do SELECT
  END IF;

  read_loop: LOOP -- declara a região de LOOP para percorrer o cursor

  IF(prm_entrada_registro = 'ocorrencia') THEN
      FETCH NEXT FROM dados_historico1 INTO var_id_next, var_status_next, var_data_acao_next, var_hora_acao_next;-- Associa a próxima linha do registro nas variaveis, obedecer a ordem do SELECT
  ELSEIF (prm_entrada_registro = 'tarefa') THEN
      FETCH NEXT FROM dados_historico2 INTO var_id_next, var_status_next, var_data_acao_next, var_hora_acao_next;-- Associa a próxima linha do registro nas variaveis, obedecer a ordem do SELECT
  END IF;

     IF done THEN -- Verificar se ainda há registros na próxima posição

       IF ( FIND_IN_SET(var_status,status_ocorrencia_nao_gera_sla) = 0 AND FIND_IN_SET(var_status,status_ocorrencia_fechada) = 0 ) THEN

        set var_data_acao_next = CURDATE();
        set var_hora_acao_next = CURTIME();

        set tempo_trabalho = tempo_trabalho + TIMESTAMPDIFF(SECOND, CONCAT(var_data_acao,' ',var_hora_acao), CONCAT(var_data_acao_next,' ',var_hora_acao_next)); -- Calcula a diferença entre as duas datas

        set tempo_livre = tempo_livre + fn_calculo_tempo_livre(var_status,var_data_acao, var_hora_acao, var_data_acao_next, var_hora_acao_next, var_id);

       END IF;

        LEAVE read_loop; -- Sair do loop
     ELSE

        set tempo_trabalho = tempo_trabalho + TIMESTAMPDIFF(SECOND, CONCAT(var_data_acao,' ',var_hora_acao), CONCAT(var_data_acao_next,' ',var_hora_acao_next)); -- Calcula a diferença entre as duas datas

         set tempo_livre = tempo_livre + fn_calculo_tempo_livre(var_status, var_data_acao, var_hora_acao, var_data_acao_next, var_hora_acao_next, var_id);

     END IF;

     SET var_status    := var_status_next;
     SET var_data_acao := var_data_acao_next;
     SET var_hora_acao := var_hora_acao_next;
     set var_id          := var_id_next;

  END LOOP;

  IF(prm_entrada_registro = 'ocorrencia') THEN
      CLOSE dados_historico1;
  ELSEIF (prm_entrada_registro = 'tarefa') THEN
      CLOSE dados_historico2;
  END IF;

  IF ( tempo_trabalho > 0 ) THEN
    SET tempo_trabalho = (tempo_trabalho - tempo_livre);
  END IF;

  RETURN tempo_trabalho;
END $$

DELIMITER ;

Comment: Funcionou! Saberia me dizer, se eu deixo um dos cursores fechado, ele ocupa algum espaço ou processamento?
Comment: Não sei, mas acredito que a partir do momento que você não chega a abrir e percorrer ele, ele não deve prejudicar em performance. Tem que dar uma pesquisada mais a fundo

Função cálculo com cursor dinamico


Distinct Append in Select

Question:
How will i distinct the value of select when i append. see the sample output below

 $(document).ready(function(){
    $("#example2").on('click',"tr#paymentedit", "click", function(data){

        var valuetoedit = new Option(($(this).find('td:eq(2)').html()), "value");
    valuetoedit.selected=true;
    $("#paymenttypeedit").append(valuetoedit);
        });
    });

Comment: Why are you allowing users to enter free form payment types at all?
Comment: its a edit payment once i click the tr it will copy the value and change it freely
Answer: Test each option to see if one exists that has a value that compares similarly and perhaps replace the value entered with the existing one (or visa versa)
You probably want to avoid using the text/label of an option as the value.  if you don't decide to do that there's no point to setting all the values to "value"  (Use valuetoedit = new Option(($(this).find('td:eq(2)').html())); instead)

function foo() {
 var valuetoedit = $('#foo').val();
 var uniq = true;
 var options = $("#paymenttypeedit option");
 for(var i=0; uniq && i < options.length; i++) {
     if (valuetoedit.toUpperCase() === options[i].text.toUpperCase()) {
         uniq = false;
         valuetoedit = this.text; // use the existing value
     }
 }
 if (uniq) {
     $("#paymenttypeedit").append(new Option(valuetoedit, null, false, true));
 }
}

function init() {
 $('#but').on('click', foo);
}

$(document).ready(init);

<select id="paymenttypeedit"></select>
<input id="foo" type="text">
<button id="but"> </button>
Comment: $(document).ready(function(){
$("#example2").one('click',"tr#paymentedit", "click", function(data){

var uniq = true;
var options = $("#paymenttypeedit option");
for(var i=0; uniq && i < options.length; i++) {
    if (valuetoedit.toUpperCase() === options[i].value.toUpperCase()) {
        uniq = false;
        valuetoedit = this.value; // use the existing value
    }
}
if (uniq) {
var valuetoedit = new Option(($(this).find('td:eq(2)').html()), "value");
valuetoedit.selected=true;
$("#paymenttypeedit").append(valuetoedit);
}

    });
});
Comment: Yeah, I didn't see you were setting all the `value` properties to "value".  I'm modified the code to use `text` instead
Comment: valuetoedit = new Option(($(this).find('td:eq(2)').html()));
var uniq = true;
var options = $("#paymenttypeedit option");
for(var i=0; uniq && i < options.length; i++) {
    if (valuetoedit.toUpperCase() === options[i].text.toUpperCase()) {
        uniq = false;
        valuetoedit = this.text; // use the existing value
    }
}
if (uniq) {
     var valuetoedit = new Option(($(this).find('td:eq(2)').html()), "value");
valuetoedit.selected=true;
$("#paymenttypeedit").append(valuetoedit);
}
Comment: Not sure what you're doing.  I've done a snippet that works
Comment: im clicking in TR and getting the value of td
Comment: @ShermaineChaingan I have no idea what that means.  You didn't put any HTML in your question and only a tiny piece of JS, so it's really hard to know what exactly you're doing.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/123194/discussion-between-shermaine-chaingan-and-tibrogargan).

Distinct Append in Select


How do I get jquery tablesorter to sort like sql server/entity?

Question: So I using custom parser to try and get tablesorter to sort like sql server.  The data I am returning from entity call can be max 50 characters (varchar(50)).
Here is my parser code:
$.tablesorter.addParser({
    // set a unique id
    id: 'entitySort',
    is: function (s) {
        // return false so this parser is not auto detected
        return false;
    },
    format: function (s) {
        // format your data for normalization

        // remove any special characters that are not alphabet or number
        return s.toLowerCase().replace(/[^a-z0-9]/g, '');
    },
    // set type, either numeric or text
    type: 'text'
});
$('#headerTable').tablesorter({
    headers: {
        0: { sorter: 'entitySort' }
    },
    widthFixed: false,
    widgets: ["stickyHeaders"],
    widgetOptions: {
        // css class name applied to the sticky header
        stickyHeaders: "tablesorter-stickyHeader",
        stickyHeaders_addResizeEvent: true
    }
});

Here is a sample of the data that is returned via entity call:
1190001676346NB
1910-AM
309AMXG_QP
309CMXG_533: LA-C130/AS057-2222
523:2.9
523PAA2.15
526PAH2.33/ROTOR-76696A
AMXG-QP

First thing I did was remove all special characters on the data thinking that would help to sort:
1190001676346NB
1910AM
309AMXGQP
309CMXG533LAC130AS0572222
52329
523PAA215
526PAH233ROTOR76696A
AMXGQP

However the tablesorter always wants to sort by number size first on text or numeric
309AMXGQP
309CMXG533LAC130AS0572222
523PAA215
526PAH233ROTOR76696A
1910AM
52329
1190001676346NB
AMXGQP

I tried padding the end of the strings with '0' to get them all the same length. I tried changing type of sort to numeric, alphanumeric and nothing is working to sort the same as sql server.  I realize the data is intensive to sort.  I am desperate for help!
Comment: I think if you want to emulate SQL Server sorting you're going to be in for a ride. Have you considered server side sorting?
Comment: Using an API to pull large amounts of data to client side.  Sorting server side defeats the purpose unfortunately.
Answer: You can use the textSorter option to change the way a column is sorted. Here is an example:
$('table').tablesorter({
    theme: 'blue',
    // custom text sorter
    textSorter: {
        // text sorter for the first column only
        0 : function(a, b){
            return a > b ? 1 : (a < b ? -1 : 0);
        }
    }
});

Comment: Mottie, can I run that textSorter option inside my "parser" after replacing special characters? Or will it handle special characters? Dont you have your own version of tablesorter? Should I be using that? Apologize for late response, apparently work decided I no longer need access to stackoverflow.
Comment: The parser is just that, it parses data, no sorting. The original tablesorter doesn't have an alphanumeric sorter, so you shouldn't need to define the textSorter (it's not an option in the original anyway).


Real Analysis: density of rationals and reals

Question: My textbook in real analysis proves that the rationals are dense in the reals by using first the archemidean principle and then constructing a fairly long and contrived proof.
What I am wondering is, is that could you not first show that the sum of two rationals divided by a rational is a rational number (the sum can be done by contradiction, and ditto for the product of two rationals), and then just point out that the arithmetic average of any two nonequal rational numbers is gaurenteed to be in between them? Proving that step should be straightforward, assume wlog xx
y+x>2x
(x+y)/2>x
And then this is similar if x and y are in general real, provided that one uses the axiom that addition and division is a closed operation.
Can someone point out why this is no rigorous if it isn't? Pardon the lack of latex... Still learning it! Cheers :)
Comment: The midpoint of two reals may not be rational.
Comment: Very true. Thanks
Answer: It is easy to prove that between two rationals there is a rational (your argument is correct) and that between two reals there is a real. But how do you deduce from that that between two reals there is always a rational number, which is the statement that you want to prove here?
Comment: @SeanThrasher If my answer was helpful, perhaps that you could mark it as the accepted answer.
Comment: Did that. Fairly new to this site sorry
Comment: @SeanThrasher I know how that is. After my first technical question here got an answer, it took me weaks until I marked it as the accepted one.
Comment: I am glad you told me. Got to give credit where credit is due!
Answer: You can do that if you know about decimal representations (yes, you know, but it looks like you are there building reals from the axioms).
If you were to define rationals as periodic decimals and irrationals as non-peridic, then you would have, for irrational $\alpha=a_0.a_1a_2...a_n...$, the rational $a_0.a_1a_2,...a_n999....$ is $> \alpha$ but $< \alpha +1=(a_0+1).a_1a_2...a_n...$ (you should take into account here that two different decimal representations can represent same number and avoid that).
With decimals, you can easily prove that between two rationals there is a rational and irrational and that between two irrationals there is a rational and irrational.


Django server not displaying the database information in the html template

Question: I am trying to do an ecommerce and when creating the database it does not update in the checkout.html. page. Below the code.
views.py
def cart(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer = customer, complete = False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total':0, 'get_cart_items':0}
    context = {'items':items, 'order':order}
    return render(request, 'store/cart.html', context)

def checkout(request):
if request.user.is_authenticated:
    customer = request.user.customer
    order, created = Order.objects.get_or_create(customer = customer, complete = False)
    items = order.orderitem_set.all()
else:
    items = []
    order = {'get_cart_total':0, 'get_cart_items':0}
context = {}
return render(request, 'store/checkout.html', context)

checkout.html
                {% for item in items %}

{{item.product.name}}

${{item.product.price|floatformat:2}}

x{{item.quantity}}

            {% endfor %}

it works for cart.html but it does not work for checkout.html and there is no errors shown to look for. Any help will be appreciated.
Answer: The context is empty. The context is a dictionary where the names of the variables used in the template map to the corresponding values.
If you thus want to pass items to the template, you write:
def checkout(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer = customer, complete = False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total':0, 'get_cart_items':0}
    # pass  items ↓    pass order ↓
    context = {'items': items, 'order': order }
    return render(request, 'store/checkout.html', context)
Here the items will be an empty queryset, since you take the orderitem_set of the order, but at that point you did not create an OrderItem objects that are linked to that Order, you thus likely should first create OrderItems for the created order.


New measures to prevent spam in comments of nodes?

Question: I have a website with a node and comments which are moderated. I have installed Cache module, Image captcha (light distorsion). There was no spam till a few months ago. I installed Honeypot module and the few messages (probably automated) stopped being entered into the moderation list.
This week the site suffered a massive amount of flood spam. This coincides with the attack which is explained in Drupal.org. Is it possible that the attackers have learned how to override Honeypot and Image Captcha countermeasures?
How can I improve the security so the spam is reduced? My client will not allow more than a very small human input to delete a few spam messages.
Answer: Maybe this module will help you: BOTCHA
There are more protection methods than just honeypot.
Answer: The Anti Spam by CleanTalk module might be another anti-spam module that could fit in your case. Some more details from its project page:

Invisible antispam without CAPTCHA, questions, puzzles, counting animals, math and etc. Just install and forget.
CleanTalk is a SaaS spam protection service for Web-sites.
CleanTalk uses protection methods which are invisible for site visitors.
Using CleanTalk eliminates needs in CAPTCHA, questions and answers, and other methods of protection, complicating the exchange of information on the site.

Optionally you may also want to look at the Comment Trust module. Here are some details about it (from its project page):

... auto-approves comments by users with previously-approved comments. It rewards trusted commenters with immediate approvals, while requiring you to approve the comments by new visitors. Works for both anonymous and authenticated users.
You can configure the threshold of approved comments an email address has to first achieve before gaining auto-approval. You can also provide a list of email addresses (or patterns of email addresses) to always exclude from auto-approval.


Use Windows Terminal in place of cmd when a command line exe is executed

Question: I have a couple command line apps (launch4j + java.exe) I use.
I'd like to run them on Windows Terminal instead of cmd.exe. But, even after installing Windows Terminal, when I execute the launch4j exe, it still runs on cmd.exe.
If I run wt myapp.exe -oneinput it works, but I'd like to run myapp.exe directly.
Is there any setting I must do so that Windows Terminal is used in place of cmd.exe?
Comment: See [this (negative) answer](https://superuser.com/a/1557629) on SU, where the question would fit better, anyway.
Comment: Tnx, I searched for it and was unable to find, then I found the https://stackoverflow.com/questions/tagged/windows-terminal tag. Very sad that it's not possible. I wish launch4j would have that option :D
Comment: Bookmark [Change Windows OS to support default terminal \[defterm\] #492](https://github.com/microsoft/terminal/issues/492) and keep fingers crossed ;-)
Answer: The Windows Terminal team are working to enable Windows Terminal to become the default command-line user experience on Windows.
Stay tuned to the Windows CommandLine Blog for news and updates on up-coming features.