text:
Q: How can I update npm on Windows? I tried this:
sudo npm cache clean -f
sudo npm install -g n
sudo n stable

...but it didn't work.
How do I do this on Windows?

A: Like some people, I needed to combine multiple answers, and I also needed to set a proxy.
This should work for anyone. I have zero desire to run an EXE file or MSI file .. uninstall/ reinstall, or manually delete files and folders. That is so 1999 :P

*

*Run this to update NPM:
Run PowerShell as administrator
npm i -g npm    // This works

I am not thinking this code actually upgrades your npm version below
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade

(courtesy of "Robert" answer)

Run this to update Node.js:
wget https://nodejs.org/download/release/latest/win-x64/node.exe -OutFile 'C:\Program Files (x86)\nodejs\node.exe'    (courtesy of BrunoLM answer)

If you get `wget : Could not find a part of the path .... "**, see below ...scroll down. Reading Web Response... It's at least punching through the firewall /proxy (if you have one or have already ran the code get through ...
Otherwise
You might need to set your proxy
npm config set proxy "http://proxy.yourcorp.com:811"    (yes, use quotes)

2 possible errors

*

*It cannot find path of the path solution "where.exe node" (courtesy of Lonnie Best Answer)
E.g. if Node.js is NOT living in "Program Files (x86)" perhaps with where.exe, it is living in 'C:\Program Files\nodejs\node.exe'.
wget https://nodejs.org/download/release/latest/win-x64/node.exe -OutFile 'C:\Program Files\nodejs\node.exe'

*Now perhaps it tries to upgrade but you get another error, "node.exe is being used by another process."

*

*Close /shutdown other consoles .. command prompts and PowerShell windows, etc. Even if you're using npm in a command prompt, close it.

npm -v  (3.10.8)
node -v     ( v6.6.0)
DONE. I'm at the version that I want.

A: How to Update Node.js:

*

*Uninstall Node.js. Click the Start menu, type "Change or Remove a Program", click on the item shown, find Node.js in the list and uninstall it.

*Delete directories, both C:\Program Files (x86)\nodejs\ and C:\Program Files\nodejs\ if they exist.

*Install the latest, https://nodejs.org/en/download
    The uninstall/delete/install seems unnecessary, but it often is and this will save your time.
    These instructions come from Microsoft.
How to Update NPM:
    https://www.npmjs.com/package/npm-windows-upgrade
    This is the official documentation for upgrading npm on windows.
All was tested and working on Windows 10 (2017).

A:
this is best tool to maintain version of NODE.Js i NVM

Node Version Manager (nvm) for Windows
but for Windows, with an installer. Download Now! This has always been a node version manager, not an io.js manager, so there is no back-support for io.js. However, node 4+ is supported.

A: Download and run the latest MSI.  The MSI will update your installed node and npm.

A: You can update your npm to the latest stable version with the following command:
 npm install npm@latest -g

Use PowerShell to run it. This command doesn't need windows administrator privileges and you can verify the result with npm -v

A: You can use Chocolatey which is a package manager for windows (like apt-get for Debian Linux).
Install fresh (you might need to uninstall previously installed versions)
> choco install nodejs

Update to the latest version
> choco update nodejs

and for npm
> choco update npm

A: For me, after totally uninstalling node 10.29, and then installing node 4.2.2, there remained a 10.29 node.exe file in my c:\windows folder.
I found this by using the following command:
where.exe node

The command returned:
C:\Windows\node.exe
C:\Program Files\nodejs\node.exe

So even though I had successfully installed version 4.2.2 via the msi executable, the command node -v would continue to report I was running version 10.29.
I resolved the problem by deleting this file:
C:\Windows\node.exe

Thereafter, node -v reported the upgraded version instead of the unwanted remnants of the prior version.

A: For NodeJS
Download required node version msi from here and install
for Npm
Run PowerShell as Administrator
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade

A: I followed josh3737 and installed the latest MSI from the Node.js homepage.
But I had the additional problem that I still had the old version of Node.js and npm on the command line. The problem was caused by the new installation, and that it was installed into
C:\Program Files (x86)\nodejs\

instead of the previous installation in
C:\Program Files\nodejs\

The new installation added the new directory into my path variable after the old one. So the old installation was still the active one in the path. After removing C:\Program Files\nodejs\ from system path and C:\Users\...\AppData\Roaming\npm from user path and restarting the command line the new installation was active.
Maybe the least path was a local problem that has nothing to do with the new installation. I had two links to AppData\Roaming\npm in it. And maybe this can also be fixed by first uninstalling Node.js and installing the new version afterwards.

A: I was also facing similar issues. I followed below mentioned steps and it worked for me:

*

*go to Windows > Start > Node.js

*

*right click on Node.js command prompt

*click on Run as administrator

*ping registry.npmjs.org

*npm view npm version

*cd %ProgramFiles%\nodejs

*npm install npm@latest
and npm updated successfully. Earlier I was trying for CMD and that was throwing error. may be some path issue that got resolved by running NodeJs Command Prompt. hope it'll work for you. try this.

A: This works fine for me

*

*
Run   Command Prompt as Administrator

*Navigate to the folder containing nodejs (eg. C:\Program Files\nodejs)

*
Run   Powershell -ExecutionPolicy Unrestricted

*
Run   npm-windows-upgrade

*This will show list of versions available to install. Just select your desired version by moving up/down key & Press Enter.

This'll update your npm

*To check the current version of npm

Run   npm --version

Command Prompt Screenshot

A: OK guys, I read (tried on Windows) all the previous stuff and all of these answers have their own disadvantages.
For the best way to update Node.js (at least for me), go to https://nodejs.org/en/
Then download the last version and install it in same folder you installed the previous version in - 1 min and it's done. You don't need to remove any old files.
Then update npm typing in cmd: npm install --save latest-version

A: To install the updates, just download the installer from the Nodejs.org site and run it again. The new version of Node.js and NPM will replace the older versions.

A: The easiest way I found so far to update Node.js is using Chocolatey.
Use Chocolatey to install or update the latest version of Node.js on Windows:
Step 1: First, ensure that you already have Chocolatey installed. If not, use an administrative shell to install chocolatey through cmd.exe or PowerShell.exe. For more information, visit: https://chocolatey.org/docs/installation
Step 2: Install with cmd.exe. Run the following command:
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

To install with PowerShell.exe, visit: https://chocolatey.org/docs/installation
Step 3: Install or Update with following commands on cmd.exe (on administrative mode)
To Install Node.js: cinst nodejs.install
To Update Node.js: cup nodejs.install

A: follow these steps for window 10 or window 8

*

*press WIN + R and type cmd and enter

*npm i -g npm@next

*npm i -g npm@next  OR npm i -g node@{version}

*Remove environment path C:\Program Files\nodejs from envrionment variable PATH.

*type refreshenv in cmd

Now you will have your new version which you installed.
Note: If you don't remove path. You will see the previous version of node.

A: PowerShell does not execute npm directly, so I suggest using
.\npm install -g npm-windows-upgrade
.\npm-windows-upgrade

And it failed with:

You wanted to install npm 6.1.0, but the installed version is 3.10.10.

A common reason is an attempted "npm install npm" or "npm upgrade npm". As of today, the only solution is to completely uninstall and then reinstall Node.js. For a small tutorial, please see http://aka.ms/fix-npm-upgrade (dead link).
Please consider reporting your trouble to npm-windows-upgrade.

A: The previous answers will work installing a new version of Node.js (probably the best option), but if you have a dependency on a specific Node.js version then the following will work: "npm install npm -g". Verify by running npm -v before and after the command.

A: Note: The question is specifically asking how to upgrade npm, not Node.js. If you want to update Node.js over a CLI on windows, I recommend running winget upgrade -q NodeJS or use chocolatey for that.
What method should I choose to update NPM?

*

*Node.js v16 or higher?

*

*npm install -g npm

*Node.js v14 or below?

*

*Consider updating to latest LTS release of Node.js

*npm-windows-upgrade
Upgrade with npm-windows-upgrade
Run PowerShell as Administrator
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade

Note: if you run the Node.js installer, it will replace the Node.js version.

*

*Upgrades npm in-place, where Node.js installed it.

*Does not modify the default path.

*Does not change the default global package location.

*Allows easy upgrades and downgrades and to install a specific version.

*A list of versions matched between NPM and Node.js (https://nodejs.org/en/download/releases/) - but you will need to download the Node.js installer and run that to update Node.js (https://nodejs.org/en/)

Upgrade with npm
npm install -g npm

Note: some users still report issues updating npm with npm, but I haven't had that experience with v16+.

A: This works fine for me to update npm on Windows 7 x64:

*

*Windows start

*All Programs

*Node.js

*Node.js command prompt (alternative click)

*Run as administrator
$ npm -g install npm

*remove C:\Program Files\nodejs\npm.cmd the new npm will be at C:\Users\username\appdata\roaming\npm\npm.cmd
Hope this helps.

A: Open PowerShell as administrator.
To install a first time you can use this small script to download the latest msi and run it
$nodeLatest=((curl https://nodejs.org/download/release/latest/).Content | findstr x64.msi) -replace "<(.*?)>", "" -replace "\s+.+", "";
wget "https://nodejs.org/download/release/latest/$nodeLatest" -OutFile (join-path $env:TEMP node.msi); Start-Process (join-path $env:TEMP node.msi)

On future upgrades you can download just node.exe and update npm with
wget https://nodejs.org/download/release/latest/win-x64/node.exe -OutFile 'C:\Program Files\nodejs\node.exe'
npm i -g npm

You should now have the latest node and npm.

I went a little further and decided to implement a nvm for Windows.
https://github.com/brunolm/nvm
Install-Module -Name power-nvm

nvm install latest
nvm default latest

A: 1.    Installing latest npm version
npm install –g npm@latest

(You can type "npm –version" to check that)

2. Installing Node
a.  Install node new version via following URL: https://nodejs.org/en/download/current/
Follow the default choices

b.  Remove C:\Users\\AppData\Roaming\NPM

c.  Remove C:\Users\\AppData\Roaming\npm-cache

Optionally:
d.  (Delete node_modules folder in your current project folder)

e.     npm cache verify

f.     npm install

A: To update NPM, this worked for me:

*

*Navigate in your shell to your node installation directory, eg C:\Program Files (x86)\nodejs

*run npm install npm (no -g option)

A: Use Upgrade npm on Windows
This is the official document for a user to upgrade npm on Windows!
Here is my screenshot!

A: For what it's worth, I had to combine several answers...

*

*Uninstall Node.js in control panel Add/remove programs.

*Delete directories, both C:\Program Files (x86)\nodejs\ and C:\Program Files\nodejs\ if they exist.

*Install the latest version, http://nodejs.org/download/

A: You can use these commands:
npm cache clean
npm update -g [package....]

If you are upgrading from a previous version of node, then you will want to update all existing global packages.
You can also specify the package name to be updated.

A: This might help someone. Neither "npm-windows-upgrade" nor the installer alone did it for me. Powershell was still using an older version of node and npm.
So this is what I did (worked for me):
1. Download the latest installer from nodejs.org. Install node. It will update your node; everywhere (Powershell, cmd etc.).
2. Install the npm-windows-upgrade package (npm install -g npm-windows-upgrade) and run npm-windows-upgrade.
I didn't uninstall anything and didn't set any paths.

A: In my case, I discovered that I had two copies of Node.js installed. One under "C:\Program Files\nodejs" and another under "C:\Program Files (x86)\nodejs".

A: This is what worked for me.

*

*Open a local folder other than the one in which nodejs is installed.

*Install npm in that folder with command    npm install npm

*Navigate to the folder containing node js. (C:\Program Files\nodejs\node_modules)

*Delete the npm folder and replace it with the npm and bin folders in the local folder.

*Run npm -v. Now you would get updated version for npm.

Note: I tried installing npm directly in "C:\Program Files\nodejs\node_modules" but it created errors.

A: *

*Start

*Search for windows powershell

*Right click and run as administrator

*Type: where.exe node (returns the path of node.exe in your system. Copy this)

*wget https://nodejs.org/download/release/latest/win-x64/node.exe -OutFile 'PATH-OF-NODE.EXE_WHICH_YOU_COPIED_JUST_NOW'

*To check if it has worked, go to your Git bash/Normal command prompt and type: node -v

*Here you can find the current version of node: https://nodejs.org/en/blog/release/


text:
Q: Why am I receiving this 500 (Internal Server Error) on my Heroku deployed React.js/Node.js/Express.js app even though everything works? I have a deployed application and I am experiencing an issue with my contact form. This is a React.js app with a node, express and mongoDB backend. It is deployed on Heroku.
Right now, when a user enters their information into the contact form it:
1. runs API.saveLead() which runs a fetch() hits the contact/lead route. The data is saved to the database.
2. then API.sendMail() is called which runs a fetch() to the contact/mail route. The data is packaged and appropriately sent to the desired email address using the nodemailer package.
Although everything is functioning appropriately, I am logging a 500 (Internal Server Error) and I cannot figure out why. This is the error:
API.js:29 POST https://www.agavepv.com/contact/mail 500 (Internal Server Error)
sendMail @ API.js:29
(anonymous) @ index.js:38
Promise.then (async)
t.handleFormSubmit @ index.js:36
(anonymous) @ react-dom.production.min.js:80
w @ react-dom.production.min.js:100
(anonymous) @ react-dom.production.min.js:104
T @ react-dom.production.min.js:124
P @ react-dom.production.min.js:153
C @ react-dom.production.min.js:142
N @ react-dom.production.min.js:166
xn @ react-dom.production.min.js:1676
ue @ react-dom.production.min.js:7257
_n @ react-dom.production.min.js:1741
Nn @ react-dom.production.min.js:1778
Pn @ react-dom.production.min.js:1753
t.unstable_runWithPriority @ scheduler.production.min.js:270
Ql @ react-dom.production.min.js:2794
ie @ react-dom.production.min.js:7242
(anonymous) @ react-dom.production.min.js:1710

The link to my gitHub can be found here: https://github.com/TheGreekCuban/agavepv
The link to the deployed site can be found here: https://www.agavepv.com
UPDATE
module.exports = {
  create: function(req, res) {
    db.Lead
      .create(req.body)
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  },
//THE CODE BELOW IS WHERE I THE ERROR IS BEING TRIGGERED
  send: function(req) {
    db.Send(req.body)
    .then(response => console.log("Message[2]: ", response))
    .catch(err => console.log(err.response));
  }
};

UPDATE [2]
const nodemailer = require("nodemailer")

const Send = (request) => {

    console.log("Request2: ", request)

    const output = `

Name: ${request.Name}

Phone: ${request.Phone}

Email: ${request.Email}

Message:

        ${request.Message}

    `

    // call the main function which will take care of the nodemailer.
    main(output)
}

async function main(output) {
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        service: "Gmail",
        auth: {
            user: process.env.email, // generated ethereal user
            pass: process.env.password // generated ethereal password
        }
    });

    // send mail with defined transport object
    let info = await transporter.sendMail({
        from: '"Admin" <[TAKENOUTFOREXAMPLE]@[EXAMPLE].com>', // sender address
        to: "[TAKENOUTFOREXAMPLE]@[EXAMPLE].com", // list of receivers
        subject: "Interested in working with you!", // Subject line
        html: output // html body
    });

    // Preview only available when sending through an Ethereal account
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    return console.log("Message sent: %s", info.messageId);
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
}
// Export the model
module.exports = Send;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert in Merge not working in Oracle I am new to Oracle. I have a table in Oracle which has 4 columns Period, Open_Flag,Creation_Dt,Updated_By.
The Period column is the Primary key of the table.  I have created a proc which will check the value of period from input parameter in the table, if its existing, the value of Open_flag has to be updated else a new record shall be inserted.
create or replace
PROCEDURE                                                                                PROC_REF_SAP_PERIOD(
V_PERIOD IN NUMBER,V_OPEN_FLAG IN VARCHAR2,V_CREATION_DT IN  DATE,V_UPDATED_BY IN VARCHAR2)
 AS
BEGIN
MERGE INTO REF_SAP_PERIOD T
USING (SELECT * FROM REF_SAP_PERIOD WHERE PERIOD=V_PERIOD  )S
ON (T.PERIOD=S.PERIOD  )
WHEN MATCHED THEN UPDATE SET OPEN_FLAG = V_OPEN_FLAG --WHERE PERIOD=V_PERIOD AND   CREATION_DT=V_CREATION_DT AND   UPDATED_BY=V_UPDATED_BY
WHEN NOT MATCHED THEN INSERT (PERIOD,OPEN_FLAG,CREATION_DT,UPDATED_BY) VALUES (V_PERIOD,V_OPEN_FLAG,V_CREATION_DT,V_UPDATED_BY);
END;
 The issue is that the Update is working well in this case, however, the insert is not working. Please help.

A: You are merging table with itself, filtered by period. Obviously, it will never see your non-existent values in itself.
Try this line instead of your USING line:
using (select V_PERIOD "period" from dual)S


text:
Q: Tool to Verify Site URLs/SiteMap? I'm moving a site from one e-commerce software to another, and I've created URL Rewriter rules to do 301 redirects from the Old URLs to the new ones. I've tested them with a small sample of URLs, but I'm looking for some sort of tool that will let me test as many of the URLs as possible. Does anyone know of a tool that I can feed a list of URLs (or a sitemap.xml). This tool will attempt to retrieve each URL, and then report the status code for each. The result should be a list of URLs with the status code, something like this:

www.site.com/oldurlformat1/ 301 Permanently Moved
www.site.com/newurlformat1/ 200 OK
www.site.com/oldurlformat2/ 301 Permanently Moved
www.site.com/newurlformat2/ 200 OK

I can almost do this with wget, but getting the summary/report at the end is where I'm stuck.

A: I've used Xenu a long time ago, for a list of URLs to check and it was ok.
From the features list, the things that might help you:

Detects and reports redirected URLs
Site Map

I haven't used it since then and can't say how well the current version works, but it might be worth a try.

A: I think you can use Google webmaster's tools to do that.
Just sign up to this service, and submit the sitmap.
You'll have a feedback on what's OK and what's wrong.
Here is the link : https://www.google.com/webmasters/tools/home


text:
Q: jQuery click() is not working in chrome and mobile I am using Jquery to hide a div and show another div when a  tag is clicked. For some reason my code works in FF and IE, but it is not functional in chrome, opera or android browser.
To be more specific, the same jquery code is also used for some other  tags in the same page and that works, but not this one.
The  tag which doesn't work is inside a bootstrap dropdown menu.
I did a lot of research about the issue, but nothing really helped.
Here is the code
JS:
$(document).ready(function() {
    $("#acc").click(function(g) {
        document.getElementById("a").style.display = "none";
        document.getElementById("b").style.display = "none";
        document.getElementById("c").style.display = "block";
    });
});

HTML:

          Settings

          Logout

My Scripts are Linked at the end of the body and are ordered this way :

A: i use javascript:void(0) to avoid conflict, and change your code to pure jQuery.

$(document).ready(function() {
    $("#acc").click(function(g) {
       $('#a').css('display','none');
       $('#b').css('display','none');
       $('#c').css('display','block');
    });
});

          Settings

          Logout

a

b

c

A: As you want to attach an event to dynamic html element,
you should use .on()
Replace:
$("#acc").click(function(g) {
    document.getElementById("a").style.display = "none";
    document.getElementById("b").style.display = "none";
    document.getElementById("c").style.display = "block";
});

With:
$('body').on('click', 'a#acc', function() {
    document.getElementById("a").style.display = "none";
    document.getElementById("b").style.display = "none";
    document.getElementById("c").style.display = "block";
});


text:
Q: In C, a cURL call anywhere, even when not executed, crashes the service I am building a small windows service which uses cURL for a small web call.
I can link cURL without issue, but if any curl_* functions are in the code - even if none are ever called - the code crashes:
Program received signal SIGSEGV, Segmentation fault.
0x00007ff8bb75f9f8 in StartServiceCtrlDispatcherW () from C:\WINDOWS\System32\sechost.dll

Here is the offending function - commenting out just the lines calling curl_* functions stops the issue:
void phone_home(identity id, char* agent_filename, char* action)
{
    CURL *curl;
    CURLcode res;
    char service_url[MAX_PATH_LEN], username[MAX_PATH_LEN];

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    get_username(username, MAX_PATH_LEN);
    sprintf(service_url, "%s/%s?identity=%lu&user=%s&agent=%s", LISTENER_HOST, action, id, username, agent_filename);

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, service_url);

        #ifdef SKIP_PEER_VERIFICATION
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        #endif

        #ifdef SKIP_HOSTNAME_VERIFICATION
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        #endif

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);

        /* Check for errors */
        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

        /* always cleanup */
        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();
}

And here is the SvcInit function that never calls that function!
VOID SvcInit( DWORD dwArgc, LPTSTR *lpszArgv)
{
    int id;
    identity last_id = 0;

    ghSvcStopEvent = CreateEvent(
        NULL,    /* default security attributes */
        TRUE,    /*  manual reset event */
    FALSE,   /* not signaled */
    NULL);   /* no name */

if ( ghSvcStopEvent == NULL)
{
    ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
    return;
}

ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );
while(1)
{
    WaitForSingleObject(ghSvcStopEvent, INFINITE);
    ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );

    if ((id = scan_for_devices())) {
        if (id != last_id) {
            last_id = id;
            printf("Found marked device 0x%lX!\n", id);
            //phone_home(id, "", ACTION_USBINSERT);
        }
    } else {
        last_id = 0;
    }

    Sleep(5000);
}

}
And the rest of the service definition code:
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#include "include/identities.h"
#include "include/identity_agent.h"

#define SVCNAME TEXT("Test")
#define SVCSHOW TEXT("Test Agent")
#define SVCDESC TEXT("Test")

SERVICE_STATUS          gSvcStatus;
SERVICE_STATUS_HANDLE   gSvcStatusHandle;
HANDLE                  ghSvcStopEvent = NULL;

VOID WINAPI SvcCtrlHandler( DWORD );
VOID WINAPI SvcMain( DWORD, LPTSTR * );

VOID ReportSvcStatus( DWORD, DWORD, DWORD );
VOID SvcInit( DWORD, LPTSTR * );
VOID SvcReportEvent( LPTSTR );

int __cdecl _tmain(int argc, TCHAR *argv[])
{
    SERVICE_TABLE_ENTRY DispatchTable[] =
    {
        { SVCNAME, (LPSERVICE_MAIN_FUNCTION) SvcMain },
        { NULL, NULL }
    };

    if (!StartServiceCtrlDispatcher( DispatchTable ))
    {
        SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
    }

    return 0;
}

VOID WINAPI SvcMain( DWORD dwArgc, LPTSTR *lpszArgv )
{
    /* Register the handler function for the service */
    gSvcStatusHandle = RegisterServiceCtrlHandler(
        SVCNAME,
        SvcCtrlHandler);

    if( !gSvcStatusHandle )
    {
        SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));
        return;
    }

    gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    gSvcStatus.dwServiceSpecificExitCode = 0;

    ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 );

    SvcInit( dwArgc, lpszArgv );
}

VOID SvcInit( DWORD dwArgc, LPTSTR *lpszArgv)
{
    int id;
    identity last_id = 0;

    ghSvcStopEvent = CreateEvent(
        NULL,    /* default security attributes */
        TRUE,    /* manual reset event */
        FALSE,   /* not signaled */
        NULL);   /* no name */

    if ( ghSvcStopEvent == NULL)
    {
        ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
        return;
    }

    ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );
    while(1)
    {
        WaitForSingleObject(ghSvcStopEvent, INFINITE);
        ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );

        if ((id = scan_for_devices())) {
            if (id != last_id) {
                last_id = id;
                printf("Found marked device 0x%lX!\n", id);
                //phone_home(id, "", ACTION_USBINSERT);
            }
        } else {
            last_id = 0;
        }

        Sleep(5000);
    }
}

VOID ReportSvcStatus( DWORD dwCurrentState,
                      DWORD dwWin32ExitCode,
                      DWORD dwWaitHint)
{
    static DWORD dwCheckPoint = 1;

    /* Fill in the SERVICE_STATUS structure. */
    gSvcStatus.dwCurrentState = dwCurrentState;
    gSvcStatus.dwWin32ExitCode = dwWin32ExitCode;
    gSvcStatus.dwWaitHint = dwWaitHint;

    if (dwCurrentState == SERVICE_START_PENDING)
        gSvcStatus.dwControlsAccepted = 0;
    else gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;

    if ( (dwCurrentState == SERVICE_RUNNING) ||
           (dwCurrentState == SERVICE_STOPPED) )
        gSvcStatus.dwCheckPoint = 0;
    else gSvcStatus.dwCheckPoint = dwCheckPoint++;

    /* Report the status of the service to the SCM. */
    SetServiceStatus( gSvcStatusHandle, &gSvcStatus );
}

VOID WINAPI SvcCtrlHandler( DWORD dwCtrl )
{
   /* Handle the requested control code. */
   switch(dwCtrl)
   {
      case SERVICE_CONTROL_STOP:
         ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);

         /* Signal the service to stop. */
         SetEvent(ghSvcStopEvent);
         ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);

         return;

      case SERVICE_CONTROL_INTERROGATE:
         break;

      default:
         break;
   }

}

VOID SvcReportEvent(LPTSTR szFunction)
{
    HANDLE hEventSource;
    LPCTSTR lpszStrings[2];
    TCHAR Buffer[80];

    hEventSource = RegisterEventSource(NULL, SVCNAME);

    if( NULL != hEventSource )
    {
        StringCchPrintf(Buffer, 80, TEXT("%s failed with %d"), szFunction, GetLastError());

        lpszStrings[0] = SVCNAME;
        lpszStrings[1] = Buffer;

        ReportEvent(hEventSource,
                    EVENTLOG_ERROR_TYPE, /* event type */
                    0,                   /* event category */
                    /*SVC_ERROR*/0,           /* event identifier */
                    NULL,                /* no security identifier */
                    2,                   /* size of lpszStrings array */
                    0,                   /* no binary data */
                    lpszStrings,         /* array of strings */
                    NULL);               /* no binary data */

        DeregisterEventSource(hEventSource);
    }
}

I am compiling with gcc -o bin/identity_service identity_agent.c identities.c -lcurl

A: As it turns out, I had not linked cURL statically, so it was looking for the cURL DLLs - which were in the mingw bin directory.... which was in my USER's path....... which services running under system cannot see
I linked curl statically with -DCURL_STATICLIB and all is right with the world


text:
Q: Angular2 Grouping Pipe I am trying to create a custom pipe for displaying data in my angular component and couldn't succeed for some reason. Can someone help me create this custom pipe to display the tickets in the following format? Here is my plunker.
 SEARCH
 Ticket Id    Ticket Type   status
 12345        chat          closed
 62363        phone         open
 48768        phone         open

 DISPUTE
 Ticket Id    Ticket Type   status
 79439        web           closed
 67797        phone         open

A: I finally got my first custom pipe working. Thanks to http://www.morphatic.com/2016/06/23/creating-a-filter-pipe-for-angular-2-in-ionic-2/. I've updated the plunker in case if anyone is interested in the solution. Since I'm new to pipes in Angular2, I'm open to suggestions to modify/simplify my solution.
@Pipe({
  name: 'ticketsGrouping',
  pure: false
})

export class TicketsGrouping implements PipeTransform {

  transform(items: Array<any>, conditions: {[field: string]: any}): Array<any> {
    if (items !== undefined) {
      return items.filter(item => {
        for (let field in conditions) {
          if (item[field] !== conditions[field]) {
            return false;
          }
        }
        return true;
      });
    }
  }
}


text:
Q: NodeJS, Express, MSSQL - How do I wait for MSSQL pool to connect and return query result before printing to console Node Version -                 16.1.0
Microsoft SQL Server 2008 -    10.50.2550.0
SQL Server Management Studio - 15.0.18358.0
Windows 10 Pro Edition -       2004
OS Build ^ -                   19041.572

Project Architecture:
root
|- <node_modules>
|- index.js
|- databaseStuff.js
|- test.js
|- package.json

Important Note, I have to run my app with the following command: node --tls-min-v1.0 index.js
I'm making an API to take information from a GitLab webhook and write to a table using NodeJS, Express, and MSSQL. I will perform various read/write operations from Stored Procedures but the first step is executing a simple query. I would like to send the result of a query as the HTTP response.
The part I'm having trouble with is timing the query around DB connection.
The errors I'm receiving contain ConnectionError code 'ENOTOPEN' (see error_console_output)
// error_console_output
Server is running..
Promise { <pending> }
Connected to DB
TypeError: Cannot read property 'on' of undefined
    at \root\node_modules\mssql\lib\tedious\request.js:428:
20
    at \root\node_modules\mssql\lib\base\connection-pool.js
:289:41
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at runNextTicks (node:internal/process/task_queues:65:3)
    at processImmediate (node:internal/timers:437:9)
\root\node_modules\mssql\lib\base\connection-pool.js:298
      return shared.Promise.reject(new ConnectionError('Connection not yet open.
', 'ENOTOPEN'))
                                   ^

ConnectionError: Connection not yet open.
    at ConnectionPool._acquire (\root\node_modules\mssql\li
b\base\connection-pool.js:298:36)
    at ConnectionPool.acquire (\root\node_modules\mssql\lib
\base\connection-pool.js:284:56)
    at Immediate.<anonymous> (\root\node_modules\mssql\lib\
tedious\request.js:409:19)
    at processImmediate (node:internal/timers:464:21) {
  code: 'ENOTOPEN'
}

Part of me is wondering if my SQL Server version isn't compatible with MSSQL or if I'm just not writing the connection properly.
// index.js
var db = require('./databaseStuff')

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  var result = db.execute();
  console.log(result);
})

var server = app.listen(8080, function () {
    console.log('Server is running..');
});

// databaseStuff.js
var sql = require("mssql");

var config = {
    user: 'user',
    password: 'password',
    server: 'server',
    database: 'DBname',
    options: {
      encrypt: true,
      trustServerCertificate: true
    }
};

var sqlQuery = "select * from Games";

async function connectDB()
{
  const pool = new sql.ConnectionPool(config);

  try
  {
    await pool.connect();
    console.log('Connected to DB');
    return pool;
  }
  catch (err)
  {
    console.log('Failed to connect to DB', err);

    return err;
  }
}

async function getGames() {
  const DB = await connectDB();

  try {
    const result = await DB.request().query(sqlQuery, function (err, res) {
      if (err) console.log(err);
      else console.log(res);
    });

    return result.recordset;
  }
  catch (err)
  {
    console.log('Error querying DB', err);

    return err;
  }

  finally
  {
    DB.close();
  }
}

async function execute()
{
  let result = await getGames();

  return result;
}

module.exports = {
  execute
};

// package.json
{
  "name": "root",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "msnodesqlv8": "^2.1.0",
    "mssql": "^7.1.0",
    "tedious": "^6.2.0"
  }
}

I had something working before I tried to deconstruct it. test.js will wait for the MSSQL query to return a result. I would use this but I would like to keep my code segmented from the main class. Note that test.js will send the SQL query result as the response body, I would like to keep this behavior. (see expected_results).
// test.js
var express = require('express');
var app = express();
var server = app.listen(8080, function () {
    console.log('Server is running..');
    var sql = require("mssql");
    // config for your database
    var config = {
        user: 'user',
        password: 'password',
        server: 'server',
        database: 'DBname',
        options: {
          encrypt: true,
          trustServerCertificate: true
        }
    };
    // connect to your database
    sql.connect(config, function (err) {
        if(err)
        {
            console.log("CONNECTION: " + err);
            return;
        }
        console.log("Connected!!");
        // create Request object
        var request = new sql.Request();
        // query to the database and get the records
        request.query('select * from Games', function (err, recordset) {
            if (err)
            {
                 console.log("QUERY: " + err);
            }
            // send records as a response
            console.log(recordset);
            //res.send(recordset);
        });
    });
});

// expected_results
{
  recordsets: [ [ [Object] ] ],
  recordset: [ { ID: 1, Name: 'GameName' } ],
  output: {},
  rowsAffected: [ 1 ]
}

EDIT(s):
app.get('/', async function(req, res) {
  try
  {
    var result = await db.execute();
    console.log(result);
  }
  catch (error)
  {
    console.log(error);
  }
})

The above change prevents 'console.log(result)' from firing before a result is returned. However, I am still experiencing the same ConnectionError from error_console_output.

A: I figured it out in case anyone runs into this problem. For further reference, please view this
My problem was due to not properly creating a connection to my database. I followed the Connection Pools section of the mssql documentation (linked earlier).
This method makes sure a connection has been created and secured before moving forward with a request
// index.js
var db = require('./databaseStuff')

var express = require('express');

var app = express();

var server = app.listen(8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});

app.get('/', async function(req, res) {
  let result = await db.execute();
  res.send(result);
  res.status(200).end();
  console.log(result);
})

// databaseStuff.js
var sql = require("mssql");

// config for your database
var config = {
    user: 'user',
    password: 'password',
    server: 'server',
    database: 'DB',
    options: {
      encrypt: true,
      trustServerCertificate: true
    }
};

// async/await style
const pool1 = new sql.ConnectionPool(config);
const pool1Connect = pool1.connect();

pool1.on('error', err => {
  console.log(err);
})

var sqlQuery = "select * from Games";

async function getGames() {
  // ensure pool has been created
  await pool1Connect;

  try
  {
    const request = pool1.request();
    const result = await request.query(sqlQuery);

    return result.recordset;
  }
  catch (err)
  {
    console.error('SQL Error', err);
  }
}

async function execute()
{
  return await getGames();
}

module.exports = {
  execute
};

// output
App now running on port 8080
[ { ID: 1, Name: 'GameName' } ]


text:
Q: jQuery syntax for variable attributes I'm trying to compact and optimize some code and have the following types that I would like to compact, but can't get the correct syntax for that:
var my_field_name = $('#my_field_name'); // a multiple select
var my_array = {"0":"123","1","456","2":"789"};
my_array = $.parseJSON(my_array);
$.each(my_array, function (k, v) {
    $("#my_field_name option[value="+v+"]").prop("selected", true);
}

so far everything's working fine, but I "would like" to use my_field_name in the $.each loop like my_field_name.("option[value="+v+"]").prop("selected", true); but this seems to be an incorrect syntax.
Is the $("#my_field_name option[value="+v+"]") the only way to go?

A: Since my_field_name is a jQuery instance for the select element, you'd use children to access its options elements:
$.each(my_array, function (k, v) {
    my_field_name.children('option[value=' + v + ']').prop("selected", true);
}

...but see also below.
It's probably worth noting that your my_array variable doesn't point to an array. In fact, that line is a syntax error (because you've used a comma after "1" rather than a colon). (If you'd used the colon you'd have an object with the keys "0", "1", and "2", but it wouldn't be an array. Granted, standard "arrays" in JavaScript aren't really arrays at all, but...) I think you wanted:
var my_array = ["123", "456", "789"];

You also don't use $.parseJSON on something that isn't a string.
If my_array actually ends up being an array (either because you've written it literally or because it's parsed from a JSON string like ["123", "456", "789"]), rather than using children you may be better off just looping through the options:
// Let's assume you get jsonString from somewhere else, and it's really a string,
// as though you had this code: jsonString = '["123", "456", "789"]'
var my_array = $.parseJSON(jsonString);
$.each($("#my_field_name")[0].options, function(index, option) {
    if ($.inArray(option.value, my_array) !== -1) {
        option.selected = true;
    }
});

The options property on a raw select DOM element (note the [0] to get to the raw element) is an array-like object with a length property, so $.each will loop over it using indexes. $.inArray will then see if the option's value is present in the array. You don't need to cache the lookup using the my_field_name variable because you only do the lookup once.
But note that that won't work if the JSON string is {"0": "123", "1": "456", "2": "789"}, because $.inArray won't work with a non-array object like that.

Re your comment below:

... in your example you're still using $("#my_field_name") and that is what I was trying to avoid, since $("#my_field_name") is already cached on top of the script and though I thought of using the var name instead of repeating $("#my_field_name") every time I need to reference that field.

If you're already doing
var my_field_name = $("#my_field_name");

...above it in the code, then naturally in any of the examples in this answer, if you see $("#my_field_name"), you can replace it directly with my_field_name. So for instance, if you see:
$.each($("#my_field_name")[0].options, function(index, option) {

and you already have my_field_name in a variable, you can change it to this;
$.each(my_field_name[0].options, function(index, option) {


text:
Q: Doesn't have access to assignment inside catch try The celsius and temperature in the while doesn't have access to the celsius and temperature in try catch. I have tried to make assignment outside of try catch but it doesn't help and doesn't comply.
using System;

namespace Hermods
{
    class Program
    {
        // method for converting Fahrenheit to Celsius with decimals
        public static double FahrToCels(int Fahr)
        {
            double cels = (Fahr - 32) * 5 / 9d;
            return cels;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hi! Which tempreture would you like to have? Choose in Fahrenheit:");
            int temprature;
            double celsius;
            try
            {
                temprature = Int32.Parse(Console.ReadLine());
                celsius = FahrToCels(temprature);
            }
            catch
            {
                Console.WriteLine("ERROR! Enter only number!");
            }

            // asking user to optimize the tempreture between 73-77C
            while (celsius < 73 || celsius > 77)
            {
                if (celsius < 73)
                {
                    Console.WriteLine("It is too cold. You have to pick a higher tempreture:");
                    celsius = FahrToCels(temprature);
                }
                else if (celsius > 77)
                {
                    Console.WriteLine("It is too hot! You have to pick a cooler tempreture:");
                    celsius = FahrToCels(temprature);
                }
            }

            Console.WriteLine(Math.Round(celsius, 1));

            Console.WriteLine("Press any key to continue:");
            Console.ReadKey();
        }
    }
}

A: you can't use them outside the try-catch because their value may never be assigned.
Just give an initial value:
public static double FahrToCels(int Fahr)
    {
        double cels = (Fahr - 32) * 5 / 9d;
        return cels;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Hi! Which tempreture would you like to have? Choose in Fahrenheit:");
        int temprature = 0;
        double celsius = 0;
        try
        {
            temprature = Int32.Parse(Console.ReadLine());
            celsius = FahrToCels(temprature);
        }
        catch
        {
            Console.WriteLine("ERROR! Enter only number!");
        }

        // asking user to optimize the tempreture between 73-77C
        while (celsius < 73 || celsius > 77)
        {
            if (celsius < 73)
            {
                Console.WriteLine("It is too cold. You have to pick a higher tempreture:");
                celsius = FahrToCels(temprature);
            }
            else if (celsius > 77)
            {
                Console.WriteLine("It is too hot! You have to pick a cooler tempreture:");
                celsius = FahrToCels(temprature);
            }
        }

        Console.WriteLine(Math.Round(celsius, 1));

        Console.WriteLine("Press any key to continue:");
        Console.ReadKey();
    }
}

A: please replace your variable with this default values
int temprature = 0;
double celsius = 0;

A: Your problem is any variable must be initialized before reading it!
int temprature;
double celsius;
try
{
    temprature = Int32.Parse(Console.ReadLine());
    celsius = FahrToCels(temprature);
}
catch
{
    Console.WriteLine("ERROR! Enter only number!");
    // You catch the error and don't throw and exception,
    // therefore it can happen that temprature and-or celsius is not initialized
}

Either initialize them before the try block
int temprature = 0;
double celsius = 0;

or throw an Exception from the catch block.


text:
Q: create installation file (.msi) for windows file system driver I have recently started working on windows file system minifilter driver. I want to create installer for my driver preferably .msi. I am using VS community edition to develop project.
I tried using Driver Install Package project in VS but that returned me nothing after build. MSDN states it's used to deploy the driver. So I guess we can't use to create installer.
Am I right?
In my quest I found out that there are APIs to develop custom installer called setupapis & DIFx. Tried developing installer with them but got errors (will make another question out of it). If this is the way are there any guides or examples available? MSDN has API specs only or atleast that's what I could find for those API but no guide on how to create installer from scratch.
Shall I need to use those APIs only or there's some available utility in VS which I can use to build installer?

A: The best option is to use a third party tool that can save you lots of time. Advanced Installer can install drivers, and other MSI authoring tools too.
You can use e free trial of Advanced Installer to test it, in about than 10 minutes you should have a working installer, the GUI is quite easy to work it (we worked a lot to make it that easy to use).


text:
Q: Nodes removal from a layered graph Given a directed layered graph $G=(V,E)$, which its nodes are arranged in $n+1$ layers $L_1,...L_{n+1}$, s.t. the first and last layers have a single source and target nodes respectively ($L_1={s}, L_{n+1}={t}$). Edges are directed and only between adjacent layers, so if $e=(u,v) \in E$  then $u \in L_i$ and $v \in L_{i+1}$.
Consider the following process: We remove nodes one-by-one from the graph. If as a result of a removal, there is a different node that is no longer reachable from $s$ or that $t$ is not reachable from it, then we remove it too and so on.
The question is--what is the largest number of removal that can be applied (not including nodes that has been removed as a result of another node's removal), without disconnecting $s$ from $t$?
Is it possible to give an upper-bound for this number, depending on the number of nodes/edges/layers in the graph? (considering the worst-case order of nodes removal)

A: You may want to look at Menger's Theorem.
This tells us that the number of nodes you can remove between $s$ and $t$ without disconnecting them is equal to the number of internally disjoint paths from $s$ to $t$ (there are directed and undirected versions of this).
Since deleting a whole layer always disconnects $s$ and $t$, there is a trivial lower bound is $\min\{|L_i|: 2\leq i \leq n\}$.
It's also easy to show that you can construct a graph with $m$ nodes, in which the smallest $s-t$ separating set has $m-2$ nodes (i.e., the whole rest of the graph, see the figure).

EDIT: It is possible to find a bound based on the order of the graph, and the number of layers. If the graph has $m$ vertices, and $n+1$ layers, then $m-2$ of the vertices (everything except $s$ and $t$) lie in the middle $n-1$ layers. Thus, by the pigeonhole principle, there is some layer $L_i$ that has at most $\lfloor \frac{m-2}{n-1} \rfloor$ vertices. Removing this whole layer disconnects $s$ and $t$, so the number of removals you can make is bounded above by $\lfloor \frac{m-2}{n-1} \rfloor$.


text:
Q: Cypress : How to verify the font color is not be as expected one I have to validate the font color as red for some set of condition. So that, I have implemented the below assertion for achieving that,
return cy.xpath(`xpathcondition`)
    .should('have.css','-webkit-text-fill-color','rgb(208, 25, 71)')

Its worked for me.
The same thing I have to validate it should not be red for some other set of condition. Could anyone suggest me how to achieve this

A: You can use the not assertion.
cy.xpath(xpathcondition).should(
  'not.have.css',
  '-webkit-text-fill-color',
  'rgb(208, 25, 71)'
)


text:
Q: Clarification on calculating probabilities for a particles location (basic) Say that we have a wave function
$$\Psi(x,t)=c_1\Psi_1(x,t)+c_2\Psi_2(x,t)$$
where the particle is confined to $[0,a]$, $\Psi_i$ corresponds to the normalised wave function for energy $E_i$, and $c_i$ comes from an initial condition.
How do we find the probability that it is an interval say $[0,\frac{1}{2}a]$ at time $t$?
Can we condition on the probability by saying that $\lvert c_i\rvert^2$ is the probability it is of energy $E_i$, and find
$$\int_0^{\frac{1}{2}a}\lvert \Psi_i\rvert^2dx$$
for each $i$ or must we calculate the integral for $\lvert \Psi\rvert^2$ over the half-interval?

A: The probability that $\psi(x,t)$ is measured to lay in the interval $[0, a/2]$ at the time $t$ is given by
$$
\int_0^{a/2} |\psi(x,t)|^2 \mathrm{d}x = \int_0^{a/2} |c_1|^2 |\psi_1|^2 + c_1^*\psi_1^*c_2\psi_2 + c_1\psi_1 c_2^* \psi_2^* + |c_2|^2|\psi_2|^2 \,\mathrm{d}x
$$
since the whole wavefunction $\psi$ should be normalised. If you assume that the energy eigenstates $\psi_i$ are normalised then that'll give you a restriction on the possible values that $c_1$ and $c_2$ can take on.


text:
Q: The underlying space of a scheme remembers its affineness? Let $f:X\rightarrow Y$ be a morphism of schemes. We know that if $Y$ is affine and $f$ induces homeomorphism on the underlying spaces then $X$ is affine. Is it true that if $X$ is affine and $f$ induces a homeomorphism on the underlying spaces then $Y$ is affine?
More generally, is it true that a scheme whose underlying space is homeomorphic (possibly via a homeomorphism that is not induced by a morphism of schemes) to the underlying space of an affine scheme is affine? EDIT: actually, the answer to the last question is a very strong "NO" as the underlying space of any scheme is sober and Noetherian sober spaces are spectral (i.e. homeomorphic to the underlying space of an affine scheme).

A: As pointed out by abx here, the following example fits the bill.
Take a nodal cubic in $\mathbb{P}^2$, this is an irreducible scheme proper over $\mathbb{C}$, take its normalization and throw out a point from the inverse image of the node. We get a $\mathbb{C}$-morphism from the affine line to our cubic, which is bijective on the underlying spaces. Since a non-empty proper closed subspace of either the affine line or the cubic is a finite union of closed points, this morphism is also closed, thus it induces a homeomorphism on the underlying spaces. I find it somewhat amusing that this example was not pointed out earlier (indeed, it seems to be even simpler than Julian Rosen's much upvoted example).

A: Here is a counterexample. Fix a field $k$, and let $Y$ be built from two copies of the affine nodal curve $y^2=x^3+x^2$, glued together on the complement of the singular point. In other words $Y$ is a nodal curve with doubled singular point. Then $Y$ is not affine because it is not separated. However, there is a homeomorphism $\mathbb{A}^1\to Y$, which is built from the usual parameterization of the nodal curve by $\mathbb{A}^1$ (which passes through the singular point twice) by choosing one of version of the singular point the first time through and the other version the second time through.


text:
Q: Java Servlet catch all web requests then call JSP page I am in the following situation:
Client makes some request -> Servlet gets all requests -> based on requested url (example: https://bla.com/classic) it fetches products from database -> invokes a jsp page and passes products array as parameter -> jsp page rendes HTML to client
How can this be achieved ?
More specific question:
1.How to catch all client requests with a servlet and get the requested url ?
2.How to call jsp from servlet and pass parameters to it, so it can render the correct HTML ?
I am trying to build an MVC-like application. In this case my servlet is the controller (gets all requests), a database-helper-class is my model (gets products from db) and the jsp file is my view (renders html).
Thanks in advance :)

A: You need a ServletFilter and a properly configured web.xml for the paths.


text:
Q: re.search in Python 3 returns None My regex can't find a match for the pattern I'm searching for in a textfile. Here is my code:
myfile = ('_%s_Mail_%s.txt' % (timestr, emailid))

urls = re.search(r'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$', myfile)
IPs = re.search(r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', myfile)
print(urls.group())
print(IPs.group())

this returns None
What's wrong with the expression?

A: You are not opening the file. You are applying the regex on the filename.
myfile = ('_%s_Mail_%s.txt' % (timestr, emailid))
with open(myfile, 'r') as f:
    data = f.read()
    urls = re.search(..., data)


text:
Q: How to make Pebble watch vibrate I have a requirement in my program to make the Pebble watch vibrate on an event say when I send a particular string from Android App to my watchapp which is running on Pebble. Is there any function or command I can invoke in my program to make Pebble vibrate?
Thanks in advance.

A: Yes, you can. The Pebble SDK provides a Vibes module. You'll need to send an AppMessage from your Android app to your "watchapp". You cannot make the watch vibrate without both interfaces. (You cannot simply pair the devices and issue a command "vibrate!" from your Android app.)
Take a look at "Integrating Pebble Watchapps with Phone Apps". You can also get an idea of how transmitting data works in their sample Android app.


text:
Q: JQuery display XSLT into my html page Can someone help me with this please?
basically I am trying to display the result of my transformed XSLT into an existing page, the transformation seem to be working, but it's not displaying the results when I run my html page. I have tried to run the XSL independently and it's seem to display correctly on his own, so that will leave me with jQuery.
Thank you
This is my code:
  $(document).ready(function(){
  displayResult();
});

function loadXMLDoc(filename)
{
var deferred = $.Deferred();
var promise = deferred.promise();

 $.ajax({
    url: filename,
    type: 'get',
    dataType: 'xml',
    success: function(data) {
        console.log("resolved");
        deferred.resolve(data);

    }, error :function(v1, v2)

 });
 return promise;

}

 function displayResult(){
 var xmlPromise = loadXMLDoc("my.xml");
 var xslPromise = loadXMLDoc("my.xsl");

 $.when(xmlPromise, xslPromise).done(function(xml, xsl){
  if (document.implementation && document.implementation.createDocument)
  {
    var xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xsl);
    var resultDocument = xsltProcessor.transformToFragment(xml, document);
    $('#example').append(resultDocument);
  } else if (window.ActiveXObject)
  {
    /* IE */
    var ex = xml.transformNode(xsl);
    $('#example').innerHTML = ex;
   }
 });
}


text:
Q: VueJS pass default prop without reference to child component I've stumbled upon this situation where I want to pass a prop to a child component that will be the default value of the component, but it will only be showed when the initial value is empty.
Parent Component:
<multi-line-input v-model="data.something" placeholder="Enter Something" :default="data.something"/>

Child Component
props: {
  value: {
    type: String,
    default: ''
  },
  default: {
    type: String,
    default: ''
  },
},
methods: {
  emitBlur (e) {
    if (!this.value && this.default) {
      this.value = this.default
    }
    this.$emit('blur')
  },
  emitInput () {
    this.$emit('input', this.$el.value)
  }
}

So what I am trying to achieve basically, is when the component loads will get the value from v-model it will also receive a default value that shouldn't change, and only used as a value when the actual value is empty on blur
The default will have the initial value of data.something and it should not change!
I tried to get rid of the reference using JSON.parse(JSON.stringify(this.value)) but it doesn't seem to work either!

A: So if I understand your question correctly, you want this behavior: upon the blur event on your <multi-line-input> component, if the value of the input is empty, then set the value to a default value which is specified by the parent (through a prop).
First of all, it is an error to do this.value = ... in your component. You must not modify props, props pass data from parent to child only, the data passed through props is not yours to modify directly from within the component.
Try something like this:

Vue.component('multi-line-input', {
  template: '<input @blur="onBlur" @input="onInput" :value="value">',
  props: {
    value: {
      type: String,
      default: '',
    },
    default: {
      type: String,
      default: '',
    },
  },
  methods: {
    onBlur() {
      if (!this.value && this.default) {
        this.$emit('input', this.default);
      }
    },
    onInput(e) {
      this.$emit('input', e.target.value);
    },
  },
});

new Vue({
  el: '#app',
  data: {
    user: null,
    initialUser: null,
  },
  created() {
    // Pretend that I'm pulling this data from some API
    this.user = {
      name: 'Fred',
      email: 'fred@email.com',
      address: '123 Fake St',
    };

    // Make a copy of the data for the purpose of assigning the
    // default prop of each input
    this.initialUser = _.cloneDeep(this.user);
  },
});

  <template v-if="user">
    <multi-line-input v-model="user.name" :default="initialUser.name"></multi-line-input>
    <multi-line-input v-model="user.email" :default="initialUser.email"></multi-line-input>
    <multi-line-input v-model="user.address" :default="initialUser.address"></multi-line-input>
  </template>

Or, if you want the default value to be determined by the component instead of the parent (through a prop), you can do something like this instead:

Vue.component('multi-line-input', {
  template: '<input @blur="onBlur" @input="onInput" :value="value">',
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  created() {
    this.def = this.value;
  },
  methods: {
    onBlur() {
      if (!this.value && this.def) {
        this.$emit('input', this.def);
      }
    },
    onInput(e) {
      this.$emit('input', e.target.value);
    },
  },
});

new Vue({
  el: '#app',
  data: {
    user: null,
  },
  created() {
    // Pretend that I'm pulling this data from some API
    this.user = {
      name: 'Fred',
      email: 'fred@email.com',
      address: '123 Fake St',
    };
  },
});

  <template v-if="user">
    <multi-line-input v-model="user.name"></multi-line-input>
    <multi-line-input v-model="user.email"></multi-line-input>
    <multi-line-input v-model="user.address"></multi-line-input>
  </template>

However I do not recommend the second approach because the child component instance will only every have one default value for its entire lifetime. Vue reuses component instances whenever possible, so it wouldn't work if Vue were to bind it to a different parent component (how/when would it update its own default state?).


text: Q: Under what conditions are continuous functions closed in the compact-open topology If $X$ is compactly generated and $Y$ is a metric space, then $C(X,Y)$ is a closed subset of $Y^X$ in the compact-open topology. My question is, when the codomain $Y$ is no longer metric (or even uniform) are there established conditions for when $C(X,Y)$ is closed in the compact-open topology?


text:
Q: Pointer to a function that takes pointer parameters I am trying to create a function pointer that takes in a pointer to double as an argument. What is the proper syntax to write in main?
This is what I have but it keeps spitting out errors.
void (*ptr)(double, double, (*double), (*double) );

A: It is the same way you would declare a double * parameter in a function's parameter list:
void (* ptr) (double, double, double *, double *);

Can be assigned to a function like:
void something (double w, double x, double *py, double *pz) {
}

This is true in the general case, no matter how complicated it gets. For example, a pointer to a function that takes an int and another function pointer (which points to a function that takes a double and a void * and returns a char*) as a parameter:
void (* ptr) (int, char * (*) (double, void *));

Then:
char * g (double w, void *) {
    ...
}

void f (int x, char * (* y) (double, void *)) {
    ...
}

// usage, elsewhere:
ptr = &f;
ptr(0, &g);


text:
Q: Invalid postback or callback argument This is the error

Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

and I'm also getting these just about as often

The state information is invalid for this page and might be corrupted.

I've read about 20 other "Invalid postback or callback argument" question & answers, and I don't think mine falls into any of the common categories:

*

*Dynamically client-side created or changed controls that ASP.NET didn't know about

*Users submitting code or bits of code, eg "<" and ">" characters

*binding data in every Page_Load event without using if (!IsPostBack) judiciously

*faulty AJAX CascadingDropDown extender

*Russians trying to hack your site (!)

*Intermittent issues on users with dialup (!)

*Mismatch between ASP.NET versions, eg having a server farm with both ASP.NET 1.1 and 2.0 in use simultaneously

I THINK my issue's most similar to the last in this list.
I'm getting errors intermittently (but often) on my 2 Microsoft Azure web server load-balanced test environment upon form postbacks.
I notice the problem happens when a page produced by one of the servers is posted back to the other.  When I take away the load balancing (just hitting one server only), the problem goes away.
I'm using Win Server 2008 R2 (IIS7.5) on one web server and Win Server 2012 (IIS8) on the other (I was familiar with 2008, and wary of 2012 but wanting to learn, so I chose to run one of each to hedge my bets, in case you're wondering).
The 2008 machine runs ASP.NET version "4.0.30319.272" and the 2012 one runs "4.0.30319.18010", but obviously different versions of IIS.
But they're both running ASP.NET 4.0.  .NET is supposed to make the underlying operating system transparent, right?  So I'm not that confident that this is causing the problem.
Re-building one server to make them the same would be quite a chore and would prefer to avoid it if the minor ASP.NET differences aren't the cause of the problem!
So are there any other reasons two servers won't accept each others' forms on postback? FYI, I've already added a  entry into my web.config on both servers to fix "Validation of viewstate MAC failed" errors I was getting.
Or are there any config changes I could do to make the servers more compatible?
Thanks!

A: So I spent the half day re-building my web "farm" and making both servers 2008R2, and the problem went away!
My (tentative) conclusion is that the differences between viewstate handling between .NET 4.0.30319... versions on Server 2008R2 vs 2012 (including the completely different __EVENTVALIDATION format) were the cause of the problem.
I can't be certain of that because maybe the way I set the 2012 server up was different to the 2008R2 server. But then, when building the 2012 server, I followed fairly strictly the 2008R2 build document I'd written, so that, as well as the 2 days I spent tinkering the builds to get it to work, raises my confidence that I didn't miss something obvious.
Moral of the story (at about 80% confidence): don't mix server versions in ASP.NET deployments, even if the version of .NET is the same.

A: I had the same problem Farm system. I tested several solutions and what worked was:

*

*Generate the machineKey on one system and then replicate to another. (I found in several forums this solution, but it alone does not work)

*Put the same type of compability. For me it was "Framework45". (From this configuration started to work).

Example:
<system.web>
...
<machineKey compatibilityMode="Framework45" decryptionKey="808A25F38661B8799CFD5B6FC5CF73D2988F5786CE46075D" validationKey="B75D59843CA111DF8596FCF865D9C0459B63B6ED474D4B23FD63A5F3A5AB18560A0D2A162191EC3354650CB37B174DDE187B29D424FC5CF60EFDA567BA64D3A3" />
...
</system.web>

A: Try putting following in your page directive-
<%@ Page EnableEventValidation="false" %>


text:
Q: Why does the Iterator::filter method accept a mutable reference as self? The signature of Iterator::filter is
fn filter<P>(self, predicate: P) -> Filter<Self, P>
where
    Self: Sized,
    P: FnMut(&Self::Item) -> bool,

Because it has self as the first parameter, I was assuming I would have to pass the iterator by value, thus moving ownership to that function. However,
I am able to call it with just a ref mut and the code compiles and runs. For example:
fn char_count(i: &mut impl Iterator<Item=char>, c: char) -> usize {
    i.filter(|&x| c == x).count()
}

What am I missing here?

A: There is confusion about the two parameters here.
The self parameter refers to the original iterator. That is, filter() moves whatever the original iterator is into the new Filter struct, which takes ownership of that iterator (the Self in Filter<Self, _>)
The predicate is a FnMut because it does not need to be an Fn. That is, the function provided as predicate is allowed to modify the context it captures while it executes. This is possible because Filter itself does not borrow predicate when it calls it. If it did, predicate would have to be an Fn(&Self::Item).
The predicate takes the iterator's items by reference. Notice the sigil in the signature FnMut(&Self::Item).


text:
Q: Hypothesis testing with Poisson RV Hi I am still having some trouble with the following question: I have mostly figured out the first part but after that is where I get confused
Say we have random variables $X $~$ Poisson(\lambda)$ and $\lambda_{1} \gt \lambda_{0} \gt 0$ set values and we want to test $H_{o}: \lambda=\lambda_{o}$ and $H_{1}: \lambda=\lambda_{1}$.
The question asks to show that the optimal test at a level $\alpha$ rejects  the null hypothesis when $\bar X_n \gt c$ and find $c$, where $\bar X_n=\frac{1}{n}(x_{1}+...+x_{n})$ and furthermore show that the test that minimizes the sum of type one and type two errors rejects the null hypothesis when  $\bar X_n \gt c*$ and find $c*$
What I have tried:
I simply use that the optimal test will reject the null hypothesis when $$f(x|\lambda_{o}) \lt kf(x|\lambda_{1})$$
ie when $$\frac{f(x|\lambda_{1})}{f(x|\lambda_{o})} \gt \frac{1}{k}$$
for which I solve that $$\bar X_{n} \gt \frac{-lnk+n(\lambda_{1}-\lambda_{o})}{nln(\lambda_{1}/\lambda_{o})}$$
So if I call the RHS my c then our optimal test rejects the null when $\bar X_{n} \gt c$
Now I know I also want to have that $Pr(\bar X_{n} \gt c : \lambda=\lambda_{o})=\alpha$ that is I want the c such that $Pr(\bar X_{n} \gt c) $given that $\lambda=\lambda_{o}$ is $\alpha$.
Ps: Is it correct to say that the optimal test at level alpha will be that test such that the type 2 error is smallest for alpha type one error?
and I am confused on how to do that,
would it be like $$\sum_{x=0}^{c'}\frac{e^{{-\lambda_{o}} \lambda_{o}^{x}}}{x!}=\alpha$$ I mean how can I find such c?
But now I am confused on the second part. I want to show that the test that minimizes the sum of the type 1 and type 2 errors rejects the null when $\bar X_{n} \gt c*$ and find that $c*$.
I know that type 1 error occurs when we reject the null even though it is true and type 2 occurs when we accept the null even though it is false. So I am confused on this part. I know our optimal test rejected in the conditions above at level $\alpha$ so is it the same test
type 1:
$P(Xn \gt c : H_{o})=\alpha$
Type 2
$P(Xn \le c : H_{1})=\beta$
I have been trying for very long and will greatly appreciate any help one can offer, I am just confused on putting it all together. Thanks

A: I'll give my opinion on this matter. The aim is indeed to compute $c$ such that $\mathbb{P}(\overline{X}_n > c \ | \ \lambda = \lambda_0) = \alpha$. To that end you'll first need to verify the distribution of $\overline{X}_n$. It is well known (and easy to prove) that the sum of independent Poisson variables is again Poisson distributed. More precisely,
\begin{align}
&\mathbb{P}(\overline{X}_n > c \ | \ \lambda = \lambda_0) \\
& = \mathbb{P}(X_1+\ldots+X_n > nc \ |\ \lambda = \lambda_0) \\
& = \sum_{k = nc+1}^{\infty} \frac{(n\lambda_0)^k e^{-n \lambda_0}}{k!} \\
& = e^{-n \lambda_0} \left(\sum_{k=0}^{\infty} \frac{(n \lambda_0)^k}{k!} -\sum_{k=0}^{nc} \frac{(n \lambda_0)^k}{k!} \right) \\
& = e^{-n \lambda_0} \left(e^{n \lambda_0} - \underbrace{\sum_{k=0}^{nc} \frac{(n \lambda_0)^k}{k!}}_{(*)} \right) = \alpha
\end{align}
There is a closed form formula for the partial sum $(*)$ of the exponential series that might be useful, however it can turn out in an implicit expression for $c$.


text:
Q: Is it possible in GraphQL to define an xpath to ignore/skip a random field and extract inner object? I'm newbie to GraphQL and I've a complicated json object in which I've a random field which I would like to ignore and get it's inner/next level object?
Suppose I've the following json returned by an external api that I'm trying to call and I would like to only extract list of user keys
{
  "users": {
       "123321": { <!-- is a random number which can be any number -->
            "user": {
                "id": "123321",
                 "name": "Bob"
                 ...
             }
       },
      "456654": {
           "user": {
               "id": "456654",
               "name": "Foo"
            }
      }
     ...
}

Ideally, when I define a query, I would like to extract and construct a map of all the user objects. If possible, can someone show me how this can be achieved, an example would be appreciated.
Many thanks!

A: The way I've solved this is to convert that object into an array before handing it off to the resolvers:
const users = {
  users: [
    {
      id: "123321",
      name: "Bob",
    },
    {
      id: "456654",
      name: "Foo",
    }
  ]
};

This allows you to make direct queries:
query {
  user {
    id
    name
  }
}

Basically, use JavaScript to change the data into the shape you need so GraphQL doesn't need to do anything special.


text:
Q: How do I make HTML5 widgets with interactive features? I am a beginner (4 months of experience with HTML5) volunteering at a non-profit and I want to create an embeddable widget.  I want to make it interactive, like I want to display a few pictures that work the way a flash ad will (think slideshow effect) and I want to be able to make it shareable to social networks and if someone wants they can embed the widget they can.  In addition, I want to be able to put buttons that take them to other pages.
I have been searching it on the web and it seems iframes are the way to go.  Am I correct or is there another way to achieve what I want to?
UPDATE:
I need something like what's shown here as an example: http://www.quackit.com/html_5/tags/html_iframe_tag.cfm
but with options of sharing it and call-to-action options with slideshow.

A: The iframe tag is useful for 'embedding' your widget on someone else's page (it's the way Youtube videos get embedded). Bear in mind that everywhere that the traffic generated by the content of that iframe will count against your bandwidth, regardless of where it's placed, since it acts like a 'portal' to that content on your server.


text:
Q: multiple str_replace functions within the same mutate() my dummy code:
x <- c("A", "B", "C", "D")
y <- c("<0.5", "~1", "<10", "~30")

df <- data.frame(x,y) %>%
  mutate(y1 = str_replace(y, "~", ""),
         y2 = as.numeric(str_replace(y1, "<", ""))/2)

Basically what I want to do in column y is:

*

*Remove the "~" from values that contain "~"

*Remove "<" from values that contain "<", then halve those values

Ideally I'll come out with a fully numeric column.
How do I go about this step without needing the interim "y1" variable? I've tried putting both into str_replace but doesn't seem to work, or creates NAs. I've also tried piping within the str_replace but that doesn't work either. Note I only want the "<" values halved.
Thanks.

A: We can concatenate several remove conditions by the OR operator:
library(tidyverse)

df <- data.frame(x = c("A", "B", "C", "D"),
                 y = c("<0.5", "~1", "<10", "~30"))

df %>%
  mutate(y2 = as.numeric(str_remove(y, "<|~")),
         y2 = if_else(str_detect(y, '<'), 0.5 * y2, y2))

which gives:
  x    y    y2
1 A <0.5  0.25
2 B   ~1  1.00
3 C  <10  5.00
4 D  ~30 30.00

Updated solution by overwriting y:
df %>%
  mutate(y = if_else(str_detect(y, '<'), 0.5 * as.numeric(str_remove(y, "<|~")), as.numeric(str_remove(y, "<|~"))))

which gives:
  x     y
1 A  0.25
2 B  1.00
3 C  5.00
4 D 30.00

Of course you could also just delete the old y column from solution 1 and rename y2 to y.

A: Update: See comment of op:
library(tidyverse)
df %>%
  mutate(y = ifelse(str_detect(y, "<"), parse_number(y)/2, parse_number(y)))

  x     y
1 A  0.25
2 B  1.00
3 C  5.00
4 D 30.00

@deschen answer is good. An alternative is to use parse_number from readr package:
library(tidyverse)

df %>%
  mutate(y2 = ifelse(str_detect(y, "<"), parse_number(y)/2, parse_number(y)))

  x    y    y2
1 A <0.5  0.25
2 B   ~1  1.00
3 C  <10  5.00
4 D  ~30 30.00


text:
Q: Detach and Reattach element on hash change I'm just learning about detach(); but am not totally clear on how to use it properly.
I'd like to detach an element with a dynamically added attribute when the document has a particular hash, and reattach (?) the element with the attribute still in place when the document has a different hash.
Seems like i'm supposed to store the element as a variable but i'm not sure how exactly.
Thanks in advance!

A: When you detach with jquery you get an jquery object representing an dom element.
This could then be appended to a document or inserted before, after or inside another element.
.append()
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
.appendTo()
Insert every element in the set of matched elements to the end of the target.
.after()
Insert content, specified by the parameter, after each element in the set of matched elements.
.before()
Insert content, specified by the parameter, before each element in the set of matched elements.
.insertAfter()
Insert every element in the set of matched elements after the target.
.insertBefore()
Insert every element in the set of matched elements before the target.
http://api.jquery.com/category/manipulation

A: Thanks Daniel but I am so green i didn't even understand some of the basics of how to deal with jquery objects . . . anyway i finally figured it out, here's a jsfiddle that might help others trying to understand detach().  (not using the hash change but figured out the basics enough to go from here)
$('#yellow').click(function(){
$('trees').css('background-color', 'yellow');
});

$('#detach').click(function () {
    $Trees= $('trees').detach();
});

$('#insert').click(function(){
   $($Trees).insertBefore('#yellow');
});

http://jsfiddle.net/milpool/0p27o7os/


text:
Q: C# Comparing two lists to check if Payroll Process was done correctly (Validation) Im am learning C# and am making a Payroll Add-On for SAP Business One.
I have completed the payroll process that calculates netpay, gross pay, PAYE, earnings, deductions etc. These calculations for each employee are entered into a temporary process data table.
I now want to do a monthly rollover (close the current month). To do so, I have to do some validation to make sure that the calculations were done correctly before removing contents from the temp process data table to a permanent one.
I want to do this by comparing two lists.
The 1st is drawn from Employee Master Data in SAP and it contains employee IDs, names, telephones, salary units etc. I have selected employeeIDs only.
The 2nd is drawn from Process_Data_Temp and it contains employee IDs, net pay (U_PD_code = SYS001) etc.
I want to match this list by making sure that all the empIDs in 1st are contained in the 2nd (exactly) and that the net pay in the 2nd list is not null ie (U_PD_code where == SYS001 is not null or empty) etc. .
I want to do three comparisons based on salary unit ie. Monthly = M, SemiMonthly =S and Weekly = W.
Right now I'm interested in Monthly.
The field salary unit is in Employee master data but not in the process data temp table so I'm not sure how I will get distinct empIDs that are on monthly pay in the temp table in order to do the comparison. I am comparing monthly employees first.
Process_Data_Temp fields
Code Name, U_Tax_year, U_Employee_ID, U_Process_month, U_PD_code U_Amount, U_Balance,

U_Employer_cont_amnt

How does one do this?
My Code So Far
private void DoMonthEndRollover()
{
// Get service instances needed
var getAllEmployees = Program.Kernel.Get<IEmployeeService>().GetAllEmployees().Where(x => x.salaryUnit.ToString() == "M");
var tempProcessData = Program.Kernel.Get<IProcessDataTempService>().GetAllProcessDataTemps();

// Get all employee IDs from first list
var employeeIdList = (from el in getAllEmployees select el.empID).Distinct();

// Get information from second list
var tempList = (from tl in tempProcessData orderby tl.U_Employee_ID select tl).Distinct(); ......not finished

// Check if all Employee IDs have net pay (Contained in Process Data Temporary table)

}

NB: The Process Data Temporary table contains calculations of all employees whether monthly, semimonthly or weekly.
I hope I am clear enough

A: Assuming that employeeIDList and tempList are both lists of integers you can use IEnumerable.Intersect to find elements that are in both lists.
int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

IEnumerable<int> both = id1.Intersect(id2);

If the output list is is the same length as your input list then they are identical.
However, in the first instance check that your two lists are the same length. If they aren't then the process has failed. Only do the Intersect check if both lists are the same length.
There is also IEnumerable.Except method that:

Produces the set difference of two sequences by using the default equality comparer to compare values.


text: Q: How to get direction turn by turn in android I'm making an Taxi app for android,I'm displaying the route on the map. My map and route works fine, but i want to show direction turn by turn, like turn right, turn left with a point on that turn by clicking that it says now turn left or right, i don't know how to do that, i have searched many times in many different ways, but non match my requirement, i need a working example of direction turn by turn, so that i can run it and study it, it would be a great help.


text:
Q: Optimal backup to swappable Hard Drive with rsync on OSX This is close to other questions, but I'm having trouble narrowing down the 'optimal' solution for my use case, if there is one.  AFAIK this is not a dupe because OSX has different options relevant for its particular flavor of hard drive format.  This is also a laptop use case, so I'm looking for solutions that are relatively quick, and they probably can't run on a cron (in case I forget to plug the external drive in before bed).
Here's what I'm using:

*

*using OSX snow leopard 10.6.7

*rsync  version 3.0.7  protocol version 30

*backup to laptop hd in external enclosure

*one partition only

Here's what I want to be able to do:

*

*shut down my laptop

*take the disk out of the external enclosure and put it into my laptop

*run laptop

So, this is not a true backup system per se -- deleted files remain unrecoverable, just an insurance policy against hd failure.  Note that I should not have to reinstall any applications or operating systems.
Here's what I'm doing now:
sudo rsync -aNHAXx --fileflags --protect-decmpfs --force-change --progress / /Volumes/EXTERNAL/

I have yet to test this.  (So first question, you think this will work?)
My question is, what can I do to improve on what I'm doing in this command line (other than putting it in a script)?  What am I not considering?
Thoughts I have:

*

*am I really preserving everything I will need

*what can I exclude? -- spotlight files?  caches?

(Inspired by codinghorror What's Your Backup Strategy? post which is now dated.)

A: My rsync script for a periodic disk clone to a disk mounted at /Volumes/Backup1 is:
sudo rsync -xrlptgoEv --progress --delete / /Volumes/Backup1/
(optional) sudo bless -folder /Volumes/Backup1/System/Library/CoreServices
That's a full bootable clone of the drive.
A few points:
You don't necessarily need to install the backup drive into your laptop. I don't see any reason you wouldn't be able to boot directly from the disk while it's in its USB or Firewire enclosure. (Hold Option at boot to select the boot disk)
Some utilities like Carbon Copy Cloner do this just as well and provide a cleaner interface.

A: I never argue with things inspired by jwz's "Backups" post. But:
First, I'd still put it in cron, and if you're worried that you'll forget to plug the drive in, then adjust your upcoming script to check for the existence of the backup volume before running the rsync. Something like:
if [ -d /Volumes/Backup ]; then
    sudo rsync -vaxE --delete --ignore-errors / /Volumes/Backup/
else
    # email, SMS, or DM a warning that the overnight backup didn't happen
fi

Second, I'm not sure if I'd use --force-change. There's normally no reason to back up data that hasn't changed, and that will slow your backups down considerably.
Third, the best test of whether or not you preserved everything you need would be to drop the backup drive into your internal bay and see if it boots and you have what you need. Odds are, you will. It's just files on a filesystem.
Fourth, I don't think I'd sweat the time to back up Spotlight caches and other things. I doubt they take up that much space, or that many files, compared to your main body of data.

A: If you want to be able to pull the hard drive out of the enclosure and put it into the laptop you're better off using Carbon Copy Cloner.  It's built from the ground up to deal with this use case.


text:
Q: Trouble accessing array of object pointers I'm writing a bit of code to model a bus. The code has an error and I have simplified the problem in the following snippet:
struct luggageTag{
    int seat;
    bool luggage;
};

int main(){

    luggageTag *tagBox[36];
    tagBox[2]->luggage = true; // EXC_BAD_ACCESS on this line
}

Why is it that the line
tagBox[2]->luggage = true;

results in bad access?

A: Because tagBox[2] is a pointer but it doesn't point anywhere, and you're trying to dereference it.
You will need to make it point to somewhere first, e.g.:
luggageTag tag;
tagBox[2] = &tag;

But unless there's a specific reason why you would need pointers, you could simply store the actual objects directly in the array:
luggageTag tagBox[36];
       // ^ remove *
tagBox[2].luggage = true; // no EXC_BAD_ACCESS!
      // ^ dot, not arrow operator

Now there's no need to make the array element point to something first.

A: A pointer is a variable much like any other, except that for a pointer, T* ptr, its value is expected to be the address of an instance of T in memory.
You've created an array of uninitialized variables - you haven't pointed them at anything.
Think of a pointer as a post-it-note with the location of a thing on it. What you've done is torn 36 blank post-it notes off the top of the stack.
You'll need to create some luggageTag's to point to, but then you'll also be responsible for freeing those objects.
struct luggageTag{
    int seat;
    bool luggage;
};

int main(){
    luggageTag *tagBox[36];
    for (size_t i = 0; i < 36; ++i) {
        tagBox[i] = new luggageTag;
    }
    tagBox[2]->luggage = true;
    // memory leak unless you do:
    // for (size_t i = 0; i < 36 ; ++i)
    //   delete tagBox[i];
}

Alternatively you could create a pointer to an array of 36 luggage tags:
struct luggageTag{
    int seat;
    bool luggage;
};

int main(){
    luggageTag *tagBox = new luggageTag[36];
    tagBox[2]->luggage = true;
    // ...
    delete [] tagBox;  // free the memory
}

If this is not part of a school exercise, you might want to look at using a std::array or std::vector.

A: You need to allocate all the objects in the array:
 luggageTag *tagBox[36];
 for(int i=0; i<36; i++)
      tagBox[i] = new luggageTag;

 tagBox[2]->luggage = true;

 for(int i=0; i<36;i++)
        delete tagBox[i];


text:
Q: taste vs tasting As I know the verb "taste" isn't normally used in Present Continuous. But I have one example when it's used. Is it correct? Why? If I use the Present Simple here, is it not correct?

The reason I get fat is that I'm always tasting things while I'm cooking.
The reason I get fat is that I always taste things while I'm cooking.

A: Both are correct uses, but there is a slightly ambiguous meaning because of taste:

I'm always tasting food while I'm cooking.

can mean

"Whenever I cook food, I make sure it's up to my standards by sampling it first."

but it could also mean,

"Whenever I cook food, I experience the strange sensation of it being in my mouth, despite not eating anything."

In this example, most speakers will assume you mean something like the first sentence instead of the second.

As I know the verb "taste" isn't normally used in Present Continuous.

It's generally fine to use taste this way. If you wanted to eliminate any ambiguity I would try a different verb:

The reason I get fat is that I always sample things while I'm cooking.

A: "Taste" as a verb is used in two ways:

This milk tastes sour.

Here the subject is the food and "taste" is a linking verb. You don't use present continuous in this sense

I taste the milk before I drink it.

Here the subject is the person, and the object is the food.  In this sense the present continuous is correct.

John is tasting the chicken, and he is smiling! It must be good.

In your situation, you are describing a "general fact" so you would normally use the simple present tense.

I always taste the food while I'm cooking.

The present continuous might be used for nuance or just to add variety and immediacy. It suggests, perhaps, repeated samples of the food.


text:
Q: Como multiplicar elementos dentro de uma array Sou iniciante no JS e estou tentando entender como fazer para criar uma função que eu consiga triplicar qualquer valor dentro do Array. Esse tá sendo o meu código, mas não to conseguindo pensar muito bem em como resolver.
function tripleTheChances(chances){
    var chances = []
for(let index = 0; index <= chances.length; index++){
    chances[index] * 3
}
    return chances[index] * 3
}

A: Basta usar o map
chances.map(x => x * 3)

ele percorrerá o array executando a função 'x * 3' por elemento
ou caso queira em uma função:
function tripleTheChances(chances){
   for(var index = 0; index < chances.length; index++){
      chances[index] *= 3;
   }
   return chances;
}

usando um operador *= para fazer a operação com o valor que já está no index,assim atualizando ele


text:
Q: Where to put the GPG keys in $HOME/.gnupg? I run OpenSuse 11.4 and KDE 4.6. I installed Thunderbird and Enigma.
Thunderbird is the following version: Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9.2.13) Gecko/20101206 SUSE/3.1.7 Thunderbird/3.1.7
I have no clue where to put the GPG key. Some said that I have to put the GPG keys in $HOME/.gnupg. But, where should i find this directory? I looked through all the directories – I am lost!
When I have several keys, can I put all of them there? Does the system find the right ones on its own?

A: If I understood correctly, you are trying to import existing keys in your keyring. Enter the following command in the terminal:
gpg --import <path-to-keyfile>