text:
Q: In REST is HATEOAS really about self-discovery or about navigation? I'm trying to learn about REST and having problems with the concept of HATEOAS (Hypermedia As The Engine Of Application State).  What is it for?
It seems to me the majority of commenters on the web think that HATEOAS should be used by a client to discover how to use a RESTful web service.  And most seem to conclude that HATEOAS is not worth including in RESTful web services for one of two reasons:
1) HATEOAS only gives URLs but these are useless by themselves without knowing what methods can be used with each URL (eg HTTP GET, POST, PUT).  Since the additional information must be passed to the client out of band (eg via documentation) then there is no point in using HATEOAS;
2) Similar to (1) but takes it a step further:  The client can figure out what methods are applicable to a given URL by calling the HTTP OPTIONS method.  However, the client still needs out of band information, to describe the format of the data it must pass for, say, POST or PUT methods.  So we end up in the same place as (1) - HATEOAS isn't sufficient for a client to discover everything it needs to know, so why bother with it.
These arguments seem valid if HATEOAS is supposed to be used by a client to discover how to use a RESTful web service.  However, is that what HATEOAS is for?  From the few examples I've seen, it seems to me to be perfect for navigating through a web service - I've performed a certain action, now what are the valid actions I can perform next?  That seems to me to gel with the "Application State" part of HATEOAS but very few articles I've read talk of it in terms of navigation, almost all are about discovery.
So, is HATEOAS about discovering how to use a RESTful web service or is it really about navigation?

A: Disclaimer: answer offered without first rereading the Fielding thesis.
HATEOAS supports the discovery of previously unknown application states.
Think state machine.  The hypermedia representation sent to the application describes a current application state, and it describes which triggers are valid transitions out of the state.
It doesn't necessarily describe how to implement the trigger.
As usual, consider the web as the Ur example.  You start your Wikipedia application by directing your browser to the landing page, and three hours later you find yourself reading about Citrus Taxonomy.
How does that happen?  Wikipedia sends a hypermedia description (text/html) of the application state (the landing page); included in the hypermedia are links (anchor tags).  The application (browser) knows what to do with those because the implementation was written with awareness of the html specification.
When we write html that conforms to a new version of the specification, the hypermedia doesn't tell old browsers how to implement it -- Netscape 2.0 doesn't magically "discover" how to implement html5 embedded video.
In general, the hypermedia document provides the triggers that are supported, but the client is expected to ignore any triggers that it doesn't recognize.  Definitions of the triggers themselves are out of band.

So, is HATEOAS about discovering how to use a RESTful web service or is it really about navigation?

Consider a "Choose Your Own Adventure" book.

To visit the Cave of Wonders, turn to page 17.

Is the book telling you how to navigate the pages, or is it telling you how to discover the story?

A: @VoiceOfUnreason's answer suggests that HATEOAS is really just about links.  However, the Programmers StackExchange question @RobertHarvey linked to, What does HATEOAS offer for discoverability and decoupling besides ability to change your URL structure more or less freely?, suggests it's more complicated than that, and HATEOAS includes both using the OPTIONS method to determine which methods can be called on a resource, and defining a media type to specify the format of data in the request and the response.
One of the answers to that question ("What does HATEOAS offer...") includes a link to a blog post from Roy Fielding, who originally defined REST: REST APIs must be hypertext-driven.  Some snippets from that blog post:

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). Servers must have the freedom to control their own namespace. Instead, allow servers to instruct clients on how to construct appropriate URIs, such as is done in HTML forms and URI templates, by defining those instructions within media types and link relations. [Failure here implies that clients are assuming a resource structure due to out-of band information, such as a domain-specific standard, which is the data-oriented equivalent to RPC's functional coupling].
A REST API should never have "typed" resources that are significant to the client. Specification authors may use resource types for describing server implementation behind the interface, but those types must be irrelevant and invisible to the client. The only types that are significant to a client are the current representation's media type and standardized relation names. [ditto]
A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user's manipulation of those representations. The transitions may be determined (or limited by) the client's knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

(As an aside: I get the impression from many blog posts that a lot of people see HATEOAS as sort of an optional extra to REST.  However, Roy Fielding's comments quoted above indicate HATEOAS is actually central to REST and you can't have a RESTful API without it.)
If anyone finds this answer useful please upvote @RobertHarvey's comment to my question above, the one that has the "What does HATEOAS offer..." link.


text:
Q: Check if Windows-application is run as a service Is there a way to determine if a Windows-process is run as a service ? Is there any fixed parent-process of all the services which I can identify to assure that the process is a service-process.

A: if application designed for run both as service and as standalone application, the best way know how application started - use command line. when you register service with CreateServiceW - pass to lpBinaryPathName some arguments. and then on start - check string returned by GetCommandLineW() - are this arguments present. if yes - you run as service, if no - as standalone application.
for example append \n symbol to the service binary file path :
WCHAR BinaryPathName[MAX_PATH + 3];
ULONG cch = GetModuleFileNameW(0, BinaryPathName + 1, _countof(BinaryPathName) - 3);
if (GetLastError() == NOERROR)
{
    BinaryPathName[0] = '\"';
    BinaryPathName[cch + 1] = '\"';
    BinaryPathName[cch + 2] = '\n';
    BinaryPathName[cch + 3] = 0;
    //CreateServiceW(.., BinaryPathName, ..);
}

(\n selected because this symbol can not be in command line if exec application manually )
and then in application entry point do very simply and fast check
if (wcschr(GetCommandLineW(), '\n'))
{
    const static SERVICE_TABLE_ENTRY ste[] = { { L"my_service_name", ServiceMain }, {} };
    StartServiceCtrlDispatcher(ste);
}
else
{
  // run as standalone application
}

i think this solution is the best. however possible and others. for example we can do next check:
ULONG SessionId;
if (ProcessIdToSessionId(GetCurrentProcessId(), &SessionId) &&
    WTSGetActiveConsoleSessionId() == SessionId)
{
    // we not run as service;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt C++ - How to protect a file My applications generates a .zip containing important files and I don't want that the end user can get access to those data. To compress I use the QuaZIP library.
My first idea was to set a password to the zip file but it seems complicated and not very secure but if you have a solution it will be enough for my need.
Otherwise do you have any idea to easily secure a file? Can I encrypt it?
Thanks a lot.
I'm Qt 5.11 and MSVC2017.

A: The easiest protection: just change the file extension (from .zip to .bin for example). For example using QFile::rename():
QFile::rename("your_file.zip", "your_file.bin");

Another way:
Read all the data from the file and encrypt it. You can use SimpleCrypt:
SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //some random number. This is your encryption key
...

QByteArray buffer = file.readAll();

QByteArray encryptedBuffer = crypto.encryptToByteArray(buffer.data());

// Write the encrypted data to a new file
QFile newFile("new_file.bin");
...
newFile.write(encryptedBuffer);

Then you can send this newFile.
On the recipient side, read all the data to a buffer from the file you received:
QByteArray encryptedBuffer = receivedFile.readAll();

SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //same random number: key should match encryption key

QByteArray yourDecryptedData = crypto.decryptToByteArray(encryptedBuffer);


text:
Q: every node in one graph have the same output in my GCN model I have several graphs and I use these graphs to train a model hoping to identify the category of each node. I have three categories, and here are the formulation of one of my graph (using the data object):
Data(x=[100,64],pos=[100,2],edge_index=[2,546],y=[100],edge_weight=[546])

x is the embedding of every node, here have 100 nodes and each node have a 64-dimension feature, pos is the coordinate of each node. A two-dimensional vector in edge_index represents an edge between two points. And the edge_weight is the weight corresponding to each edge.
Here is my GCN model:
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv

# GCN model with 2 layers
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = GCNConv(data.num_features, 16)
        self.conv2 = GCNConv(16, int(data.num_classes))

    def forward(self):
        x, edge_index = data.x, data.edge_index
        x = F.relu(self.conv1(x, edge_index))
        x = F.dropout(x, training=self.training)
        x = self.conv2(x, edge_index)
        return F.log_softmax(x, dim=1)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

data =  data.to(device)

model = Net().to(device)

and here is my training code:
for epoch in range(epoches):
    for img_path in img_paths: #in order to build the graph
         data=build_graph(img_path)
         model.train()
         optimizer.zero_grad()
         output=GCNmodel(data)
         F.nll_loss(output,target).backward()
         optimizer.step()

but using this code, every node in one graph have the same output, especially have the negative num.
enter image description here
Note:The category 1 and 2 of each picture is balanced, the category 3 in every image is samller. But the data should not be the main reason for this result
It confuse me  lots of time, I am very grateful, if you can help me.


text:
Q: Force break-line to fit text in begin{cases} I need to show an equation with begin{cases} however the text is bigger than the column of my article and I couldn't find a way to force it to break the line.
Code:
\[
    Match_D =
\begin{cases}
    1,        & \text{if $D_j$ matches a single detected rectangle,} \\
    0,        & \text{if $D_j$ does not match any detected rectangle,} \\
    f_{sc}(k) & \text{if $D_j$ matches several $(k)$ detected rectangles}
\end{cases}
\]

\[
    Match_G =
\begin{cases}
    1,        & \text{if $G_i$ matches a single detected rectangle,} \\
    0,        & \text{if $G_i$ does not match any detected rectangle,} \\
    f_{sc}(k) & \text{if $G_i$ matches several $(k)$ detected rectangles}
\end{cases}
\]

Regards

A: You can use a \parbox of fixed width:
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\[
  Match_D =
  \begin{cases}
    1,        & \parbox{.3\linewidth}{if $D_j$ matches a single detected rectangle,} \\[3ex]
    0,        & \parbox{.3\linewidth}{if $D_j$ does not match any detected rectangle,} \\[3ex]
    f_{sc}(k) & \parbox{.3\linewidth}{if $D_j$ matches several $(k)$ detected rectangles}
  \end{cases}
\]

\[
  Match_G =
  \begin{cases}
    1,        & \parbox[t]{.3\linewidth}{if $G_i$ matches a single detected rectangle,} \\[3ex]
    0,        & \parbox[t]{.3\linewidth}{if $G_i$ does not match any detected rectangle,} \\[3ex]
    f_{sc}(k) & \parbox[t]{.3\linewidth}{if $G_i$ matches several $(k)$ detected rectangles}
  \end{cases}
\]
\end{document}

You can use [t]op alignment (see Match_G) or (the default) [c]entered alignment (see Match_D).

A: Two variants without having to measure whatever: one with the empheqenvironment and  tabulars, another with the cases* environment  from mathtools. The first way enables you to easily number or  subnumber each case if you wish. cases*is just a cases environment in which the 2nd column is automatically in text mode.
It require only loading empheq, which loads mathtools, which loads amsmath.
\documentclass{article}
\usepackage{empheq}

\begin{document}

\begin{subequations}
\begin{empheq}[left={\mathrm{Match}_G=\empheqlbrace}]{alignat=2}
  & 1 & \quad& \begin{tabular}[t]{l}
if $G_i$ matches a single \\ detected rectangle,
\end{tabular} \\
 & 0 & & \begin{tabular}[t]{l}
if $G_i$ does not match \\ any detected rectangle,
\end{tabular} \\
 & f_{sc}(k) & & \begin{tabular}[t]{l}
if $G_i$ matches several \\ $(k)$ detected rectangle,
\end{tabular}
\end{empheq}
\end{subequations}

\[
  \mathrm{Match}_G =
  \begin{cases*}
    1, & if $G_i$ matches a single \\[-0.5ex]
      & detected rectangle, \\%[0.5ex]
    0, & if $G_i$ does not match\\[-0.5ex]
     & any detected rectangle, \\%[0.5ex]
    f_{sc}(k) & if $G_i$ matches several \\[-0.5ex]
     & $(k)$ detected rectangles
  \end{cases*}
\]

\end{document}

A: I found a more elegant way:
\begin{equation}
        Match_D =
        \begin{cases}
            1,        & \text{if $D_j$ matches a single detected rectangle,} \\
            0,        & \text{if $D_j$ does not match any detected} \\&\text{rectangle}, \\
            f_{sc}(k) & \text{if $D_j$ matches several $(k)$ detected} \\&\text{rectangles}
        \end{cases}
\end{equation}

This will ensure your equations in the conditions are rendered correctly, and you can break at any position as you wish.


text:
Q: How do we prove the statement $x^{2} \geq 36$ implies $|x| \geq 6$ by contradiction? Proof by contradiction seems to confuse me and I need help with this specific question.
In particular, how do we prove the following statement by contradiction:
If $x^2 \geq 36$ then $|x|\geq 6$ (?)

A: Easy :). Assume $|x|<6$, and just square the result. Around $x=6$, $x^2$ increases as $x$ increases. If $x<6$, $x^2<6^2=36$. Since $x^2$ is an even function, $(-x)^2<36$ as well, and that's our contradiction.


text:
Q: Node.js - Create executable with PKG I have an application in node.js and now I'm trying to create a executable to run the application without all project files but I'm having problems when I try use pkg (https://github.com/zeit/pkg#detecting-assets-in-source-code).
In package.json I add this:
"pkg": {
"scripts": "public/js/*.js",
"assets": [
  "views/**/*"
],
"targets": "node6"

},
In console I run this command and I don't have any error in this process and create 3 platforms executable, pkg index.js --output
When I run the executable It starts with no errors and when I access to browser it returns me this error:
Error: Failed to lookup view "login" in views directory "/snapshot/Picking/views"
at EventEmitter.render (/snapshot/Picking/node_modules/express/lib/application.js:580:17)
at ServerResponse.render (/snapshot/Picking/node_modules/express/lib/response.js:1008:7)
at ServerResponse.app.use.res.render (/snapshot/Picking/index.js:0)
at index (/snapshot/Picking/controllers/loginController.js:0)
at Layer.handle [as handle_request] (/snapshot/Picking/node_modules/express/lib/router/layer.js:95:5)
at next (/snapshot/Picking/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/snapshot/Picking/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/snapshot/Picking/node_modules/express/lib/router/layer.js:95:5)
at /snapshot/Picking/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/snapshot/Picking/node_modules/express/lib/router/index.js:335:12)

In index.js I have this line to access views folder:
app.set("views", path.join(__dirname, 'views'));

How can I solve this situation?
Thank you

A: You set your assets path into "scripts", but you must set this path to "assets", like this:
"pkg": {
"assets": [
  "views/**/*",
  "public/js/*.js"
],
"targets": "node6"

because "scripts" for node.js files. And your app not found frontend js-files.

A: You can't use app.set("views", path.join(__dirname, 'views')); because pkg is placing your views in the snapshot directory, so your project won't find it.
You have to explicitly indicate where your views are when rendering:
res.render(path.join(__dirname, '..', 'views/index'));


text:
Q: how to create a batch file that executes a single command on all the files in a directory how to create a batch file that executes a single command on all the files in a directory
For Example,  directory C;\Test  contains 30 files with an .ini extension. I could run each file individually by using the command  Trade abc.ini, bcd.ini, cde.ini ..... and so forth.
I would like to have a batch file to run the trade command on all the files in the directory without having to name each file individually. Thanks for your help!

A:
how to create a batch file that executes a single command on all the files in a directory

for %%f in (*.ini) do call echo %%f

And replace "echo" with your own command.

A: you can use forfiles to do that
FORFILES /M *.ini /C "cmd /c Trade @file"


text:
Q: how to pass token as header authuriazation token in laravel I am trying to create a get API.
I am using Larvel passport for generating token
I want to pass generated token as header for the API.
How can I do that?
public function getalluser(User $user)
{

 $user = User::where('id', $user)->first();
 return response()->json([
            'user' => $user,
 ]);
}
}

Here even with out passing the authorization token I am getting some response if there is no token passed I want error and I want to pass token in order for this API to work

A: As I understand your question - you want to get an authenticated user by token.
Follow installation instructions from Laravel docs - https://laravel.com/docs/9.x/passport#installation
Especially this part:

Finally, in your application's config/auth.php
configuration file, you should define an api authentication guard and
set the driver option to passport. This will instruct your application
to use Passport's TokenGuard when authenticating incoming API
requests:
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

To authenticate users you should use the api guard.
Now you can create route to get current authenticated user - https://laravel.com/docs/9.x/passport#via-middleware
Route::get('/user', function (\Illuminate\Http\Request $request) {
    // You will get authenticated user here
    $user = $request->user();
    dump($user);

    return new \Illuminate\Http\JsonResponse(['id' => $user->id], 200);
})->middleware('auth:api');

And here is about how pass authentication token to your app - https://laravel.com/docs/9.x/passport#passing-the-access-token
Just add Authorization header with this value Bearer: <PUT_HERE_YOUR_TOKEN>, replace <PUT_HERE_YOUR_TOKEN> with your issued token.
UPD:
If you want to get token used to authenticate user, you can look at Passport middleware source code - https://github.com/laravel/passport/blob/11.x/src/Guards/TokenGuard.php
if ($this->request->bearerToken()) {
    return $this->user = $this->authenticateViaBearerToken($this->request);
} elseif ($this->request->cookie(Passport::cookie())) {
    return $this->user = $this->authenticateViaCookie($this->request);
}


text:
Q: How do I convert an ATL/MFC CString to a QString? Given the encoding of the project is probably Unicode (but not for sure) what is the best way of converting ATL::CString to QString?
What I have thought of is this:
CString c(_T("SOME_TEXT"));
//...
std::basic_string<TCHAR> intermediate((LPCTSTR)c);
QString q;

#ifdef _UNICODE
q = QString::fromStdWString(intermediate);
#else
q = QString::fromStdString(intermediate);
#endif

Do you think that it works? Any other ideas?

A: You don't need the intermediate conversion to a std::string. The CString class can be treated as a simple C-style string; that is, an array of characters. All you have to do is cast it to an LPCTSTR.
And once you have that, you just need to create the QString object depending on whether the characters in your CString are of type char or wchar_t. For the former, you can use one of the standard constructors for QString, and for the latter, you can use the fromWCharArray function.
Something like the following code (untested, I don't have Qt installed anymore):
CString c(_T("SOME_TEXT"));
QString q;

#ifdef _UNICODE
q = QString::fromWCharArray((LPCTSTR)c, c.GetLength());
#else
q = QString((LPCTSTR)c);
#endif

Edit: As suggested in the comments, you have to disable "Treat wchar_t as a built-in type` in your project's Properties to get the above code to link correctly in Visual Studio (source).
For _UNICODE, I believe you could also use the fromUtf16 function:
CString c(_T("SOME TEXT"));
QString q = QString::fromUtf16(c.GetBuffer(), c.GetLength());


text:
Q: How to assign a variable using firebase javascript Reading the firebase doc this line:
database.ref('/').once('value').then(function(snapshot)

That is from a paragraph titled "Read data once" which I'm assuming reads in all the data from the database.
I'm just struggling to figure out how to assign data from the object that is returned to a variable in javascript.
What I want to do is populate a dropdown list with place names.
For instance if I have a field called Location in the db containing place names eg Sydney, Melbourne, Brisbane how would I get the data from the returned object and assign it a variable called place so I can then use the place variable to populate the html dropdown list.

A: You can try with this simple code -
database.ref('/').once('value').then(function(snapshot){
    var list = snapshot.val();
    if(list)
    {
        for (item in list)
        {
            itemIndex = item;
            item = list[item];
            //access your properties of the object say - item.location
        }
    }
});

A: You have to user 'child_added'
example:
var dbRef = firebase.database().ref().child('someChild');
    dbRef.on('child_added', function(snap){
      var res = snap.val().theValueYouNeed;
   });

The code above gets the specific child in your db like this:
someChild:{
     theValueYouNeed:"some value"
    }

Then you can populate your list with the values.
I hope this helps!


text:
Q: Powershell5 Compact code by combining foreach, begin, process, and replace command Can I get the same results with less code?
The code searches sample.bat for the strings AROUND LINE {1-9999} and LINE2 {1-9999} and replaces {1-9999} with the {line number} the code is on.
sample.bat:
AROUND LINE 262
LINE2 1964

Old code:
gc $env:temp\sample.bat | foreach -Begin {$lc = 1} -Process {
  $_ -replace "AROUND LINE \d*", "AROUND LINE $lc";
  $lc += 1
} | Out-File -Encoding Ascii $env:temp\results.bat
(gc $env:temp\results.bat) | foreach -Begin {$lc = 1} -Process {
  $_ -replace "LINE2 \d*", "LINE2 $lc";
  $lc += 1
} | Out-File -Encoding Ascii $env:temp\results.bat

Current code:
(gc $env:temp\sample.bat) | foreach -Begin {$lc = 1} -Process {
  $_ -replace "AROUND LINE \d*", "AROUND LINE $lc";
  $lc += 1
} | foreach -Begin {$lc = 1} -Process {
  $_ -replace "LINE2 \d*", "LINE2 $lc";
} | Out-File -Encoding Ascii $env:temp\sample.bat

Expected results:
AROUND LINE 1
LINE2 2

Actual results:
AROUND LINE 1
LINE2 2

A: You can make this work with a single regex:
gc $env:temp\sample.bat | foreach -Begin {$lc = 1} -Process {
  $_ -replace '(?<=AROUND LINE |LINE2 )\d+', $lc++
} | Set-Content -Encoding Ascii $env:temp\results.bat

Note that I'm using '...' (single quotes) rather than "..." (double quotes) to enclose the regex, which is preferable to rule out potential confusion arising from PowerShell performing string expansion (interpolation) first.
$lc++ returns the current $lc value and increments it by 1 afterwards, obviating the need for the $lc += 1 statement.
Also, I've replaced Out-File with Set-Content, as they're functionally the same for saving strings, but the latter is faster.
Finally, to match one or more digits, use \d+ rather than \d*.
A note on $_ -replace '(?<=AROUND LINE |LINE2 )\d+', $lc++:

*

*Regex (?<=AROUND LINE |LINE2 )\d+ uses a look-behind assertion ((?<=...) to look for either (|) string AROUND LINE  or string LINE2 before one or more (+) digits (\d).

*

*The look-behind assertion is by design not considered part of the match, so that the substring getting replaced is limited to the run of digits, i.e., the number only.

*$lc++ is the replacement operand: it returns the current value of variable $lc and increments its value afterwards; note that even though $lc is a number ([int]), PowerShell automatically converts it to a string for the replacement.

Generally, though, you can simply chain -replace operations:
# ...
$_ -replace 'AROUND LINE \d+', "AROUND LINE $lc" -replace 'LINE2 \d+', "LINE2 $lc"
++$lc
# ...


text:
Q: How to find a matching string to a string from one text file in another text file? I have two text files. Both of them have the same content but the formatting of each is different. In one file there are extra spaces between words or letters. There are different line breaks as well. For example:
File1:
The annotation framework we presented is
embedded in the Knowledge Management and
Acquisition Platform Semantic Turkey (Pazienza, et
al., 2012), and comes out-the-box with a few
annotation families which differ in the underlying
annotation model and, notably, in the tasks they
support. The default handlers take into consideration
the annotation of atomic ontological resources, and
complex activities that are provided as macros, e.g.
the creation of new instances, the definition of new
subclasses in OWL, or of narrower concepts in
SKOS.

File2:
Theannotationframework we presented is
embedded in th e K n o w l e d ge Management and
Acquisition Platform Semantic Turkey (Pazienza, et
al., 2012), and comes out-the-
box with a few
annotation families which differ in the underlying
annotation model and, notably, in the tasks they
support. The default handlers take into consideration
the a n n o t a t i o n  o f a t o m i c ontological resources, and
complex activities that are provided as macros, e.g.
the creation of new instances, the definition of new
subclasses in OWL, or of narrower concepts in
SKOS.

Suppose I select the String the Knowledge Management from File1 and I want to match it with the String th e K n o w l e d ge Management in File2.
How can I achieve it? There are no fixed deformities in the second file. Only surety is that the characters are in the same order in both the files and they could be possibly separated by extra spaces or the space between them could be missing.
I thought of applying Sellers Algorithm or Viterbi Algorithm but, I am not sure about it. Approximate string matching could be expensive as well.
Any lead would be helpful.
Thanks a lot!

A: You should realize that you don't have two texts but virtually a single one, with all characters at the same position !
By what magic ? Well, it suffices to strip-off all white space and separators, or, better, skip them when you move forward from one character to the next.
You can easily traverse both texts in parallel, staying synchronized, and no search is necessary !
For example, both "the Knowledge Management" and "th e K n o w l e d ge Management" run from position 45 to 67.

If you don't know the starting position of the search string in the first text, then perform an ordinary search in the first text (with or without spaces, that's up to you), and traverse the second text to the same position.
The annotation framework we presented is
0          1         2           3
0122345678901223467890122344567890123345

If you need to perform numerous string locations in a text, traversing from the beginning every time becomes costly. Then you can use an index table that associates the whitespace-less location to the ordinary location, and perform binary searches when necessary.

A: You could import the files as strings, and remove all the white space from both. It should then be a straight string matching activity.
If you also need the start index of the matching pattern, get the index of the starting point in the collapsed string and run a for loop over the spaced out version, counting only characters.


text:
Q: With Gson, how to parse JSON response having complex structure As you can see the objects matchField and actions are arrays holding objects having different members. Please say what should be my class structure to get this JSON data parsed so that I can get all the data (Please note that the objects in n matchField and actions can have other members- not only the ones in this response). Also is there any other way with GSON(other than using gson.fromJson) to get this done?
{
"node": {
    "id": "00:00:00:00:00:00:00:01",
    "type": "OF"
},
"flowStatistic": [
    {
        "flow": {
            "match": {
                "matchField": [
                    {
                        "type": "DL_TYPE",
                        "value": "2048"
                    },
                    {
                        "mask": "255.255.255.255",
                        "type": "NW_DST",
                        "value": "10.0.0.1"
                    }
                ]
            },
            "actions": [
                {
                    "type": "SET_DL_DST",
                    "address": "7a11761ae595"
                },
                {
                    "type": "OUTPUT",
                    "port": {
                        "node": {
                            "id": "00:00:00:00:00:00:00:01",
                            "type": "OF"
                        },
                        "id": "1",
                        "type": "OF"
                    }
                }
            ],
            "priority": 1,
            "idleTimeout": 0,
            "hardTimeout": 0,
            "id": 0
        },
        "tableId": 0,
        "durationSeconds": 62500,
        "durationNanoseconds": 513000000,
        "packetCount": 0,
        "byteCount": 0
    },
    {
        "flow": {
            "match": {
                "matchField": [
                    {
                        "type": "DL_TYPE",
                        "value": "2048"
                    },
                    {
                        "mask": "255.255.255.255",
                        "type": "NW_DST",
                        "value": "10.0.0.2"
                    }
                ]
            },
            "actions": [
                {
                    "type": "OUTPUT",
                    "port": {
                        "node": {
                            "id": "00:00:00:00:00:00:00:01",
                            "type": "OF"
                        },
                        "id": "2",
                        "type": "OF"
                    }
                }
            ],
            "priority": 1,
            "idleTimeout": 0,
            "hardTimeout": 0,
            "id": 0
        },
        "tableId": 0,
        "durationSeconds": 62500,
        "durationNanoseconds": 508000000,
        "packetCount": 0,
        "byteCount": 0
    },
    {
        "flow": {
            "match": {
                "matchField": [
                    {
                        "type": "DL_TYPE",
                        "value": "2048"
                    },
                    {
                        "type": "IN_PORT",
                        "value": "OF|2@OF|00:00:00:00:00:00:00:01"
                    }
                ]
            },
            "actions": [
                {
                    "type": "SET_NW_TOS",
                    "tos": 30
                }
            ],
            "priority": 500,
            "idleTimeout": 0,
            "hardTimeout": 0,
            "id": 0
        },
        "tableId": 0,
        "durationSeconds": 62252,
        "durationNanoseconds": 633000000,
        "packetCount": 0,
        "byteCount": 0
    }
]

}
Following are the POJOs created
public class FlowStatisticsList {

@Expose
@SerializedName("node")
private Node node;
@Expose
@SerializedName("flowStatistic")
private List<FlowStatistic> flowStatistic = new ArrayList<FlowStatistic>();

public Node getNode() {
    return node;
}

public void setNode(Node node) {
    this.node = node;
}

public List<FlowStatistic> getFlowStatistic() {
    return flowStatistic;
}

public void setFlowStatistic(List<FlowStatistic> flowStatistic) {
    this.flowStatistic = flowStatistic;
}

}
public class FlowStatistic {

@Expose
@SerializedName("flow")
private Flow flow;
@Expose
@SerializedName("tableId")
private long tableId;
@Expose
@SerializedName("durationSeconds")
private long durationSeconds;
@Expose
@SerializedName("durationNanoseconds")
private long durationNanoseconds;
@Expose
@SerializedName("packetCount")
private long packetCount;
@Expose
@SerializedName("byteCount")
private long byteCount;

public Flow getFlow() {
    return flow;
}

public void setFlow(Flow flow) {
    this.flow = flow;
}

public long getTableId() {
    return tableId;
}

public void setTableId(long tableId) {
    this.tableId = tableId;
}

public long getDurationSeconds() {
    return durationSeconds;
}

public void setDurationSeconds(long durationSeconds) {
    this.durationSeconds = durationSeconds;
}

public long getDurationNanoseconds() {
    return durationNanoseconds;
}

public void setDurationNanoseconds(long durationNanoseconds) {
    this.durationNanoseconds = durationNanoseconds;
}

public long getPacketCount() {
    return packetCount;
}

public void setPacketCount(long packetCount) {
    this.packetCount = packetCount;
}

public long getByteCount() {
    return byteCount;
}

public void setByteCount(long byteCount) {
    this.byteCount = byteCount;
}

}
public class Flow {

@Expose
@SerializedName("match")
private Match match;
@Expose
@SerializedName("actions")
private List<Action> actions = new ArrayList<Action>();
@Expose
@SerializedName("priority")
private long priority;
@Expose
@SerializedName("idleTimeout")
private long idleTimeout;
@Expose
@SerializedName("hardTimeout")
private long hardTimeout;
@Expose
@SerializedName("id")
private long id;

public Match getMatch() {
    return match;
}

public void setMatch(Match match) {
    this.match = match;
}

public List<Action> getActions() {
    return actions;
}

public void setActions(List<Action> actions) {
    this.actions = actions;
}

public long getPriority() {
    return priority;
}

public void setPriority(long priority) {
    this.priority = priority;
}

public long getIdleTimeout() {
    return idleTimeout;
}

public void setIdleTimeout(long idleTimeout) {
    this.idleTimeout = idleTimeout;
}

public long getHardTimeout() {
    return hardTimeout;
}

public void setHardTimeout(long hardTimeout) {
    this.hardTimeout = hardTimeout;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

}
public class Match {

@Expose
@SerializedName("matchField")
private List<MatchField> matchField = new ArrayList<MatchField>();

public List<MatchField> getMatchField() {
    return matchField;
}

public void setMatchField(List<MatchField> matchField) {
    this.matchField = matchField;
}

}
I'm stuck at creating POJOs for Action and MatchField.
The following snippet is used to deserialize the response
gson.fromJson(jsonString, FlowStatisticsList.class)

A: The following are the POJO classes that you need to create to parse the JSON data into corresponding java object
FlowStatisticsList:
public class FlowStatisticsList {
    private Node node;

    private List<FlowStatistic> flowStatistic = new ArrayList<FlowStatistic>();

    // getters, setters & toString methods
}

Node:
public class Node {
    private String id;
    private String type;

    // getters, setters & toString methods
}

FlowStatistic:
public class FlowStatistic {
    private Flow flow;

    private long tableId;
    private long durationSeconds;
    private long durationNanoseconds;
    private long packetCount;
    private long byteCount;

    // getters, setters & toString methods
}

Flow:
public class Flow {
    private Match match;

    private List<Action> actions = new ArrayList<Action>();

    private long priority;
    private long idleTimeout;
    private long hardTimeout;
    private long id;

    // getters, setters & toString methods
}

Match:
public class Match {
    private List<MatchField> matchField = new ArrayList<MatchField>();

    // getters, setters & toString methods
}

MatchField:
public class MatchField {
    private String mask;
    private String type;
    private String value;

    // getters, setters & toString methods
}

Action:
public class Action {
    private String type;
    private String address;
    private int tos;

    private Port port;

    // getters, setters & toString methods
}

Port:
public class Port {
    private Node node;

    private String type;
    private String id;

    // getters, setters & toString methods
}

and finally the parsing is as follows:
Gson gson = new GsonBuilder().create();
FlowStatisticsList object = gson.fromJson(jsonData, FlowStatisticsList.class);
System.out.println(object);


text:
Q: Insert statement with where in sql in stored procedure I wonder why the below stored procedure is not working.It gives error invalid syntax near WHERE.
ALTER PROCEDURE salary

    @salary int = 0,
    @id int =0

AS
 SET NOCOUNT ON

BEGIN
  begin
    insert into account (Salary) values (@salary) where staffId = @id;
  end
END

A: there's no "where" on insert syntax.
example :
insert into account (staffid, salary) values (@id, @salary);

or you could use update syntax to update the data.
update account set salary = @salary where staffid = @id;


text:
Q: How to have a NSCollectionView item have dynamic height based on text field I have a NSCollectionView which presents items in a list.

my layout is defined by
private func configureCollectionView() {
    let flowLayout = NSCollectionViewFlowLayout()

    flowLayout.itemSize.width = self.view.frame.width
    //flowLayout.itemSize.height = 50
    flowLayout.minimumLineSpacing = 8
    myCollectionView.collectionViewLayout = flowLayout
    view.wantsLayer = true
}

When a long peice of text is entered as an item, I am trying to get the item height for that 'cell' to grow/expand with the content of the text.
I have setup my contsraints using AutoLayout and I fairly certain that it is setup correctly for this, but my item height remains fixed at 50 (I can't tell where this is getting set).
I am trying to take advantage of
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize

But I'm not having much luck with this either as I don't know how to best figure out what the Size should be (the height in this case)
Any suggestions on this problem?
Thanks!

A: You can use sizeThatFits with your desired width and a big enough height
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {

    let string = strings[indexPath.item]
    let size = NSTextField(labelWithString: string).sizeThatFits(NSSize(width: 400, height: 800))

    return NSSize(width: 400, height: size.height > 80 ? size.height : 80)
}


text:
Q: Directories at C:/ visible only to one user account on Windows 7 A machine running W7 has two user accounts:
Account 1
Type: Administrator
Directories at C:/ are called 'path_a', 'path_b' and 'path_c'

Account 2
Type: non-Administrator
Directory at C:/ is called 'path_a'

A separate instance of Seafile running on each user account does an automatic back-up on all of the paths.  Each user account has a separate Seafile account associated with it.
the two accounts should share only one folder, path_a
Question
Is it possible to make path_b and path_c invisible to Account 2?  The user does not need to know that the folders exist.
What we've tried
We've successfully adjusted permissions, however, we would like to avoid the user of Account 2 seeing the message "You don't currently have permission to access this folder".
We've also come across a suggestion to hide directory.  We're wondering, however, if there is a cleaner way.


text:
Q: How to handle Object reference not set to an instance of an object when using LINQ and let? I have the following code to get some data about companies:
XDocument doc = XDocument.Load(new StringReader(searchPayload));
XNamespace ns = ConfigurationManager.AppSettings["WebServiceNamespace"];

var businesses = (from node in doc.Descendants(ns + "searchResultsRecord")
                  let ABN = node.Element(ns + "ABN")
                  let mainName = node.Element(ns + "mainName")
                  let legalName = node.Element(ns + "legalName")
                  let mainTradingName = node.Element(ns + "mainTradingName")
                  let otherTradingName = node.Element(ns + "otherTradingName")
                  let mainBusinessPhysicalAddress = node.Element(ns + "mainBusinessPhysicalAddress")
                  select new
                  {
                      Name = new
                      {
                          organisationName = (string)mainTradingName.Element(ns + "organisationName"),
                          score = (string)mainTradingName.Element(ns + "score"),
                          isCurrentIndicator = (string)mainTradingName.Element(ns + "isCurrentIndicator"),
                      },
                      ABN = new
                      {
                          identifierValue = (string)ABN.Element(ns + "identifierValue"),
                          identifierStatus = (string)ABN.Element(ns + "identifierStatus"),
                      },
                      Location = new
                      {
                          stateCode = (string)mainBusinessPhysicalAddress.Element(ns + "stateCode"),
                          postCode = (string)mainBusinessPhysicalAddress.Element(ns + "postcode"),
                          isCurrentIndicator = (string)mainBusinessPhysicalAddress.Element(ns + "isCurrentIndicator"),
                      }
                  }).ToList();

searchPayload is a SOAP message returned from a web service and it returnes up to 200 searchResultRecords of which some of them have a mainName node, some legalNode, some all of the nodes and so on. If I use the code above I get the error in the topic because obviously not all result records have all nodes so how can I handle this?
In Name = new I want to get available "name" nodes
Thanks

A: I can't see anything in the lets that would through, since node should always be non-null. And outside the lets the only time you use it is in blah.Element(..) - so you have two choices:

*

*filter out the ones that won't work (will remove data):
....
let mainTradingName = node.Element(ns + "mainTradingName")
where mainTradingName != null
....

*check before using .Element (will default some fields to blank):
...
organisationName = mainTradingName == null ? "" :
      (string)mainTradingName.Element(ns + "organisationName"),
...


text:
Q: How should I use Regex with specified character? I am writing a code about inputting. Because the keyboard is customized, so the characters "/[]#*._" may appear but I forbid it!!
Actually I can write the code as below:
    if (!_UID.IndexOf(@"/").Equals(-1))
    {
        return ErrorMessage;
    }
    else if (!_UID.IndexOf(@"\").Equals(-1))
    {
        return ErrorMessage;
    }
    else if (!_UID.IndexOf(@"[").Equals(-1))
    {
        return ErrorMessage;
    }
    else if (!_UID.IndexOf(@"]").Equals(-1))
    {
        return ErrorMessage;
    }
    else if (!_UID.IndexOf(@"#").Equals(-1))
    {
        return ErrorMessage;
    }
    else if (!_UID.IndexOf(@"*").Equals(-1))
    {
        return ErrorMessage;
    }
    else if (!_UID.IndexOf(@".").Equals(-1))
    {
        return ErrorMessage;
    }
    else if (!_UID.IndexOf(@"_").Equals(-1))
    {
        return ErrorMessage;
    }

But it's so cheap!! It's clearly that I wanna to forbid those chars in the TextBox and I hope I can express the code with Regex, how should I coding this??

A: You can make it easier by doing something like this
foreach(char c in "/[]#*._"){
   if(!_UID.IndexOf(c.ToString()) == -1) return ErrorMessage;
}

But if you really want regex, you could do
if(!Regex.IsMatch(_UID, "[/[]#*._]")){
   return ErrorMessage;
}

A:
if(!Regex.IsMatch(_UID, "[/[]#*._]")){
   return ErrorMessage;
}

This is wrong in two aspects:

*

*It's an error if there is a forbidden character matched, so the ! is out of place; correct:
if (Regex.IsMatch(…)) return ErrorMessage;

*[/[]#*._] is not a character class with the set of characters / [ ] # * . _, because the first ] ends the character class [/[], which is then followed by #* . _ ]; this would match something like "…[###x_]…", not what is desired. To include ] in a character class, it can be placed right after the opening bracket. Correct:
if (Regex.IsMatch(_UID, "[]/[#*._]")) return ErrorMessage;


text:
Q: how to read excel column with dates before and after year 1900 I am trying to import an xlsx spreadsheet containing birthdays from the year 1899 and earlier.
I use read_excel() from the readxl package and get warning messages such as below:

In read_fun(path = path, sheet_i = sheet, limits = limits, shim =
  shim,  :   Expecting date in B278 / R278C2: got '08/09/1897'

on inspection there are NAs where there should be dates.
Any help on how to import a mix of dates spanning 1900 would be appreciated.


text:
Q: Flutter logic issue I'm building this small game , it's similar to Qix game .
I already built the first screens now i need to implement the functionality  , the car should be moving using the buttons , and while moving it should draw like a container behind it until it feel all the stadium .
this is where I'm making the car moves :
class _GameScreenState extends State<GameScreen> {
  double xPosition = Random().nextInt(230).toDouble();
  double yPposition = Random().nextInt(200).toDouble();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/bg.png"),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            children: [
              // Game play
              Expanded(
                flex: 6,
                child: Stack(
                  children: [
                    Container(
                      height: MediaQuery.of(context).size.height,
                      width: MediaQuery.of(context).size.width,
                      color: Colors.transparent,
                    ),
                    Positioned(
                      bottom: yPposition,
                      left: xPosition,
                      child: Image.asset("assets/images/car.png"),
                    )
                  ],
                ),
              ),
              // Player inputes
              Expanded(
                child: Container(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            RoundIconButton(
                              onPress: () {
                                setState(() {
                                  yPposition--;
                                });
                              },
                              icon: Icons.arrow_downward,
                            ),
                            RoundIconButton(
                              onPress: () {
                                setState(() {
                                  yPposition++;
                                });
                              },
                              icon: Icons.arrow_upward,
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            RoundIconButton(
                              onPress: () {
                                setState(() {
                                  xPosition--;
                                });
                              },
                              icon: Icons.arrow_back,
                            ),
                            RoundIconButton(
                              onPress: () {
                                setState(() {
                                  xPosition = xPosition + 10;
                                });
                              },
                              icon: Icons.arrow_forward,
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

I also need the car keep moving when I press the button , in my case it moves only one time

A: You can a timer how often you like to change the position.
To get tap event, GestureDetector is suitable in this case,
we will use onPanStart to update the value using timer and onPanEnd to cancel the timer.
Run on dartPad.
  late Timer timer;

  final duration = const Duration(milliseconds: 100);
  void moveUp(_) {
    timer = Timer.periodic(duration, (timer) {
      setState(() {
        yPposition++;
      });
    });
  }

  void moveDown(_) {
    timer = Timer.periodic(duration, (timer) {
      setState(() {
        yPposition--;
      });
    });
  }

  void moveRight(_) {
    timer = Timer.periodic(duration, (timer) {
      setState(() {
        xPosition++;
      });
    });
  }

  void moveLeft(_) {
    timer = Timer.periodic(duration, (timer) {
      setState(() {
        xPosition--;
      });
    });
  }

  void onEnd(_) {
    timer.cancel();
  }

and method will be used
Row(
      children: [
        GestureDetector(
          onPanStart: moveDown,
          onPanEnd: onEnd,
          child: Icon(Icons.arrow_downward),
        ),
        GestureDetector(
          onPanStart: moveUp,
          onPanEnd: onEnd,
          child: Icon(Icons.arrow_upward),
        ),
      ],
    ),
    Row(
      children: [
        GestureDetector(
          onPanStart: moveRight,
          onPanEnd: onEnd,
          child: Icon(Icons.arrow_forward),
        ),
        GestureDetector(
          onPanStart: moveLeft,
          onPanEnd: onEnd,
          child: Icon(Icons.arrow_back),
        ),
      ],
    ),
  ],
),


text:
Q: Pandas read google sheet data types wrong I read some Google Sheet data through GSpread and Pandas; however, Pandas gives my dtype as object and I cannot change it.
I'm sure that my Google Sheet values are numbers, apart from the headers, which are strings. Matplotlib will not allow me to plot a graph, as it throws a type error.
The issue is solved if I download the file as CSV but I would like to read the file directly from the google sheet.
Here is the code:
main_worksheet=sh.worksheet('Sheet3')

data = main_worksheet.get_all_values()
headers = data.pop(0)

df = pd.DataFrame(data, columns=headers, dtype='int64')

df['week'].astype(str).astype(int)

print(df['week'])

And the result:
0     28
1     29
2     30
3     31
4     32
5     33
6     34
7     35
8     36
9     37
10    38
11    39
12    40
13    41
14    42
15    43
16    44
17    45
18    46
19    47
20    48
Name: week, dtype: object

A: Having the same problem.
Apparently, when reading a google sheet with pandas, it doesn't allow having different data types in the same column.
If it finds different data types in the same column it converts everything into a string/object, but it's strange because when you check specific values that are strings, now they are defaulted to NaN.
To solve that problem you need to convert the entire column into the same format "Plain text" from google sheets and then if you need to change the data type as it was you can do it using the apply method once you have read the dataframe.
Problem:
enter image description here
Reading with pandas
enter image description here
SOLUTION:
enter image description here
Reading with pandas
enter image description here


text:
Q: Remove duplicates in each line of a file How can I remove duplicates in each line, for example here?
1 1 1 2 1 2 3
5 5 4 1 2 3 3

I'd like to get this output:
1 2 3
5 4 1 2 3

There are lots of lines (100,000) and in each line I want unique values.
Perl might be the fastest, but how can I do it in Perl or Bash?

A: Since ruby comes with any Linux distribution I know of:
ruby -e 'STDIN.readlines.each { |l| l.split(" ").uniq.each { |e| print "#{e} " }; print "\n" }' < test

Here, test is the file that contains the elements.
To explain what this command does—although Ruby can almost be read from left to right:

*

*Read the input (which comes from < test through your shell)

*Go through each line of the input

*Split the line based on one space separating the items, into an array (split(" "))

*Get the unique elements from this array (in-order)

*For each unique element, print it, including a space (print "#{e} ")

*Print a newline once we're done with the unique elements

A: Not pure bash, but ...:
while read line; do
    printf "%s\n" $line | sort -u | tr '\n' ' '
    echo ''
done < file

The lines will be sorted as a byproduct.

A: Here is an option using awk:
awk '{ while(++i<=NF) printf (!a[$i]++) ? $i FS : ""; i=split("",a); print ""}' infile > outfile

Edit Updated with comments:

*

*while (++i<=NF)
Initializes the while loop, precrementing "i" since $0 is the full line in awk.
So it starts at $1 (first field).  Loops through the line until the end (less than or equal to  'NF' which is built into awk for "Number of Fields").  The default field separator is a  space, you could change the default separator easily.

*printf (!a[$i]++) ? $i FS : ""
This is a ternary operation.
So, if input is not in the array !a[$i]++, then it prints $i, if it is, it prints "".  (You could remove the ! and reverse the $i FS : "" if you don't like it this way).

*i=split("",a)
Normally, that's a null split.  In this case, it resets I for the next line.

*print ""
ends the line for the output (not 100% why, actually), otherwise you would have an output of:
1 2 3 5 4 1 2 3 instead of
1 2 3
5 4 1 2 3


text:
Q: Getting error while hashing password with bcrypt: can not find module bcrypt_lib.node I'm working on an api project with node.js and receive this error while trying to hash my code with bcrypt package :
  throw err;
  ^

Error: Cannot find module '/home/emad/work/node.js/npm-demo/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node'
Require stack:
- /home/emad/work/node.js/npm-demo/node_modules/bcrypt/bcrypt.js
- /home/emad/work/node.js/npm-demo/routes/users.js
- /home/emad/work/node.js/npm-demo/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
    at Function.Module._load (internal/modules/cjs/loader.js:841:27)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/home/emad/work/node.js/npm-demo/node_modules/bcrypt/bcrypt.js:6:16)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/home/emad/work/node.js/npm-demo/routes/users.js:1:16)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/home/emad/work/node.js/npm-demo/index.js:8:14)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/emad/work/node.js/npm-demo/node_modules/bcrypt/bcrypt.js',
    '/home/emad/work/node.js/npm-demo/routes/users.js',
    '/home/emad/work/node.js/npm-demo/index.js'
  ]
}

My OS is a Ubuntu 18.04.5 LTS and I installed all the dependecies that was written down in bcrypt page in npm site

A: try below steps and run:-

*

*Delete node_modules folder

*run npm cache clean --force

*npm install


text:
Q: how to read the values from completablefuture after it is returned from the method List<CompletableFuture<GreetHolder>> completableFutures = langList.stream()
                                                                  .map(lang -> getGreeting(lang))
                                                                  .collect(Collectors.toList());

CompletableFuture<Void> allFutures = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]));

CompletableFuture<List<GreetHolder>> allCompletableFuture = allFutures.thenApply(future -> {
    return completableFutures.stream().map(completableFuture -> completableFuture.join()).collect(Collectors.toList());
});

CompletableFuture completableFuture = allCompletableFuture.thenApply(greets -> {
    return greets.stream().map(GreetHolder::getGreet).collect(Collectors.toList());
});

completableFuture.get();

private CompletableFuture<GreetHolder> getGreeting (String lang){
    return CompletableFuture.supplyAsync(() -> {
        try {
            logger.info("Task execution started.");
            Thread.sleep(2000);
            logger.info("Task execution stopped.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new GreetHolder(getGreet(lang));
        }, pool);
    }
}

I want to read the List of greeting values returned from either from allCompletableFuture or completableFutureCompleted. I am not sure how to read the values returned by getGreeting method and output the list to the screen. Please feel free to modify the code if needed in the last step.

A: Your greetings are returned by completableFuture.get(); but you aren't capturing them in your example.
Assuming "getGreet" returns a string, does this work?
List<String> greetings = completableFuture.get();


text:
Q: Unwanted border appearing on video element I'm trying to get rid of the border around this video http://bit.ly/ZihaJV The idea is that the video plays on a white background with no borders. The problem might be due to the ratio of the video and the size of the player.
I also found this post but it doesn't solve the problem. I don't even have access to Flash to compile the swf. videojs disable black background
Using a  with a white border around the video to hide the black lines appearing might be a work around but I run into a problem because the video needs to be responsive.
The actual webpage shows more borders than this testing one. Sorry but I can't show the original.
Thanks and any help will be welcome.

A: In the video you linked to, the border line along the top of the video is part of the video file itself, so it's an issue with the original file or the way you edited it. (I often have this problem with videos. Quite annoying.)
A quick visual fix with CSS would be to pull the top of the video up a bit and hide the line at the top:
.video-js .vjs-tech {
    top: -2px;
}

.video-js {
    overflow: hidden;
}

But yeah, that's a little cheeky.

A: The way I finally sorted out following ralph.m comments is as follow:
.video-js .vjs-tech {
  /* make the video larger so it can hide*/
  width: 102%;
  height: 102%;
  /* displace video to hide*/
  left: -5px;
  /* allow space for hiding*/
  margin: -10px;
  position: absolute;
  top: 0;
}

.video-js {
  /* make sure overflow is hidden*/
  overflow: hidden;
}


text:
Q: Issue retrieving Shared preference values We are saving the following from one application:
final CheckBoxPreference mCheckPref = new CheckBoxPreference(sContext);
mCheckPref.setKey("alertnotification");

and we are retrieving it from a second application follows:
mContext = context.createPackageContext("com.android.abc",Context.CONTEXT_INCLUDE_CODE |     Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean alertnotification = prefs.getBoolean("alertnotification",true);

I always get the alertnotification as false, even during the first time where I have set the default value to be true. Why does this happen?

A: http://developer.android.com/reference/android/content/SharedPreferences.html
"Note: currently this class does not support use across multiple processes. This will be added later."


text:
Q: Replace all plain text links with href and remove https, https and www I am trying to replace all plain links with hrefs and remove the beginning part of the url.
The current code I am working with finds https and http links and replaces them, but it doesn't work with www. plain links.

var links = $('#links').text();

var formatText = links.replace(/((http|https|www):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '$1
');

$('#links2').html(formatText);

https://www.example.com/

https://www.example.com/blah/blah/

http://www.example.com/

http://www.example.com/blah/blah

www.example.com/

www.example.com/blah/blah

I would also like the https, http and www. removed from the link text aswell, for example:
example.com/
example.com/

Does anyone know how?

A: You can use
/^.*?\.(.*)/

If you want the original link in the href attribute then you can use ${link} or if you want the link with domain only then you can use ${group}

const links = [
  "https://www.example.com/",
  "https://www.example.com/blah/blah/",
  "http://www.example.com/",
  "http://www.example.com/blah/blah",
  "www.example.com/",
  "www.example.com/blah/blah",
];
const result = links.map((link) =>
  link.replace(/^.*?\.(.*)/, (...args) => {
    const [, group] = args;
    return ` <a href="${link}" target="_blank">${group}</a><br>`;
  })
);

console.table(result);


text:
Q: dpkg error processing package gdm3 (--configure) After I upgraded from 16.04 to 17.04 I have a black screen.
I ran:
sudo apt-get update
sudo apt full-upgrade -f
dpkg error processing package gdm3 (--configure) subprocess installed post-installation script returned error exit status 10 . Errors weres encountered while processing: gdm3


text:
Q: C++ Errors: " 'class' does not name a type" and "invalid use of incomplete type 'struct ...' " Here is a very repetitive issue, also here in StackOverflow, but I do not manage to solve my problem even trying the different answers. So, I have some classes:
main.cpp:
#include "foo.h"
#include "bar.h"

...

foo.h:
#include "bar.h"
class foo {
  foo();
  bar& bind(bar &b);
  gru& bind(gru &g);
};

bar.h:
#include "foo.h"
class bar {
  bar();
  foo& bind(foo &f);
  gru& bind(gru &g);
};

Clearly, I have a cyclic dependency. So I get the infamous error 'bar' does not name a type. In this case, I add class bar; to foo declaration and delete the #include. When I do that, I get: invalid use of incomplete type 'struct bar'.
I tried in some different ways, also adding class foo; to bar, but I always have some kind of error. In this last case I get:
bar.cpp:48:11: error: prototype for 'foo& bar::bind(bar::foo&)' does not match any in class 'bar'
bar.h:55:12: error: candidates are: gru& bar::bind(gru&)
bar.h:54:13: error:                 bar::foo& bar::bind(bar::foo&)

Plus, I never get any complain about gru. Which, as an additional information, was already there in this program, working perfectly along with bar and main, before I added foo.
Any helpful ideas? Thanks a lot :)

A: in foo.h
  #pragma once //(or use a guard symbol)
  class bar;
  class foo
  {
     bar & bind(bar & b);
  };

in bar.h
  #pragma once //(or use a guard symbol)
  class foo;
  class bar
  {
     foo & bind(foo & f);
  };

in foo.cpp
#include <foo.h>
#include <bar.h>

bar foo:bind(bar & b)
{
  // here you can use bar methods
}

in bar.cpp
#include <bar.h>
#include <foo.h>

foo bar:bind(foo & f)
{
  // here you can use foo methods
}

A: This will compile fine for me (NOTE: This is without instantiating either the foo or bar class):
FILE bar.h CONTAINS:
#ifndef BAR_H
#define BAR_H

#include "foo.h"

class foo;
class gru;

class bar {

  bar();
  foo& bind(foo &f);
  gru& bind(gru &g);
};

#endif

FILE foo.h CONTAINS:
#ifndef FOO_H
#define FOO_H
#include "bar.h"
class bar;
class gru;
class foo {
  foo();
  bar& bind(bar &b);
  gru& bind(gru &g);
};

#endif

MAIN .cpp FILE CONTAINS:
#include "foo.h"
#include "bar.h"

A: The C++ compiler is very old, and furthermore, the part that handles this example in your code is not the compiler itself, but a part of the compiler chain known as the preprocessor. If we can agree on the C++ compiler being not very smart, the preprocessor is a dull, but friendly, assistant.
A *.cpp file is is compiled and later linked with the other *.cpp files in your program. The .h files actually do not have any meaning by themselves: this separation is supposedly an advantage for programmers. The key point here is that, no matter how many *.h files you included in your *.cpp file, finally there will be just a huge, generated cpp file contaning the whole code present in your *.h files, and also the source code present in your *.cpp file itself.
A cyclic dependency could be solved by many ways, but, as you can imagine, the compiler does not even have the opportunity to handle anything before the problem is produced. Cyclic dependencies are not supported in C or C++.
More modern compilers, such as Java or C#, are able to extract the public interface of classes, and use this information when the A class is needed for the B class, and viceversa. Again, this is not possible in C++.
The only solution would be to rewrite your code. The objective is to eliminate the cyclic #include directives. Actually, if your code is as simple as you are showing here, you can easily solve it by using a forward declaration:
// foo.h
class bar;

class foo {
  foo();
  bar& bind(bar &b);
  gru& bind(gru &g);
};

--
// bar.h
class foo;

class bar {
  bar();
  foo& bind(foo &f);
  gru& bind(gru &g);
};

--
// main.cpp
#include "foo.h"
#include "bar.h"

// ...
int main()
{
    // ...
}

A forward declaration makes it possible to let the compiler know that this class actually is going to exist, and you are declaring its presence ahead, but not giving details about its contents. That's why you can just use this forward declaration for a pointer (or reference), inside another class (the compiler would need the size of the forwarded class in order to be able to create an attribute, and that's impossible without details).
There are other concepts to work here, such as compiler guards, for example.
Hope this helps.

A: Thank you a lot guys for the answers. In many ways they were helpful.
In the end I realized that I had to reorder all the #include's in my code, because, as you may have realized, there were a lot more coding and what I put here was a simpler version (sorry for that).
So, my final solution was to  include class bar; in foo.h and class foo; in bar.h. Then reorder the includes in main.cpp and the Makefile.
Thanks again ;-)


text:
Q: Where to define a one-shot constant for most efficient code? Which variant is most efficient, and why? Or will they get optimized to the same code?
char inplace(int i) {
    // [some check if 0<=i<=2 here]
    return "azS"[i];
}

char infunc(int i) {
    const char s[] = "azS";
    // [some check if 0<=i<sizeof(s)/sizeof(s[0])-1 here]
    return s[i];
}

const char s[] = "azS";
char inglobals(int i) {
    // [some check if 0<=i<sizeof(s)/sizeof(s[0])-1 here]
    return s[i];
}

Please don't rant about how premature optimization is evil, this is just irresistible curiosity inherent for a born C++'er ;)

A: I just compiled and disassembled your code. inplace and inglobals are identical. This is very intuitive: the compiler can store the const string in the .rodata section.
Weirdly, gcc produces quite a lot of code for infunc (see below), probably because you "insist" on having s on the stack. Defining s as static makes infunc produce the same code as inplace and inglobals.

0000000000000010 :
  10:   48 83 ec 18             sub    $0x18,%rsp
  14:   48 63 ff                movslq %edi,%rdi
  17:   64 48 8b 04 25 28 00    mov    %fs:0x28,%rax
  1e:   00 00
  20:   48 89 44 24 08          mov    %rax,0x8(%rsp)
  25:   31 c0                   xor    %eax,%eax
  27:   c7 04 24 61 7a 53 00    movl   $0x537a61,(%rsp)
  2e:   0f b6 04 3c             movzbl (%rsp,%rdi,1),%eax
  32:   48 8b 54 24 08          mov    0x8(%rsp),%rdx
  37:   64 48 33 14 25 28 00    xor    %fs:0x28,%rdx
  3e:   00 00
  40:   75 05                   jne    47
  42:   48 83 c4 18             add    $0x18,%rsp
  46:   c3                      retq
  47:   e8 00 00 00 00          callq  4c

EDIT
The location %fs:0x28 is related to GCC's stack protector. Disabling it give the following code:

0000000000000010 :
  10:   48 63 ff                movslq %edi,%rdi
  13:   c7 44 24 f0 61 7a 53    movl   $0x537a61,-0x10(%rsp)
  1a:   00
  1b:   0f b6 44 3c f0          movzbl -0x10(%rsp,%rdi,1),%eax
  20:   c3                      retq

So, in this case, GCC chose to store your string inline with the code and copy it on the stack during execution. I would argue this is very efficient, since your processor's cache is already filled with the string, so no memory access occurs.
EDIT
To sum up, all three versions are equivalent. Nevertheless, depending on your compiler implementation, one may turn out to be more efficient than the other. For GCC, infunc seems more efficient for short strings, as the string is fetched along with the instructions. For larger strings, I would use inplace or inglobals.

A: I think that the compiler would produce the same for 1 and 3, and might produce the same for 2 (depending slightly on whether it realised it could get away with not actually copying the data onto the stack). I'm also assuming this isn't in a header or class somewhere, which would make a lot of difference (I know your code doesn't look like it is, but I'm just being cautious).
In general, unless optimisation proved otherwise, I'd go for minimising the scope of a declaration (which rules out 3). And between 1 and 2 the chances of going wrong if you change the contents of the string are much higher for 1.
Which leaves me suggesting that it is likely to make no difference in the generated code, but option 2 is a lot lot better than the other 2.


text:
Q: C# Process is not restoring to task bar after form is closed I have this Form5 and When i load it, is supposed to load google chrome into this window form if chrome is already running or not then is going to start a new process.
Then issue stands at when im closing the Form5 then chrome is not being unembedded from the window form and as you can see on Form5_FormClosed is the code that is supposed to restore the window back to task bar but nothing happens and sometimes after 1 of 100 is working. What im doing wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TrinityItemCreator
{
    public partial class Form5 : Form
    {
        private string urlDestination;

        private Process myprocess;

        public Form5(string urlTarget)
        {
            InitializeComponent();
            urlDestination = urlTarget;
        }

        [DllImport("user32.dll")]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        // HWND Constants
        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        static readonly IntPtr HWND_TOP = new IntPtr(0);
        static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

        // P/Invoke
        [DllImport("user32.dll")]
        static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private void Form5_Load(object sender, EventArgs e)
        {
            Process[] pname = Process.GetProcessesByName("chrome");
            if (pname.Length != 0) // chrome is already opened
            {
                //Process.Start("chrome", urlDestination);
                Process[] processlist = Process.GetProcesses();
                foreach (Process theprocess in processlist)
                {
                    if (theprocess.ProcessName == "chrome")
                    {
                        SetParent(theprocess.MainWindowHandle, panel2.Handle);
                        int left = 1;
                        int top = 1;
                        int width = 876;
                        int height = 656;

                        SetWindowPos(theprocess.MainWindowHandle, HWND_TOP, left, top, width, height, 0);
                        myprocess = theprocess;
                    }
                }
            }
            else
            {
                myprocess = Process.Start("chrome", urlDestination);
                Thread.Sleep(1000);
                SetParent(myprocess.MainWindowHandle, panel2.Handle);
                int left = 1;
                int top = 1;
                int width = 876;
                int height = 656;

                SetWindowPos(myprocess.MainWindowHandle, HWND_TOP, left, top, width, height, 0);
            }
        }

        private void Form5_FormClosed(object sender, FormClosedEventArgs e)
        {
                SetParent(myprocess.MainWindowHandle, IntPtr.Zero);
                ShowWindow(myprocess.MainWindowHandle, 3); // maximize back
                ShowWindow(myprocess.MainWindowHandle, 2); // minimize to taskbar
                Thread.Sleep(1500);
        }

        private void ButtonMyTemplates_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}


text:
Q: 16.04.1 LiveCD briefly boots into TTY1, then black screen; TTY1 asks for username/password I run a dual boot w/ Windows 7. Recently, I installed Windows 7 Service Pack 1 which, surprise surprise, screwed up Grub and left Windows the default OS w/ no option to boot into Ubuntu. This is usually a pretty easy fix (boot-repair), but the problem is I can't get a LiveCD that boots.
When I boot from a LiveCD usb, the screen flicks to TTY1, then to a black screen. The screen stays black unless I press ctrl + alt + F1 to get back to TTY1, where I'm then asked for a username and password. I've tried ubuntu with a blank password and this does not work.
I'm using this image. I've tried with a fresh USB multiple times. Anyone have any ideas?

A: Try using EasyUEFI in Windows to adjust the boot order -- move the ubuntu item to the top of the boot list. This should fix the problem; however, be aware that there are buggy EFIs that may forget boot entries or have problems with re-ordering them. There's also a slim chance that Windows has deleted the Ubuntu entry, in which case it will have to be re-created.


text:
Q: Access automatically mounted owncloud/nextcloud mountpoint in gnome In PureOS (Gnome desktop) I have added an Owncloud instance (by using the Nextcloud configuration panel). Where do I access the folder I can reach by Nautilus via bash? In other words: Where is the mount point for Own-/Nextcloud instances?
I once found this by googling, however, now I do not with searches like

where is Nextcloud automatically mounted gnome

get me e.g. to the Nextcloud documentation. However, there is no such information. More terminal specific searches usually give me results on how to mount Nextcloud by terminal which is not my goal.

A: Found it by right clicking

So the folder location is
/run/user/1000/gvfs/dav:host=<host>,ssl=true,user=<user>,prefix=%2Fowncloud%2Fremote.php%2Fwebdav


text:
Q: Using pydev with Eclipse on OSX I setup PyDev with this path for the python interpreter
/System/Library/Frameworks/Python.framework/Versions/2.5/Python
since the one under /usr/bin were alias and Eclipse won't select it. I can run my python script now but cannot run the shell as an external tool. The message I get is
variable references empty selection ${resource_loc}
Same if I use {container_loc}
Any thoughts ?
Sunit

A: I installed the Python.org version as well, this is a must.
I finally got PyDev working in Eclipse by pointing the interpreter to:
/Library/Frameworks/Python.framework/Versions/2.6/bin/python

manually.  If you don't do it manually (by using the Autoconfig) it seems to not find the right version.

A: Common practice seems to be to install an up-to-date Python 2.5 from python.org and use that instead of the system installation. I saw that recommended here and there when I got started on Mac OS X.
It installs under /Library (as opposed to /System/Library) so the system Python is intact. Pydev has /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python as its configured Python interpreter and all is well.
Can't state for sure that your trouble is due only to using the system's Python installation; in any case this way I have no trouble. Also, this way when you fiddle with your development environment (install things in site-packages, upgrade Python), anything that uses the system Python is sure to be unaffected.

A: I know this is a ancient post... but, in case of some newbee like me to get the better answer.
I just using "Eclipse Marketplace" from the "Help" menu and search for keyword "python" or "PyDev" to get PyDev, and get it successfully installed.
AND, you should add PyDev to the top-right dock.
For the instance, my eclipse on my laptop's OSX is (Version: Indigo Service Release 2 Build id: 20120216-1857).
Have fun, folks! :)

A: I believe ${resource_loc} or ${container_loc} (without any argument) are based on the current selection in your workbench when you are launching your script.
So are you selecting the right resource when selecting that script through the "external tool" runner ?
At least, click on the project name before you run one of the external programs.
Note: it works with a selection in the Navigator or Package Explorers views (the latest might not be available in PyDev environment though)


text:
Q: Finding action handlers in Ember debugger I'm finding that when I put my form's actions handlers into the controllers action property as is now recommended these handlers no longer are visible within the Ember debugger. Is that correct or am I missing something?
To illustrate ... I have the following controller:
App.UomsController = Ember.ArrayController.extend({
    testing: null,
    actions: {
        addUom: function() {
            var router = this.get('target');
            router.transitionTo('uoms.new');
        }
    }
});

The property testing shows up clearly enough in the debugger but not actions and consequently no way to get to the addUom method.

A: The actions is managed by Ember.ActionHandler. At the moment, it will copy that info in the _actions property. So controller._actions.someAction, will return the action handler.
For example:
App.IndexController = Ember.Controller.extend({
    actions: {
        lorem: Ember.K,
        ipsum: Ember.K,
        showActionsInController: function() {
            alert(Ember.keys(this._actions)); // will display 'lorem,ipsum,showActionsInController'
        }
    }
});

Here is a fiddle with this in action http://jsfiddle.net/marciojunior/8xfRJ/


text:
Q: Is Mega Millions Positive Expected Value? Given the rapid rise of the Mega Millions jackpot in the US (now advertised at \$640 million and equivalent to a "cash" prize of about \$448 million), I was wondering if there was ever a point at which the lottery became positive expected value (EV), and, if so, what is that point or range?
Also, a friend and I came up with two different ways of looking at the problem, and I'm curious if they are both valid.
First, it is simple to calculate the expected value of the "fixed" prizes. The first five numbers are selected from a pool of 56, the final "mega" ball from a pool of 46. (Let us ignore taxes in all of our calculations... one can adjust later for one's own tax rate which will vary by state). The expected value of all these fixed prizes is \$0.183.
So, then you are paying \$0.817 for the jackpot prize. My plan was then to calculate the expected number of winners of the jackpot (multiple winners split the prize) to get an expected jackpot amount and multiply by the probability of selecting the winning numbers (given by $\binom{56}{5} * 46 = 1 \text{ in } 175,711,536$). The number of tickets sold can be easily estimated since \$0.32 of each ticket is added to the prize, so:
(Current Cash Jackpot - Previous Cash Jackpot) / 0.32 = Tickets Sold
$(448 - 252) / 0.32 = 612.5$ million tickets sold (!!).
(The cash prizes are lower than the advertised jackpot. Currently, they are about 70% of the advertised jackpot.) Obviously, one expects multiple winners, but I can't figure out how to get a precise estimate, and various web sources seem to be getting different numbers.
Alternative methodology: My friend's methodology, which is far simpler, is to say 50% of this drawing's sales will be paid out in prizes (\$0.18 to fixed prizes and \$0.32 to the jackpot). Add to that the carried over jackpot amount (\$250 million cash prize from the unwon previous jackpot) that will also be paid out. So, your expected value is $\$250$ million / 612.5 million tickets sold = \$0.40 from the previous drawing + \$0.50 from this drawing = \$0.90 total expected value for each \$1 ticket purchased (before taxes). Is this a valid approach or is it missing something? It's far simpler than anything I found while searching the web for this.
Added: After considering the answer below, this is why I don't think my friend's methodology can be correct: it neglects the probability that no one will win. For instance, if a $1$ ticket was sold, the expected value of that ticket would not be $250 million + 0.50 since one has to consider the probability of the jackpot not being paid out at all. So, additional question: what is this probability and how do we find it? (Obviously it is quite small when $612.5$ million tickets are sold and the odds of each one winning is $1:175.7$ million.) Would this allow us to salvage this methodology?
So, is there a point that the lottery will be positive EV? And, what is the EV this week, and the methodology for calculating it?

A: As you say, the chance of a winning ticket is about 1 in 176M.  The expected number of  winners is therefore 612.5/176 or about 3.5.  The expected prize for a winner is not simply \$448M/3.5 as the average of inverses is not the inverse of the average.  You quote \$640M as the jackpot early, but then seem to use \$448M for your calculation.
Your friend's approach is fine, too.  I haven't checked whether your numbers are consistent.  The EV only goes down as more tickets are sold, as the \$0.40 per ticket goes down, so this time it will never be above \$1.
Added:  the value of the carryover $C$ is $\frac C{176M}$ for the first ticket bought as the chance of winning.  In general, it is $\frac {C\cdot P_{win}}{n}$ where $P_{win}$ is the probability of somebody winning =$1-(\frac {176M-1}{176M})^n$ and $n$ is the number of new tickets bought.  For $n$ large, $P_{win} \approx 1$ and we get the earlier formula.

A: Regarding the last part of your question about the probability of nobody winning, I think we can approach it in the following way.  Assume for the sake of argument that all tickets are randomly generated and independent of one another.  A given ticket will lose the jackpot with probability $p = \frac{175711535}{175711536}$.  Since we said the tickets were independent, the probability of two tickets losing $p^2$, and in general, the probability of $n$ tickets all losing is $p^n$.  With 612.5 million tickets sold, this equates to roughly a 3% chance that nobody wins $(p^{612500000})$.
Now it is not strictly the case that the tickets in play are random and independent from one another.  I suspect that could lead to more duplicate tickets (birthdays, etc.), and consequently a slightly higher chance of nobody winning.  I don't have a good framework for estimating that, but I doubt it affects results that much.
Edit: As a related aside, these ticket assumptions allow us to use the binomial distribution to find the probability of exactly $n$ winners for our choice of $n$.  Here is a random sampling of that distribution for 50 drawings:
$$7, 3, 3, 4, 0, 4, 1, 3, 5, 1, 7, 4, 3, 5, 5, 6, 5, 6, 3, 5, 2, 2, 2, 1, 5, 3, 5, 2, 3, 6, 9, 1, 4, 1, 4, 3, 4, 2, 2, 5, 3, 3, 4, 0, 2, 5, 6, 5, 1, 3$$
As you can see, there's a decent chance of 4, 5, 6, or more jackpot winners.

A: I did a fairly extensive analysis of this question last year.  The short answer is that by modeling the relationship of past jackpots to ticket sales we find that ticket sales grow super-linearly with jackpot size.  Eventually, the positive expectation of a larger jackpot is outweighed by the negative expectation of ties.  For MegaMillions, this happens before a ticket ever becomes EV+.

A: An interesting thought experiment is whether it would be a good investment for a rich person to buy every possible number for \$175,711,536.  This person is then guaranteed to win!  Then you consider the resulting size of the pot (now a bit larger), the probability of splitting it with other winners, and the fact that you get to deduct the \$175.7M spent from your winnings before taxes.  (Thanks to Michael McGowan for pointing out that last one.)
The current pot is \$640M, with a \$462M cash payout.  The previous pot was \$252M cash payout, so using \$0.32 into the cash pot per ticket, we have 656,250,000 tickets sold.  I, the rich person (who has enough servants already employed that I can send them all out to buy these tickets at no additional labor cost) will add about \$56M to the pot.  So the cash pot is now \$518M.
If I am the only winner, then I net (\$518M + \$32M (my approximate winnings from smaller prizes)) * 0.65 (federal taxes) + 0.35 * \$176M (I get to deduct what I paid for the tickets) = \$419M.  I live in California (of course), so I pay no state taxes on lottery winnings.  I get a 138% return on my investment!  Pretty good.  Even if I did have to pay all those servants overtime for three days.
If I split the grand prize with just one other winner, I net \$250M.  A 42% return on my investment.  Still good.  With two other winners, I net $194M for about a 10% gain.
If I have to split it with three other winners, then I lose.  Now I pay no taxes, but I do not get to deduct my gambling losses against my other income.  I net \$161M, about an 8% loss on my investment.  If I split it with four other winners, I net \$135M, a 23% loss.  Ouch.
So how many will win?  Given the 656,250,000 other tickets sold, the expected number of other winners (assuming a random distribution of choices, so I'm ignoring the picking-birthdays-in-your-numbers problem) is 3.735.  Hmm.  This might not turn out well for Mr. Money Bags.  Using Poisson, $p(n)={\mu^n e^{-\mu}\over n!}$, where $\mu$ is the expected number (3.735) and $n$ is the number of other winners, there is only a 2.4% chance of me being the only winner, a 9% chance of one other winner, a 17% chance of two, a 21% chance of three, and then it starts going down with a 19% chance of four, 14% for five, 9% for six, and so on.
Summing over those, my expected return after taxes is \$159M.  Close.  But about a 10% loss on average.
Oh well.  Time to call those servants back and have them make me a sandwich instead.
Update for October 23, 2018 Mega Millions jackpot:
Same calculation.
The game has gotten harder to win, where there are now 302,575,350 possible numbers, and each ticket costs \$2. So now it would cost $605,150,700 to assure a winning ticket. Also the maximum federal tax rate has gone up to 39.6%.
The current pot (as of Saturday morning -- it will probably go up more) has a cash value of \$904,900,000. The previous cash pot was \$565,600,000. So about 530 million more tickets have been or are expected to be purchased, using my previous assumption of 32% of the cost of a ticket going into the cash pot. Then the mean number of winning tickets, besides the one assured for Mr. Money Bags, is about 1.752. Not too bad actually.
Summing over the possible numbers of winners, I get a net win of $\approx$\$60M! So if you can afford to buy all of the tickets, and can figure out how to do that in next three days, go for it! Though that win is only a 10% return on investment, so you could very well do better in the stock market. Also that win is a slim margin, and is dependent on the details in the calculation, which would need to be more carefully checked. Small changes in the assumptions can make the return negative.
Keep in mind that if you're not buying all of the possible tickets, this is not an indication that the expected value of one ticket is more than \$2. Buying all of the possible ticket values is $e\over e-1$ times as efficient as buying 302,575,350 random tickets, where you would have many duplicated tickets, and would have less than a 2 in 3 chance of winning.

A: The only way to see positive expected value is for no one to win tonight and for there to be some kind of major attention-grabbing popular culture or other kind of phenomenon which causes people to uncharacteristically forget that the lottery exists so that ticket sales are unusually low at the same time that a jackpot is high.
Short of this, ticket sales will tend to grow dramatically as the jackpot grows causing the expected number of winners splitting the jackpot to substantially diminish the expected size of the payout given a correctly picked entry.
Listening to people's rationalizations around this is dizzying:
A: "Look, the jackpot is 640M and the odds are only 1:175M that sounds like +EV!"
B: "The present value of the jackpot is more like 448M..."
A: "That still sounds like +EV"
B: "And you have to pay significant taxes..."
A: "Still +EV"
B: "And lots of people are playing so even if you do win you will probably split with a number of others."
A: "Yeah, but in that case I will win at least 100M which is more than I can imagine."
B: "Which is the same as any other ordinary Mega Millions week; massively -EV."


text:
Q: cancel button to close fancybox 2.x I've created a confirmation windows for a form using fancybox 2.x. Everything with it is working, the form submits and load a fancybox windows with all the proper confirmation information. At the bottom of the confirmation page I have a submit button and a cancel button.
I'm using this code to load the fancybox window when the submit button is clicked.
    $("#contact-form").live('submit', function(e) {
            $.ajax({
                type: "POST",
                cache: false,
                url: "/form_datas/confirm/",
                data: $("#contact-form").serialize(),
                dataType: 'text',
                success: function(data) {
                    $.fancybox(data, {
                        width:600,
                        closeBtn: false,
                        openEffect: 'none',
                        closeEffect: 'none',
                        onCancel: fancyClose(),
                        onClose: fancyClose(),
                    });
                }
            });

            return false;
    });

The buttons on the confirmation window/fancybox modal window:
<input class="submit btn button adbtn" id="confirmSubmitBtn" type="submit" value="Confirm">
<button type="button" class="submit btn button adbtn" id="stopBtn">Cancel</button>

The below code works with the submit button, but not the cancel button. Any ideas?
$( document ).ready(function() {
    $("#confirmSubmitBtn").click(function(e) {
        e.preventDefault();
        parent.$.fancybox.close(true);
        $("#contact-form").submit();
        return false;
    });

    $("#stopBtn").click(function(e) {
        e.preventDefault();
        parent.$.fancybox.close(true);
        return false;
    });
});


text:
Q: Webpack Dev Server React Subfolder Not Working I have a webpack dev server that I want to server from a folder. Example url would be:
localhost/app
I have in my webpack config:
devServer: {
    hot: true,
    contentBase: path.resolve(__dirname, "dist"),
    port: 3002,
    host: "0.0.0.0",
    publicPath: "/app",
    historyApiFallback: true,
    disableHostCheck: true
},
output: {
    path: path.join(__dirname, "dist"),
    publicPath: "/app/",
    filename: "app.[hash].js"
}

This works fine. I can load up my app by going to localhost/app. But since I am using react I want to use a router, and when I go to a route under that subfolder I get an error:
Cannot GET /app/user

If I change everything back to server from / then the routing works. I would like to serve from a folder and have routing work still with webpack dev server, but I am not sure if that is possible.
Here is my app and routes.
import React from "react";
import { render } from "react-dom";
import { AppContainer } from "react-hot-loader";
import { BrowserRouter } from 'react-router-dom';

import App from "./components/App";

const renderApp = Component => {
    render(
        <AppContainer>
            <BrowserRouter basename="/app">
                <App />
            </BrowserRouter>
        </AppContainer>,
        document.getElementById("root")
    );
};

renderApp(App);

if (module.hot) {
    module.hot.accept(() => renderApp(App));
}

App.js
import React, { Component } from "react";
import { Route } from 'react-router-dom';
import Login from './Login';

export default class App extends Component {
    render() {
        return (
            <div>
                <Route exact path="/" component={Login}/>
                <Route exact path="/user" component={Login}/>
            </div>
        );
    }
}

I am new to webpack and have searched around to get sub folders to work and they all say that is how it supposed to work.
Any ideas?
Thanks

I got it to work by changing:
historyApiFallback: {
  index: '/app',
}

A: I got it to work by changing:
historyApiFallback: {
  index: '/app',
}


text:
Q: Variable Multiple Criteria for Autofilter in VBA I'm looking to use VBA autofilter to better sort my data as I work through it.  I have around a 1000 rows each with a unique number and I'd like to be able to filter that data to the ID numbers I need at that moment.  Basically, the autofilter code below does the job for those 5 specific entries, but is there a way of making that a more flexible?
ActiveSheet.Range("$A$13:$Y$1045").AutoFilter Field:=1, Criteria1:=Array( _
        "1776", "1870", "2029", "2051", "2086"), Operator:=xlFilterValues

I picture using something along the lines of:
ActiveSheet.Range("$A$13:$Y$1045").AutoFilter Field:=1, Criteria1:=Array( _
        TexBox2.Value, TextBox2.Value), Operator:=xlFilterValues

but no joy.  I'm a bit of a newbie, so huge apologies if this is a huge waste of time.  Many thanks in advance for any help!

A: I think you should be little more precise:
ActiveSheet.Range("$A$13:$Y$1045").AutoFilter Field:=1, Criteria1:=Array( _
    UserForm1.TexBoxt1.Value, UserForm1.TextBox2.Value) _
    , Operator:=xlFilterValues

where UserForm1 is the name of your userform. Be sure that you did not unloaded it before running this piece of code (you may .Hide it and still have access to the controls).