text:
Q: java.lang.illegalargumentexception - thrown by HttpURLConnection getHeaderFieldKey() method, host = null I'm trying to build a simple linkchecker application. I extract all href attributes from a webpage, and output to a file. I then check what I have parsed against a regex to check for valid URLs, and output the valid URLs to another file. I then visit those URLs and output any broken links to a third file.
In the abridged code below, it is assumed that the hrefs have already been extracted and listed in page_contents.txt. I provide the content for that text file here:
http://computing.dcu.ie/~humphrys/
http://computing.dcu.ie/~humphrys/
http://computing.dcu.ie/~humphrys/blog.html
http://computing.dcu.ie/~humphrys/teaching.html
http://computing.dcu.ie/~humphrys/research.html
http://computing.dcu.ie/~humphrys/contact.html
http://computing.dcu.ie/~humphrys/
http://computing.dcu.ie/~humphrys/ca249/
http://computing.dcu.ie/~humphrys/ca318/
http://computing.dcu.ie/~humphrys/ca425/
http://computing.dcu.ie/~humphrys/ca651/
http://w2mind.computing.dcu.ie/
http://w2mind.org/
index.html
computers.internet.html
#world
#ireland
#uk
#multimedia
#internet
http://www.pressreader.com/
http://www.pressdisplay.com/
http://www.newspaperdirect.com/
http://www.newseum.org/todaysfrontpages/
http://news.google.com/
http://news.google.com/news?ned=uk
http://news.google.com/news?ned=en_ie
http://www.google.com/alerts
http://en.wikinews.org/
http://news.yahoo.com/
http://uk.news.yahoo.com/
http://www.apimages.com/
http://en.wikipedia.org/wiki/Next_Media_Animation
http://www.youtube.com/user/NMAWorldEdition
http://www.youtube.com/user/NMANews
http://www.time.com/
http://www.newsweek.com/
http://www.economist.com/
http://www.salon.com/
http://www.tnr.com/
http://thenewrepublic.com/
http://www.nytimes.com/
http://www.nypost.com/
http://www.washingtonpost.com/
http://www.latimes.com/
http://www.wsj.com/
http://www.jpost.com/
http://www.smh.com.au/
http://www.theonion.com/
http://www.theonion.com/content/video
http://www.youtube.com/user/TheOnion
http://www.theonion.com/content/radionews
http://www.thedailymash.co.uk/
http://themire.net/
http://waterfordwhispersnews.com/
http://www.evilgerald.com/
http://www.langerland.com/
http://www.portadownnews.com/
http://www.portadownnews.com/archive.htm
http://www.irishurls.com/
http://www.irishtimes.com/
http://www.irish-times.com/
http://www.ireland.com/
http://notices.irishtimes.com/
http://www.irishtimes.com/search/
http://www.independent.ie/
http://www.unison.ie/irish_independent/
http://www.independent.ie/search/index.jsp
http://www.announcement.ie/
http://www.iannounce.co.uk/Republic-of-Ireland/52
http://www.sbpost.ie/
http://www.thepost.ie/
http://archives.tcm.ie/businesspost/
http://en.wikipedia.org/wiki/Sunday_Tribune
http://www.irishexaminer.com/
http://www.examiner.ie/
http://www.magill.ie/
http://www.villagemagazine.ie/
http://www.phoenix-magazine.com/
http://www.hotpress.com/
http://www.emigrant.ie/
http://groups.google.com/groups/dir?sel=gtype%3D0%2Cusenet%3Die&
http://www.listenlive.eu/ireland.html
http://www.rte.ie/
http://www.rte.ie/player/
http://www.rte.ie/tv/
http://www.rte.ie/news/
http://www.rte.ie/aertel/170-01.html
http://www.rte.ie/radio/
http://www.rte.ie/radio1/
http://www.rte.ie/smiltest/radio_new.smil
http://www.rte.ie/lyricfm/
http://dynamic.rte.ie/av/live/radio/lyric.smil
http://www.rte.ie/aertel/184-01.html
http://www.tv3.ie/
http://www.tg4.ie/
http://www.tnag.ie/
http://www.rte.ie/aertel/
http://www.rte.ie/aertel/103-01.html
http://www.irishtimes.com/weather/
http://www.rte.ie/weather/
http://dir.yahoo.com/Regional/Countries/United_Kingdom/News_and_Media/
http://www.thetimes.co.uk/
http://www.the-times.co.uk/
http://www.timesonline.co.uk/
http://en.wikipedia.org/wiki/The_Times
http://www.thesundaytimes.co.uk/
http://www.sunday-times.co.uk/
http://archive.timesonline.co.uk/tol/archive/
http://www.thetimes.co.uk/tto/archive/
http://www.newsint-archive.co.uk/
http://www.newstext.com.au/
http://www.telegraph.co.uk/
http://www.independent.co.uk/
http://www.guardian.co.uk/
http://en.wikipedia.org/wiki/The_Guardian
http://www.observer.co.uk/
http://observer.guardian.co.uk/
http://archive.guardian.co.uk/
http://browse.guardian.co.uk/
http://www.guardian.co.uk/Archive/
http://users.guardian.co.uk/help/search/
http://www.spectator.co.uk/
http://www.private-eye.co.uk/
http://www.newstatesman.co.uk/

I have run the program using several different pages with no problem, but with one particular page I have the following error message:
Exception in thread "main" java.lang.IllegalArgumentException: protocol = http host = null
    at sun.net.spi.DefaultProxySelector.select(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.followRedirect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getHeaderFieldKey(Unknown Source)
    at test2.main(test2.java:77)

The error is at this line of the code
String name = http.getHeaderFieldKey(i);

Responses to previous questions around this topic suggest that the problem is that the program is reading a url's host as null. I have no idea why this may be the case (assuming that host being null is the root of the problem?). It appears that the url causing the issue is http://www.newstatesman.co.uk/ which appears to be well-formed and no different to any of the many other urls which are processed correctly by the program.
This is more or less my first question so any constructive comments on the problem or my question formulation are welcomed.
import javax.swing.text.html.*;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.BadLocationException;
import java.net.*;
import java.io.*;
import java.util.regex.*;

class test2
{
    public static void main (String args[]) throws Exception
    {
        String fileOut2 = System.getProperty("user.dir") + File.separator + "page_contents.txt";
        String fileURLOut = System.getProperty("user.dir") + File.separator + "urls.txt";
        String brokenLinks = System.getProperty("user.dir") + File.separator + "broken2.html";

        BufferedReader URLIn = new BufferedReader(new FileReader(fileOut2));
        PrintWriter URLOut = new PrintWriter(new FileWriter(fileURLOut));
        PrintWriter brokenOut = new PrintWriter(new FileWriter(brokenLinks));

        try
        {

            String urlPattern = "((https?|ftp|gopher|telnet):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";

            String x;

            while ((x = URLIn.readLine()) != null)
            {
                System.out.println("Entered while loop!");
                Pattern p =     Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);

                Matcher m = p.matcher(x);

                if (m.find())
                {
                    URLOut.println(x.substring(m.start(0),m.end(0)));

                    URL url = new URL(x.substring(m.start(0),m.end(0)));
                    HttpURLConnection http = (HttpURLConnection)url.openConnection();
                    http.setConnectTimeout(5000);
                    for (int i=0; ; i++)
                    {
                        String name = http.getHeaderFieldKey(i);
                        String value = http.getHeaderField(i);

                        if (name == null && value == null)     // end of headers
                        {
                            break;
                        }

                        if (name == null)     // first line of headers
                        {
                            if(!value.substring(9, 12).equals("200"))
                            {
                                brokenOut.println("
" + url + "" + " " + value.substring(9, 12) + "
");
                            }
                        }
                        else
                        {
                            System.out.println(name + "=" + value + "!!!!!!");
                        }
                    }
                }
            }

        } catch (MalformedURLException e)
        {
            System.out.println("Malformed URL!!!!!");
        } catch (IOException e)
        {
            throw new RuntimeException("IO Exception!!!!!", e);
        } finally
        {
            if (URLIn != null)
            {
                URLIn.close();
            }
            if (URLOut != null)
            {
                URLOut.close();
            }
            if (brokenOut != null)
            {
                brokenOut.close();
            }
        }
    }
}

A: You want to deal with Exception in the loop, it gives you some chance to recover from bad url.


text:
Q: Boost equivalent of std::async() Without using boost::thread and boost::bind directly, is there a way to implement the equivalent of the following code?
std::string func()
{
    std::string str("Hello from async task!");
    return str;
}

int main()
{
    auto ftr = std::async(&func);
    std::cout << "Hello from main!";
    std::string str = ftr.get();
    std::cout << str << std::endl;
    return 0;
}

Specifically, this part: auto ftr = std::async(&func); ?

A: Certainly. Simply make async<T>(std::function<T()>) return a future which invokes func() the moment it's first waited-for. You won't get any asynchronicity, but the API doesn't actually guarantee that the function will run asynchronously, so that's not a problem.
If you have access to an OS-specific threading library, you could of course use that as well.
Note, however, that storing exceptions cannot be implemented portably; it requires additional support from the C++ implementation, unless you can restrict the exceptions supported to ones with a polymorphic clone function. See this question for more information.
The final implementation might look a bit like this (untested):
// NOTE - we assume a SINGLE THREADED environment

template<typename T>
class myfuture_detail {
    mutable boost::variant<T, boost::function<T()> > val;

public:
    myfuture_detail(const boost::function<T()> &f)
        : val(f) { }

    const T &get() const {
        if (T *t = boost::get<T>(&val)) {
            return *t;
        } else {
            boost::function<T()> f = *boost::get<boost::function<T> >(&val);
            val = f();

            T *t = boost::get<T>(&val);
            assert(t);

            return *t;
        }
    }
};

template<typename T>
class myfuture {
    boost::shared_ptr<myfuture_detail<T> > ptr;

public:
    myfuture(const boost::function<T()> &f)
        : ptr(boost::make_shared<myfuture_detail<T> >(f))
    {}

    myfuture() { }

    const T &get() const {
        return ptr->get();
    }
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: What do negative & positive accelerations stand for exactly ? ( iOS ) Please excuse me in advance if I should be asking this in a Physics forum, but given that I'm talking about the iPhone's acceleration, coming from the accelerometer, I decided to post it here.
Whenever I push the iPhone (device lying on the table - screen facing upwards) forward (towards the top of the device), the accelerometer seems to be recording negative acceleration for the most part, with a few positive acceleration values, on that same Y-axis, appearing here and there from time to time.
This is a sample of the acceleration values on the Y-axis, during such a forward movement across the Y-axis :
-0.02
-0.03
-0.04
-0.03
-0.04
-0.04
-0.07
-0.02
-0.02
-0.02
-0.02
 0.00 // what's happening here ?
 0.02 // what's happening here ?
 0.02 // what's happening here ?
-0.00
-0.02
-0.03
-0.03
 0.02 // what's happening here ?
 0.04 // what's happening here ?
 0.01 // what's happening here ?
-0.00
-0.04
-0.03
-0.02
-0.03
-0.05

What do the negative acceleration values stand for and what do the positive ones stand for in the above example ?
If I understand correctly, negative acceleration values mean the device is accelerating forward at that point.
Now, positive acceleration values would mean the device is moving backwards, while 0.00 acceleration would mean the device is either standing still* or moving at a constant speed.
So why do I get those positive acceleration values during that forward movement of the device?
Am I missing something ?
The only reason I'm asking, obviously, is because I want to create a method in order to know whether the device is moving forward or backwards on the Y-axis.
*I also noticed a 0.01 value comes and goes even when the device is completely immobile, but I'm guessing this is just noise, right?

A:
So why do I get those positive acceleration values during that forward movement of the device?

Ehm, you seem to be understanding that an acceleration of 0 means no acceleration, i. e. being still or moving at a constant speed. Now if you move the phone at a seemingly constant speed in one direction, it might not be perfectly constant - both small positive and negative accelerations may occur.

*I also noticed a 0.01 value comes and goes even when the device is completely immobile, but I'm guessing this is just "noise" right?

Right. The accelerometer sensor is not perfect. It reacts to many other factors than just pure acceleration. I'm not aware of the exact internals of how the iPhone's accelerometer works, but if I guess right, it's a piezoelectric one, so it can be sensitive to other kind of physical (mechanical and electromagnetic) effects.


text:
Q: change button text winapi I'm new to WINAPI programming. I want to make a simple tic-tac-toe game on windows forms, but i have a problem when i want to change button text. My code compiles, but that SendMessage function just don't work. My code :
#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>

#define __T(x) L ## x

#define BUTTON_1x1 1
#define BUTTON_1x2 2
#define BUTTON_1x3 3

#define BUTTON_2x1 4
#define BUTTON_2x2 5
#define BUTTON_2x3 6

#define BUTTON_3x1 7
#define BUTTON_3x2 8
#define BUTTON_3x3 9

HWND hWnd;
HWND _3x3;
HWND _3x2;
HWND _3x1;
HWND _2x3;
HWND _2x2;
HWND _2x1;
HWND _1x3;
HWND _1x2;
HWND _1x1;

LRESULT CALLBACK WindowProc(HWND hWnd,
                     UINT message,
                     WPARAM wParam,
                     LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance,
               HINSTANCE hPrevInstance,
               LPSTR lpCmdLine,
               int nCmdShow)
{
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));

wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = "WindowClass1";

RegisterClassEx(&wc);
hWnd = CreateWindowExW(NULL,
                      L"WindowClass1",    // name of the window class
                      L"Desas",   // title of the window
                      WS_OVERLAPPEDWINDOW,    // window style
                      300,    // x-position of the window
                      300,    // y-position of the window
                      380,    // width of the window
                      480,    // height of the window
                      NULL,    // we have no parent window, NULL
                      NULL,    // we aren't using menus, NULL
                      hInstance,    // application handle
                      NULL);    // used with multiple windows, NULL
ShowWindow(hWnd, nCmdShow);
MSG msg;

while(GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
return msg.wParam;
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
    case WM_CREATE:
        {
            HWND _1x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "21",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x1,
                                        NULL,
                                        NULL);

            HWND _1x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "32",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x2,
                                        NULL,
                                        NULL);
            HWND _1x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x3,
                                        NULL,
                                        NULL);

            HWND _2x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "32",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x1,
                                        NULL,
                                        NULL);
            HWND _2x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x2,
                                        NULL,
                                        NULL);

            HWND _2x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "23",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x3,
                                        NULL,
                                        NULL);

            HWND _3x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x1,
                                        NULL,
                                        NULL);

            HWND _3x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "33",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x2,
                                        NULL,
                                        NULL);

            HWND _3x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x3,
                                        NULL,
                                        NULL);

            HWND _PLAYER_TXT = CreateWindowEx(NULL,
                                        "STATIC",
                                        "PLAYER :",
                                        WS_VISIBLE | WS_CHILD | SS_LEFT,
                                        230, 50, 100, 30,
                                        hWnd,
                                        (HMENU) 999,
                                        NULL,
                                        NULL);
        } break;

        case WM_COMMAND:
        {
                if (LOWORD(wParam) == BUTTON_3x3)
            {
                std::cout << "!!!!!" << std::endl; //test(if buttonclick message is  recived)

                SendMessage(_3x3, WM_SETTEXT, 0, (LPARAM) _T("NewText")); //not working
            }
        } break;

    case WM_DESTROY:
        {
            PostQuitMessage(0);
            return 0;
        } break;
}
return DefWindowProc (hWnd, message, wParam, lParam);
}

Sorry for this bunch of code. I would make it shorter, if I knew which part is important. Sorry for my bad english. Thank you.

A: Your line
HWND _3x3 = CreateWindowEx...

shadows the global. If you debugged the program, you would have noticed that _3x3 was NULL when you tried to send the message.

A: try this:
case WM_COMMAND:
{
   if(LOWORD(wParam) == BUTTON_3x3)
   {
         _3x3 = NULL;
         _3x3 = CreateWindowEx(0,
                                         WC_BUTTON,
                                        "Text",230, 300, 100, 100,
                                         hwnd,
                                        (HMENU)BUTTON_3x3,
                                         NULL, NULL);
   }
}
      break;

A: I thing your window is ANSI, but you compiled your project as UNICODE. (Using TCHAR.h)

A: You have to call DefWindowProc to handle any other message, like WM_SETTEXT and others. You can simply put it in the default case of the switch you already have in your WindowProc.


text:
Q: Change border color on legend in Chart.js I would like to remove or change the color of my border on the legend fields.
Today, there is a grey border but I can't change the color, I would like it to be like the color of the box.
I have tried to add a borderWidth in legend without success.
I managed to change the border color in the graph but I can't do it in the legend.
This my Chart code:
    var chart = document.getElementById("chart-out-rating");
    var myChart = new Chart(chart, {
      type: 'bar',
      data: {
        labels: datasetPrimeurPrice.year,
        datasets: [{
          label: 'Prix HT',
          data: datasetPrimeurPrice.outingPrice,
          backgroundColor: [
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)',
            'rgba(255, 166, 48, 0.3)'
          ],
          borderColor: [
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)',
            'rgba(255, 166, 48)'
          ],
          borderWidth: 1,
          yAxisID: 'y-axis-1'
        },
        {
          label: 'Note',
          type: 'line',
          data: datasetPrimeurPrice.rating,
          fill: false,
          usePointStyle: true,
          backgroundColor: '#71B37C',
          borderColor: '#71B37C',
          hoverBackgroundColor: '#71B37C',
          hoverBorderColor: '#71B37C',
          yAxisID: 'y-axis-2'
        }
        ]
      },
      options: {
        tooltips: {
          mode: 'label',
          callbacks: {
            label: function (tooltipItems, data) {
              if (tooltipItems.datasetIndex == 0) {
                return data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.yLabel + ' €';
              } else {
                return data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.yLabel;
              }
            }
          }
        },
        scales: {
          xAxes: [{
            display: true,
            gridLines: {
              display: false
            },
            labels: {
              show: true
            }
          }],
          yAxes: [{
            type: "linear",
            display: true,
            position: "left",
            id: "y-axis-1",
            gridLines: {
              display: false
            },
            labels: {
              show: true

            },
            ticks: {
              beginAtZero: true,
              callback: function (value, index, values) {
                return value + " €";
              }
            }
          }, {
            type: "linear",
            display: true,
            position: "right",
            id: "y-axis-2",
            gridLines: {
              display: false
            },
            labels: {
              show: true,
              usePointStyle: true
            },
            ticks: {
              min: 75
            }
          }]
        },
        responsive: true,
        maintainAspectRatio: true,
        showLines: false,
        legend: {
          display: true,
          labels: {
            borderWidth: 0
          }
        }
      }
    });

You can see the result on my page :
Graph with Chart.js

A: What might work is setting the color of the border to transparent, or an opacity to 0 (same result). What you have now is:
borderColor: ['rgba(255, 166, 48)', ...]

What my example would look like is:
borderColor: ['rgba(255, 255, 255, 0)', ...]

Hope this helps you out and works ;-)


text:
Q: Two formula with proof needed for the integral transform I have two questions about integral transform:
1.
I would like to know how to derive the Fourier sine transform of $x^{-1}e^{-ax^2}$, $|\arg a|<\frac{\pi}{2}$. i.e. $\int_{0}^{\infty}x^{-1}e^{-ax^2} \sin(xy)dx$,$y>0$
2.
I would like to know how to write $\int_{-\infty}^{\infty}\frac{\exp\left(-\pi^2 t^2+2i\pi x t\right)}{t} dt=\int_{-\infty}^{\infty}i\pi\; \text{sgn}(x-t) \frac{1}{\sqrt{\pi}}e^{-t^2} dt$
Also, are there any books about the derivation of different integral transform? What I can find is a table of different integral transform, but there is no book which explain derivations of different integral transform.


text:
Q: break Parallel.ForEach if user press key 'c' If user press 'c' then Parallel.ForEach should break without cancelling started tasks. Now my program is waiting for user, how can I do that the user can write 'c' in any moment and program will cancel when started tasks have finished?
List<int> companies = new List<int> { 56, 1, 18, 26, 37, 45, 47, 50, 56, 60 };
Parallel.ForEach(companies, (company, state) =>
{
    if (Console.ReadKey().KeyChar == 'c')
    {
        state.Break();
    }

    MyFunction(company);
});

EDIT - final solution:
try
{
    List<int> companies = new List<int> { 78, 1, 18, 26, 37, 45, 47, 50, 56, 60 };
    CancellationTokenSource cts = new CancellationTokenSource();
    ParallelOptions po = new ParallelOptions();
    po.CancellationToken = cts.Token;

    Task.Factory.StartNew(() =>
    {
        if (Console.ReadKey().KeyChar == 'c')
        {
            cts.Cancel();
        }
    });

    Parallel.ForEach(companies, (company, state) =>
    {
        MyFunction(company);

        po.CancellationToken.ThrowIfCancellationRequested();
    });
}
catch (OperationCanceledException ex)
{
    Console.WriteLine("Cancelled program");
}

A: Your Console.ReadKey method call should not be inside the Parallel.ForEach, instead, it should be directly after it.
Then, use that read key to cancel the foreach using a CancellationToken.
See: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-parallel-for-or-foreach-loop


text:
Q: JCS cache returns null for cached values not already in memory I want to use JCS to save heap space in a standalone Java application by caching less frequently used objects on disk. I would have thought this is the simplest use case for JCS but even this is proving impossible to figure out.
I have a test configuration where MaxObjects=5 (as explained here, this means beyond 5 objects any other objects should be cached on disk) and MaxPurgatorySize=1. Therefore when my test program adds 10 values to a CacheAccess object, some values should be cached on disk and when the 10 values need to be read from the CacheAccess object they should be retrieved from disk. However, the CacheAccess only gives back 5 values and 5 nulls. After running I can see non-empty files were created, so it doesn't appear to be an IO issue. No exceptions are thrown. JCS version is 3.1.
Configuration:
# DEFAULT CACHE REGION
jcs.default=diskCache
jcs.default.cacheattributes=org.apache.commons.jcs3.engine.CompositeCacheAttributes
jcs.default.cacheattributes.MaxObjects=5
jcs.default.cacheattributes.MemoryCacheName=org.apache.commons.jcs3.engine.memory.lru.LRUMemoryCache
jcs.default.cacheattributes.UseMemoryShrinker=false
jcs.default.cacheattributes.MaxMemoryIdleTimeSeconds=60
jcs.default.cacheattributes.ShrinkerIntervalSeconds=10
jcs.default.cacheattributes.DiskUsagePatternName=SWAP
jcs.default.elementattributes=org.apache.commons.jcs3.engine.ElementAttributes
jcs.default.elementattributes.IsEternal=true
jcs.default.elementattributes.MaxLife=-1
jcs.default.elementattributes.IdleTime=-1
jcs.default.elementattributes.IsSpool=true
jcs.default.elementattributes.IsRemote=false
jcs.default.elementattributes.IsLateral=false

# AVAILABLE AUXILIARY CACHES
jcs.auxiliary.diskCache=org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCacheFactory
jcs.auxiliary.diskCache.attributes=org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCacheAttributes
jcs.auxiliary.diskCache.attributes.DiskPath=${user.dir}/jcs_swap
jcs.auxiliary.diskCache.attributes.MaxPurgatorySize=1
jcs.auxiliary.diskCache.attributes.MaxKeySize=10000000
jcs.auxiliary.diskCache.attributes.OptimizeAtRemoveCount=-1
jcs.auxiliary.diskCache.attributes.OptimizeOnShutdown=false
jcs.auxiliary.diskCache.attributes.ClearDiskOnStartup=true
jcs.auxiliary.diskCache.attributes.DiskLimitType=COUNT

Program:
import org.apache.commons.jcs3.JCS;
import org.apache.commons.jcs3.access.CacheAccess;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        CacheAccess<Integer, String> cache = JCS.getInstance("TestRegion");
        for (int i = 0; i < 10; i++) {
            cache.put(i, "String number " + i);
        }
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            strings.add(cache.get(i));
        }
        System.out.println(String.join("\n", strings));
    }
}

Output:
Jun 30, 2022 5:50:28 PM org.apache.commons.jcs3.engine.control.CompositeCacheManager
INFO: Instance is null, creating with config [/cache.ccf]
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCacheManager
INFO: Creating cache manager from config file: /cache.ccf
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCacheManager
INFO: Setting default auxiliaries to "diskCache"
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCacheManager
INFO: setting defaultCompositeCacheAttributes to [ useLateral = true, useRemote = true, useDisk = true, maxObjs = 5, maxSpoolPerRun = -1, diskUsagePattern = SWAP, spoolChunkSize = 2 ]
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCacheManager
INFO: setting defaultElementAttributes to [ IS_LATERAL = false, IS_SPOOL = true, IS_REMOTE = false, IS_ETERNAL = true, MaxLifeSeconds = -1, IdleTime = -1, CreateTime = 1656607829077, LastAccessTime = 1656607829077, getTimeToLiveSeconds() = -1, createTime = 1656607829077 ]
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCacheConfigurator
INFO: Parsed regions []
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCacheManager
INFO: Finished configuration in 47 ms.
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCacheConfigurator
INFO: No special ElementAttribute class defined for key [jcs.region.TestRegion.elementattributes], using default class.
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.memory.AbstractDoubleLinkedListMemoryCache
INFO: initialized MemoryCache for TestRegion
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.engine.control.CompositeCache
INFO: Constructed cache with name [TestRegion] and cache attributes [ useLateral = true, useRemote = true, useDisk = true, maxObjs = 5, maxSpoolPerRun = -1, diskUsagePattern = SWAP, spoolChunkSize = 2 ]
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.auxiliary.AuxiliaryCacheConfigurator
INFO: No cache event logger defined for auxiliary [jcs.auxiliary.diskCache]
Jun 30, 2022 5:50:29 PM org.apache.commons.jcs3.auxiliary.AuxiliaryCacheConfigurator
INFO: Using standard serializer [org.apache.commons.jcs3.utils.serialization.StandardSerializer@498d318c] for auxiliary [jcs.auxiliary.diskCache]
Jun 30, 2022 5:50:30 PM org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCache
INFO: Region [TestRegion] : Set maxKeySize to: "10,000,000"
Jun 30, 2022 5:50:30 PM org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCache
INFO: Region [TestRegion] : Cache file root directory: C:\Java\JcsTest\jcs_swap
Jun 30, 2022 5:50:30 PM org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCache
INFO: Region [TestRegion] : ClearDiskOnStartup is set to true. Ignoring any persisted data.
Jun 30, 2022 5:50:30 PM org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCache
INFO: Region [TestRegion] : Indexed Disk Cache is alive.
null
null
null
null
null
String number 5
String number 6
String number 7
String number 8
String number 9

I've tried changing many of the parameters in the configuration file to no avail as well as using a GroupCacheAccess. The only way I've found to avoid null values is to increase MaxObjects or MaxPurgatorySize, but this means the objects are never cached to disk in the first place (except when JCS shuts down) and there is no memory saved, which defeats the purpose of using JCS.
Edit:
By adding Thread.sleep(60_000) to the end of my program I can see that the files created are "0 KB" in the file explorer, and only become non-empty when the program ends and JCS shuts down. So I'm not even sure the disk cache is being written to (except at shutdown), even though it is creating the empty TestRegion.data and TestRegion.key files and the memory cache appears to have evicted some objects.


text:
Q: How to do DI using nInject if two projects into presentation layer One of application has below design:
Presentation layer:
1) MVC 4 (contains reference to WCF service) and using ninject DI for controller constructor inject - where interface and implementation are both on same project - MVC.
BAL and DAL
2) WCF Service
Converted to below design:
1) MVC (no service reference and removed ninject and only contains interfaces which are injecting into controller)
2) New library project (contain reference of MVC project and implementation of interfaces which are existed into MVC application) and added ninject module for DI.
3) WCF service
Problem:
When I execute the first design approach then, it works fine and I found, controller injected interface instance but, when I have make loosely couple for WCF service reference and added into new separate project and move each interfaces into that separate project then, on execution of MVC application, it gives me below error:
System.MissingMethodException: No parameterless constructor defined for this object.
this looks like issue due to ninject DI.
NOTE: In MVC, project, there is no NinjectWebCommon and ServiceModule both are moved into that newly added class library project. Interfaces which are injecting into controller are existed into MVC project and its implementation existed int newly added class library project.
Please suggest me what is wrong here.
thank You


text:
Q: Calling Java from Python: "Can't find or load class" Error I'm trying to call a java program from python using command line. The code is as follows:
subprocess.check_output(["java", "pitt.search.semanticvectors.CompareTerms", "-queryvectorfile","termvectors.bin","term1","term2"])

I get the following error:
Error: Could not find or load main class pitt.search.semanticvectors.CompareTerms

This happens when I run the program from PyDev (version 2.5 in Eclipse 3.7.2). However, if I run the same code from the terminal, it works and I get the result I want.
I'm almost sure that the problem is related with some configuration of PyDev and how it handles the java CLASSPATH, which is:
/Users/feralvam/Programas/semanticvectors-3.4/semanticvectors-3.4.jar:/Users/feralvam/Programas/lucene-3.5.0/lucene-core-3.5.0.jar:/Users/feralvam/Programas/lucene-3.5.0/contrib/demo/lucene-demo-3.5.0.jar:

The class "pitt.search.semanticvectors.CompareTerms" is in "semanticvectors-3.4.jar".
Any help you could give me would be really appreciated.
Thanks!

A: The solution proposed by @eis worked. Now, the command is:
subprocess.check_output(["java", "-classpath", "/Users/feralvam/Programas/semanticvectors-3.4/semanticvectors-3.4.jar:/Users/feralvam/Programas/lucene-3.5.0/lucene-core-3.5.0.jar:/Users/feralvam/Programas/lucene-3.5.0/contrib/demo/lucene-demo-3.5.0.jar:", "pitt.search.semanticvectors.CompareTerms", "-queryvectorfile","/Users/feralvam/termvectors.bin","term1","term2"])


text:
Q: Default updateDateInput doesn't work going forward I have a simple app which uses a dynamic UI element, updateDateInput, to ensure that the user is only able to select dates in the designated year. The selected date should always default to the first day of the selected year.
library(shiny)
library(tidyverse)
library(lubridate)

ui <- fluidPage(
  selectInput("year", "Select Year:",
              choices = 2010:2020, selected = 2015),
  dateInput("date", "Select Date:", value = NULL)
)

server <- function(input, output, session) {
  observeEvent(input$year,
               updateDateInput(session, "date",
                               min = ymd(paste(input$year, "01-01", sep = "-")),
                               max = ymd(paste(input$year, "12-31", sep = "-")),
                               value = ymd(paste(input$year, "01-01", sep = "-"))))
}

shinyApp(ui, server)

When moving the selected year backwards (e.g 2015 - 2014), the selected date automatically updates to the first of the month. However, when the user moves the date forwards, from 2015 to 2016, the selected date default to null and the user needs to manually search to get to the current year dates.
Can anyone help me figure out why this is happening?

A: This is a nasty problem, and one that it took me ages to track down when it happened to me.  The problem is that updateDateInput appears to make changes that aren't atomic.  That is, they don't occur all at once, but rather sequentially.  Therefore, when changing more than one parameter of the input widget at at time, it's possible that the value is momentarily invalid.
The trick is to make sure that the selected date is valid at all times during the update.  That means making the changes in two stages, and in an order that depends on whether you're moving forwards or backwards in time.
Here's a working solution.
library(shiny)
library(tidyverse)
library(lubridate)

ui <- fluidPage(
  selectInput("year", "Select Year:",
              choices = 2010:2020, selected = 2015),
  dateInput("date", "Select Date:", value = NULL)
)

server <- function(input, output, session) {
  observeEvent(input$year, {
    req(input$date, input$year)

    # Are we going backwards or forwards?
    if (as.numeric(input$year > year(input$date))) {
      updateDateInput(
        session,
        "date",
        max = ymd(paste(input$year, "12-31", sep = "-")),
        value = ymd(paste(input$year, "01-01", sep = "-")),
      )
      updateDateInput(
        session,
        "date",
        min = ymd(paste(input$year, "01-01", sep = "-"))
      )
    } else {
      updateDateInput(
        session,
        "date",
        min = ymd(paste(input$year, "01-01", sep = "-")),
        value = ymd(paste(input$year, "01-01", sep = "-"))
      )
      updateDateInput(
        session,
        "date",
        max = ymd(paste(input$year, "12-31", sep = "-"))
      )
    }
  })
}

shinyApp(ui, server)


text:
Q: When do I must use the spread operator in useReducer? I've noticed that in many useReducer examples, the spread operator is used in the reducer like this:
const reducer = (state, action) => {
  switch (action.type) {
    case 'increment1':
      return { ...state, count1: state.count1 + 1 };
    case 'decrement1':
      return { ...state, count1: state.count1 - 1 };
    case 'increment2':
      return { ...state, count2: state.count2 + 1 };
    case 'decrement2':
      return { ...state, count2: state.count2 - 1 };
    default:
      throw new Error('Unexpected action');
  }
};

However in many of my practices, I removed ...state and had no issues at all. I understand that ...state is used to preserve the state of the remaining states, but would a reducer preserve those states already so the ...state is not needed?
Can someone give me some examples where ...state is a must and causes issues when removed with useReducer hook? Thanks in advance!

A: No, a reducer function alone would not preserve existing state, you should always be in the habit shallow copy existing state. It will help you avoid a class of state update bugs.
A single example I can think of when spreading the existing state may not be necessary is in the case where it isn't an object.
Ex: a "count" state
const reducer = (state = 0, action) => {
  // logic to increment/decrement/reset state
};

Ex: a single "status" state
const reducer = (state = "LOADING", action) => {
  // logic to update status state
};

Spreading the existing state is a must for any state object with multiple properties since a new state object is returned each time, in order to preserve all the existing state properties that are not being updated.
Edit 1

Can you give an example when NO shallow copying causing state update bugs?

const initialState = {
  data: [],
  loading: false,
};

const reducer = (state, action) => {
  switch(action.type) {
    case LOAD_DATA:
      return {
        ...state,
        loading: true,
      };

    case LOAD_DATA_SUCCESS:
      return {
        ...state,
        data: action.data,
        loading: false
      };

    case LOAD_DATA_FAILURE:
      return {
        loading: false,
        error: action.error,
      };

    default:
      return state;
  }
};

As can been seen in this example, upon a data load failure the reducer neglects to copy the existing state into the new state object.
const [state, dispatch] = useReducer(reducer, initialState);

...

useEffect(() => {
  dispatch({ type: LOAD_DATA });
  // logic to fetch and have loading failure
}, []);

return (
  <>
    ...
    {state.data.map(...) // <-- throws error state.data undefined after failure
    ...
  </>
);

Any selector or UI logic that assumes state.data always exists or is always an array will fail with error. The initial render will work since state.data is an empty array and can be mapped, but upon a loading error state.data is removed from state.


text:
Q: I'm failing to solve a cubic equation SOLUTION:
Because I made the substition of $t = x + \frac {b}{3a}$, I had to substract $\frac {b}{3a}$ from my final answer, giving me the formula for x: $x = u + v - \frac {b}{3a}$.
I'm trying to write my own cubic equation solver program using C#, but I am getting the wrong answer. I'm pretty sure all my code is correct, so I suspect I'm doing something wrong with the calculations itself. I suspect I'm just missing a step or made a fundamental mistake in solving the cubic equation. Please keep in mind I have never solved a cubic equation before.
I will thoroughly explain all the steps I have taken, in the hopes of you finding the mistake.
First, I depressed the cubic from the standard form of $ax^3 + bx^2 + cx + d$ into $x^3 + px + q$.
From this video by Mathologer, I learned how to do this (he explains it at 16:05).
He stated that p and q should be set equal to these values:
$$p = \frac ca - \frac {b^2}{3a^2}$$
$$q = \frac {2b^3}{27a^3} - \frac{bc}{3a^2} + \frac da$$
So you would get the formula:
$$x^3 + (\frac ca - \frac {b^2}{3a^2})x + (\frac {2b^3}{27a^3} - \frac{bc}{3a^2} + \frac da)$$
After that, I calculated the discriminant, with the method show in Mathologer's video at 19:00:
$$(\frac q2)^2 + (\frac p3)^3$$
With the discriminant calculated, I could move on to the next step, in which I check if the discriminant is positive, zero or negative. Right now I'm having issues with the answer I get from the positive discriminant.
I then calculated the values for u and v (method shown at 23:00) and added them together to get the value of x.
$$u = \sqrt[3]{-\frac q2 + \sqrt{(\frac q2)^2 + (\frac p3)^3}}$$
$$v = \sqrt[3]{-\frac q2 - \sqrt{(\frac q2)^2 + (\frac p3)^3}}$$
$$x = u + v$$
When I input: a = 2, b = 3, c = 4, d = 5. I get the result: $x = -0.8711$. But when I graphed $2x^3 + 3x^2 + 4x + 5$ in Desmos, I found that it should be: $x = -1.3711$. I tripled checked all the steps with my calculator, so I don't think it's just a calculation error.
I tested all the steps I took, and found that:
$p = 1.25$
$q = 1.75$
$discriminant = 0.8379$
$u = 0.3431$
$v = -1.2142$
Something interesting I noticed was that my answer is exactly 0.5 higher than what it should be. Coincidence?
Does anyone see what I did wrong here?

A: When you depress a cubic, you make the substitution $t = x+b/3a$.
For your example that would be $t = x+3/(2\cdot 3) =x + 1/2$.
You're using $x$ in two ways.  In your depressed equation, the $x$ should be a different variable, say $t$.  You're getting $-0.8711$ for $t$.  But $t=x+1/2$, so....


text:
Q: Memcached possibly leaking memory I am having a really odd problem and I am lost a bit as I do not know what to do any more.
We are running in production 4 dedicated memcached boxes. All boxes have 48Gb of RAM, they are running memcached and nothing else and the daemon's memory limit is set to 42Gb.
The problem is that no matter the amount of traffic and gets/sets the boxes receive the cache will fill up on all 4 of them to about 38Gb but then the amount of free RAM available to the operating system will start slowly dropping over the course of several days until the boxes will start swapping, filling up the swap and thrashing! Now this is really strange as there is nothing else running on the boxes that could fill up the rest of the RAM and memcached is eating up 38Gb and not growing (at least that is what the graphs and the stats show).
I have tried setting the swappiness to 0 but it didn't help. I have tried lowering the cache limit even more but I get the same behavior.
I am running Centos 5.6, 2.6.18-238, memcached 1.4.4 and libevent-1.4.13-1.
Have any of you ran into a similar problem before? Could memcached possibly be leaking memory and not showing up in the graphs or the usual Linux tools?
Thanks!
Dan

A: First things first: is it really necessary for you to have such high memory limit for memcached? Would less than 42 GB be enough in practise?

A: Memcached could leak memory (these things happen), but it'd show up in the memory accounting.  Absent a fairly unlikely kernel bug, memory accounting will be accurate.  The long and the short of it is that you're missing something in your diagnostic actvities.  Collect more data and keep staring at it.


text:
Q: Technical help for disk space allocation im trying to install Ubuntu but am facing some problems with data allocations. apparently the current partitions made it such that i cant install this OS without erasing the current one (Windows 7)
this is what the installation menu gives:
dev/sda1 size 161000MB used: 119000MB dev/sda2 size 102MB used 35MB dev/sda3 size 246000MB used 46000 MB dev/sda4 size 237000MB used 3200MB
any tips to quickly get over this? note that i need to keep windows 7 only for a couple of programs, so i dont need to have too much memory for it.

A: Looks like this is related to Allocating drive space?.
Boot in to windows 7.
Open my computer and see if you can free up any drive (like D drive/E drive which are hard disk partitions).You can correlate the drive naming in windows and linux (reported in question) by comparing the sizes as well. If there is one such drive, move all the data in that drive to another drive and so that you can delete it.
Then ,in windows, Go to Settings -> Control Panel -> Administrative Tools -> Computer Management -> Storage -> Disk Management'. Locate the drive you identified, select it and delete the partition from the menu. That space will become free space.  Boot using Ubuntu install CD and use that partition to install Ubuntu.


text:
Q: MySQL - two counts with different WHERE in one query table
field1 field2
a       1
b
c       3
e       4
f

I need to count field1 and not empty field2 with on query:
SELECT COUNT(field1) FROM table
+
SELECT COUNT(field2) FROM table WHERE field2 != ''

result should be 5 and 3 in one query.
Is it possible?

A: SELECT
    (SELECT COUNT(field1) FROM table) AS count1,
    (SELECT COUNT(field2) FROM table WHERE field2 != '') AS count2

A: Yet another way:
SELECT COUNT(field1), COUNT(IF(field2='', NULL, field2))
    FROM ...

A: Easy as pie :)
select count(field1), count(field2)
from my_table

Result:
+--------+--------+
| field1 | field2 |
+--------+--------+
| 5      | 3      |
+--------+--------+

If the empty values in the field2 column are '' (empty strings) instead of actual NULL, you can try this:
select count(field1), sum(case when field2 != '' then 1 else 0 end)
from my_table;

A: to combine the results of queries with identical column formats, use UNION between them
SELECT w FROM x
UNION
SELECT y FROM z


text:
Q: How to passing data from middleware to components/api in Next Js 13? i just trying Next Js 13 middleware feature. But i confuse how to passing data from middleware to components/page/api.
For example i try to pass payload or who user is currently loggin.
Normally without middleware feature, i just make middleware file and if jwt verify true, i will send/pass payload data to my components/api
import {example} from 'middleware/example'

const payload = await example(req, res)

But if i using Next Js 13 feature and i read the docs, i just find how to send response like
return new NextResponse(
  JSON.stringify({
    success: false,
    message: 'authentication failed'
  }),
  { status: 401, headers: { 'content-type': 'application/json' } }
)

if i use that, it will return json data, and not continue the middleware chain, if i use
return NextResponse.next()

it will continue the middleware chain, but how do i passing my payload data to components/page/api?.
im trying like this
return NextResponse.next({tes: "tes"})

but i can't find how to get that data from components/api.
This is my middleware code
if (request.nextUrl.pathname.startsWith('/api/posts')) {
        const requestHeaders = new Headers(request.headers)
        const authorization = requestHeaders.get('authorization')

        if (!authorization) {
            return new NextResponse(
                JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        const authSplit = authorization.split(' ')
        const [authType, authToken] = [
            authSplit[0],
            authSplit[1]
        ]

        if (authType !== 'Bearer') {
            return new NextResponse(
                JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        const payload = await verify(authToken)

        if (!payload) {
            return new NextResponse(
                JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        return NextResponse.next()
    }


text:
Q: Recommend a research-level book on econometrics, particularly for the theory of linear regression for random regressors X Can anyone suggest a research monograph (with proofs or at least detailed references) for econometrics?
Specifically, I'm looking to learn about the theory of linear regression and all the usual topics there for random regressors (finite sample and asymptotic properties of LSE, interval estimation and hypothesis test, etc.). I would like it to include multivariate linear regression if possible. The problem with the usual statistics books is that they nearly always assume fixed regressors.
Hayashi's Econometrics is one book I found, which is okay. Although it seems closer to a classroom textbook than a research book. Any other better suggestions?


text:
Q: Simple Calendar I'm using the ACF (Advanced Custom Fields) and selected the date picker.
I'm wondering if anyone has created a simple calendar plugin that can grab the field and produce a calendar. How should I do that?

A: As @Vincius mentioned above, I don't think anyone has created a full-blown calendar with ACF and ACF alone. But - that doesn't mean you can't plug into other Event Calendars (or --> attach the ACF data onto their Events post type). For example:
Sugar Event Calendar

*

*It has a filter hooks (look on that page, under Hooks) that allow you to override each query generated by the plugin. That way, if you had another post type, you could override the default query from post_type => 'events' to post_type => array('events','your_post_type')

*If you setup your ACF fields and attach them to the Event post type, what you can then do is  remove_meta_box() on whatever  meta boxes you would like to hide (that would have date info) and then setup your ACF fields to map to the same meta_keys. This one is more dangerous though - as if the dev changes something with how the meta fields are saved, you could run into trouble.

But, if you use the second example and just add-on additional data you need, every decent event plugin will allow you to override the respective views for each area - and you can then use normal ACF functions to output your data. Thanks!

A: I don't know any plugin like this. Anyway, you should provide specific information of what kind of calendar you want. By general means, strtotime is your friend.
For example, to generate a day listing of the current month with a highlighted date from the custom field, you would do something like:
$date_field = date( 'Y-m-d', strtotime( get_field( 'date_field' ) ) );
$current_month = date( 'Y-m-' );
for ( $day = 1; $day < date( 't' ); $day++ ) {
    $day_of_month = $current_month . $day;
    if ( $day_of_month == $date_field )
        <?php echo $day_of_month; ?>
    else
        <?php echo $day_of_month; ?>
}

Note: the above code is not tested.


text:
Q: Electric field in a parallel plate capacitor I am trying to calculate electric field between two parallel plates () using Gauss's law and using field due to sheet of charge. The fields using both the methods is not matching. I am not able to point out the mistake. I am attaching the derivations

A: As you know that the electric field due to an infinite plane is given by $E=\frac{\sigma}{2\epsilon_{\circ}}$.
Between the two plates, there are two different fields. One due the positively charged plate and another due the negatively charged plate. So using the superposition principle, the electric field between the plates will be given by the addition of the fields due to both the plates, thus,
$E=\frac{\sigma}{2\epsilon_{\circ}}+\frac{\sigma}{2\epsilon_{\circ}}$
$E=\frac{\sigma}{\epsilon_{\circ}}$
This electric field will be directed from the positive plate to the negative plate.
For an infinitely large plate the electric field is independent of the distance of the point where electric field is to be calculated.
In the region outside the plate, electric field will be $0$.
Now, $C=\frac{Q}{V}$
$C=\frac{Q}{Ed}$
$C=\frac{Q}{\frac{\sigma}{\epsilon_{\circ}}d}$
But, $\sigma=\frac{Q}{A}$ , where A is the area of the plates.
Therefore,
$C=\frac{A\epsilon_{\circ}}{d}$
To be precise,
$C=\frac{A\epsilon}{d}$,
Where, $\epsilon=\epsilon_{r}\epsilon_{\circ}$.


text:
Q: How to list all virtual directories and subdirectories using Azure Storage Client Library for .NET (BLOBS) How to list ALL directories AND subdirectories in a blob container?
This is what I have so far:
public List<CloudBlobDirectory> Folders { get; set; }

public List<CloudBlobDirectory> GetAllFoldersAndSubFoldersFromBlobStorageContainer()
{
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

    if (container.Exists())
    {
        Folders = new List<CloudBlobDirectory>();

        foreach (var item in container.ListBlobs())
        {
            if (item is CloudBlobDirectory)
            {
                var folder = (CloudBlobDirectory)item;
                Folders.Add(folder);
                GetSubFolders(folder);
            }
        }
    }

    return Folders;
}

private void GetSubFolders(CloudBlobDirectory folder)
{
    foreach (var item in folder.ListBlobs())
    {
        if (item is CloudBlobDirectory)
        {
            var subfolder = (CloudBlobDirectory)item;
            Folders.Add(subfolder);
            GetSubFolders(subfolder);
        }
    }
}

The above code-snippet gives me the list that I want but I am unsure about the recursive method and other .NET/C# syntax and best practice programming patterns. Simply put, I would like the end result to be as elegant and as performant as possible.
How can the above code-snippet be improved?

A: Only issue with your otherwise very elegant code is that it makes too many calls to storage service to fetch the data. For each folder/sub folder, it goes to the storage service and gets the data.
You could avoid that by list all blobs from a container and then figure out if it is a directory or blob on the client side. For example, take a look at this code here (It's not as elegant is yours but hopefully it should give you an idea about what I am trying to convey):
    static void FetchCloudBlobDirectories()
    {
        var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
        var containerName = "container-name";
        var blobClient = account.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference(containerName);
        var containerUrl = container.Uri.AbsoluteUri;
        BlobContinuationToken token = null;
        List<string> blobDirectories = new List<string>();
        List<CloudBlobDirectory> cloudBlobDirectories = new List<CloudBlobDirectory>();
        do
        {
            var blobPrefix = "";//We want to fetch all blobs.
            var useFlatBlobListing = true;//This will ensure all blobs are listed.
            var blobsListingResult = container.ListBlobsSegmented(blobPrefix, useFlatBlobListing, BlobListingDetails.None, 500, token, null, null);
            token = blobsListingResult.ContinuationToken;
            var blobsList = blobsListingResult.Results;
            foreach (var item in blobsList)
            {
                var blobName = (item as CloudBlob).Name;
                var blobNameArray = blobName.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
                //If the blob is in a virtual folder/sub folder, it will have a "/" in its name.
                //By splitting it, we are making sure that it is indeed the case.
                if (blobNameArray.Length > 1)
                {
                    StringBuilder sb = new StringBuilder();
                    //Since the blob name (somefile.png) will be the last element of this array and we're not interested in this,
                    //We only iterate through 2nd last element.
                    for (var i=0; i<blobNameArray.Length-1; i++)
                    {
                        sb.AppendFormat("{0}/", blobNameArray[i]);
                        var blobDirectory = sb.ToString();
                        if (blobDirectories.IndexOf(blobDirectory) == -1)//We check if we have already added this to our list or not
                        {
                            blobDirectories.Add(blobDirectory);
                            var cloudBlobDirectory = container.GetDirectoryReference(blobDirectory);
                            cloudBlobDirectories.Add(cloudBlobDirectory);
                            Console.WriteLine(cloudBlobDirectory.Uri);
                        }
                    }
                }
            }
        }
        while (token != null);
    }

A: My function I use to get all the files and sub directories.
Please note to assign your BlobContainer object in the constructor or somewhere before running the function so it wont call it for every file/directory
  public IEnumerable<String> getAllFiles(string prefix, bool slash = false) //Prefix for, slash for recur, see folders
    {
        List<String> FileList = new List<string>();
        if (!BlobContainer.Exists()) return FileList; //BlobContainer is defined in class before this is run
        var items = BlobContainer.ListBlobs(prefix);

        foreach (var blob in items)
        {
            String FileName = "";
            if (blob.GetType() == typeof(CloudBlockBlob))
            {
                FileName = ((CloudBlockBlob)blob).Name;
                if (slash) FileName.Remove(0, 1); //remove slash if file
                FileList.Add(FileName);
            }
            else if (blob.GetType() == typeof(CloudBlobDirectory))
            {
                FileName = ((CloudBlobDirectory)blob).Prefix;
                IEnumerable<String> SubFileList = getAllFiles(FileName, true);
                foreach (String s in SubFileList)
                {
                    FileList.Add(s);
                }
            }
        }

        return FileList;
    }


text:
Q: WPF host object in new thread Want to host object not in gui thread, all methods of this object will run in this new thread.
Something like that:
Thread thread = new Thread(() =>
{
    MyDataInstance = new MyData();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

But this will not work.
Is there any nice way to do it?
(Can create window in other thread, make it invisible, and then host it there, but it seems not the best solution)

A: You need to call a method that does something. All you are doing with your current code is setting up your data instance.
So you need to call a method like this:
Thread thread = new Thread(new ThreadStart(MethodThatDoesStuff)) { MyDataInstance = new MyData(); };

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

MethodThatDoesStuff will have to have a loop so that it continues do to things forever, or have some other control mechanisms (setting up event handlers etc.)


text:
Q: Google App Engine JPA 2.0 - java.lang.ClassNotFoundException: javax.persistence.spi.ProviderUtil I have been scouring the internet for hours today and can't get this resolved.
I am trying to get my Google App Engine project configured to use JPA 2.0 with the latest as of this time Datanucleus packages. Everything compiles fine, but I keep getting a runtime exception:
Caused by: java.lang.ClassNotFoundException: javax.persistence.spi.ProviderUtil
I am including the relevant parts of my pom.xml that refer to all the persistence stuff as well as my persistence.xml file.
Here is what I think are the relevant parts of my pom.xml:
<gae.version>1.7.4</gae.version>
<datanucleus.version>3.1.1</datanucleus.version>

<dependency>
    <groupId>javax.jdo</groupId>
    <artifactId>jdo-api</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.geronimo.specs</groupId>
    <artifactId>geronimo-jpa_2.0_spec</artifactId>
    <version>1.1</version>
</dependency>
<dependency>
    <groupId>com.google.appengine.orm</groupId>
    <artifactId>datanucleus-appengine</artifactId>
    <version>2.1.1</version>
</dependency>
<dependency>
    <groupId>org.datanucleus</groupId>
    <artifactId>datanucleus-core</artifactId>
    <version>${datanucleus.version}</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.datanucleus</groupId>
    <artifactId>datanucleus-api-jpa</artifactId>
    <version>${datanucleus.version}</version>
</dependency>
<dependency>
    <groupId>org.datanucleus</groupId>
    <artifactId>datanucleus-api-jdo</artifactId>
    <version>${datanucleus.version}</version>
</dependency>

<plugin>
    <groupId>org.datanucleus</groupId>
    <artifactId>maven-datanucleus-plugin</artifactId>
    <version>${datanucleus.version}</version>
    <configuration>
        <api>JPA</api>
        <verbose>true</verbose>
    </configuration>
    <executions>
        <execution>
            <phase>process-classes</phase>
            <goals>
                <goal>enhance</goal>
            </goals>
        </execution>
    </executions>
 </plugin>

Here is my persistence.xml file contents: I updated the provider as per the instructions on the Google App Engine web site
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

    <persistence-unit name="transactions-optional">
        <provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
        <properties>
            <property name="datanucleus.NontransactionalRead" value="true"/>
            <property name="datanucleus.NontransactionalWrite" value="true"/>
            <property name="datanucleus.ConnectionURL" value="appengine"/>
        </properties>
    </persistence-unit>
</persistence>

Here is the stack trace I am getting:
Caused by: java.lang.ClassNotFoundException: javax.persistence.spi.ProviderUtil
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:213)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 56 more

Can someone please point me in the right direction of what dependency I am missing?
What are the exact versions of the Datanucleus, Google and JPA dependencies that I need for the latest libraries?

A: You say you're using JPA 2.0, but you put geronimo-jpa_3.0_spec v1.1.1 in your CLASSPATH, and that is JPA 1.0 API. As per the GAE JPA plugin POM, using geronimo-jpa_2.0_spec v1.1 would make more sense, since it is the JPA 2.0 API. GAE JPA plugin and DataNucleus compatibility is defined in http://code.google.com/p/datanucleus-appengine/wiki/Compatibility

A: Use Google AppEngine DataNucleus plugin:
<dependency>
    <groupId>com.google.appengine.orm</groupId>
    <artifactId>datanucleus-appengine</artifactId>
    <version>2.1.2</version>
</dependency>


text:
Q: Visual display Debuggers like DDD I am having massive troubles installing ddd on my Mac OSX lion.
Anyone know of any other visual display debuggers like ddd ?
It has to Visual display debugger.
I have eclipse on my mac , does it come with a debugger? if yes how to get to it?


text:
Q: Считывать сигнал с изображения Всем доброго!
Подскажите в каком направлении двигаться, с чего начать, можно ли вообще это реализовать?
Нужно следующие: Из прямой трансляции считывать определенный видеоролик, после чего подавать сигнал для замещения прямой трансляции на плейлист с роликами. Также продолжать анализировать прямую трансляцию для считывания того же самого видео ролика, чтобы завершить замещение прямой трансляции плейлистами, то есть вернуть в исходное состояние.


text:
Q: Python dictionaries into yaml documents using PyYaml I have two python dictionaries which I want to write to a single yaml file, with two documents:
definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}

The yaml file should look like:
--- !define
one: 1
two: 2
three: 3

-- !action
run: yes
print: no
report: maybe
...

Using PyYaml I did not find a clear way to do that. I'm sure there is a simple method, but digging into PyYaml documentation, only got me confused. Do I need a dumper, emitter, or what? And what type of output each of these types produces? Yaml text? yaml nodes? YAMLObject? Anyway I would be grateful for any clarifications.

Following unutbu's answer below, here is the most concise version I could come up with:
DeriveYAMLObjectWithTag is a function to create a new class, derived from YAMLObject with the required tag:
def DeriveYAMLObjectWithTag(tag):
    def init_DeriveYAMLObjectWithTag(self, **kwargs):
        """ __init__ for the new class """
        self.__dict__.update(kwargs)

    new_class = type('YAMLObjectWithTag_'+tag,
                    (yaml.YAMLObject,),
                    {'yaml_tag' : '!{n}'.format(n = tag),
                    '__init__' :  init_DeriveYAMLObjectWithTag})
    return new_class

And here is how to use DeriveYAMLObjectWithTag to get the required Yaml:
definitions = {"one" : 1, "two" : 2, "three" : 3, "four" : 4}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
namespace = [DeriveYAMLObjectWithTag('define')(**definitions),
             DeriveYAMLObjectWithTag('action')(**actions)]

text = yaml.dump_all(namespace,
                     default_flow_style = False,
                     explicit_start = True)

Thanks to all those who answered. I seems there's a lack of functionality in PyYaml, and this is the most elegant way to overcome it.

A: Well, I'm still looking into automatic comments (couldn't find the docs for that right away) but this should do the trick:
import yaml

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}

output = yaml.dump(actions, default_flow_style=False, explicit_start=True)
output += yaml.dump(definitions, default_flow_style=False, explicit_start=True)

print output

One word of caution, dictionaries are unordered, so the order of your resulting YAML is not guaranteed. If you want order in the house - look at OrderedDict.

A: How about:
class Bunch(yaml.YAMLObject):
    yaml_tag = u'!Bunch'
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        return '{c}({a})'.format(
            c = self.__class__.__name__,
            a = ', '.join(
                ['='.join(map(str,item)) for item in self.__dict__.items()]))
tag_names = ['define', 'action']
namespace = {}
for name in tag_names:
    namespace[name] = type(name, (Bunch,), {'yaml_tag':u'!{n}'.format(n = name)})

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
text = yaml.dump_all([namespace['define'](**definitions),
                      namespace['action'](**actions)],
                     default_flow_style = False,
                     explicit_start = True)
print(text)

which yields
--- !define
one: 1
three: 3
two: 2
--- !action
print: 'no'
report: maybe
run: 'yes'

And to load the YAML back into Python objects:
for item in  yaml.load_all(text):
    print(item)
    # define(one=1, three=3, two=2)
    # action(print=no, report=maybe, run=yes)

The subclasses of YAMLObject were used to create the application-specific tags.


text:
Q: ¿Cómo eliminar doble, dobles comillas de un String? Tengo esta cadena en String
 ""texto1"": {
   ""texto"": ""17/10/2021""

Y necesito eliminar una de las dobles comillas que existen de forma que quede de la siguiente manera
 "texto1": {
        "texto2": "17/10/2021"

A: la variable dobleComilla es la cadena que tiene las doble comillas
 string dobleComilla= "\"texto1\": {\n   \"texto\": \"17/10/2021\"";

Lo primero que tienes que hacer es utilizar el metodo Replace() y agregas la comilla deseada a obtener
 string resultado= dobleComilla.Replace("\"texto\": \"", "\"texto2\": \"");
            Console.Write(resultado);

resultado final de la variable resultado
"texto1": {
   "texto2": "17/10/2021"

A: Has de indagar un poco en los métodos que posee el tipo string. Para tu caso lo que te va ayudar es el método Replace que te va a sustituir una cadena por otra.
string dcom = "\x022\x022"; // Cadena que contiene dos doble comilla:  ""
// En esta variable texto se recrea la cadena inicial.
string texto = dcom + "texto1" + dcom + ":{" +
               dcom + "texto"  + dcom + ":"+
               dcom + "17/10/2021" + dcom;

// Muestra el valor de la variable texto que es tu input en el problema
Console.WriteLine(texto);
// Reemplazamos las dos dobles comillas por una sola.
texto = texto.Replace(dcom, "\x022");
// Mostramos el resultado
Console.WriteLine(texto);

A: Podrías probar esto:
//cuando se detecta que un string viene con comillas en la visualizacion aparece como ("\"texto\"")
texto=texto.Replace("\"","")
//o tambien
texto=texto.Replace(@"""","")


text:
Q: How can I point a domain to multiple ports based on the directory I am browsing to? I have a server running at home. This server is running on a public IP which is defined on my domain as an A record.
Everything is working currently.
I run Apache for a small website along with Confluence.
Apache: 80
Confluence: 8090

What I want to know is how can I set this up so if I browse to:
domain.net/confluence
Will Apache know that it should redirect this to port 8090? Is this simply handled through setting up a virtual host for the same IP but pointing it to that directory and having it listen on 8090?

A: So I figured out I can do this with nginx, which I had planned on setting up anyway.
This is what I did!
Added this under nginx/sites-available
    server {
    listen www.thelavender.net:80;
    server_name www.thelavender.net;
    location /confluence {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8090/confluence;
    }
}

copied this to nginx/sites-enabled
in my conf/server.xml for Confluence I added the following:
proxyName="www.xxxxxxx.net" proxyPort="80" />

to the end of the following block of code:
<Connector port="8090" connectionTimeout="20000" redirectPort="8443"
            maxThreads="48" minSpareThreads="10"
            enableLookups="false" acceptCount="10" debug="0" URIEncoding="UTF-8"
            protocol="org.apache.coyote.http11.Http11NioProtocol"

Restarted both Confluence and Nginx and BOOM!!!  Nginx is forwarding port 8090 to 80 and I no longer have to use the ugly URL with the port!!
SWEET!
UPDATE
I wanted to come back and update this as I found a better way to setup my server blocks for multiple applications running under the same domain. In my case, I wanted to run Confluence and JIRA behind the same domain.
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

root /usr/share/nginx/html;
index index.html index.htm;

server_name www.example.com;

location / {
    try_files $uri $uri/ =404;
}

location /jira/ {
   proxy_set_header X-Forwarded-Host $host;
   proxy_set_header X-Forwarded-Server $host;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://192.168.1.2:8080;
   }

location /confluence/ {
   proxy_set_header X-Forwarded-Host $host;
   proxy_set_header X-Forwarded-Server $host;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8090;
   client_max_body_size 10M;
}
}

Or even simpler
server {
listen 80;

server_name www.example.com;

location /confluence {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://localhost:8090/confluence;
}

location /jira {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://localhost:8080/jira;
    client_max_body_size 10M;
}
}

Turdah!!!!


text:
Q: FQL Query to retrieve photos works on newer Facebook accounts but not older ones When I input the query below, I get an Ilist object with all photos in an album
"SELECT pid, src_small, src_big FROM photo WHERE aid = '100003240429199_12493' "

When I input this one below, I get 0 results.
"SELECT pid, src_small, src_big FROM photo WHERE aid = '730676042_444686' "

I am pulling the cover photo for an album. Here is the code:
var query = string.Format("SELECT pid, src_small, src_big FROM photo WHERE aid = '{0}' ", usrid + "_" + albid);
var result2 = (IList<object>)fb.Query(query);
string hold = "", pid = "", small = "", big = "";
foreach (object g in result2)
{
   hold = g.ToString();
   string[] sub = hold.Split(',');
   pid = sub[0].Replace("{\"pid\":\"", "");
   pid = pid.Replace("\"", "");

   small = sub[1].Replace("\"src_small\":\"", "");
   small = small.Replace("\"", "");

   big = sub[2].Replace("\"src_big\":\"", "");
   big = big.Replace("\"}", "");
   th = new FolderExplorer.ThumbNail(usrid + "_" + albid, big, small);
   thmbs.Add(th);
   break;
}
}

Why does the query not work with older facebook accounts (shorter userId's) - I tried several accounts and the results were consistent.

A: My Facebook account is an older one and my album IDs have no underscore in them.  As far as I know, you can't generate an album ID based on their User ID.
You would be better off running a query like this to get all the cover photo for each user's album
fql?q=SELECT pid, src_small, src_big FROM photo WHERE object_id in (select cover_object_id from album where owner = me())


text:
Q: Regex to match not start of line I have the following XML tag
<list message="2 < 3">

I want to replace the < in the text with <
Need a regex to match < if it doesn't appear at the start of line.

A: [^<]+ = one or more characters that are not <
< = the < you're looking for
replace:
([^<]+)<

with:
$1<

A: The dot '.' means "any value"
.<

Anyway, I suppose you don't want whitespaces, either. If so, then
\S\s*<

A: Most likely you can do this using lookbehind:
/(?<!^)</

see: http://www.regular-expressions.info/lookaround.html

A: This would give you "<" after the first instance:
[^<]<

A: Try this:
(?<="[^"]*)<(?=[^"]*")

A: @duncan's method works fine if you just want to replacing, but it doesn't match the <.
and all the lookbehind wont work if you a using javascript. because javascript doesn't support lookbehind, unless you turn on the --harmony flag in nodejs or experimental javascript features in chrome.
But lookahead will work here, which is:

/(?!^)</

will match the < which is not at the begining of a line.
and the replacing will be:

'<list message="2 < 3">'.replace(/(?!^)</, '<')


text:
Q: Cloud Foundry : Spring boot vs WAR file I am new to the world of Cloud, CloudFoundry, Saas, PaaS, IaaS, etc.
So I have few very fundamental questions.

*

*Who is better Spring boot or war file in terms of deploying an application or a service to a cloud using cloud foundry?

*WHY ?

*If I want to deploy my war file on a PaaS cloud then who kicks it off?

*As in where is the server?

*How will I know which server my war file is deployed to?

*Is using Spring-boot with embeded tomcat for PaaS mandatory?

*What if my application does not use spring-boot (no spring reference in pom as well) then can I deploy my application war file on  cloud? How?

A: There is nothing like better in war or Spring boot jar. They both are underhood same things, where Spring boot jar manages the server embedded in it and war does not have that.
Cloud Foundry has something like BuildPacks. You need to define a buildpack when you do a cf push. If you select a java build pack it has the things required to run a war on server. It gets the Java, Tomcat Server and all other dependencies needed to run the war.
https://github.com/cloudfoundry/java-buildpack

Cloud foundry creates a droplet, which is basically the execution context with all required dependencies. This is used to run the actual VM on the cloud.
You need not know which server your war is deployed to. That is the basic idea behind the cloud deployment. It may be on a single/multiple VMs under the hood. So what you need to know is something called routes. Routes are the actual addresses to your apps. You need to create routes and bind them to your application, and later app can be accessed using the routes.
https://docs.cloudfoundry.org/devguide/deploy-apps/routes-domains.html#routes

No using embedded servers is not mandatory in Any Cloud PAAS. War can be directly deployed. All PAAS platforms has support for this. Cloud foundry way of doing this is through build packs.
CF : https://docs.cloudfoundry.org/buildpacks/
Heroku : https://devcenter.heroku.com/articles/java-webapp-runner
Any application/ non spring apps which is plain war or jar can be used to run on PAAS platforms.


text:
Q: Jar file is not executed in with Dockerfile I am building docker image of my application. And I would like to run jar file when I run my docker image. However, I get this error:
Could not find or load main class

Main class is set in the manifest file of the jar file. If I run my jar file from terminal or bash script it works fine. So this error is only observed while running docker:
docker run -v my-volume:/workdir container-name

Are there some configurations missing in my Dockerfile or jar file should be copied/added?
Here is my Dockerfile:
FROM java:8

ENV SCALA_VERSION 2.11.8
ENV SBT_VERSION 1.1.1
ENV SPARK_VERSION 2.2.0
ENV SPARK_DIST spark-$SPARK_VERSION-bin-hadoop2.6
ENV SPARK_ARCH $SPARK_DIST.tgz
WORKDIR /opt

# Install Scala
RUN \
  cd /root && \
  curl -o scala-$SCALA_VERSION.tgz http://downloads.typesafe.com/scala/$SCALA_VERSION/scala-$SCALA_VERSION.tgz && \
  tar -xf scala-$SCALA_VERSION.tgz && \
  rm scala-$SCALA_VERSION.tgz && \
  echo >> /root/.bashrc && \
  echo 'export PATH=~/scala-$SCALA_VERSION/bin:$PATH' >> /root/.bashrc

# Install SBT
RUN \
  curl -L -o sbt-$SBT_VERSION.deb https://dl.bintray.com/sbt/debian/sbt-$SBT_VERSION.deb && \
  dpkg -i sbt-$SBT_VERSION.deb && \
  rm sbt-$SBT_VERSION.deb

# Install Spark
RUN \
    cd /opt && \
    curl -o $SPARK_ARCH http://d3kbcqa49mib13.cloudfront.net/$SPARK_ARCH && \
    tar xvfz $SPARK_ARCH && \
    rm $SPARK_ARCH && \
    echo 'export PATH=$SPARK_DIST/bin:$PATH' >> /root/.bashrc

EXPOSE 9851 9852 4040 9092 9200 9300 5601 7474 7687 7473
VOLUME /workdir

CMD java -cp "target/scala-2.11/demo_consumer.jar" consumer.SparkConsumer

A: I believe this is because the command you execute from the Docker container are not in the right folder. You could try to execute the commands from the workdir:
docker run -v my-volume:/workdir -w /workdir container_name
If that does not work, you could inspect what's inside the container. Either with a ls:
docker run -v my-volume:/workdir -w /workdir container_name bash -c 'ls -lah'
Or by accessing its bash session:
docker run -v my-volume:/workdir -w /workdir container_name bash
p.s: if bash does not work, try with sh.


text:
Q: C++ c-tor handle default member value construction exception? I want to handle exception in a default-value constructed class member. Something like this:
int func()
{
    throw 9.0;

    return 9;
}

struct T
{
    T() try {
    }
    catch(...)
    {
        cout << __func__ << endl;
    }
    int a{func()};
} ;

Is it possible? And what does the latest ISO C++ standard says about it?
EDIT: I actually verified myself it works on most compilers but is it well-defined and should I normally use this construct?

A:
Is it possible?

Yes, that exception would be handled by the function-level handler just like any other thrown by a member's initialiser. Note that, in the function-try-block of a constructor, the exception is rethrown after handling it. This is what you want if the initialisation of a sub-object failed, since the complete object is not valid.

And what does the latest ISO C++ standard says about it?

I don't have C++14 yet, but C++11 said:

15/4: An exception thrown during the execution of the compound-statement or, for constructors and destructors,
  during the initialization or destruction, respectively, of the class's subobjects, transfers control to a handler
  in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers
  control to other handlers.

and 15.3/15 specifies that it's rethrown in this case.

should I normally use this construct?

Probably not - there's little you can do to handle the failure of a sub-object's initialisation, so usually no point in catching and rethrowing the exception. You might want to report the error as the exception passes through.

A: That is not possible, you can only catch the exception for thing you do inside the constructor body, like this:
struct T
{
    T() {
    try { a = func();}
    catch(...)
    {
        cout << __func__ << endl;
    }
    }
}

Also you should catch the exception, but not in the ctor, but where the object is constructed. That is:
try {
    T t;//construct
}
catch(...)
{};

That way you get the failure on construction.


text:
Q: Managing Perl habits in a Python environment Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful.
Subtle variable misspelling can waste an extraordinary amount of time.
I understand the variable declaration issue is quasi-religious among python folks
I'm not arguing for language changes or features, just a reliable bridge between
the 2 languages that will not cause my perl habits sink my python efforts.
Thanks.

A: Splitting Python classes into separate files (like in Java, one class per file) helps find scoping problems, although this is not idiomatic python (that is, not pythonic).
I have been writing python after much perl and found this from tchrist to be useful, even though it is old:
http://linuxmafia.com/faq/Devtools/python-to-perl-conversions.html
Getting used to doing without perl's most excellent variable scoping has been the second most difficult issue with my perl->python transition. The first is obvious if you have much perl: CPAN.

A: I like the question, but I don't have any experience in Perl so I'm not sure how to best advise you.
I suggest you do a Google search for "Python idioms".  You will find some gems.  In particular:
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
http://docs.python.org/dev/howto/doanddont.html
http://jaynes.colorado.edu/PythonIdioms.html
As for the variable "declaration" issue, here's my best advice for you:
Remember that in Python, objects have a life of their own, separate from variable names.  A variable name is a tag that is bound to an object.  At any time, you may rebind the name to a different object, perhaps of a completely different type.  Thus, this is perfectly legal:
x = 1    # bind x to integer, value == 1
x = "1"  # bind x to string, value is "1"

Python is in fact strongly typed; try executing the code 1 + "1" and see how well it works, if you don't believe me.  The integer object with value 1 does not accept addition of a string value, in the absence of explicit type coercion.  So Python names never ever have sigil characters that flag properties of the variable; that's just not how Python does things.  Any legal identifier name could be bound to any Python object of any type.

A: In python $_ does not exist except in the python shell and variables with global scope are frowned upon.
In practice this has two major effects:

*

*In Python you can't use regular expressions as naturally as Perl, s0 matching each iterated $_ and similarly catching matches is more cumbersome

*Python functions tend to be called explicitly or have default variables

However these differences are fairly minor when one considers that in Python just about everything becomes a class. When I used to do Perl I thought of "carving"; in Python I rather feel I am "composing".
Python doesn't have the idiomatic richness of Perl and I think it is probably a mistake to attempt to do the translation.

A: Read, understand, follow, and love PEP 8, which details the style guidelines for everything about Python.
Seriously, if you want to know about the recommended idioms and habits of Python, that's the source.

A: Don't mis-type your variable names. Seriously. Use short, easy, descriptive ones, use them locally, and don't rely on the global scope.
If you're doing a larger project that isn't served well by this, use pylint, unit tests and coverage.py to make SURE your code does what you expect.
Copied from a comment in one of the other threads:
"'strict vars' is primarily intended to stop typoed references and missed-out 'my's from creating accidental globals (well, package variables in Perl terms). This can't happen in Python as bare assignments default to local declaration, and bare unassigned symbols result in an exception."


text:
Q: Working with GD ( imagettftext() ) and UTF-8 characters Just for the record - my first question here but hopefully not my last input in the community.
But that's not why I'm here.
I'm currently developing a simple system that has to generate an image with a text on it. Everthing went well until I realised that GD cannot handle UTF-8 characters like

ā, č, ž, ä, ø, é

and so on.
To clear things up - I'm using imagettftext()
Trying to solve my problem I dug into depths of google and some solutions were returned, none of them, sadly, solved my problem completely.
Currently I'm using this script I found in this thread - PHP function imagettftext() and unicode
private function properText($text){

    // Convert UTF-8 string to HTML entities
    $text = mb_convert_encoding($text, 'HTML-ENTITIES',"UTF-8");
    // Convert HTML entities into ISO-8859-1
    $text = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
    // Convert characters > 127 into their hexidecimal equivalents
    $out = "";
    for($i = 0; $i < strlen($text); $i++) {
        $letter = $text[$i];
        $num = ord($letter);
        if($num>127) {
          $out .= "&#$num;";
        } else {
          $out .=  $letter;
        }
    }

    return $out;

}

and it works fine for some characters but not all of them, for example, a with umlaut isn't converted correctly.
So at this point I'm not sure where and what to look for anymore as I cannot predict the user input. To be more precise, the system is pulling artist names from an xml feed and using the data for the image generation (I'm not planning to support hieroglyphs).
I've made sure that the data gathered from the feed is indeed UTF-8 by using PHP's mb_detect_encoding() and I've made sure that all the characters that currently aren't displayed correctly are indded in the font file I'm feeding to the imagettftext()
function by checking it with windows charmap tool.
Hopefully I can find my answer here and thank you for your help in advance!
edit
To clarify - the characters are not displayed correctly, or, to be more precise, are replaced by malformed characters. Here is a screenshot -

it should read "José González"
edit No2
Using bin2hex() function on data retrieved from the xml feed returns this.
José González -> 4a6f73c3a920476f6e7ac3a16c657a
// input -> bin2hex(input)

edit - fixed
As I continued my research I came up with an answer for my problem, this piece of code did it!
$text = mb_convert_encoding($text, "HTML-ENTITIES", "UTF-8");
$text = preg_replace('~^(&([a-zA-Z0-9]);)~',htmlentities('${1}'),$text);
return($text);

Now all the characters that troubled me are displayed correctly!

A: As I continued my research I came up with an answer for my problem, this piece of code did it!
private function properText($text){
    $text = mb_convert_encoding($text, "HTML-ENTITIES", "UTF-8");
    $text = preg_replace('~^(&([a-zA-Z0-9]);)~',htmlentities('${1}'),$text);
    return($text);
}

Now all the characters (and all the new ones I've seen) that troubled me are displayed correctly!

A: In first place make sure your IDE is not saving file in another encoding than UTF8. For example new Intellij IDEA 9 changed UTF-8 to WINDOWS-1250 on Windows platform. If you won't notice that and you will use constant strings for testing, it is pretty crazy to debug.


text:
Q: How to echo values from two indexed arrays in an alternating fashion? I have this code:
<?php
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName[] = $arrayName2;
$arrayName[] = $arrayName3;
foreach ($arrayName as $key) {
    foreach($key as $innerKey) {
        echo $innerKey;
    }
}
?>

And it brings: 123567abcdef. How can I get 123abc567def?

A: Just try this:
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName = array_combine($arrayName2,$arrayName3);
foreach ($arrayName as $key => $value) {
  echo $key.$value;
}

A: Here is a one-liner using array_map() and implode():
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');

$result=implode(array_map(function($v1,$v2){return $v1.$v2;},$arrayName2,$arrayName3));
echo $result;
// output: 123abc567def

Or if you are simply echoing and don't need a variable, this will be more efficient than Adhan's solution because it doesn't have to modify the input data:
array_map(function($v1,$v2){echo $v1,$v2;},$arrayName2,$arrayName3);
// output: 123abc567def

And finally, this is a more efficient foreach version because array_combine() is unnecessary:
foreach($arrayName2 as $k=>$a){
    echo $a,$arrayName3[$k];
}
// output: 123abc567def

A: How about something like this:
for ($i = 1; $i < yourendvariable; $i = i + 2) {
    echo "arrayname[i] arrayname2[i + 1]";
}


text:
Q: TextExpander and AppleScript to get file path on Mac I would like to create a TextExpander snippet that will prompt me to choose a file in the Finder and copy the file path to the text editor I am working in.
It should work like this:

*

*I am working in NVAlt

*I enter the TextExpander command (e.g. ;path)

*I am prompt top choose a file

*The file path is copied to the note I am working in.

I figured I'll do it using AppleScript, so I tried this:
set source_folder to choose file with prompt "Please select a file."
tell application "System Events"
   set item_list to POSIX path of every disk item of source_folder
end tell
return "path:" & item_list

But it is not returning anything to the text note I am working in...
Any suggestion how I should do it?
PS: I used the POSIX command to the folder name as ".../.../.../" instead of "...:...:..."

A: There are multiple things wrong in the script but instead of trying to correct your script I've looked what textExpander tells me to do. On the help section about textExpander on smilesoftware.com site they say:

The script executes in the context of the TextExpander application.
  The script can perform various actions, but the snippet will expand to
  whatever text is returned.

When looking at the your goal you simply need to coerce the returned alias from the choose file command into a string and return that. So a single line like below should be enough to use to return an HFS path to a file

return choose file with prompt "Please select a file." as string

if you want to return the file path as POSIX Path you only need this:
return POSIX path of (choose file with prompt "Please select a file.")

If you want the path to be prefixed with "path:" like in your example code:
return "path:" & (choose file with prompt "Please select a file.")

NOTE: there is an implicit coerce of the choose file results, no explicit coercion is needed.
EDIT: I've downloaded textExpander myself and it seems that showing dialog in the context of textExpander will behave wrong. So what I did was looking up the front most application and showing the dialog there, it's also better looking. Then I tell that application explicitly to show the choose file prompt and return the result of the choose file prompt. Here is the code:
tell application "System Events"
    set applicationName to (name of every process whose frontmost is true) as string
end tell

using terms from application "AppleScript Editor"
    tell application applicationName
        set expansionString to (choose file "Please select a file.") as string
    end tell
end using terms from

return expansionString