Q:

This method must return a result of type InputStream

I'm getting an error stating This method must return a result of type InputStream
However I've added return statement for InputStream into the source method. So I'm not sure why this issue is occurring. (The issue began when I attempted to integrate a previously used publish progress method in my current source.)
SOURCE:
        /*
         * Sends a query to server and gets back the parsed results in a bundle
         * urlQueryString - URL for calling the webservice
         */

        protected synchronized InputStream getQueryResults(String urlQueryString)
                throws IOException, SAXException, SSLException,
                SocketTimeoutException, Exception {

            try {
                // HttpsURLConnection https = null;
                String uri = urlQueryString;

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                BasicNameValuePair mdn1, mdn2,id1,id2;
                if (MDN.equals("")) {
                    mdn1 = new BasicNameValuePair("mdn1", null);
                    mdn2 = new BasicNameValuePair("mdn2", null);
                } else {
                    mdn1 = new BasicNameValuePair("mdn1", mdN1.toString());
                    mdn2 = new BasicNameValuePair("mdn2", mdN2.toString());

                }

                BasicNameValuePair car = new BasicNameValuePair("car", caR);
                if (ICCID.equals("")) {
                     id1 = new BasicNameValuePair("id1", null);
                     id2 = new BasicNameValuePair("id2", null);
                } else {
                     id1 = new BasicNameValuePair("id1",
                            iD1.toString());
                     id2 = new BasicNameValuePair("id2",
                            iD2.toString());
                }

                nameValuePairs.add(mdn1);
                nameValuePairs.add(mdn2);
                nameValuePairs.add(car);
                nameValuePairs.add(id1);
                nameValuePairs.add(id2);

                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
                        nameValuePairs, "ISO-8859-1");
                KeyStore trustStore = KeyStore.getInstance(KeyStore
                        .getDefaultType());
                trustStore.load(null, null);

                SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                HttpParams params = new BasicHttpParams();
                HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

                SchemeRegistry registry = new SchemeRegistry();
                registry.register(new Scheme("http", PlainSocketFactory
                        .getSocketFactory(), 80));
                registry.register(new Scheme("https", sf, 443));

                ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                        params, registry);

                HttpClient httpClient = new DefaultHttpClient(ccm, params);
                params = httpClient.getParams();
                HttpClientParams.setRedirecting(params, true);

                HttpPost httpPost = new HttpPost(uri);
                httpPost.addHeader("Authorization",
                        getB64Auth("nmundru", "abc123"));

                httpPost.setHeader("Content-Type", "text/plain; charset=utf-8");

                Log.v("httpPost", httpPost.toString());

                httpPost.setEntity(urlEncodedFormEntity);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                System.out.println("response...." + httpResponse.toString());
                Log.v("response...", httpResponse.toString());

                stream = httpResponse.getEntity().getContent();

                // save the InputStream in a file

                try {

                    FileOutputStream fOut = openFileOutput("settings.xml",
                            Context.MODE_WORLD_READABLE);

                    DataInputStream in = new DataInputStream(stream);
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(in));
                    String strLine;
                    while ((strLine = br.readLine()) != null) {
                         System.out.println(strLine); //to print the response
                        // in logcat
                        fOut.write(strLine.getBytes());

                    }
                    fOut.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                fis = openFileInput("settings.xml");

            } catch (Exception e) {
                Log.e(LOG_TAG, e.toString());

                // e.printStackTrace();
                tryagain();

            } finally {
                // https.disconnect();
            }

            publishProgress(R.drawable.loading_full,
                    R.drawable.loading_empty, R.drawable.loading_empty,
                    R.drawable.loading_empty, R.drawable.loading_empty);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block

            }
            publishProgress(R.drawable.loading_full,
                    R.drawable.loading_full, R.drawable.loading_empty,
                    R.drawable.loading_empty, R.drawable.loading_empty);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block

            }
            publishProgress(R.drawable.loading_full,
                    R.drawable.loading_full, R.drawable.loading_full,
                    R.drawable.loading_empty, R.drawable.loading_empty);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block

            }
            publishProgress(R.drawable.loading_full,
                    R.drawable.loading_full, R.drawable.loading_full,
                    R.drawable.loading_full, R.drawable.loading_empty);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block

            }
            publishProgress(R.drawable.loading_full,
                    R.drawable.loading_full, R.drawable.loading_full,
                    R.drawable.loading_full, R.drawable.loading_full);

            // Sleep for 1/2 second
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block

            return stream;
        }
    }

A:

Currently you're only returning the stream if the final try block throws InterruptedException, as your return statement is in the catch block. I think you meant to put the return statement one brace later - after the catch block. Otherwise, the end of the try/catch statement is reachable (because the try block might not throw an exception) which means you can get to the end of the method without returning anything - that's what the compiler's complaining about.
So instead of this:
protected synchronized InputStream getQueryResults(...) {
    ...
    // Indentation fixed for clarity
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       return stream;
    }
}

You want:
protected synchronized InputStream getQueryResults(...) {
    ...
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
       // TODO Auto-generated catch block
    }
    return stream;
}

If you had formatted your code appropriately - which your IDE would be happy to do for you - you'd have been able to see this more clearly for yourself, I suspect.

A:

instead of this:
  return stream;
    }
}

do this:
  }
return stream;
}


Q:

Как в vs Code выйти со скобки в конец строки комбинацией клавиш?

например var number = "word|"
или var arr = [2,3|]
Какой комбинацией клавиш выйти в конец строки(где стоит | это курсор) стрелка и end не выход

A:

Горячие клавиши настраиваются. File - Preferences - Keyboard Shortcuts

За переход к концу строки отвечает id - cursorEnd

значение горячих клавиш для которого можно поменять на удобные.


Q:

Django: How to catch InvalidPage exception in class-based views?

Django gives me 404 error when the page number is invalid (ex. localhost/?page=9999).
But I want to redirect it the the first page. In function-based views, this can be done by catching InvalidPage exception.
Does anyone know how to do it in class-based views.
Thanks in advance.

A:

Override get_paginator in your class and run your checks there. Then override dispatch to redirect or return the normal view:
class MyListView(ListView):
    ...
    def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True):
        paginator = super(MyListView, self).get_paginator(queryset, per_page, orphans=orphans, allow_empty_first_page=allow_empty_first_page)
        try:
            paginator.page(self.kwargs.get('page', 1))
        except EmptyPage: # or InvalidPage, but that's less precise
            self.is_empty = True

        return paginator

    def dispatch(self, request, *args, **kwargs):
        response = super(MyListView, self).dispatch(request, *args, **kwargs)
        if getattr(self, 'is_empty', False):
            return HttpResponseRedirect('/some/other/url/')
        else:
            return response


Q:

Can you apply an apostrophe to any word?

If I were to say The skill is could I say it as The skill's? Or would this not work? Also, if it does work, could I apply to it to any word?

A:

One of the functions of the apostrophe is as a written designation of missing letters. While it would probably be understood by native speakers that the word is is being shortened if you said, "The skill's hard to acquire," that's not really an accepted use of an apostrophe in written English. If you were to write dialogue, though, I think it would pass.
We do that in speech all the time for the verb is or has and other constructions that are not written out.

The dog's in the neighbor's yard again! (dog is)
The game's already started. (game has)

Could you apply it to any word? No more than you can use is or has after every word and have it make sense.


Q:

Is $\{(\epsilon + \cos(x))^{2k}\}_{k\in\mathbb{N}}$ a family of good kernels?

Show that for any $0<\delta<\pi$,
  $$\lim_{k\to \infty} c_k\int_{\delta<|x|<\pi} \left(\epsilon + \cos(x)\right)^{2k} dx = 0 $$
  where $\epsilon >0$ is some small number (for example, $0.01$) and $c_k$ is chosen so that
  $$\frac{c_k}{2\pi} \int_{-\pi}^\pi \left(\epsilon + \cos(x)\right)^k dx = 1$$

My ultimate goal is to show that trigonometric polynomial is dense. I understand that Fejer kernels is good kernels and they are trigonometric polynomials. But I am curious if there is a simpler construction.
In terms of what I am trying to prove here, I feel like the picture is clear. More specifically, when you raise $\epsilon + \cos(x)$ to the $2k$-th power, most of it will vanish since they have absolute value less than $1$. But I am having trouble coming up with a rigorous proof.
Unwrapping the definition, for any $\alpha>0$, we want to find $K$ such that whenver $k>K$, we have
$$c_k \int_{\delta<|x|<\pi} (\epsilon + \cos(x))^{2k} dx  < \alpha$$
Then the best thing I have is something like "Given  $\alpha$ and $\delta$, we can always raise the power enough times so that the $\epsilon + \cos(x)$ is small enough, and thus the whole integral gets small enough". I am not sure if this is rigorous enough though.
Any help is greatly appreciated.

A:

I would say that the double approximation
$$ \forall x\in\left[-\frac{\pi}{2},\frac{\pi}{2}\right],\qquad 1-\frac{x^2}{2}\leq\cos(x)\leq e^{-x^2/2}$$
is everything we need. By approximating $\varepsilon+\cos(x)$ with $(1+\varepsilon)\,e^{-\frac{x^2}{2(1+\varepsilon)}} $ we have that
$$ \int_{-\pi/2}^{\pi/2}\left(\varepsilon+\cos x\right)^{2k}\,dx \approx (1+\varepsilon)^{2k}\int_{\mathbb{R}}\exp\left(-\frac{kx^2}{1+\varepsilon}\right)\,dx = (1+\varepsilon)^{2k+\frac{1}{2}}\sqrt{\frac{\pi}{k}} $$
and the main contribute to the LHS is concentrated in a smaller and smaller neighbourhood of zero as $k\to +\infty$. That happens every time we consider a kernel strongly resembling a Gaussian kernel, since:
$$ \forall K>0,\qquad \int_{0}^{+\infty}e^{-K x^2}\,dx = \frac{1}{2}\sqrt{\frac{\pi}{K}},\qquad \int_{0}^{+\infty}x\cdot e^{-K x^2}\,dx = \frac{1}{2K}.$$


Q:

baseURL not working for UIWebView?

I am currently creating a UIWebView where I load a NSString that I get from my server service. its just a simple HTML string, then I load it into a UIWebView like this:
urlAddress = [[NSURL alloc] initWithString:URLString];

//try removing cache so new stylesheet shows everytime- not sure if this is working yet
[[NSURLCache sharedURLCache] removeAllCachedResponses];

[InfoWebview loadHTMLString:returnedHtmlString baseURL:urlAddress];

Then for some reason the images are not showing and the style sheet is not working.
For instance my baseURL looks like this
https://myserveraddress/

and then the code for the CSS looks like this
<link rel="stylesheet" type="text/css" href="Data/iPhone/my.css">

My questions are this
How does baseURL prefix itself onto that href? dose it request that css as the loadHTMLString loads onto the WebView? or something different
And How can I output the infoWebView source to NSString? to see if baseURL is prefixing itself onto those href links? or dose it now work like that?
Any help would be greatly appreciated.

A:

How does baseURL work?

Here are some helpful examples from the AFNetworking documentation:
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL];                  // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL];          // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL];                 // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL];                 // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL];                // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/

Basically, any files in your HTML will be assumed to be in the location specified in the Base URL.  If the HTML specifies files beginning with /, the domain name will stay the same but the path of the Base URL will be ignored.  If the HTML specifies files beginning with http(s)://, the entire Base URL will be ignored.
In your example, the URL would resolve to https://myserveraddress/Data/iPhone/my.css.

How can I output the infoWebView source to NSString?

A simple solution is:
NSString *html = [InfoWebview stringByEvaluatingJavaScriptFromString:
                                         @"document.body.innerHTML"];

More info and discussion on this topic is available on Stack Overflow here.


Q:

Shared Network install / config priority

I'd like to deploy Blender with a custom startup scene and some enabled addons on a network drive, so that every user here can run Blender from there with all the settings and addons.
Sounds easy enough, but the problem is that the users can't generate their own startup/settings because the config folder on the server has a higher priority than the user  config (they would change the settings for all users).
This doesn't make sense at all, and it is different in all other software I can think of. User settings shall always override system settings. Is there a special reason why it is that way in Blender? And even more important: is there a workaraound?
Thanks!

A:

Blender searches three places for a startup file in the following order -

local  - located next to the blender application.
user   - located in the users home folder.
system - located in a shared system location (like /usr/share)

When you save your settings it is saved to the same location as it would be read from at startup.
This works well with the way blender allows you to have multiple copies on your machine, each can have their own config settings unique to that copy.
In your situation you have the local settings in a shared location that you consider a system location.
One option is to compile your own version that ignores the local copy.
Another is to copy your initial startup file into place on each machine.
Maybe the users could start a small setup script instead of blender (or appears to be blender) that checks existence of user config and copies your initial setup to the users machine from the network drive, obviously not located in the proper startup location and then starts blender.


Q:

Why using import BaseHTTPServer in Python?

This is the code I got from Tutorial of how to make local server by using python script to run in Terminal
import SimpleHTTPServer
import SocketServer
import BaseHTTPServer
import os

HOSTNAME = "localhost"

PORT = 8000

HANDLER = SimpleHTTPServer.SimpleHTTPRequestHandler

os.chdir("/Users/Team/Desktop/python server")

httpd = SocketServer.TCPServer((HOSTNAME, PORT), HANDLER)

print "serving at port", PORT
httpd.serve_forever()

I wonder why they have to import the  BaseHTTPServer? can anyone explain me about that? below is the version from Python.org
import SimpleHTTPServer
import SocketServer

PORT = 8000

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

You'll see that there is no import BaseHTTPServer, can anyone explain to me why?
and these code are in Python 2.7 if I want to change it into python 3 Do I still need to import BaseHTTPServer?

A:

Importing it has has meaningful impact, as you have discovered. As for why it is there - who knows? Maybe the author of the tutorial intended to use it later in the tutorial, or maybe it was adapted from a larger sample. The point is if nothing is referencing it, you don't need to import it.
The same applies to python 3.


Q:

How to run Nginx within a Docker container and set it up to reload its configuration every 6h?

I'm runnign NGINX in a Docker container, and I'm trying to find a way to start it up using docker run in a way that would order my NGINX to reload its configuration every 6h. I need this to be done, because I also use Certbot in another container, and I'd like the SSL certificate renewal process to be automated and applied, and for that I neen NGINX to reload its configuration on schedule.
At this point I use the folowing docker run sequence (more or less):
docker run --restart=always -d -p 80:80 -p 443:443  \
  --name=nginx_RevPr nginx:latest                   \
  /bin/bash -c 'while :; do sleep 6h & wait ${!}; nginx -s reload; done & nginx -g "daemon off;"'
The container created this way is running and working fine. The only problem I have is that I actually don't know if NGINX is really realoading its configuration. docker logs doesn't show anything.
I'd like to approach this problem in a twofold way:

How can I output to terminal / docker logs (echo?) the succcessful nginx -s reload modifying my /bin/bash -c 'while :; do sleep 6h & wait ${!}; nginx -s reload; done & nginx -g "daemon off;"'?
In case I miss something (I'm a beginner for both Docker and NGINX): do you see a way to achieve the results I'd like to get in a more reasonable way?

Please don't suggest Docker Compose.
Thank you for your attention.

A:

OK, I got it working.
I changed the CMD args line to:
/bin/sh -c 'while :; do sleep 6h & wait ${!}; nginx -s reload && echo NGINX config reload for Certbot - OK; done & nginx -g "daemon off;"'
My main mistake was to enter the CMD using /bin/bash, where I should do /bin/sh. And the following nginx -s reload && echo NGINX config reload for Certbot - OK solved the problem with notyfying docker logs about config reload.


Q:

How much HP do the healing potions restore?

I'm still fairly low-level, and a minor healing potion still gets me to full HP, even if I'm almost dying. How many HPs do the different kind of Healing potions restore?

A:

From http://us.battle.net/d3/en/item/potion/:

Minor Health Potion: 250 life, req. level 1
Lesser Health Potion: 400 life, req. level 6
Health Potion: 550 life, req. level 11
Greater Health Potion: 1000 life, req. level 16
Major Health Potion: 1600 life, req. level 21
Super Health Potion: 2500 life, req. level 26
Heroic Health Potion: 4500 life, req. level 37
Resplendent Health Potion: 6500 life, req. level 47
Runic Health Potion: 9000 life, req. level 53
Mythic Health Potion: 12500 life, req. level 58


Q:

$\mathbb Z^n$ as a quotient of $\mathbb Z^m$

It is quite obvious that if $n\le m$, the group $\mathbb Z^n$ can be obtained as a quotient of $\mathbb Z^m$. But is the converse statement also true? That is, if $\mathbb Z^n$ is a quotient of $\mathbb Z^m$, is $n\le m$? In that case, is there an easy proof?

A:

A basis of $\mathbb{Z}^m$ has $m$ elements. Therefore every quotient of $\mathbb{Z}^m$ is generated by $m$ (or fewer) elements. If $\mathbb{Z}^n$ is a quotient of $\mathbb{Z}^m$, it is therefore generated by at most $m$ elements. And if $\mathbb{Z}^n$ is generated by $k$ elements $\{a_1,\dotsc,a_k\}$, the images $\{b_1,\dotsc,b_k\}$ of these elements in $Q = \mathbb{Z}^n/(2\mathbb{Z}^n)$ generate $Q$. We can view $Q$ in a natural way as a vector space over $\mathbb{F}_2$, since every element of $Q\setminus \{0\}$ has order $2$. On the one hand, we know that $Q$ contains $2^n$ elements, so the dimension is $n$. On the other hand, it is generated as a group, hence as an $\mathbb{F}_2$-vector space, by the $k$ elements $\{b_1,\dotsc,b_k\}$, hence $n = \dim_{\mathbb{F}_2} Q \leqslant k$.

A:

If we have a surjective homomorphism $f\colon\mathbb{Z}^m\to\mathbb{Z}^n$, then this homomorphism splits, so
$$
\mathbb{Z}^m\cong\ker f\oplus\mathbb{Z}^n.
$$
Tensoring with $\mathbb{Q}$ gives
$$
\mathbb{Q}^m\cong(\ker f\otimes\mathbb{Q})\oplus\mathbb{Q}^n
$$
and therefore $n\le m$.


Q:

Scraping tr class information using Excel VBA

I've created a simple program in Excel VBA to scrape all the information in a table from https://www.nasdaq.com/market-activity/stocks/aapl/financials. I've used similar code for other websites but for some reason I can't get this one working. Can anyone point what I'm missing? Any help would be much appreciated.
"EDITED CODE"
Public Sub GetCompanyFinancials()

Dim XMLPage As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim HTMLTables As MSHTML.IHTMLElementCollection
Dim HTMLTable, HTMLRow, HTMLCell As MSHTML.IHTMLElement

XMLPage.Open "GET", "https://www.nasdaq.com/market-activity/stocks/aapl/financials", False
XMLPage.send

HTMLDoc.body.innerHTML = XMLPage.responseText

Set HTMLTables = HTMLDoc.getElementsByTagName("table")

For Each HTMLTable In HTMLTables
    For Each HTMLRow In HTMLTable.getElementsByTagName("tr")
        For Each HTMLCell In HTMLRow.Children
            Debug.Print HTMLCell.innerText
        Next HTMLCell
    Next HTMLRow
Next HTMLTable

End Sub

A:

I'm sure there are MANY ways to do this kind of thing.  Here is one.
Sub Web_Table_Option_Two()
    Dim HTMLDoc As New HTMLDocument
    Dim objTable As Object
    Dim lRow As Long
    Dim lngTable As Long
    Dim lngRow As Long
    Dim lngCol As Long
    Dim ActRw As Long
    Dim objIE As InternetExplorer
    Set objIE = New InternetExplorer
    objIE.Navigate "https://www.nasdaq.com/market-activity/stocks/aapl/financials"

    Do Until objIE.ReadyState = 4 And Not objIE.Busy
        DoEvents
    Loop
    Application.Wait (Now + TimeValue("0:00:03")) 'wait for java script to load
    HTMLDoc.body.innerHTML = objIE.Document.body.innerHTML
    With HTMLDoc.body
        Set objTable = .getElementsByTagName("table")
        For lngTable = 0 To objTable.Length - 1
            For lngRow = 0 To objTable(lngTable).Rows.Length - 1
                For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
                    ThisWorkbook.Sheets("Sheet1").Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
                Next lngCol
            Next lngRow
            ActRw = ActRw + objTable(lngTable).Rows.Length + 1
        Next lngTable
    End With
    objIE.Quit
End Sub

Result:


Q:

passing a function to replace with regex with match as arg

This javascript code needs to pass the invoke the function convert and use its returned value to replace every match. But it is not sending the cid value to the convert function. Any idea how to? Thanks
const convert = function (cid) {
    console.log('got: ' + cid); // got NAN
    const converted = Math.round(Number(cid) * 16.3871);
    console.log(converted);
    return converted
};
    return myStr.replace(/(\d{3})/g, convert('$1'));
}

A:

Don't invoke the convert function as the second replace parameter. It will be invoked automatically and pass $1 match on its own as 1st convert argument.
And the second return is incorrect (out of function).
const convert = function (cid) {
      console.log('got: ' + cid); // got NAN
      const converted = Math.round(Number(cid) * 16.3871);
      console.log(converted);
      return converted;
    };

var someString = 'abc134def';

console.log(someString.replace(/(\d{3})/g, convert));


Q:

MySQL is not using INDEX in subquery

I have these tables and queries as defined in sqlfiddle.
First my problem was to group people showing LEFT JOINed visits rows with the newest year. That I solved using subquery.
Now my problem is that that subquery is not using INDEX defined on visits table. That is causing my query to run nearly indefinitely on tables with approx 15000 rows each.
Here's the query.  The goal is to list every person once with his newest (by year) record in visits table.
Unfortunately on large tables it gets real sloooow because it's not using INDEX in subquery.
SELECT *
FROM people
LEFT JOIN (
  SELECT *
  FROM visits
  ORDER BY visits.year DESC
) AS visits
ON people.id = visits.id_people
GROUP BY people.id

Does anyone know how to force MySQL to use INDEX already defined on visits table?

A:

Your query:
SELECT *
FROM people
LEFT JOIN (
  SELECT *
  FROM visits
  ORDER BY visits.year DESC
) AS visits
ON people.id = visits.id_people
GROUP BY people.id;

First, is using non-standard SQL syntax (items appear in the SELECT list that are not part of the GROUP BY clause, are not aggregate functions and do not sepend on the grouping items). This can give indeterminate (semi-random) results.
Second, ( to avoid the indeterminate results) you have added an ORDER BY inside a subquery which (non-standard or not) is not documented anywhere in MySQL documentation that it should work as expected. So, it may be working now but it may not work in the not so distant future, when you upgrade to MySQL version X (where the optimizer will be clever enough to understand that ORDER BY inside a derived table is redundant and can be eliminated).

Try using this query:
SELECT
    p.*, v.*
FROM
    people AS p
  LEFT JOIN
        ( SELECT
              id_people
            , MAX(year) AS year
          FROM
              visits
          GROUP BY
              id_people
         ) AS vm
      JOIN
          visits AS v
        ON  v.id_people = vm.id_people
        AND v.year = vm.year
    ON  v.id_people = p.id;

The: SQL-fiddle
A compound index on (id_people, year) would help efficiency.

A different approach. It works fine if you limit the persons to a sensible limit (say 30) first and then join to the visits table:
SELECT
    p.*, v.*
FROM
    ( SELECT *
      FROM people
      ORDER BY name
        LIMIT 30
    ) AS p
  LEFT JOIN
    visits AS v
      ON  v.id_people = p.id
      AND v.year =
    ( SELECT
          year
      FROM
          visits
      WHERE
          id_people = p.id
      ORDER BY
          year DESC
        LIMIT 1
     )
ORDER BY name ;


Q:

List of a subclass within its class

The context here is a school project for a Library system, the library has both magazines and books.
We have an abstract class Register which is extended by Book and Magazine. Now there's need to implement a Copy class , that can be used for both books and magazines, which contains return date, owner, yadda yadda.
Now this has become very confusing for us, Copy should extend either Book or Magazine, and these two must have an ArrayList of their copies inside them.
I'm sorry for the lack of especification in the question but we're absolutely stuck and confused on the matter of implementing a subclass list within its superclass.

A:

From your description, seems that Copy class should not extend any of those classes, but instead have an association to Register, like this:
public class Copy {
    Register original;
    Register copy;
}

In this way, you can know the original Register instance and the copy of this. The problem with the above design is that you can have an original of type Book and a copy of type Magazine, or viceversa. To solve this, you can use generics:
public class Copy<T extends Register> {
    T original;
    T copy;
}

Then, in Book class, you may have something like this:
public class Book {
    List<Copy<Book>> copies;
}


Q:

Measuring Q and Bandwidth of an RLC series circuit using Oscilloscope

I have a HNC Lab assignment coming up. As part of the prep for the lab work we have been given an RLC series circuit for which we had to calculate some values such as volt drop , Wn, Q and Bs, which I've since done. We then have to use simulation software, in this case Multisim, to simulate the circuit and compare the values measured to the values calculated.
Currently I'm stuck on measuring q factor and bandwidth within Multisim. I'm assuming an oscilloscope should be used but I'm unsure where it should be connected and how to interpret the plot received. I've been searching google for a couple of days but cannot find any information.
The values of the circuit are R 500Ohms, L 56mH, C10nF, Vs 5Vpk @ 10KHz.
I used Wn = 1/ Sqrt(LC) to calculate the resonant frequency, which came to 42.258k. I've confirmed this within multisim.
Any help would be much appreciated.

A:

Bandwidth is an AC parameter, so you should run an AC sweep to find it. I haven't used Multisim in years, but I seem to recall there being a Simulation menu, and it was in there. From there you can calculate Q using the definition \$Q=\dfrac{f_r}{\Delta f}\$.


Q:

How to use View Binding with Included Views?

View Binding got released with v3.6.
Docs:
https://developer.android.com/topic/libraries/view-binding
My question is, does anyone know how to use view binding with included layouts?
Given Layout that includes another Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/my_header"
        layout="@layout/item_header"
        android:layout_width="match_parent"
        android:layout_height="100dp" />

</LinearLayout>

I am trying to reference items inside of the item_header layout.
binder.my_header (<-- this just returns back the view)
binder.root (<-- this just returns back the root view)

Even if I add an id to the root of the item_header, such as id="@+id/parent_id" and try to reference that, I receive null pointer exceptions
binder.parentId (<-- I have access to views inside of the item_header, however, I receive exceptions. Says that "parentId" cannot be found)

How to reference the layout, item_header?

A:

Let's suppose that the layout in your question is activity_main.xml. The generated view binding class for it is ActivityMainBinding. Similarly, for item_header.xml, the generated view binding is ItemHeaderBinding.
If we pretend that item_header.xml has a TextView named @+id/foo, then you wind up with this chunk of Kotlin:
class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val mainBinding = ActivityMainBinding.inflate(layoutInflater)

    setContentView(mainBinding.root)

    mainBinding.myHeader.foo.text = "this is a test"
  }
}

So, the ActivityMainBinding object should have a property with the android:id that you gave to the <include> — myHeader in this case. That should be an ItemHeaderBinding, as view binding appears to set up the nested binding object for the <include>. Since myHeader is an ItemHeaderBinding, you can then reference widgets on it just as you would if you directly inflated ItemHeaderBinding yourself.
Note that view binding appears to convert lower_snake_case into lowerCamelCase, so the my_header ID turns into myHeader in terms of the generated code.


Q:

Node Multer diskStorage filename not working

I'm using the diskStorage engine to assign the destination and filename to images being received by my API. Here is my code:
const express = require('express')
const router = express.Router()

const multer = require('multer')
const destination = 'imgs/'
const filename = (req, file, cb) =>{cb(null, new Date().toISOString + '_' + file.originalname)}
const storage = multer.diskStorage({destination, filename})
const upload = multer({storage: storage})

const Imagen = require('../dataaccess/model/Imagen')

Everything works fine except the naming of my file. Instead of my file being named something like:
'YYYY-MM-DDTHH:mm:ss.sssZ_file.jpeg'

it's named:
'function toISOString() { [native code] }_t1.jpg'

Below is the endpoint code:
router.post('/img/new', upload.single('newImage'), async (req, res)=>{

    /**
     * Validación de la existencia del archivo en la petición
     */
     if(!req.file){
         res.status(400).json({
             'message' : 'Error en los parámetros. No hay ningún archivo.',
             'req' : res.body,
         })
     }

    var username = req.body.username;
    let fecha = new Date();

    /**
     * Validación de los parámetros obligatorios
     */

     if(!username || !fecha){
         res.status(400).json({
             'mensaje' : 'Parámetros incompletos',
             'error' : err
         })
         return
     }

     /**
      * Creación del nuevo Objeto Imagen
      */
     var img = new Imagen({
         username: username,
         fecha: fecha,
         path: req.file.path
     })

     await img.save( function (err, doc){
         if(err){
             res.status(500).json({
                 'mensaje' : 'Hubo un error al subir la imagen',
                 'error' : error
             })
             console.error(err)
             return
         }
         res.json(doc)
     })
}),

A:

Notice this line const filename = (req, file, cb) =>{cb(null, new Date().toISOString + '_' + file.originalname)};. You are not calling toISOString function. Your code should look like this:
const filename = (req, file, cb) =>{cb(null, new Date().toISOString() + '_' + file.originalname)};

Hope it helps.


Q:

Knockout Observable array not being observed?

Let me start with a screencast of the current behaviour. As you can see, when I add a role for the user jbrown, the role doesn't show where it should!
But if I navigate away to another user, then back to jbrown, the role(s) does show!
Here is the ViewModel in question:
function UsersViewModel() {
  var self = this;
  // data with some removed for brevity
  self.isLoaded = ko.observable(false);
  self.selectedUser = ko.observable();
  self.SelectedUserHasRoles = ko.computed(function () {
    if (self.isLoaded()) {
      return self.selectedUser().roles().length > 0;
    }
    return false;
  });

  self.UserHasAllAvailableRoles = ko.computed(function () {
    if (self.isLoaded()) {
      return self.userAvailableRoles().length === 0;
    }
    return false;
  });

  // isLoaded gets set to true when AJAX call to server
  // is a success and data is returned

  // operations with some removed for brevity
  self.setCurrentUser = function (user) {
    const newRolesArray = self.roles().filter(function (role) {
      return !contains(user.roles(), role);
    });
    self.userAvailableRoles(newRolesArray);
    self.selectedUser(user);
  }

  self.addUser = function () {
    self.users.push(new User({ Username: this.newUsernameText() }));
    self.newUsernameText('');
    self.NewUserFormIsVisible(false);
    self.AddRolesFormIsVisible(true);
    self.setCurrentUser(self.users()[self.users().length - 1]);
  };

  self.addRoleForSelectedUser = function() {
    self.selectedUser().roles().push(new Role({ Name: self.selectedRole().name() }));
    self.AddRolesFormIsVisible(false);
    $.post('http://localhost:23926/admin/acl/addusertorole', { username: self.selectedUser().name(), role: self.selectedRole().name() },
    function () {
      console.log('user role created at db!');
    },
    'json');
  }
}

And here is the HTML markup in question:

My Observable array of roles must be getting populated because as you saw, when I navigate away and back, I can see the roles I've added.
What am I missing?

A:

You're trying to push the new role to the underlying, untracked, array instead of the observable array.
self.addRoleForSelectedUser = function() {
    self.selectedUser().roles().push(new Role({ Name: self.selectedRole().name() }));
    ...
}

You just need to remove the set of parenthesis after "roles" so that it looks like:
self.selectedUser().roles.push(new Role({ Name: self.selectedRole().name() }));


Q:

Sending mass notifications with signalR and hangfire, saving server resources

I'm programming a SignalR push notification system that uses a hangfire task to push notifications to all the users, lets assume i have 10,000 users and i want to notify them when their account is one month old in the website, what would be more efficient?  Assigning one scheduled task per user to be executed one month after the registration or having a Hangfire task that runs daily and finds me the users that have one month old accounts and notify them.
The task to assign to hangfire will be the following:

Deactivate inactive profiles and send an email telling the user their account has been deactivated.
Close posts or inquiries that been inactive for x amount of time and notify them via notification
The system should be able to find top 10 posters and notify them via email and website notification they have been selected to have extra benefits.
The task will notify in real time every hour to all the users what was their best score for that week.

Thanks in advance.

A:

Your solution sounds extremely complex for something as simple as this. Are all of these users online all the time? So do you really need to use SignalR for this? Or even Hangfire?
Normally you would do it like this, when user loads a page check if account is over month old and show notification in the UI. Or is there are a reason you can't do it like this?


Q:

Does an actionscript for loop run backwards?

I have discovered something that really baffles me concerning the actionscript for-loops.
I have an AIR app that has a for loop:
for (var k:int = 0; k < 10; k++)
{
   Alert.show(k.toString(), "Message", Alert.YES);
}

But the output starts at 10 counting backwards to 0. Is this just all in the way AIR is compiled at runtime or does the loop actually run backwards?

A:

The loop itself does not run backwards, of course. When you pop up a new Alert using Alert.show(..., the Alert shows on top of everything else already displayed.
So, your first Alert, with "0" pops up first.
Next, the Alert with "1" pops up (on top of the Alert with "0")
...
Finally, the Alert with "9" pops up (on top of the other Alerts)


Q:

How to make a child DIV remove color transparency from a parent with 40% transparent color on an image?

I have a parent div with:
background-image: url('img.jpg');
background-color: rgba(0,0,0,0.4);
and a child div:
width: 400px;
height: 400px;

How to make the child DIV show a part of the parent's background-image without the black transparency?

.parent {
  width: 500px;
  height: 500px;
  background: url('http://i.imgur.com/Y6a49hy.png');
}

.child {
  background-color: rgba(0, 0, 0, 0.7);
  width: 100%;
  height: 100%;
}

.non-shadowed-div {
  width: 300px;
  height: 300px;
}

      This div shouldn't be shadowed like the rest of the square

A:

One option is to do it with box-shadow:

.outer {
  background: url('https://fillmurray.com/400/200') no-repeat center;
  height: 600px;
  width: 100%;
  background-size: cover;
  position: relative;
  overflow: hidden
}

.inner {
  position: absolute;
  top: 25%;
  left: 25%;
  width: 50%;
  height: 50%;
  background: transparent;
  box-shadow: 0 0 0 1000px rgba(0,0,0,.5);
}

lalalalala


Q:

In-App Purchase screen is not as expected for beta testing

I am testing an app via test flight right now. When I am testing the in-app purchase portion of the app, it asks me for my app store username and password. I was not expecting this (I was expecting the standard faceID or TouchID in-app purchase interface to come up).
The developer says I must enter in my password when prompted. I do not want to do this as I am expecting a different kind of experience.
The app the developer has uploaded is prompting me with this prompt:
https://d.pr/i/LGfZ5V
And is asking me for my password. Which I don’t want to give.
I would expect something like this instead:
https://d.pr/i/b4l4xg
Which is the normal in-app purchasing experience I am used to.
The developer says it is a limitation of test flight for beta apps. However, I am not sure. Does anyone here know if this is legitimate? Or is it something the developer just may not be aware of?

A:

What you are seeing is the correct experience when testing in-app purchases in a TestFlight version. That prompt comes from Apple when you initiate a purchase.


Q:

remove HTML tags from cell strings : excel Formula

I have a Data with HTML tags in excel sheet like below:
This is test data
Nice

 Go on this is next Cell
Very goood .....

SO, Basically I want to delete or replace all html tags with space in excel sheet.

A:

Apply Replace All with <*> pattern:

To open this go to Ribbon Home > Find & Select > Replace... or simply press CTRL+H.
Extra spaces may be further removed using TRIM function. Good luck!

A:

Open VBA in Excel (Alt +F11), click on the project name (spreadsheet name) in the project explorer on the right. Insert -> New Module. Paste the user defined function below into the module Window. Save as .XLSM which allow Macros.
type the function '=StripHTML(A2)' assuming your data is in cell A2. You can also download a working example here:
http://jfrancisconsulting.com/how-to-strip-html-tags-in-excel/
Function StripHTML(cell As Range) As String
    Dim RegEx As Object
    Set RegEx = CreateObject("vbscript.regexp")
    Dim sInput As String
    Dim sOut As String
    sInput = cell.Text

    sInput = Replace(sInput, "\x0D\x0A", Chr(10))
    sInput = Replace(sInput, "\x00", Chr(10))

    'replace HTML breaks and end of paragraphs with line breaks
    sInput = Replace(sInput, "
", Chr(10) & Chr(10))
    sInput = Replace(sInput, "
", Chr(10))

    'replace bullets with dashes
    sInput = Replace(sInput, "
", "-")

    'add back all of the special characters
    sInput = Replace(sInput, "–", "–")
    sInput = Replace(sInput, "—", "—")
    sInput = Replace(sInput, "¡", "¡")
    sInput = Replace(sInput, "¿", "¿")
    sInput = Replace(sInput, """, "")
    sInput = Replace(sInput, "“", "")
    sInput = Replace(sInput, "”", "")
    sInput = Replace(sInput, "", "'")
    sInput = Replace(sInput, "‘", "'")
    sInput = Replace(sInput, "’", "’")
    sInput = Replace(sInput, "«", "«")
    sInput = Replace(sInput, "»", "»")
    sInput = Replace(sInput, " ", " ")
    sInput = Replace(sInput, "&", "&")
    sInput = Replace(sInput, "¢", "¢")
    sInput = Replace(sInput, "©", "©")
    sInput = Replace(sInput, "÷", "÷")
    sInput = Replace(sInput, ">", ">")
    sInput = Replace(sInput, "<", "<")
    sInput = Replace(sInput, "µ", "µ")
    sInput = Replace(sInput, "·", "·")
    sInput = Replace(sInput, "¶", "¶")
    sInput = Replace(sInput, "±", "±")
    sInput = Replace(sInput, "€", "€")
    sInput = Replace(sInput, "£", "£")
    sInput = Replace(sInput, "®", "®")
    sInput = Replace(sInput, "§", "§")
    sInput = Replace(sInput, "™", "™")
    sInput = Replace(sInput, "¥", "¥")
    sInput = Replace(sInput, "á", "á")
    sInput = Replace(sInput, "Á", "Á")
    sInput = Replace(sInput, "à", "à")
    sInput = Replace(sInput, "À", "À")
    sInput = Replace(sInput, "â", "â")
    sInput = Replace(sInput, "Â", "Â")
    sInput = Replace(sInput, "å", "å")
    sInput = Replace(sInput, "Å", "Å")
    sInput = Replace(sInput, "ã", "ã")
    sInput = Replace(sInput, "Ã", "Ã")
    sInput = Replace(sInput, "ä", "ä")
    sInput = Replace(sInput, "Ä", "Ä")
    sInput = Replace(sInput, "æ", "æ")
    sInput = Replace(sInput, "Æ", "Æ")
    sInput = Replace(sInput, "ç", "ç")
    sInput = Replace(sInput, "Ç", "Ç")
    sInput = Replace(sInput, "é", "é")
    sInput = Replace(sInput, "É", "É")
    sInput = Replace(sInput, "è", "è")
    sInput = Replace(sInput, "È", "È")
    sInput = Replace(sInput, "ê", "ê")
    sInput = Replace(sInput, "Ê", "Ê")
    sInput = Replace(sInput, "ë", "ë")
    sInput = Replace(sInput, "Ë", "Ë")
    sInput = Replace(sInput, "í", "í")
    sInput = Replace(sInput, "Í", "Í")
    sInput = Replace(sInput, "ì", "ì")
    sInput = Replace(sInput, "Ì", "Ì")
    sInput = Replace(sInput, "î", "î")
    sInput = Replace(sInput, "Î", "Î")
    sInput = Replace(sInput, "ï", "ï")
    sInput = Replace(sInput, "Ï", "Ï")
    sInput = Replace(sInput, "ñ", "ñ")
    sInput = Replace(sInput, "Ñ", "Ñ")
    sInput = Replace(sInput, "ó", "ó")
    sInput = Replace(sInput, "Ó", "Ó")
    sInput = Replace(sInput, "ò", "ò")
    sInput = Replace(sInput, "Ò", "Ò")
    sInput = Replace(sInput, "ô", "ô")
    sInput = Replace(sInput, "Ô", "Ô")
    sInput = Replace(sInput, "ø", "ø")
    sInput = Replace(sInput, "Ø", "Ø")
    sInput = Replace(sInput, "õ", "õ")
    sInput = Replace(sInput, "Õ", "Õ")
    sInput = Replace(sInput, "ö", "ö")
    sInput = Replace(sInput, "Ö", "Ö")
    sInput = Replace(sInput, "ß", "ß")
    sInput = Replace(sInput, "ú", "ú")
    sInput = Replace(sInput, "Ú", "Ú")
    sInput = Replace(sInput, "ù", "ù")
    sInput = Replace(sInput, "Ù", "Ù")
    sInput = Replace(sInput, "û", "û")
    sInput = Replace(sInput, "Û", "Û")
    sInput = Replace(sInput, "ü", "ü")
    sInput = Replace(sInput, "Ü", "Ü")
    sInput = Replace(sInput, "ÿ", "ÿ")
    sInput = Replace(sInput, "", "´")
    sInput = Replace(sInput, "", "`")

    'replace all the remaining HTML Tags
    With RegEx
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
    .Pattern = "<[^>]+>" 'Regular Expression for HTML Tags.

    End With
    sOut = RegEx.Replace(sInput, "")
    StripHTML = sOut
    Set RegEx = Nothing
    End Function


Q:

Prevent batch file in CMD from closing without using Pause

Currently I want to run a batch file that fires the command git log and show me that log.
After that I need to be able to commit and view the status so this prompt may not disappear after a key press.
I've searched the net and the only answer people have is pause which close the prompt after a keypress.
Does anyone have the solution for me? Currently I made a shortcut to cmd.exe and made the target my folder, but I want to execute some commands also.
Thanks in advance.

A:

This (below) tested OK in Windows 7.  To exit the window it creates, type "exit" when done.

start cmd /K "cd \[the-target-folder] && git log"

Where:
  [the-target-folder] you replace with your target folder
Note:
  && lets you run two commands on one line
  /K is a parameter to the cmd shell program which which carries out the command specified by string and remains.


Q:

What is the correct WCF net.tcp binding security for this scenario?

I have a WCF service which is hosted in a Windows Service and has net.tcp endpoint. The clients are in the same LAN (Workgroup) as the service but they don't have the server's Windows user accounts.
PS: When I set the Security.Mode to None in both client and server, I receive the following error:

The requested upgrade is not supported
  by '{SERVICE ADDRESS}'This could be due to mismatched
  bindings (for example security enabled
  on the client and not on the server).

A:

Nettcp binding is secure by default, your clients must provide Windows credentials because all messages are signed and encrypted over tcp. Setting it to none will probably cause a problem, you'll want something like:
<netTcpBinding>
     <binding name="netTcp">
       <security mode="Transport">
         <transport clientCredentialType="Windows" />
       </security>
     </binding>
</netTcpBinding>

A:

OK, I solved the problem.
I don't know why it is like this, but if I uncheck the "Use simple file sharing" in Folder Options of the server, everything works perfectly.


Q:

What is the correct way of returning a file in a Rest webservice request?

I need to return a file in my webservice. I am bit in doubt of what is the best/correct/execpted way. (I am using JSON).
I can:

simply return the file (as normal download) with the correct mime type, etc. via HTTP
encode de file (eg: Base64 or other) and send it inside the JSON answer
return a json answer with the url where the file can be found.

A:

All three are valid, depending on the client's needs, so why not make it the client's choice?
Let's say it's an image/jpeg file:
If the client sent the Accept: image/jpeg header, you return the file as a normal download.
If the client sent the Accept: image/jpeg header and the Accept-Encoding: base64, you return it as a normal download, Base64 encoded.
If the client sends the Accept: text/uri-list header, you return a plain text response with the URI for the image stored somewhere else.
There are no standard mimetypes to return base64 or links inside json, but you can use some standard of your own and create a vnd mimetype, as long as you document it.


Q:

If $NP \neq co-NP$ then no $NP-complete$ problem can be in $co-NP$

If $NP \neq co-NP$ then no $NP-complete$ problem can be in $co-NP$.
I found a proof on Wikipedia that I didn't fully get:
https://en.wikipedia.org/wiki/Co-NP
In the line "from this it follows that the set of complements..". Why does it follow? It seems like the author took a complement from both sides of the equation, but that can't be right, can it?

A:

We will show the contrapositive: if some NP-complete problem is in coNP, then NP=coNP. Suppose that $L$ is some NP-complete problem which is in coNP. Let $A$ be any problem in NP. Then there is a polytime reduction $f$ from $A$ to $L$ (since $L$ is NP-complete), which means that $x \in A$ iff $f(x) \in L$. Since $L$ is in coNP, this shows that $A$ is in coNP. Hence NP is a subset of coNP.
Now let $B$ be any problem in coNP. Then there is a polytime reduction $f$ such that $x \in B$ iff $f(x) \in \overline{L}$ (since $L$ is NP-complete and $\overline{B}$ is in NP). Since $\overline{L}$ is in NP, this shows that $B$ is in NP, and so coNP is a subset of NP. We conclude that NP=coNP.


Q:

Calculating In Degree and Out Degree in a single query

I could use the below query for "In Degree" successfully:
match a=(p:Person)-->(q:Person{Address:'0xa1e4380a3b1f749673e270229993ee55f35663b4'})
RETURN count(a) as In_Degree

I could use the below query for "Out Degree" successfully:
match a=(p:Person)<--(q:Person{Address:'0xa1e4380a3b1f749673e270229993ee55f35663b4'})
RETURN count(a) as Out_Degree

But when I club both and write the query as below, then Cypher is giving the result of "Out Degree".
match a=(p:Person)-->(q:Person{Address:'0xa1e4380a3b1f749673e270229993ee55f35663b4'}),b=(r:Person)<--(s:Person{Address:'0xa1e4380a3b1f749673e270229993ee55f35663b4'})
RETURN count(a) as In_Degree, count(b) as Out_Degree

Am I missing something here? Could someone help me with this please?

A:

Can you try this query :
MATCH (p:Person{Address:'0xa1e4380a3b1f749673e270229993ee55f35663b4'})
RETURN size((p)<--(:Person)) AS In_Degree, size((p)-->(:Person)) AS Out_Degree

Cheers.


Q:

What's wrong with this proof? (Regular languages)

We want to show that for any fixed $n$, $\bigcup_{i=1}^n L_i$ is regular when all $L_i$ are regular.
I understand that this is only true for finite $n$. However, what's wrong with the following proof for infinite $n$ by induction?
Define $L^k$ to be $\bigcup_{i=1}^k L_i$.
For the basis step, we choose $n=1$. Then we have $L^k = L^1 = L_1$ which is regular by definition.
For the inductive hypothesis, let us assume that $L^k$ is regular with $k < n$. Then by the definitions of regular expressions, $L^k \bigcup L_{k+1}$ is also regular. But this is $L^{k+1}$ and so $L^{k+1}$ is regular.
Again, I understand why $n$ cannot be infinite. I am interested as to what point this proof is wrong.

A:

If you want to prove something for all ordinals, you usually need to do transfinite induction and you have two inductive steps to deal with: (i) successor ordinals: from $\phi(\alpha)$ conclude $\phi(\alpha+1)$ and (ii) limit ordinals: from $\phi(\alpha)$ for all $\alpha < \lambda$, conclude $\phi(\lambda)$. If you only do the successor case, you have proved that $\phi(n)$ holds for all finite $n$, but you can't conclude that $\phi(\alpha)$ holds for any infinite $\alpha$ (the canonical counter-example is when $\phi(\alpha)$ is defined to mean $\alpha$ is finite).


Q:

Uniqueness of the number of degrees of freedom

As per my knowledge, degrees of freedom of any physical system are the number of independent quantities(coordinates) which need to be specified in order to specify the state of a system uniquely. However, my question is, why is there a unique number of degrees of freedom for any system?
Or, to put it differently, if a set of $n$ independent coordinates describes the state of the system completely, why is it true that any other set of $n$ independent coordinates also describes the state of the system completely?
And why can there not be a set of $m$ independent coordinated which also describe the state of the system completely, where $m>n$ ?

A:

I think that the term "degree of freedom" had been initially derived from the observation that the system may be completely described by $n$ independent coordinates - they said: "well, if this $n$ is really a characteristic of the system - let's give it a name!". It is my personal belief that the name comes from a classical kinematics: if a body can't move "freely" in some direction - this reduces $n$ by one.
Therefore, your question may be reduced to the following one: "why the number of independent coordinates which describe the system completely does not depend on coordinates themselves?". Am I right here?
Mathematical answer:
We describe systems by means of linear algebra. There is a concept of a basis in linear algebra: a (minimal) set of independent vectors is a basis, while the projection of any vector from a state-space of a system on this set preserves the norm of the state-space vectors (there are many alternative definitions).
What the above definition says is that if you find a set of (independent) vectors, and can represent any state of the system in terms of these vectors without loosing any information - this set of vectors is a basis.
Why do we require the set of vectors to be minimal? Well, you can add another independent vector to this set, but if the system has no component in this additional coordinate - this vector is redundant. Real life example: you can describe the position of a body using three vector coordinates (x, y, z). You can expand this set of three vectors with a vector of velocity of the wind (which is clearly independent with any of the positional vectors of the body), but we need not worry what the wind is. We are measuring the position of a body.
So, we have a basis, what now? Well, there is a theorem in linear algebra which proves that if you have a basis for the state-space, and you find another basis, then the dimensions of these bases are the same. This means that you always need exactly $n$ independent coordinates to describe the system completely (without loss of information).
Intuitive answer:
This one is very tricky, because all the discussion about "coordinates" and "independence" is bound to the framework of linear algebra. Really, I find it very hard to reason the above statements intuitively.
Maybe this: assume that there is finite number of properties of interest in the system (as it is usually the case). You are given $n$ boundary conditions which are not related - none of them can be derived from the rest. In this case, each boundary condition allows you to express a single property of your system. If you find that these $n$ boundary conditions describe all the properties of interest - this means that you have $n$ properties of interest.
Now, if you're given with $m > n$ unrelated boundary conditions, you can express $m$ properties of your system. However, we have already shown that you have just $n$ properties of interest. Conclusion: the $m$ unrelated boundary conditions describe $m - n$ parameters which you are not interested in. Throw them away because they obscure your view.


Q:

Interactive Text Area with Strict Guidelines

I'm trying to build an interactive text area where a user must enter specific text.
So for example I may ask a user to enter the answer to 'Does a dog bark?' If the user enters 'Yes' the box will turn green and if they enter anything else the box will turn red (green indicating correct and red indicating wrong).
I hope that is clear? Any help would be much appreciated!

A:

This is not possible in HTML. The closest you can get is to use the pattern attribute on an input element, as in <input pattern=Yes>. But the handling of valid vs. invalid input will then be at the hands of the browser, if it supports this attribute. Any controlled styling and/or functional handling of valid vs. invalid input needs to be handled with CSS and/or JavaScript or server-side form handlers.
If you define where the handling should take place, the problem becomes tractable. Note that if you check the input client-side, the correct answer will be visible to any user who views the source code (though you can try to obfuscate it).


Q:

What tactics can I use to prevent users from discovering what language a website is written in?

So, if you are writing a website using Java and JSP's and didn't want users to know what language you written it in. What techniques would you use?

A:

If you are using some sort of framework, like Struts2, you'll have an extension (*.action, or whatever you choose) mapped to the dispatcher servlet. The dispatcher "forwards" the request to the JSP, which is in the WEB-INF directory. Users only see the URL that was directed to the servlet, and get back HTML. They can't tell what the template language was. Since you can choose whatever you like for the servlet mapping, you could make something up, or even misdirect them with something like ".php" or ".asp".
Of course, you might have some JSPs right in the web app directory, rather than in WEB-INF. You can give these a different extension, and tell the container to process them as JSPs by creating a <jsp-property-group> with a url-pattern element that specifies the fake extension in web.xml.
You'll also need to examine your container's documentation to determine how to hide any server version information that might be sent. Another thing to explore is how to change the session cookie name to something other than "jsessionid". That's a bit of a giveaway, but it's part of the Servlet specification, and some containers don't support changing it.

A:

Along with other answers here, you'll want to make sure you're handling your application errors correctly. If you let an Exception out and the web container handles it, it'll be pretty obvious what you're using.


Q:

EditBoxPreference() storing the value as an int instead a string

I'm writing an Android application that can easily back up files and folders to the users PC. One of the things I wanted to implement was allowing the client running on the Android device to change the port I will be sending the file to.
For this, I've created an EditTextPreference to store the value.
The code I'm using to get this value back is
port = prefs.getString("serverPort", "<unset>");

However, this returns a string and I need an int, so I tried to use
sendPort = Integer.parseInt(port);

But this crashes the Android application, with (I think) a number format exception.
Is there anyway I can explicitly store the value that is entered as an Integer to make it easier?
I tried to use the method
port = prefs.getInt(...);

but that didn't work either.
Thanks for any help.

A:

This will take whatever is entered into your edit text and put it in an int.
int yourValue = Integer.valueOf(editText.getText().toString());

Note that Integer.valueOf() will return a format exception if you put a String in it that doesn't have an integer value.
You can then use
prefsEdit.putInt("serverPort", yourValue);
prefsEdit.commit();

to save it to preferences. And this to retrieve it
int port = prefs.getInt("serverPort", -1);


Q:

BJT push-pull for a MOSFET

I'm looking for a way to drive a MOSFET with discrete components.
Actually I need to drive a bunch of MOSFETs, with currents of 100-150A.
And I'm wondering it would be possible not to use driving ICs, to have more control over functionality, less complexity, less cost.
I've experimented with different arrangements, with resistors and capacitors. I'm using an oscilloscope to monitor ringing, rise/fall times etc.
The problem is that as soon as I introduce resistors, rise/fall time becomes very high.
The input signal has a rise/fall time of only about ~8-10 ns.
Using the BJTs alone, the signal is easily duplicated at similar rise/fall times.
But once the gate capacitance is introduced, the rise/fall time becomes significantly higher, e.g. 300-2000 ns.
I've thus been experimenting with different methods to reduce the rise/fall time:
Method A: NPN+PNP (Voltage-follower? current sourcing from Vcc?)
I made the following circuit, not realizing that the gate voltage would never be more than the input signal voltage.
I need the gate voltage to be more than 10V to minimize Rdson.

simulate this circuit – Schematic created using CircuitLab
Method B: PNP+NPN
I've experimented with different resistors and capacitors:

simulate this circuit
But I found that:

The capacitor reduces rise ringing, but increases fall ringing and time => removed
All resistors except R2 and R3 had a detrimental impact on rise/fall characteristics => removed
Using potentiometers for R2 and R3, I found that the best resistance was R3=4k and R2=1.5k.
Rise time 490ns, fall time 255ns.

I'm a bit worried that the gate voltage isn't dropping low enough, e.g. seems to stay at around 400mV. Although ground seems to be read at 250mV, so maybe the breadboard is just crappy.
How low should the gate voltage be to prevent any heat build-up in when the signal is constant low (off)?
I'm wondering if there's anything else I can do to improve the performance?
Improved circuit:

simulate this circuit
Oscilloscope:
Note: apparently the input signal was inverted on the oscilloscope by setting. I'll update the screenshots later...

Also, I've included the base of the PNP in the following screenshots.  Is it supposed to look like this? It looks a bit funky.
It seems the problem is that the NPN stays switched on, thus preventing the gate from charging.

A:

Your BJTs are in a follower configuration.  This means that they can provide current gain, but not voltage gain.  In fact the emitters will be a diode drop BELOW the base for positive going signals.  If you got to 6V on the gate you must have had around 6.7V out of your signal generator.
The BJT Wiki page has links to the 3 common forms of amplifier which explains more about the characteristics of BJT amplifiers.
BJT Wiki
The current gain is a good thing because in order to charge the gate capacitance of the FET in a short period of time you need high peak currents: I=C*dv/dt.
One way to get a higher voltage swing would be to add a BJT level shifter before your gate drive stage to translate from 5V to 12V.  Of course a single stage BJT level shifter would invert the signal, but often you can deal with that at the signal source.

The pull-up resistor will have to be sufficiently small in value so that you get an acceptable rise time for your application.  VCC would  be your 12V supply and the base resistor should be sized to guarantee saturation with the 5V drive, given the beta of the transistor.  !Y should connect to the bases of your BJT gate driver stage.
However, if your goal is fast rise and fall times from the FET and not learning about BJTs, you should probably use a commercial gate driver IC.  Look for options from IR/Infineon, Texas Instruments, Intersil or Maxim.
Here's a low-cost option from TI:
UCC27517

A:

The first version - a push-pull emitter follower should be fine if only the  max available mosfet VGS = +4,3 V is enough. The pulldown resistor about 100 Ohm should be inserted from BJT emitters to GND to ensure  mosfet's off-state, because the PNP does not pull down effectively under +0,7 V.
Additionally a few Ohm damping resistor inserted just into mosfet's gate terminal should prevent some ringing caused by capacitance and wire inductance.
Your second version has a shortcut. Think about the current route Q2 base->R3->R2->Q1 base.
Emitter follower has no saturation and thus no turn off delay due the diffusion capacitance.
As other answers propose, use a gate driver IC. It does the job with zero tuning and a having lower probablity to behave unthinkably during operation voltage transitions.
Addendum due questioner's comment that states the current to be 100 A
100 amperes on-state Id needs serious attention and even more if the switching rate is high. Do a test run by driving the gate from an ordinary 50 Ohm Zout square wave signal generator. Use low switching frequency and start with more than +6V unipolar signal for safety. Oscilloscope in Vgs gives an idea how big charge is needed to inject and remove for state transitions in wanted transition time. That determines the wanted drive current. Oscilloscope in Vds reveals the needed Vgs.
The described measurements are the basement for designing the driver capable enough.

A:

Other folks have already suggested IC MOSFET drivers. Sounds like you really want to do a discrete driver.
Here's a circuit and it's basically what would be inside a driver IC. This results in 100 Amp switching with about 100 ns transition time to keep MOSFET power dissipation at a minimum.
Q1 is a simple inverting level translator to get the signal swing to 12 Volts. M2 and M3 form a MOSFET push-pull driver. R4 and R5 are there to limit the shoot-through current to prevent damage to M2 and M3 because as their gates transition between 0 and 12V they will be both on for a small fraction of time.
Without R4 and R5, the shoot-through current would exceed their maximum drain current ratings. In an actual IC, M2 and M3 would be sized small enough to have high enough Rds-on instead of putting actual resistors.
Additionally, M2/M3 does an inversion to get back to normal logic. Finally, M3 serves as the high current driver to handle the 100 Amp current.

Note that there is about 2 us delay in shutting off M1. If you're not switching your load at a high frequency, then this 2us would be of no concern.
I definitely would not recommend using these parts; I just picked these from whatever LTspice had. For example, M1 is limited to 35A continuous, so replace these parts with something appropriate for your design and re-run the simulation. Then test out in your prototype to confirm performance. Anyway, this circuit might be a good starting point for you.


Q:

Derby Metastore directory is created in spark workspace

I have spark 2.1.0 installed and integrated with eclipse and hive2 installed and metastore configured in Mysql also placed hive-site.xml file in spark >> conf folder. I'm trying to access tables already present in hive from eclipse.
when I execute the program metastore folder and derby.log file is been created in spark workspace and eclipse console show the below INFO:
Setting MetaStore object pin classes with hive.metastore.cache.pinobjtypes="Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order"
17/06/13 18:26:43 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
17/06/13 18:26:43 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
17/06/13 18:26:43 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
17/06/13 18:26:43 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
17/06/13 18:26:43 INFO Query: Reading in results for query "org.datanucleus.store.rdbms.query.SQLQuery@0" since the connection used is closing
17/06/13 18:26:43 INFO MetaStoreDirectSql: Using direct SQL, underlying DB is MYSQL

spark can't able to locate the configured mysql metastore database
also throwing the error
Exception in thread "main" java.lang.IllegalArgumentException: Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':

Code:
import org.apache.spark.SparkContext, org.apache.spark.SparkConf
import com.typesafe.config._
import org.apache.spark.sql.Row
import org.apache.spark.sql.SparkSession

object hivecore {

  def main(args: Array[String]) {

val warehouseLocation = "hdfs://HADOOPMASTER:54310/user/hive/warehouse"

val spark = SparkSession
  .builder().master("local[*]")
  .appName("hivecore")
  .config("spark.sql.warehouse.dir", warehouseLocation)
  .enableHiveSupport()
  .getOrCreate()

import spark.implicits._
import spark.sql

sql("SELECT * FROM sample.source").show()

}
}

Build.sbt
libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.1.0"
libraryDependencies += "com.typesafe" % "config" % "1.3.0"
libraryDependencies += "org.apache.spark" % "spark-sql_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-hive_2.11" % "2.1.0"
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.42"

NOTE : I can able to access the hive tables from Spark-shell
Thanks

A:

When you put context.setMaster(local), it may not look for the spark configurations that you setup in cluster; specially when you trigger it from ECLIPSE.
Make a jar out of it; and trigger from cmd as spark-submit --class <main class package> --master spark://207.184.161.138:7077 --deploy-mode client
The master ip: spark://207.184.161.138:7077 should be replace with your cluster's ip and spark port.
And, remember to initialize HiveContext to trigger query on underlying HIVE.
val hc = new HiveContext(sc)
hc.sql("SELECT * FROM ...")


Q:

What is the default learningRate and decay of the adam optimizer

According to the documentation, the learningRate is optionnal in the adam optimizer.
If non set what is the default learningRate ?
Is it computed dynamically according to the variables values ?

A:

As you can see in the source code which is linked to on the doc page, the default values are (currently):
learningRate = 0.001
beta1 = 0.9
beta2 = 0.999


Q:

Django : load a restricted set of fields of objects loaded using a foreign key

I have the following code, using Django ORM
    routes =Routes.objects.filter(scheduleid=schedule.id).only('externalid')
    t_list = [(route.externalid, route.vehicle.name) for route in routes])

and it is very slow, because the vehicle objects are huge (dozens of fields, and I cannot change that, it is coming from a legacy database). A lot of time is devoted to create the Vehicle objects, while I only need the name field of this object.
Is there a more efficient way to obtain t_list ? I am looking for something like only() for accessing objects through a foreign key.
EDIT :
the solution is the following :
routes=Routes.objects.filter(scheduleid=schedule.id).select_related("vehicle")
routes= routes.only('externalid','vehicle__name')

Does there exist something similar ?

A:

You should be able to do this, I think. Warning: not tested Tested using local models. Generated query looked good.
routes = Routes.objects.select_related('vehicle').filter(**conditions).only(
            'externalid', 'vehicle__name')

For this to work there should be a vehicle foreign key field declared in Routes model. This is 'cause select_related() only follows forward relationships.


Q:

How to get div which contain specific text

I have following situation:

Editing personal data

     Your personal data has been updated.

I am trying to get div with text "Your personal data has been updated." using this:
 $('div:contains("Your personal data has been updated.")');

But I get all divs up. (Parent divs). Is possible to get only one div.
Edit:
Thanks for all answers.

A:

All parents divs contain this text too. Use id for your selector or add only-child suffix
$( "div ... :only-child" )


Q:

Jquery filupload giving error JSON.parse: unexpected end of data

I'm using Jquery_fileupload (JFU) to send files to an amazon s3 bucket.
When a file it chosen by the user, the file is auto uploaded successfully and amazon returns a status code 204 no content. I've changed the s3 policy to return a 200 code for simplicity.
The problem is JFU gives an error message for each file even though there's no error:
In firefox it's:  SyntaxError: JSON.parse: unexpected end of data
In chrome it's: SyntaxError: Unexpected end of input
Any ideas to resolve this would be helpful. Thanks
JFU setup:
    $(document).ready(function() {
      $('#fileupload').fileupload({
        dropZone: $('#dropzone'),
        autoUpload: true,
        paramName: 'file',
        singleFileUploads: false,
        limitMultiFileUploads: 1,
        sequentialUploads: true,
        multipart: true,
        uploadTemplateId: null,
        downloadTemplateId: null,
        filesContainer: $('#upload-files-container'),
        uploadTemplate: function (o) {
          var rows = $();
          $.each(o.files, function (index, file) {
            var row = $('
' +
            '	' +
            '	' +
            '	' +
            (file.error ? '	' :
            '
' +
            '

	'
            ) + '<button class="btn btn-warning">Cancel</button>
');
            row.find('.name').text(file.name);
            row.find('.size').text(o.formatFileSize(file.size));
            if (file.error) {
              row.find('.error').text(
                locale.fileupload.errors[file.error] || file.error
              );
            }
            rows = rows.add(row);
          });
          return rows;
        },
        downloadTemplate: function (o) {
          var rows = $();
          $.each(o.files, function (index, file) {
            var row = $('
' +
            (file.error ? '		' +
            '		' :
            '	' +
            '	' +
            '		'
            ) + '
');
            row.find('.size').text(o.formatFileSize(file.size));
            if (file.error) {
              row.find('.name').text(file.name);
              row.find('.error').text(
                locale.fileupload.errors[file.error] || file.error
              );
            } else {
              row.find('.name a').text(file.name);
              if (file.thumbnail_url) {
                row.find('.preview').append('')
                .find('img').prop('src', file.thumbnail_url);
                row.find('a').prop('rel', 'gallery');
              }
              row.find('a').prop('href', file.url);
            }
            rows = rows.add(row);
          });
          return rows;
        }
      })
    });

S3 Policy data if helpful:
def policy_data
  {
    expiration: @options[:expiration],
    conditions: [
      ["starts-with", "$utf8", ""],
      ["starts-with", "$key", ""],
      ["content-length-range", 0, @options[:max_file_size]],
      {bucket: @options[:bucket]},
      {acl: @options[:acl]},
      {success_action_status: "200"}
    ]
  }
end

A:

Likewise, I found that Jquery_fileupload 'failed' because of improperly the formatted json response -- whether it's a browser issue or S3, I don't know. The file actually uploads just fine, but the invalid json throws an error.
At any rate, I fixed it by setting the JFU option:
dataType: 'xml'

then converting the response from xml to json. (For that I used the x2js library.)
Here's my AngularJS 'fileuploaddone' listener:
$scope.$on('fileuploaddone', function(e, data) {
  var response;
  response = x2js.xml2json(data.result);
  $scope.file_url = response != null ? (_ref = response.PostResponse) != null ? _ref.Location : void 0 : void 0;
});


Q:

User obj problems with Instagram API

I created an instagram developer account and got client_secret and client_id, I successfully authenticated my own user (myusername) and received an access_token.
When I try to use this endpoint
https://api.instagram.com/v1/users/search?q=[USERNAME]&access_token=[ACCESS TOKEN]
For the user that I authenticated with 'myusername' it returns a user obj as follow but for any other usernames other than this I only get:
{"meta":{"code":200},"data":[]}

My question is if I have a list of instagram IDs.
Is there a way to get public data of these users?
What I need to get for each of these users, is an object similar to this:
{"username":"someusername","bio":"","website":"","profile_picture":"https://scontent.cdninstagram.com/hphotos-xpt1/t51.2885-19/119054229_960211434022564_1442328159_a.jpg","full_name":"Robert Some Last Name","counts":{"media":12,"followed_by":13,"follows":350},"id":"23237xxxxx"}

Any help would be much appreciated.
Best,

A:

I guess your app is in Sandbox mode.
I hope you know Instagram has recently changed their api structure and endpoints and introduced a concept called Sandbox mode. So if your app was created after Nov 17 of 2015, it is automatically placed in Sandbox mode.
So for Sandbox mode, you can only fetch data from verified Sandbox users of your app. Sandbox mode is basically like a filter, only your app's verified sandbox users are allowed to pass through.
For details, check my question-cum-answer here : Sandbox explained in brief.
Now since the users you are trying to fetch aren't verified sandbox users for your app, you will receive empty data(as if those users didn't existed for your app)
Hope it helps you!


Q:

How to implement tokenizer.rbegin() and rend() for boost::tokenizer?

I'm playing around with boost::tokenizer however I realize that it does not support rbegin() and rend(). I would like to ask how can I add these two functions to the existing class?
This is from the boost site:
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main() {
 string str( "12/12/1986" );
 typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
 boost::char_separator<char> sep( "/" );
 tokenizer tokens( str, sep );
 cout << *tokens.begin() << endl;
    // cout << *tokens.rbegin() << endl; How could I implement this?
 return 0;
}

Update
This is my current progress. I first navigate to the src of tokenizer:
//===========================================================================
  // A container-view of a tokenized "sequence"
  template <
    typename TokenizerFunc = char_delimiters_separator<char>,
    typename Iterator = std::string::const_iterator,
    typename Type = std::string
  >
  class tokenizer {
  private:
    typedef token_iterator_generator<TokenizerFunc,Iterator,Type> TGen;

    // It seems that MSVC does not like the unqualified use of iterator,
    // Thus we use iter internally when it is used unqualified and
    // the users of this class will always qualify iterator.
    typedef typename TGen::type iter;

  public:

    typedef iter iterator;
    typedef iter const_iterator;
    typedef Type value_type;
    typedef value_type& reference;
    typedef const value_type& const_reference;
    typedef value_type* pointer;
    typedef const pointer const_pointer;
    typedef void size_type;
    typedef void difference_type;

    tokenizer(Iterator first, Iterator last,
              const TokenizerFunc& f = TokenizerFunc())
      : first_(first), last_(last), f_(f) { }

    template <typename Container>
    tokenizer(const Container& c)
      : first_(c.begin()), last_(c.end()), f_() { }

    template <typename Container>
    tokenizer(const Container& c,const TokenizerFunc& f)
      : first_(c.begin()), last_(c.end()), f_(f) { }

    void assign(Iterator first, Iterator last){
      first_ = first;
      last_ = last;
    }

    void assign(Iterator first, Iterator last, const TokenizerFunc& f){
      assign(first,last);
      f_ = f;
    }

    template <typename Container>
    void assign(const Container& c){
      assign(c.begin(),c.end());
    }

    template <typename Container>
    void assign(const Container& c, const TokenizerFunc& f){
      assign(c.begin(),c.end(),f);
    }

    iter begin() const { return iter(f_,first_,last_); }
    iter end() const { return iter(f_,last_,last_); }

  private:
    Iterator first_;
    Iterator last_;
    TokenizerFunc f_;
  };

Then I focus on the two methods:
iter begin() const { return iter(f_,first_,last_); }
iter end() const { return iter(f_,last_,last_); }

since it returns a constructor of type iter( f_, first_, last_ ), I then move to the source of this class. And iter is actually:
 typedef typename TGen::type iter;

which is token_iterator_generator class. And this class's implementation is:
template <
        class TokenizerFunc = char_delimiters_separator<char>,
        class Iterator = std::string::const_iterator,
        class Type = std::string
    >
    class token_iterator_generator {

    private:
    public:
        typedef token_iterator<TokenizerFunc,Iterator,Type> type;
    };

So now I figured out that the iterator of Tokenizer class is actually token_iterator<>. And the token_iterator's implementation really freaked me out:
template <class TokenizerFunc, class Iterator, class Type>
  class token_iterator
      : public iterator_facade<
            token_iterator<TokenizerFunc, Iterator, Type>
          , Type
          , typename detail::minimum_category<
                forward_traversal_tag
              , typename iterator_traversal<Iterator>::type
            >::type
          , const Type&
        >
  {

      friend class iterator_core_access;

      TokenizerFunc f_;
      Iterator begin_;
      Iterator end_;
      bool valid_;
      Type tok_;

      void increment(){
          BOOST_ASSERT(valid_);
          valid_ = f_(begin_,end_,tok_);
      }

      const Type&  dereference() const {
          BOOST_ASSERT(valid_);
          return tok_;
      }
      template<class Other>
      bool equal(const Other& a) const{
          return (a.valid_ && valid_)
              ?( (a.begin_==begin_) && (a.end_ == end_) )
              :(a.valid_==valid_);

      }

      void initialize(){
          if(valid_) return;
          f_.reset();
          valid_ = (begin_ != end_)?
              f_(begin_,end_,tok_):false;
      }
  public:
      token_iterator():begin_(),end_(),valid_(false),tok_() { }

      token_iterator(TokenizerFunc f, Iterator begin, Iterator e = Iterator())
          : f_(f),begin_(begin),end_(e),valid_(false),tok_(){ initialize(); }

      token_iterator(Iterator begin, Iterator e = Iterator())
            : f_(),begin_(begin),end_(e),valid_(false),tok_() {initialize();}

      template<class OtherIter>
      token_iterator(
            token_iterator<TokenizerFunc, OtherIter,Type> const& t
            , typename enable_if_convertible<OtherIter, Iterator>::type* = 0)
            : f_(t.tokenizer_function()),begin_(t.base())
            ,end_(t.end()),valid_(!t.at_end()),tok_(t.current_token()) {}

      Iterator base()const{return begin_;}

      Iterator end()const{return end_;};

      TokenizerFunc tokenizer_function()const{return f_;}

      Type current_token()const{return tok_;}

      bool at_end()const{return !valid_;}

  };

This class is very complex, and I'm lost here :( ! The inheritance part from iterator_facade<> was so complex.
Any idea should I go next?
Thanks,

A:

You can of course make a new class that implements this by simply iterating the string using a normal tokenizer and store the values in a vector. Then implement rend and rbegin using the vector.
Simple and little risk of making an error, albeit probably not the fastest nor least memory intensive at run-time. Unless you know that this is going to be a problem this is the route I would take since it is very easy and fast to implement.
You specifically ask for extending the existing class however, which I think is a bad idea. In this case the easiest is probably to alter the constructor that takes a container (the one you are using) to instanciate an internal tokenizer object using rbegin() and rend() instead of begin() and end() for the container. To implement your own rbegin() and rend() start off with the iterators you get from begin and end from the internal tokenizer. The tokens returned from these are probably going to be backwards though, so you would need to reverse those. The actual iterator type would probably be pretty easy to implement using the boost::iterators package though.
Note that you would need to take special care for the constructors that take explicit iterators, or decide only to implement a subset of the class' functionality for your reverse iterators (in which case you should probably use a separate class that keeps two internal tokenizers anyway instead of pretending to be a boost::tokenizer).
The alternative to this is to alter the char_separator (and the other separator classes) so that you can explicitly specify which specialization of the tokenizer_detail::assign_or_plus_equal so that you can add each char at the beginning of each partial string instead of the end.
Hope this helps. I would go for the first alternative or just simply change my requirements so that I don't need the reverse iterators.


Q:

WASAPI Event driven capture naudio

Is it possible to capture a line-in signal with NAudio in exclusive, event-driven mode?
If yes, is there an example available?

A:

The WasapiCapture class does not support event mode currently. As it happens, I just did a check-in to support exclusive mode though, which will be part of NAudio 1.7 when it is released shortly. If you need event-driven mode, then you could just take a copy of the WasapiCapture class and make the modifications yourself.


Q:

Mejorar expresión regular para validar decimales

Tengo una expresión regular para validar un valor decimal el cual deberia permitir al usuario escribir una cantidad máxima de 7 números enteros o 7 enteros con 2 decimales, el detalle es que mi expresión me esta forzando a escribir los 7 números enteros con sus 2 decimales y lo que quiero lograr es que se pueda escribir por ejemplo 1234567.50 o 1234567, comparto la manera en la que estoy probando la expresión
onChangeValue(value:any){
    console.log(value.match(/^(\d{0,7})(\.\d{1,2})$/));
}

A:

EDITADO: Gracias a @Julio por señalar un problema en la expresión.
La expresión regular que buscas es:
exp_regular = /^(\d{1,7})(\.\d{1,2}){0,1}$/

Las llaves hacen coincidir la parte decimal una o ninguna vez.
> "0".match(exp_regular)
(3) ["0", "0", undefined, index: 0, input: "0", groups: undefined]

> "0.1".match(exp_regular)
(3) ["0.1", "0", ".1", index: 0, input: "0.1", groups: undefined]

> "1234567.89".match(exp_regular)
(3) ["1234567.89", "1234567", ".89", index: 0, input: "1234567.89", groups: undefined]

> "12345678.90".match(exp_regular)
null

> "12345678.90.90".match(exp_regular)
null

> "1234567.901".match(exp_regular)
null

Lo único que tienes que tener en cuenta con esa expresión regular es que el segundo grupo de coincidencia lleva el punto decimal. Puedes arreglarlo con otra expresión ligeramente cambiada y entonces quedarte con primer y tercer grupos:
> exp_regular2 = /^(\d{1,7})(\.(\d{1,2})){0,1}$/

> "1234567.90".match(exp_regular)
(3) ["1234567.90", "1234567", ".90", index: 0, input: "1234567.90", groups: undefined]

> "1234567.90".match(exp_regular2)
(4) ["1234567.90", "1234567", ".90", "90", index: 0, input: "1234567.90", groups: undefined]

> "1234567.90".match(exp_regular)[2]
".90"

> "1234567.90".match(exp_regular2)[3]
"90"


Q:

This LINQ Model Query seems extremely inefficient

I'm new to LINQ, but I have some background in T-SQL. I know there are probably 100 different ways to design a T-SQL statement that would run this much more efficiently, but I'm not sure how I would do it in LINQ and I would like to stick with LINQ.
This works perfectly well, I just hate the way it looks and am unsure of how to fix it.
I am using MVC3, C#, LINQ, Entity Framework 4.3
public class CollectionRepository : ICollectionRepository {
    private CollectionEntities db = new CollectionEntities();

    public IEnumerable<Collection> GetCollectionByUid(long id) {
        var _collection = (from c in db.UserCollections
                          where c.uid == id
                          orderby c.CreateDate descending
                          select new Collection {
                              Name = c.CollectionName,
                              Type = (from t in db.CollectionTypes
                                      where t.ctypeid == c.Type
                                      select t.CollectionTypeName).FirstOrDefault(),
                              Created = c.CreateDate,
                              Count = (from f in db.Figures
                                       where f.CollectionID == c.cid
                                       select f).Count()
                          }).ToList();
        return _collection;
    }
}

The constructors it points to:
public class Collection {
    public string Name { get; set; }
    public string Type { get; set; }
    public DateTime Created { get; set; }
    public int Count { get; set; }
}

A:

As this is EF code, assuming you have all the associations set up correctly, you should be able to write it something like this:
public IEnumerable<Collection> GetCollectionByUid(long uid) {
    var result =
       (from collection in db.UserCollections
        where collection.uid == uid
        orderby collection.CreateDate descending
        select new Collection {
            Name = collection.CollectionName,
            Type = collection.CollectionType.CollectionTypeName,
            Created = collection.CreateDate,
            Count = collection.Figures.Count(),
        }).ToList();
    return result;
}

My only real criticism is the variable names.
Local variables or parameters should not be prefixed with an underscore.  IMHO, it should only be allowed for private instance fields.  So rather than using _collection, it would be better off as collection (though I used result for the name here instead).
Parameter names are very much part of the documentation as well (especially so in C# and .NET in general).  The method is called GetCollectionByUid which suggests you provide a uid.  The parameter name should reflect that.  Call it uid since that's what it is.
Personal preference but I also prefer to write out the full/reasonable-length variable names in queries.  I reserve significantly shortened variable names (i.e., one character variable names) in lambda expressions.


Q:

Basic DeckGL map with controller buttons in React

I am trying to get a basic DeckGL example working.
What should I do to see control buttons like image below? It is just taking too much time so decided to ask the SO community.

import React from 'react';
import DeckGL from 'deck.gl';
import { StaticMap } from 'react-map-gl';

// Initial viewport settings
const initialViewState = {
    longitude: 170.6362,
    latitude: -44.1321,
    zoom: 6,
    pitch: 55,
    bearing: 0
};
const MAPBOX_ACCESS_TOKEN = 'pk.xyz';

export default class App extends React.Component {

    render() {
        return (
            <DeckGL
                controller={true}
                initialViewState={initialViewState}

            >
                <StaticMap
                    mapStyle="mapbox://styles/mapbox/dark-v9"
                    mapboxApiAccessToken={MAPBOX_ACCESS_TOKEN} />
            </DeckGL>
        );
    }
}

Hopefully assisting someone who can spot the issue, here is a ticket from Deck's GH issues.

A:

import React from 'react';
import DeckGL from 'deck.gl';
import StaticMap, { NavigationControl } from 'react-map-gl';
const initialViewState = {
  longitude: -1.6362,
  latitude: 53.8321,
  zoom: 10,
  pitch: 55,
  bearing: 0,
}

export default class App extends React.Component {

  render() {
    return (
      <DeckGL
        //changing viewport is another question's code.
        initialViewState={initialViewState}>
        <StaticMap>
          <div className='mapboxgl-ctrl-bottom-right'>
            <NavigationControl
              onViewportChange={viewport => this.setState({ viewport })} />
          </div>
        </StaticMap>
      </DeckGL>
    );
  }
}

This is the full clean code. For some reason codesandbox.io does not find deck.gl to add as dependency. Will create a basic repo and link it here.


Q:

R execute script/function during installation

I am developing a package and I would like to know what is the best way to execute a script at installation time.
Essentially I want to make sure that third-party tools are installed,
retrieve them when I can and raise an error if some dependency is missing.
I am not referring only to R packages, but also to system-wide headers, fonts and similar dependencies.
What is the best strategy to follow in this case?

A:

Scripts to be run before installation should be placed in an executable file called configure (will be executed on Linux/Unix/Mac computers) or in a file called configure.win (will be executed in Windows computers).


Q:

Error when running glmnet through Rscript and nohup

When creating a predictive model with the glmnet package in R, I observed the same error mentioned both here and here. But the proposed solution of reinstalling the glmnet package does not fix my problem.
Minimal working example my_glmnet_script.R:
#!/usr/bin/env Rscript --vanilla

# load libraries
library(methods)
library(glmnet)
library(doParallel)

# create toy model
n = 100
p = 250
x = matrix(rnorm(n*p), n, p)
y = matrix(rnorm(n), n, 1)

# number of parallel cores to use
ncores = 4
registerDoParallel(ncores)

# print this before glmnet throws error
print(sessionInfo())

# fit model
my.glmnet = cv.glmnet(x=x, y=y, grouped=FALSE, parallel=TRUE, nfolds=n)
cat("end script.\n")

My command:
nohup Rscript my_glmnet_script.R > nohup.out 2> nohup.err &

Output file nohup.out:

R version 3.4.3 (2017-11-30)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS/LAPACK: /usr/lib64/R/lib/libRblas.so

locale:
[1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8       LC_NAME=C
[9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] parallel  methods   stats     graphics  grDevices utils datasets
[8] base

other attached packages:
[1] doParallel_1.0.11 iterators_1.0.8   glmnet_2.0-16 foreach_1.4.3
[5] Matrix_1.2-12

loaded via a namespace (and not attached):
[1] compiler_3.4.3   codetools_0.2-15 grid_3.4.3       lattice_0.20-35

Error file nohup.err:

nohup: ignoring input
Loading required package: Matrix
Loading required package: foreach
Loaded glmnet 2.0-16

Loading required package: iterators
Loading required package: parallel
Error in .Fortran("get_int_parms", fdev = double(1), eps = double(1), : "get_int_parms" not available for .Fortran() for package "glmnet"
Calls: cv.glmnet -> glmnet -> glmnet.control -> .Fortran
Execution halted

Output from Rscript --version:

R scripting front-end version 3.3.3 (2017-03-06)

The confusing part is that the following command works just fine:
Rscript my_glmnet_script.R

It also runs fine if I call source("my_glmnet_script.R") from within R.
Why does  nohup behave badly with glmnet and Rscript? Is there an R package that I could load that would make this work?

A:

Turns out that nohup is probably not the problem.
From my question, the R version from nohup is R v3.4.3, while Rscript --version returns R v3.3.3. This is because my $PATH points to my personal R (v3.3.3) before using the system-wide R (v3.4.3).
Why does the system-wide R get called? The answer lies in the script hash-bang:
#!/usr/bin/env Rscript --vanilla
To wit, calling /usr/bin/env Rscript --version yields

R scripting front-end version 3.4.3 (2017-11-30)

and the system-wide R looks for glmnet in my personal (v3.3.3) library, the first entry of .libPaths(), which was never compiled for 3.4.3:
/usr/bin/Rscript -e ".libPaths(.libPaths()[2:3]); library('glmnet')"

Error in library("glmnet") : there is no package called ‘glmnet’

Moral of story: stay organized when multiple R versions are installed on your server!