Programs & Examples On #Node.js

Node.js is an event-based, non-blocking, asynchronous I/O framework that uses Google's V8 JavaScript engine and libuv library. It is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.

Node.js - get raw request body using Express

// Change the way body-parser is used
const bodyParser = require('body-parser');

var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}
app.use(bodyParser.json({ verify: rawBodySaver, extended: true }));




// Now we can access raw-body any where in out application as follows
request.rawBody;

How do I install the babel-polyfill library?

Like Babel says in the docs, for Babel > 7.4.0 the module @babel/polyfill is deprecated, so it's recommended to use directly core-js and regenerator-runtime libraries that before were included in @babel/polyfill.

So this worked for me:

npm install --save [email protected]
npm install regenerator-runtime

then add to the very top of your initial js file:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

"unexpected token import" in Nodejs5 and babel?

@jovi all you need to do is add .babelrc file like this:

{
  "plugins": [
    "transform-strict-mode",
    "transform-es2015-modules-commonjs",
    "transform-es2015-spread",
    "transform-es2015-destructuring",
    "transform-es2015-parameters"
  ]
}

and install these plugins as devdependences with npm.

then try babel-node ***.js again. hope this can help you.

Install Node.js on Ubuntu

For the latest Node.js

sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -

sudo apt-get install nodejs
node -v
npm -v

Node - how to run app.js?

Assuming I have node and npm properly installed on the machine, I would

  • Download the code
  • Navigate to inside the project folder on terminal, where I would hopefully see a package.json file
  • Do an npm install for installing all the project dependencies
  • Do an npm install -g nodemon for installing all the project dependencies
  • Then npm start OR node app.js OR nodemon app.js to get the app running on local host

Hope this helps someone

use nodemon app.js ( nodemon is a utility that will monitor for any changes in your source and automatically restart your server)

How to build minified and uncompressed bundle with webpack?

You should export an array like this:

const path = require('path');
const webpack = require('webpack');

const libName = 'YourLibraryName';

function getConfig(env) {
  const config = {
    mode: env,
    output: {
      path: path.resolve('dist'),
      library: libName,
      libraryTarget: 'umd',
      filename: env === 'production' ? `${libName}.min.js` : `${libName}.js`
    },
    target: 'web',
    .... your shared options ...
  };

  return config;
}

module.exports = [
  getConfig('development'),
  getConfig('production'),
];

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

nodejs npm global config missing on windows

Even though we have the .NPMRC can be in 3 locations, Please NOTE THAT - the file under the Per-User NPM config location take precedence over the Global & Built-in configurations.

  1. Global NPM config => C:\Users\%username%\AppData\Roaming\npm\etc\npmrc
  2. Per-user NPM config => C:\Users\%username%.npmrc
  3. Built-in NPM config => C:\Program Files\nodejs\node_modules\npm\npmrc

To find out which file is getting updated, try setting the proxy using the following command npm config set https-proxy https://username:[email protected]:6050

After that open the .npmrc files to see which file get updated.

Replace multiple strings with multiple other strings

using Array.prototype.reduce():

const arrayOfObjects = [
  { plants: 'men' },
  { smart:'dumb' },
  { peace: 'war' }
]
const sentence = 'plants are smart'

arrayOfObjects.reduce(
  (f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence
)

// as a reusable function
const replaceManyStr = (obj, sentence) => obj.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)

const result = replaceManyStr(arrayOfObjects , sentence1)

Example

_x000D_
_x000D_
// /////////////    1. replacing using reduce and objects_x000D_
_x000D_
// arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)_x000D_
_x000D_
// replaces the key in object with its value if found in the sentence_x000D_
// doesn't break if words aren't found_x000D_
_x000D_
// Example_x000D_
_x000D_
const arrayOfObjects = [_x000D_
  { plants: 'men' },_x000D_
  { smart:'dumb' },_x000D_
  { peace: 'war' }_x000D_
]_x000D_
const sentence1 = 'plants are smart'_x000D_
const result1 = arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence1)_x000D_
_x000D_
console.log(result1)_x000D_
_x000D_
// result1: _x000D_
// men are dumb_x000D_
_x000D_
_x000D_
// Extra: string insertion python style with an array of words and indexes_x000D_
_x000D_
// usage_x000D_
_x000D_
// arrayOfWords.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence)_x000D_
_x000D_
// where arrayOfWords has words you want to insert in sentence_x000D_
_x000D_
// Example_x000D_
_x000D_
// replaces as many words in the sentence as are defined in the arrayOfWords_x000D_
// use python type {0}, {1} etc notation_x000D_
_x000D_
// five to replace_x000D_
const sentence2 = '{0} is {1} and {2} are {3} every {5}'_x000D_
_x000D_
// but four in array? doesn't break_x000D_
const words2 = ['man','dumb','plants','smart']_x000D_
_x000D_
// what happens ?_x000D_
const result2 = words2.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence2)_x000D_
_x000D_
console.log(result2)_x000D_
_x000D_
// result2: _x000D_
// man is dumb and plants are smart every {5}_x000D_
_x000D_
// replaces as many words as are defined in the array_x000D_
// three to replace_x000D_
const sentence3 = '{0} is {1} and {2}'_x000D_
_x000D_
// but five in array_x000D_
const words3 = ['man','dumb','plant','smart']_x000D_
_x000D_
// what happens ? doesn't break_x000D_
const result3 = words3.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence3)_x000D_
_x000D_
console.log(result3)_x000D_
_x000D_
// result3: _x000D_
// man is dumb and plants
_x000D_
_x000D_
_x000D_

Basic HTTP authentication with Node and Express 4

Simple Basic Auth with vanilla JavaScript (ES6)

app.use((req, res, next) => {

  // -----------------------------------------------------------------------
  // authentication middleware

  const auth = {login: 'yourlogin', password: 'yourpassword'} // change this

  // parse login and password from headers
  const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
  const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')

  // Verify login and password are set and correct
  if (login && password && login === auth.login && password === auth.password) {
    // Access granted...
    return next()
  }

  // Access denied...
  res.set('WWW-Authenticate', 'Basic realm="401"') // change this
  res.status(401).send('Authentication required.') // custom message

  // -----------------------------------------------------------------------

})

note: This "middleware" can be used in any handler. Just remove next() and reverse the logic. See the 1-statement example below, or the edit history of this answer.

Why?

  • req.headers.authorization contains the value "Basic <base64 string>", but it can also be empty and we don't want it to fail, hence the weird combo of || ''
  • Node doesn't know atob() and btoa(), hence the Buffer

ES6 -> ES5

const is just var .. sort of
(x, y) => {...} is just function(x, y) {...}
const [login, password] = ...split() is just two var assignments in one

source of inspiration (uses packages)


The above is a super simple example that was intended to be super short and quickly deployable to your playground server. But as was pointed out in the comments, passwords can also contain colon characters :. To correctly extract it from the b64auth, you can use this.

  // parse login and password from headers
  const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
  const strauth = Buffer.from(b64auth, 'base64').toString()
  const splitIndex = strauth.indexOf(':')
  const login = strauth.substring(0, splitIndex)
  const password = strauth.substring(splitIndex + 1)

  // using shorter regex by @adabru
  // const [_, login, password] = strauth.match(/(.*?):(.*)/) || []

Basic auth in one statement

...on the other hand, if you only ever use one or very few logins, this is the bare minimum you need: (you don't even need to parse the credentials at all)

function (req, res) {
//btoa('yourlogin:yourpassword') -> "eW91cmxvZ2luOnlvdXJwYXNzd29yZA=="
//btoa('otherlogin:otherpassword') -> "b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk"

  // Verify credentials
  if (  req.headers.authorization !== 'Basic eW91cmxvZ2luOnlvdXJwYXNzd29yZA=='
     && req.headers.authorization !== 'Basic b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk')        
    return res.status(401).send('Authentication required.') // Access denied.   

  // Access granted...
  res.send('hello world')
  // or call next() if you use it as middleware (as snippet #1)
}

PS: do you need to have both "secure" and "public" paths? Consider using express.router instead.

var securedRoutes = require('express').Router()

securedRoutes.use(/* auth-middleware from above */)
securedRoutes.get('path1', /* ... */) 

app.use('/secure', securedRoutes)
app.get('public', /* ... */)

// example.com/public       // no-auth
// example.com/secure/path1 // requires auth

Proper way to return JSON using node or Express

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you and returns the response in JSON format.

Example:

res.json({"foo": "bar"});

Node.js global variables

Use a global namespace like global.MYAPI = {}:

global.MYAPI._ = require('underscore')

All other posters talk about the bad pattern involved. So leaving that discussion aside, the best way to have a variable defined globally (OP's question) is through namespaces.

Tip: Development Using Namespaces

node.js - how to write an array to file

If it's a huuge array and it would take too much memory to serialize it to a string before writing, you can use streams:

var fs = require('fs');

var file = fs.createWriteStream('array.txt');
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

Make sure to resolve/reject the promises used in the test cases, be it spies or stubs make sure they resolve/reject.

Send response to all clients except sender

I am using namespaces and rooms - I found

socket.broadcast.to('room1').emit('event', 'hi');

to work where

namespace.broadcast.to('room1').emit('event', 'hi');

did not

(should anyone else face that problem)

Which ORM should I use for Node.js and MySQL?

One major difference between Sequelize and Persistence.js is that the former supports a STRING datatype, i.e. VARCHAR(255). I felt really uncomfortable making everything TEXT.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

How to access a preexisting collection with Mongoose?

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

mongoose.model('Question', 
               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

Express.js Response Timeout

In case you would like to use timeout middleware and exclude a specific route:

var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests

app.use('/my_route', function(req, res, next) {
    req.clearTimeout(); // clear request timeout
    req.setTimeout(20000); //set a 20s timeout for this request
    next();
}).get('/my_route', function(req, res) {
    //do something that takes a long time
});

Run JavaScript in Visual Studio Code

I am surprised this has not been mentioned yet:

Simply open the .js file in question in VS Code, switch to the 'Debug Console' tab, hit the debug button in the left nav bar, and click the run icon (play button)!

Requires nodejs to be installed!

How to set custom location for local installation of npm package?

On Windows 7 for example, the following set of commands/operations could be used.

Create an personal environment variable, double backslashes are mandatory:

  • Variable name: %NPM_HOME%
  • Variable value: C:\\SomeFolder\\SubFolder\\

Now, set the config values to the new folders (examplary file names):

  • Set the npm folder

npm config set prefix "%NPM_HOME%\\npm"

  • Set the npm-cache folder

npm config set cache "%NPM_HOME%\\npm-cache"

  • Set the npm temporary folder

npm config set tmp "%NPM_HOME%\\temp"

Optionally, you can purge the contents of the original folders before the config is changed.

  • Delete the npm-cache npm cache clear

  • List the npm modules npm -g ls

  • Delete the npm modules npm -g rm name_of_package1 name_of_package2

How can I add a .npmrc file?

Assuming you are using VSTS run vsts-npm-auth -config .npmrc to generate new .npmrc file with the auth token

NodeJS w/Express Error: Cannot GET /

You need to define a root route.

app.get('/', function(req, res) {
  // do something here.
});

Oh and you cannot specify a file within the express.static. It needs to be a directory. The app.get('/'.... will be responsible to render that file accordingly. You can use express' render method, but your going to have to add some configuration options that will tell express where your views are, traditionally within the app/views/ folder.

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

Restart node upon changing a file

Follow the steps:

  1. npm install --save-dev nodemon

  2. Add the following two lines to "script" section of package.json:

"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"

as shown below:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
}
  1. npm run devstart

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

You can directly set the content type like below:

res.writeHead(200, {'Content-Type': 'text/plain'});

For reference go through the nodejs Docs link.

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

User this link for perfact solution for ws https://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html

You have to just do below step..

Go to /etc/apache2/mods-available

Step...1

Enable mode proxy_wstunnel.load by using below command

$a2enmod proxy_wstunnel.load

Step...2

Go to /etc/apache2/sites-available

and add below line in your .conf file inside virtual host

ProxyPass "/ws2/"  "ws://localhost:8080/"

ProxyPass "/wss2/" "wss://localhost:8080/"

Note : 8080 mean your that your tomcat running port because we want to connect ws where our War file putted in tomcat and tomcat serve apache for ws. thank you

My Configuration

ws://localhost/ws2/ALLCAD-Unifiedcommunication-1.0/chatserver?userid=4 =Connected

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case, neither the port nor the host was the problem. The index.js was divided into 2 files. server.js:

//server.js
const express = require('express')
const path = require('path')

const app = express()

app.use(express.static(path.resolve(__dirname, 'public')));
// and all the other stuff
module.exports = app

//app.js
const app = require('./server');
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
    console.log('Server is running s on port: ' + port)
});

from package.json we ran node app.js.

Apparently that was the problem. Once I combined the two into one file, the Heroku app deployed as expected.

How to read file with async/await properly?

This is TypeScript version of @Joel's answer. It is usable after Node 11.0:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

Node.js throws "btoa is not defined" error

I understand this is a discussion point for a node application, but in the interest of universal JavaScript applications running on a node server, which is how I arrived at this post, I have been researching this for a universal / isomorphic react app I have been building, and the package abab worked for me. In fact it was the only solution I could find that worked, rather than using the Buffer method also mentioned (I had typescript issues).

(This package is used by jsdom, which in turn is used by the window package.)

Getting back to my point; based on this, perhaps if this functionality is already written as an npm package like the one you mentioned, and has it's own algorithm based on W3 spec, you could install and use the abab package rather than writing you own function that may or may not be accurate based on encoding.

---EDIT---

I started having weird issues today with encoding (not sure why it's started happening now) with package abab. It seems to encode correctly most of the time, but sometimes on front end it encodes incorrectly. Spent a long time trying to debug, but switched to package base-64 as recommended, and it worked straight away. Definitely seemed to be down to the base64 algorithm of abab.

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

Angular - ng: command not found

I had a lot of issues installing it on a mac with all the permission errors Finally the following line solve the issue.

sudo npm i -g @angular/cli

adding .css file to ejs

app.use(express.static(__dirname + '/public'));
<link href="/css/style.css" rel="stylesheet" type="text/css">

So folder structure should be:

.
./app.js
./public
 /css
 /style.css

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

how to check for datatype in node js- specifically for integer

You can check your numbers by checking their constructor.

var i = "5";

if( i.constructor !== Number )
{
 console.log('This is not number'));
}

ERROR in Cannot find module 'node-sass'

My problem was that a webfilter didn't allow me to download the node-sass package, when I executed the command

npm i

After the installation of the Windows Build Tools

npm i -g windows-build-tools

it build node-sass on it's own and now I can use it.

PS: I also installed Python 2.7.17 before, but I don't think that helped.

Test process.env with Jest

Depending on how you can organize your code, another option can be to put the environment variable within a function that's executed at runtime.

In this file, the environment variable is set at import time and requires dynamic requires in order to test different environment variables (as described in this answer):

const env = process.env.MY_ENV_VAR;

const envMessage = () => `MY_ENV_VAR is set to ${env}!`;

export default myModule;

In this file, the environment variable is set at envMessage execution time, and you should be able to mutate process.env directly in your tests:

const envMessage = () => {
  const env = process.env.MY_VAR;
  return `MY_ENV_VAR is set to ${env}!`;
}

export default myModule;

Jest test:

const vals = [
  'ONE',
  'TWO',
  'THREE',
];

vals.forEach((val) => {
  it(`Returns the correct string for each ${val} value`, () => {
    process.env.MY_VAR = val;

    expect(envMessage()).toEqual(...

Reading all files in a directory, store them in objects, and send the object

async/await

const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)

try {
  async function emitData(directory) {
    let filenames = await pathnames
    var ob = {}
    const data = filenames.map(async function(filename, i) {
      if (filename.includes(".")) {
        var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
          encoding: "utf8",
        })
        ob[filename.replace(".js", "")] = await storedFile
        socket.emit("init", { data: ob })
      }
      return ob
    })
  }

  emitData(directory)
} catch (err) {
  console.log(err)
}

Who wants to try with generators?

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

Putting this before the command seems to work NODE_TLS_REJECT_UNAUTHORIZED=0. ex: NODE_TLS_REJECT_UNAUTHORIZED=0 npm ...

It would be best to figure out how to make node see self signed certificate as valid. strict-ssl suggestion above didn't work for me for some reason. If you understand the security implications and need a temporary quick fix, this is what I found in some random github issues during Google search of the error.

Node update a specific package

Always you can do it manually. Those are the steps:

  • Go to the NPM package page, and search for the GitHub link.
  • Now download the latest version using GitHub download link, or by clonning. git clone github_url
  • Copy the package to your node_modules folder for e.g. node_modules/browser-sync

Now it should work for you. To be sure it will not break in the future when you do npm i, continue the upcoming two steps:

  • Check the version of the new package by reading the package.json file in it's folder.
  • Open your project package.json and set the same version for where it's appear in the dependencies part of your package.json

While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.

Node.js: what is ENOSPC error and how to solve?

I was having Same error. While I run Reactjs app. What I do is just remove the node_modules folder and type and install node_modules again. This remove the error.

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

How to downgrade Node version

Steps to downgrade to node8

brew install node@8
brew link node@8 --force

if warning remove the folder and files as indicated in the warning then again the command :

brew link node@8 --force

nvm is not compatible with the npm config "prefix" option:

Note:
to remove, delete, or uninstall nvm - just remove the $NVM_DIR folder (usually ~/.nvm)
you can try :
rm -rf ~/.nvm

env: node: No such file or directory in mac

I got such a problem after I upgraded my node version with brew. To fix the problem

1)run $brew doctor to check out if it is successfully installed or not 2) In case you missed clearing any node-related file before, such error log might pop up:

Warning: You have unlinked kegs in your Cellar Leaving kegs unlinked can lead to build-trouble and cause brews that depend on those kegs to fail to run properly once built. node

3) Now you are recommended to run brew link command to delete the original node-related files and overwrite new files - $ brew link node.

And that's it - everything works again !!!

How to run server written in js with Node.js

I open a text editor, in my case I used Atom. Paste this code

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

and save as

helloworld.js

in

c:\xampp\htdocs\myproject 

directory. Next I open node.js commamd prompt enter

cd c:\xampp\htdocs\myproject

next

node helloworld.js

next I open my chrome browser and I type

http://localhost:1337

and there it is.

Node.js Port 3000 already in use but it actually isn't?

I had the same problem. (The below steps work fine on Windows 10):

  1. Open Task manager (press Ctrl+Alt+Delete)
  2. Select the 'Processes tab'
  3. Search for 'Node.js: Server-side JavaScript'
  4. Select it and click on 'End task' button

Now you can run npm start.

Hope it helps you.

Automatically start forever (node) on system restart

I would suggest using crontab. It's easy to use.

How to

  1. To start editing run the following replacing the "testuser" with your desired runtime user for the node process. If you choose a different user other than yourself, you will have to run this with sudo.

    $ crontab -u testuser -e
    
  2. If you have never done this before, it will ask you which editor you wish to edit with. I like vim, but will recommend nano for ease of use.

  3. Once in the editor add the following line:

    @reboot /usr/local/bin/forever start /your/path/to/your/app.js
    
  4. Save the file. You should get some feedback that the cron has been installed.

  5. For further confirmation of the installation of the cron, execute the following (again replacing "testuser" with your target username) to list the currently installed crons:

    $ crontab -u testuser -l 
    

Note that in my opinion, you should always use full paths when executing binaries in cron. Also, if the path to your forever script is not correct, run which forever to get the full path.

Given that forever calls node, you may also want to provide the full path to node:

@reboot /usr/local/bin/forever start -c /usr/local/bin/node /your/path/to/your/app.js

Further Reading

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

For anyone getting this using ServiceStack backend; add "Authorization" to allowed headers in the Cors plugin:

Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));

MomentJS getting JavaScript Date in UTC

Calling toDate will create a copy (the documentation is down-right wrong about it not being a copy), of the underlying JS Date object. JS Date object is stored in UTC and will always print to eastern time. Without getting into whether .utc() modifies the underlying object that moment wraps use the code below.

You don't need moment for this.

new Date().getTime()

This works, because JS Date at its core is in UTC from the Unix Epoch. It's extraordinarily confusing and I believe a big flaw in the interface to mix local and UTC times like this with no descriptions in the methods.

Render basic HTML view?

From the Express.js Guide: View Rendering

View filenames take the form Express.ENGINE, where ENGINE is the name of the module that will be required. For example the view layout.ejs will tell the view system to require('ejs'), the module being loaded must export the method exports.render(str, options) to comply with Express, however app.register() can be used to map engines to file extensions, so that for example foo.html can be rendered by jade.

So either you create your own simple renderer or you just use jade:

 app.register('.html', require('jade'));

More about app.register.

Note that in Express 3, this method is renamed app.engine

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

Node.js Generate html

If you want to create static files, you can use Node.js File System Library to do that. But if you are looking for a way to create dynamic files as a result of your database or similar queries then you will need a template engine like SWIG. Besides these options you can always create HTML files as you would normally do and serve them over Node.js. To do that, you can read data from HTML files with Node.js File System and write it into response. A simple example would be:

var http = require('http');
var fs   = require('fs');

http.createServer(function (req, res) {
  fs.readFile(req.params.filepath, function (err, content) {
    if(!err) {
      res.end(content);
    } else {
      res.end('404');
    }
  }
}).listen(3000);

But I suggest you to look into some frameworks like Express for more useful solutions.

Node.js Error: Cannot find module express

In your case your express module is installed at C:\Users\Dmitry\AppData\Roaming\npm\node_modules\express, but you need to get this module in to your project directory. So you should copy the file the express module folders from C:\Users\Dmitry\AppData\Roaming\npm\node_modules\ to your project directory as : C:\ChatServer\Server\node_modules. If you do not have a folder named 'node_modules' in your project folder, then create it first and paste those files into this folder. This method worked for me on my windows pc. Restart your node server and once again run the command node C:\ChatServer\Server>node server.js. It should work now !!!!

How can I update npm on Windows?

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.

Error: Cannot find module html

This is what i did for rendering html files. And it solved the errors. Install consolidate and mustache by executing the below command in your project folder.

$ sudo npm install consolidate mustache --save

And make the following changes to your app.js file

var engine = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');

And now html pages will be rendered properly.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This is the real proxy redirection to the intended server.

server {
  listen          80;
  server_name     localhost;
location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
    proxy_pass http://xx.xxx.xxx.xxx/;
    proxy_redirect off;
    proxy_set_header Host $host;

  }
}

how to implement login auth in node.js

I tried this answer and it didn't work for me. I am also a newbie on web development and took classes where i used mlab but i prefer parse which is why i had to look for the most suitable solution. Here is my own current solution using parse on expressJS.

1)Check if the user is authenticated: I have a middleware function named isLogginIn which I use on every route that needs the user to be authenticated:

 function isLoggedIn(req, res, next) {
 var currentUser = Parse.User.current();
 if (currentUser) {
     next()
 } else {
     res.send("you are not authorised");
 }
}

I use this function in my routes like this:

  app.get('/my_secret_page', isLoggedIn, function (req, res) 
  {
    res.send('if you are viewing this page it means you are logged in');
  });

2) The Login Route:

  // handling login logic
  app.post('/login', function(req, res) {
  Parse.User.enableUnsafeCurrentUser();
  Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
    res.redirect('/books');
  }, function(error) {
    res.render('login', { flash: error.message });
  });
});

3) The logout route:

 // logic route
  app.get("/logout", function(req, res){
   Parse.User.logOut().then(() => {
    var currentUser = Parse.User.current();  // this will now be null
    });
        res.redirect('/login');
   });

This worked very well for me and i made complete reference to the documentation here https://docs.parseplatform.org/js/guide/#users

Thanks to @alessioalex for his answer. I have only updated with the latest practices.

How do I uninstall a package installed using npm link?

If you've done something like accidentally npm link generator-webapp after you've changed it, you can fix it by cloning the right generator and linking that.

git clone https://github.com/yeoman/generator-webapp.git;
# for fixing generator-webapp, replace with your required repository
cd generator-webapp;
npm link;

Invalidating JSON Web Tokens

This is primarily a long comment supporting and building on the answer by @mattway

Given:

Some of the other proposed solutions on this page advocate hitting the datastore on every request. If you hit the main datastore to validate every authentication request, then I see less reason to use JWT instead of other established token authentication mechanisms. You've essentially made JWT stateful, instead of stateless if you go to the datastore each time.

(If your site receives a high volume of unauthorized requests, then JWT would deny them without hitting the datastore, which is helpful. There are probably other use cases like that.)

Given:

Truly stateless JWT authentication cannot be achieved for a typical, real world web app because stateless JWT does not have a way to provide immediate and secure support for the following important use cases:

User's account is deleted/blocked/suspended.

User's password is changed.

User's roles or permissions are changed.

User is logged out by admin.

Any other application critical data in the JWT token is changed by the site admin.

You cannot wait for token expiration in these cases. The token invalidation must occur immediately. Also, you cannot trust the client not to keep and use a copy of the old token, whether with malicious intent or not.

Therefore: I think the answer from @matt-way, #2 TokenBlackList, would be most efficient way to add the required state to JWT based authentication.

You have a blacklist that holds these tokens until their expiration date is hit. The list of tokens will be quite small compared to the total number of users, since it only has to keep blacklisted tokens until their expiration. I'd implement by putting invalidated tokens in redis, memcached or another in-memory datastore that supports setting an expiration time on a key.

You still have to make a call to your in-memory db for every authentication request that passes initial JWT auth, but you don't have to store keys for your entire set of users in there. (Which may or may not be a big deal for a given site.)

How to check if that data already exist in the database during update (Mongoose And Express)

Here is another way to accomplish this in less code.

UPDATE 3: Asynchronous model class statics

Similar to option 2, this allows you to create a function directly linked to the schema, but called from the same file using the model.

model.js

 userSchema.statics.updateUser = function(user, cb) {
  UserModel.find({name : user.name}).exec(function(err, docs) {
    if (docs.length){
      cb('Name exists already', null);
    } else {
      user.save(function(err) {
        cb(err,user);
      }
    }
  });
}

Call from file

var User = require('./path/to/model');

User.updateUser(user.name, function(err, user) {
  if(err) {
    var error = new Error('Already exists!');
    error.status = 401;
    return next(error);
  }
});

Combine or merge JSON on node.js without jQuery

A normal loop?

function extend(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

var object3 = extend({}, object1, object2);

That's a basic starting point. You may want to add things like a hasOwnProperty check, or add some logic to handle the case where multiple source objects have a property with the same identifier.

Here's a working example.

Side note: what you are referring to as "JSON" are actually normal JavaScript objects. JSON is simply a text format that shares some syntax with JavaScript.

Specify path to node_modules in package.json

yes you can, just set the NODE_PATH env variable :

export NODE_PATH='yourdir'/node_modules

According to the doc :

If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)

Additionally, node will search in the following locations:

1: $HOME/.node_modules

2: $HOME/.node_libraries

3: $PREFIX/lib/node

Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.

These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.

Source

Share variables between files in Node.js?

If we need to share multiple variables use the below format

//module.js
   let name='foobar';
   let city='xyz';
   let company='companyName';

   module.exports={
    name,
    city,
    company
  }

Usage

  // main.js
    require('./modules');
    console.log(name); // print 'foobar'

How to redirect to another page in node.js

In another way you can use window.location.href="your URL"

e.g.:

res.send('<script>window.location.href="your URL";</script>');

or:

return res.redirect("your url");

Cannot install packages using node package manager in Ubuntu

On Linux Mint 17, I tried both solutions (creating a symlink or using the nodejs-legacy package) without success.

The only thing that finally worked for me was using the ppa from Chris Lea:

sudo apt-get purge node-*
sudo apt-get autoremove 
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

This installed node version 10.37 and npm 1.4.28. After that, I could install packages globally.

How to fix Error: listen EADDRINUSE while using nodejs?

Got this error when we accidentally had two local Express environments in the same instance pointing to the same port.

If you got this far down this list of answers, I hope this will be helpful and solve your problem.

Reading value from console, interactively

I had to write a "tic-tac-toe" game in Node that took input from the command line, and wrote this basic async/await block of code that did the trick.

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

async function getAnswer (prompt) {
  const answer = await new Promise((resolve, reject) =>{
    rl.question(`${prompt}\n`, (answer) => {
      resolve(answer)
    });
  })
  return answer
}

let done = false
const playGame = async () => {
  let i = 1
  let prompt = `Question #${i}, enter "q" to quit`
  while (!done) {
    i += 1
    const answer = await getAnswer(prompt)
    console.log(`${answer}`)
    prompt = processAnswer(answer, i)
  }
  rl.close()
}

const processAnswer = (answer, i) => {
  // this will be set depending on the answer
  let prompt = `Question #${i}, enter "q" to quit`
  // if answer === 'q', then quit
  if (answer === 'q') {
    console.log('User entered q to quit')
    done = true
    return
  }
  // parse answer

  // if answer is invalid, return new prompt to reenter

  // if answer is valid, process next move

  // create next prompt
  return prompt
}

playGame()

Express: How to pass app-instance to routes from a different file?

Use req.app, req.app.get('somekey')

The application variable created by calling express() is set on the request and response objects.

See: https://github.com/visionmedia/express/blob/76147c78a15904d4e4e469095a29d1bec9775ab6/lib/express.js#L34-L35

How to solve npm error "npm ERR! code ELIFECYCLE"

This solution fixed the error in Win10.

Please install globally npm install -g node-pre-gyp

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

Parsing Query String in node.js

You can use the parse method from the URL module in the request callback.

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    response.end('Hello ' + queryData.name + '\n');

  } else {
    response.end("Hello World\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

I suggest you read the HTTP module documentation to get an idea of what you get in the createServer callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.

update package.json version automatically

I want to add some clarity to the answers this question got.

Even thought there are some answers here that are tackling properly the problem and providing a solution, they are not the correct ones. The correct answer to this question is to use npm version

Is there a way to edit the file package.json automatically?

Yes, what you can do to make this happen is to run the npm version command when needed, you can read more about it here npm version, but the base usage would be npm version patch and it would add the 3rd digit order on your package.json version (1.0.X)

Would using a git pre-release hook help?

You could configure to run the npm version command on the pre-release hook, as you need, but that depends if that is what you need or not in your CD/CI pipe, but without the npm version command a git pre-release hook can't do anything "easily" with the package.json

The reason why npm version is the correct answer is the following:

  1. If the user is using a folder structure in which he has a package.json he is using npm if he is using npm he has access to the npm scripts.
  2. If he has access to npm scripts he has access to the npm version command.
  3. Using this command he doesn't need to install anything more in his computer or CD/CI pipe which on the long term will reduce the maintainability effort for the project, and will help with the setup

The other answers in which other tools are proposed are incorrect.

gulp-bump works but requires another extra package which could create issues in the long term (point 3 of my answer)

grunt-bump works but requires another extra package which could create issues in the long term (point 3 of my answer)

How to run TypeScript files from command line?

None of the other answers discuss how to run a TypeScript script that uses modules, and especially modern ES Modules.

First off, ts-node doesn't work in that scenario, as of March 2020. So we'll settle for tsc followed by node.

Second, TypeScript still can't output .mjs files. So we'll settle for .js files and "type": "module" in package.json.

Third, you want clean import lines, without specifying the .js extension (which would be confusing in .ts files):

import { Lib } from './Lib';

Well, that's non-trivial. Node requires specifying extensions on imports, unless you use the experimental-specifier-resolution=node flag. In this case, it would enable Node to look for Lib.js or Lib/index.js when you only specify ./Lib on the import line.

Fourth, there's still a snag: if you have a different main filename than index.js in your package, Node won't find it.

Transpiling makes things a lot messier than running vanilla Node.

Here's a sample repo with a modern TypeScript project structure, generating ES Module code.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

I fixed this (for development) with a simple nginx proxy...

# /etc/nginx/sites-enabled/default
server {
  listen 80;
  root /path/to/Development/dir;
  index index.html;

  # from your example
  location /search {
    proxy_pass http://api.master18.tiket.com;
  }
}

"Please try running this command again as Root/Administrator" error when trying to install LESS

I kept having this problem because windows was setting my node_modules folder to Readonly. Make sure you uncheck this.

enter image description here

'react-scripts' is not recognized as an internal or external command

When I make a new project using React, to install the React modules I have to run "npm install" (PowerShell) from within the new projects ClientApp folder (e.g. "C:\Users\Chris\source\repos\HelloWorld2\HelloWorld2\ClientApp"). The .NET core WebApp with React needs to have the React files installed in the correct location for React commands to work properly.

How to auto-reload files in Node.js?

i found a simple way:

delete require.cache['/home/shimin/test2.js']

Apache Cordova - uninstall globally

Super late here and I still couldn't uninstall using sudo as the other answers suggest. What did it for me was checking where cordova was installed by running

which cordova

it will output something like this

/usr/local/bin/

then removing by

rm -rf /usr/local/bin/cordova

How to call a Python function from Node.js

Most of previous answers call the success of the promise in the on("data"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.

const { spawn } = require('child_process');
const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter

/** remove warning that you don't care about */
function cleanWarning(error) {
    return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}

function callPython(scriptName, args) {
    return new Promise(function(success, reject) {
        const script = pythonDir + scriptName;
        const pyArgs = [script, JSON.stringify(args) ]
        const pyprog = spawn(python, pyArgs );
        let result = "";
        let resultError = "";
        pyprog.stdout.on('data', function(data) {
            result += data.toString();
        });

        pyprog.stderr.on('data', (data) => {
            resultError += cleanWarning(data.toString());
        });

        pyprog.stdout.on("end", function(){
            if(resultError == "") {
                success(JSON.parse(result));
            }else{
                console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
                const error = new Error(resultError);
                console.error(error);
                reject(resultError);
            }
        })
   });
}
module.exports.callPython = callPython;

Call:

const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});

python:

try:
    argu = json.loads(sys.argv[1])
except:
    raise Exception("error while loading argument")

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

Both of these usages can be applied:

// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });

// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));

Getting HTTP headers with Node.js

Using the excellent request module:

var request = require('request');
  request("http://stackoverflow.com", {method: 'HEAD'}, function (err, res, body){
  console.log(res.headers);
});

You can change the method to GET if you wish, but using HEAD will save you from getting the entire response body if you only wish to look at the headers.

Get the client's IP address in socket.io

on socket.io 1.3.4 you have the following possibilities.

socket.handshake.address,

socket.conn.remoteAddress or

socket.request.client._peername.address

How can I use async/await at the top level?

Node -
You can run node --experimental-repl-await while in the REPL. I'm not so sure about scripting.

Deno -
Deno already has it built in.

Passing a variable from node.js to html

use res.json, ajax, and promises, with a nice twist of localStorage to use it anywhere, added with tokens for that rare arcade love. PS, you could use cookies, but cookies can bite on https.

webpage.js

function (idToken) {
    $.ajax({
        url: '/main',
        headers: {
            Authorization: 'Bearer ' + idToken
        },
        processData: false,
    }).done(function (data) {
        localStorage.setItem('name', data.name);
        //or whatever you want done.
    }).fail(function (jqXHR, textStatus) {
        var msg = 'Unable to fetch protected resource';
        msg += '<br>' + jqXHR.status + ' ' + jqXHR.responseText;
        if (jqXHR.status === 401) {
            msg += '<br>Your token may be expired'
        }
        displayError(msg);
    });

server.js, using express()

app.get('/main',
passport.authenticate('oauth2-jwt-bearer', { session: false }),
function (req, res) {
    getUserInfo(req) //get your information to use it.
        .then(function (userinfo) {  //return your promise
            res.json({ "name": userinfo.Name});
            //you can declare/return more vars in this res.json.
            //res.cookie('name', name); //https trouble
        })
    .error(function (e) {console.log("Error handler " + e)})
    .catch(function (e) {console.log("Catch handler " + e)});
});

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

In a nutshell, this is the code which works for me :)

WebDriver driver;
WebElement element;
String value;

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='"+ value +"';", element);

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

npm ERR! network getaddrinfo ENOTFOUND

Step 1: Set the proxy npm set proxy http://username:password@companyProxy:8080

npm set https-proxy http://username:password@companyProxy:8080

npm config set strict-ssl false -g

NOTES: No special characters in password except @ allowed.

How to convert Blob to File in JavaScript

Typescript

public blobToFile = (theBlob: Blob, fileName:string): File => {       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Javascript

function blobToFile(theBlob, fileName){       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Output

screenshot

File {name: "fileName", lastModified: 1597081051454, lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 601887, …}
lastModified: 1597081051454
lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time) {}
name: "fileName"
size: 601887
type: "image/png"
webkitRelativePath: ""
__proto__: File

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

process.env.NODE_ENV is adding a white space do this

process.env.NODE_ENV.trim() == 'production'

'gulp' is not recognized as an internal or external command

Go to My Computer>Properties>Advance System Settings>Environment Variables>

Under the variables of Administrator edit the PATH variable & change its value to "C:\Users\Username\AppData\Roaming\npm". Note: The username in the path will be the current Admin user's name that you have logged in with.

Running Node.js in apache?

If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:

<?php
    shell_exec("node nodeScript.js"); // without arguments
    shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>

The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:

<?php
    $evilUserData = "'; [malicious commands here];";
    shell_exec("node nodeScript.js '{$evilUserData}'");
?>

How to yum install Node.JS on Amazon Linux

The easiest solution is this( do these as root)

sudo su root
cd /etc
mkdir node
yum install wget
wget https://nodejs.org/dist/v9.0.0/node-v9.0.0-linux-x64.tar.gz
tar -xvf node-v9.0.0-linux-x64.tar.gz
cd node-v9.0.0-linux-x64/bin
./node -v
ln -s /etc/node-v9.0.0-linux-x64/bin/node node

enter image description here

How to remove all files from directory without removing directory in Node.js

There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.

Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.

const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });

https://www.npmjs.com/package/rimraf

sequelize findAll sort order in nodejs

If you are using MySQL, you can use order by FIELD(id, ...) approach:

Company.findAll({
    where: {id : {$in : companyIds}},
    order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})

Keep in mind, it might be slow. But should be faster, than manual sorting with JS.

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

internal/modules/cjs/loader.js:582 throw err

Something weird happened to me last night. I ran command node run watch instead of npm run watch. I tried doing everything on this thread but nothing worked out for me. I was frustrated but eventually noticed that I ran the command wrong. I was laughing out loud. Sometimes this things happened. Enjoying learning Nodejs though.

npm - how to show the latest version of a package

There is also another easy way to check the latest version without going to NPM if you are using VS Code.

In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions

image shows the latest versions of modules in vscode

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

First I just find in npm module mongodb the file index.js ..node_modules\mongodb\node_modules\bson\ext\index.js

and change path to js version in catch block

bson = require('../build/Release/bson'); to bson = require('../browser_build/bson');

but then I just changed it like this, all the similar... previously installed the module... : bson = require('bson');

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?

using xl = Microsoft.Office.Interop.Excel;

xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;

Simple as that!

HTH, Z

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

Unix - copy contents of one directory to another

Quite simple, with a * wildcard.

cp -r Folder1/* Folder2/

But according to your example recursion is not needed so the following will suffice:

cp Folder1/* Folder2/

EDIT:

Or skip the mkdir Folder2 part and just run:

cp -r Folder1 Folder2

What's the best way to test SQL Server connection programmatically?

Execute SELECT 1 and check if ExecuteScalar returns 1.

An error occurred while executing the command definition. See the inner exception for details

I've just run into this issue and it was because I had updated a view in my DB and not refreshed the schema in my mapping.

Problems with Android Fragment back stack

If you are Struggling with addToBackStack() & popBackStack() then simply use

FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment(), "Home");
ft.commit();`

In your Activity In OnBackPressed() find out fargment by tag and then do your stuff

Fragment home = getSupportFragmentManager().findFragmentByTag("Home");

if (home instanceof HomeFragment && home.isVisible()) {
    // do you stuff
}

For more Information https://github.com/DattaHujare/NavigationDrawer I never use addToBackStack() for handling fragment.

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

The answer is here: http://sysadminsjourney.com/content/2010/02/01/apache-modproxy-error-13permission-denied-error-rhel/

Which is a link to a blog that explains:

SELinux on RHEL/CentOS by default ships so that httpd processes cannot initiate outbound connections, which is just what mod_proxy attempts to do.

If this is the problem, it can be solved by running:

 /usr/sbin/setsebool -P httpd_can_network_connect 1

And for a more definitive source of information, see https://wiki.apache.org/httpd/13PermissionDenied

Reading data from DataGridView in C#

Code Example : Reading data from DataGridView and storing it in an array

int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
    for (int j = 0; j < StartDataView.Columns.Count; j++)
    {
        if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
        {
            try
            {
                n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
            }
            catch (Exception Ee)
            { //get exception of "null"
                MessageBox.Show(Ee.ToString());
            }
        }
    }
}

How do I print a list of "Build Settings" in Xcode project?

Apple's "Build Setting Reference" documentation for what's officially documented (or as rjstelling's answer shows, use env in a build script to see what Xcode actually passes you.

In case the above link changes, Google search for: "build setting reference" site:developer.apple.com

How to stop VBA code running?

This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).

As Microsoft states:

Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).

Here is an illustrative example:

Sub RunSomeMacros()

    Call FirstPart
    Call SecondPart

    'the below code will not be executed if user clicks yes during SecondPart.
    Call ThirdPart
    MsgBox "All of the macros have been run."

End Sub

Private Sub FirstPart()
    MsgBox "This is the first macro"

End Sub

Private Sub SecondPart()
    Dim answer As Long
    answer = MsgBox("Do you want to stop the macros?", vbYesNo)

    If answer = vbYes Then
        'Stops All macros!
        End
    End If

    MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub

Private Sub ThirdPart()
    MsgBox "Final Macro was run."
End Sub

How to get the type of a variable in MATLAB?

Use the class function

>> b = 2
b =
     2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
char

How to open a new form from another form

You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.

It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.

Converting a Java Keystore into PEM Format

Try Keystore Explorer http://keystore-explorer.org/

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. It does openssl/pkcs12 as well.

JAVA_HOME is set to an invalid directory:

On Window 10, the problem was with the semicolon ;.

Go to edit the system environment variables and delete the semicolon at the end of JAVA_HOME value C:\Program Files\Java\jdk1.8.0_144

In other words, convert this C:\Program Files\Java\jdk1.8.0_12; to C:\Program Files\Java\jdk1.8.0_12

You might have to delete your entry in the Windows Dialog and create a new one. If you ever had multiple entries and get the bigger Form view, Windows automatically inserts a ; at the end of each entry, even if you only have one entry left.

Storing a Key Value Array into a compact JSON string

If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.

For example:

var data = ["slide0001.html", "Looking Ahead"];

var C_KEY = 0;
var C_VALUE = 1;

var value = data[C_VALUE];

So, now, your data can be:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]

If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}

... which would then be handled by the parser.

C# Iterate through Class properties

You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.

For a hint, you could possibly do something like:

Record record = new Record();

PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
    property.SetValue(record, value);
}

Where value is the value you're wanting to write in (so from your resultItems array).

How to check the maximum number of allowed connections to an Oracle database?

I thought this would work, based on this source.

SELECT
  'Currently, ' 
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of ' 
  || DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX) 
  || ' connections are used.' AS USAGE_MESSAGE
FROM 
  V$LICENSE VL

However, Justin Cave is right. This query gives better results:

SELECT
  'Currently, ' 
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of ' 
  || VP.VALUE 
  || ' connections are used.' AS USAGE_MESSAGE
FROM 
  V$PARAMETER VP
WHERE VP.NAME = 'sessions'

Extracting text OpenCV

Here is an alternative approach that I used to detect the text blocks:

  1. Converted the image to grayscale
  2. Applied threshold (simple binary threshold, with a handpicked value of 150 as the threshold value)
  3. Applied dilation to thicken lines in image, leading to more compact objects and less white space fragments. Used a high value for number of iterations, so dilation is very heavy (13 iterations, also handpicked for optimal results).
  4. Identified contours of objects in resulted image using opencv findContours function.
  5. Drew a bounding box (rectangle) circumscribing each contoured object - each of them frames a block of text.
  6. Optionally discarded areas that are unlikely to be the object you are searching for (e.g. text blocks) given their size, as the algorithm above can also find intersecting or nested objects (like the entire top area for the first card) some of which could be uninteresting for your purposes.

Below is the code written in python with pyopencv, it should easy to port to C++.

import cv2

image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours

# for each contour found, draw a rectangle around it on original image
for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # discard areas that are too large
    if h>300 and w>300:
        continue

    # discard areas that are too small
    if h<40 or w<40:
        continue

    # draw rectangle around contour on original image
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)

# write original image with added contours to disk  
cv2.imwrite("contoured.jpg", image) 

The original image is the first image in your post.

After preprocessing (grayscale, threshold and dilate - so after step 3) the image looked like this:

Dilated image

Below is the resulted image ("contoured.jpg" in the last line); the final bounding boxes for the objects in the image look like this:

enter image description here

You can see the text block on the left is detected as a separate block, delimited from its surroundings.

Using the same script with the same parameters (except for thresholding type that was changed for the second image like described below), here are the results for the other 2 cards:

enter image description here

enter image description here

Tuning the parameters

The parameters (threshold value, dilation parameters) were optimized for this image and this task (finding text blocks) and can be adjusted, if needed, for other cards images or other types of objects to be found.

For thresholding (step 2), I used a black threshold. For images where text is lighter than the background, such as the second image in your post, a white threshold should be used, so replace thesholding type with cv2.THRESH_BINARY). For the second image I also used a slightly higher value for the threshold (180). Varying the parameters for the threshold value and the number of iterations for dilation will result in different degrees of sensitivity in delimiting objects in the image.

Finding other object types:

For example, decreasing the dilation to 5 iterations in the first image gives us a more fine delimitation of objects in the image, roughly finding all words in the image (rather than text blocks):

enter image description here

Knowing the rough size of a word, here I discarded areas that were too small (below 20 pixels width or height) or too large (above 100 pixels width or height) to ignore objects that are unlikely to be words, to get the results in the above image.

Open a local HTML file using window.open in Chrome

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

Nothing Worked for me.

Object not found! The requested URL was not found on this server. localhost

Is the Config/setup.php file actually in /test/content/home/ or is in your document root? it is best to make all references relative to your document root.

include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";

Your current code assumes that the location of setup.php is in /text/content/home/Config/setup.php, is this correct?

Check if $_POST exists

Try

if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
    echo "Cool";
}

How to uninstall Anaconda completely from macOS

In my case (Mac High Sierra) it was installed at ~/opt/anaconda3.

https://docs.anaconda.com/anaconda/install/uninstall/

Git submodule head 'reference is not a tree' error

Just stumbled upon this problem, and none of these solutions worked for me. What turned out to be the solution for my issue is actually much simpler: upgrade Git. Mine was 1.7.1, and after I upgraded it to 2.16.1 (latest), the problem went away without a trace! Guess I'm leaving it here, hope it helps someone.

how to display a javascript var in html body

Index.html:

<html>
<body>
    Javascript Version: <b id="version"></b>
    <script src="app.js"></script>
</body>
</html>

app.js:

var ver="1.1";
document.getElementById("version").innerHTML = ver;

document.all vs. document.getElementById

According to Microsoft's archived Internet Explorer Dev Center, document.all is deprecated in IE 11 and Edge!

How to read/process command line arguments?

As you can see optparse "The optparse module is deprecated with and will not be developed further; development will continue with the argparse module."

How to get a enum value from string in C#?

baseKey choice;
if (Enum.TryParse("HKEY_LOCAL_MACHINE", out choice)) {
     uint value = (uint)choice;

     // `value` is what you're looking for

} else { /* error: the string was not an enum member */ }

Before .NET 4.5, you had to do the following, which is more error-prone and throws an exception when an invalid string is passed:

(uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE")

Hiding the address bar of a browser (popup)

You could make the webpage scroll down to a position where you can't see the address bar, and if the user scrolls, the page should return to your set position. In that way, Mobile browsers when scrolled down , will try to guve you full-screen experience. So it will hide the address bar. I don't know the code, someone else might put up the code.

Javascript / Chrome - How to copy an object from the webkit inspector as code

Right click on data which you want to store

  • Firstly, Right click on data which you want to store -> select "Store as global variable" And the new temp variable appear like bellow: (temp3 variable): New temp variable appear in console
  • Second use command copy(temp_variable_name) like picture: enter image description here After that, you can paste data to anywhere you want. hope useful/

Maven2 property that indicates the parent directory

I accessed the dir above using ${basedir}..\src\

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How do I configure Maven for offline development?

If you're using IntelliJ, you can simply go to Preferences -> Build, Execution, Deployment -> Build Tools -> Maven and check/uncheck Work offline.

JSONException: Value of type java.lang.String cannot be converted to JSONObject

Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.

So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.

BTW. i used UTF-8 encoding on both sides. PHP side: header('Content-type=application/json; charset=utf-8');

JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

So try the solution one by one 1,2,3,4...! Hope it helps you guys!

try {
            jObj = new JSONObject(json.substring(3));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
        }

max value of integer

Actually the size in bits of the int, short, long depends on the compiler implementation.

E.g. on my Ubuntu 64 bit I have short in 32 bits, when on another one 32bit Ubuntu version it is 16 bit.

clear javascript console in Google Chrome

On the Chrome console right click with the mouse and We have the option to clear the console

How to delete file from public folder in laravel 5.1

For Delete files from the public folders, we can use the File::delete function into the Laravel. For use File need to use File into the controller OR We can use \File. This consider the root of the file.

// Delete a single file
File::delete($filename);

For delete Multiple files

// Delete multiple files
File::delete($file1, $file2, $file3);

Delete an array of Files

// Delete an array of files
$files = array($file1, $file2);
File::delete($files);

surface plots in matplotlib

check the official example. X,Y and Z are indeed 2d arrays, numpy.meshgrid() is a simple way to get 2d x,y mesh out of 1d x and y values.

http://matplotlib.sourceforge.net/mpl_examples/mplot3d/surface3d_demo.py

here's pythonic way to convert your 3-tuples to 3 1d arrays.

data = [(1,2,3), (10,20,30), (11, 22, 33), (110, 220, 330)]
X,Y,Z = zip(*data)
In [7]: X
Out[7]: (1, 10, 11, 110)
In [8]: Y
Out[8]: (2, 20, 22, 220)
In [9]: Z
Out[9]: (3, 30, 33, 330)

Here's mtaplotlib delaunay triangulation (interpolation), it converts 1d x,y,z into something compliant (?):

http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.griddata

jQuery: go to URL with target="_blank"

Question: How can I open the href in the new window or tab with jQuery?

var url = $(this).attr('href').attr('target','_blank');

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

Tomcat in Eclipse does not use catalina.sh or bat. To setup memory for managed Tomcat use VM settings in server run configuration

Deserialize json object into dynamic object using Json.net

Json.NET allows us to do this:

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

Output:

 1000
 string
 6

Documentation here: LINQ to JSON with Json.NET

See also JObject.Parse and JArray.Parse

Can pm2 run an 'npm start' script

To use npm run

pm2 start npm --name "{app_name}" -- run {script_name}

How can I avoid ResultSet is closed exception in Java?

A ResultSetClosedException could be thrown for two reasons.

1.) You have opened another connection to the database without closing all other connections.

2.) Your ResultSet may be returning no values. So when you try to access data from the ResultSet java will throw a ResultSetClosedException.

Jenkins Host key verification failed

Jenkins is a service account, it doesn't have a shell by design. It is generally accepted that service accounts. shouldn't be able to log in interactively.

To resolve "Jenkins Host key verification failed", do the following steps. I have used mercurial with jenkins.

1)Execute following commands on terminal

             $ sudo su -s /bin/bash jenkins

provide password

2)Generate public private key using the following command:

              ssh-keygen

you can see output as ::

Generating public/private rsa key pair. 
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 

3)Press Enter --> Do not give any passphrase--> press enter

             Key has been generated

4) go to --> cat /var/lib/jenkins/.ssh/id_rsa.pub

5) Copy key from id_rsa.pub

6)Exit from bash

7) ssh@yourrepository

8) vi .ssh/authorized_keys

9) Paste the key

10) exit

11)Manually login to mercurial server

Note: Pls do manually login otherwise jenkins will again give error "host verification failed"

12)once manually done, Now go to Jenkins and give build

Enjoy!!!

Good Luck

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Posed question

Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.

Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.

Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:

Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.

Application-specific question

However, returning to your task, I'd research 2 topics:

  1. metrics commonly used for your specific task - it lets (a) to compare your method with others and understand if you do something wrong, and (b) to not explore this by yourself and reuse someone else's findings;
  2. cost of different errors of your methods - for example, use-case of your application may rely on 4- and 5-star reviewes only - in this case, good metric should count only these 2 labels.

Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:

  1. Accuracy, which is used, e.g. in

Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."

(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.

Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.

(link)

  1. MSE (or, less often, Mean Absolute Error - MAE) - see, for example,

Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).

(link) - they explore both accuracy and MSE, considering the latter to be better

Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.

(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.

Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.

About approaches, not metrics

Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.

Which one is the best PDF-API for PHP?

Personally I prefer to use dompdf for simple PDF pages as it is very quick. you simply feed it an HTML source and it will generate the required page.

however for more complex designs i prefer the more classic pdflib which is available as a pecl for PHP. it has greater control over designs and allows you do do more complex designs like pixel-perfect forms.

Attempt to set a non-property-list object as an NSUserDefaults

The code you posted tries to save an array of custom objects to NSUserDefaults. You can't do that. Implementing the NSCoding methods doesn't help. You can only store things like NSArray, NSDictionary, NSString, NSData, NSNumber, and NSDate in NSUserDefaults.

You need to convert the object to NSData (like you have in some of the code) and store that NSData in NSUserDefaults. You can even store an NSArray of NSData if you need to.

When you read back the array you need to unarchive the NSData to get back your BC_Person objects.

Perhaps you want this:

- (void)savePersonArrayData:(BC_Person *)personObject {
    [mutableDataArray addObject:personObject];

    NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
    for (BC_Person *personObject in mutableDataArray) { 
        NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
        [archiveArray addObject:personEncodedObject];
    }

    NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
    [userData setObject:archiveArray forKey:@"personDataArray"];
}

c# .net change label text

you should convert test type >>>> test.tostring();

change the last line to this :

Label1.Text = "Du har nu lånat filmen:" + test.tostring();

How to change the datetime format in pandas

You can try this it'll convert the date format to DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)

How to import js-modules into TypeScript file?

In your second statement

import {FriendCard} from './../pages/FriendCard'

you are telling typescript to import the FriendCard class from the file './pages/FriendCard'

Your FriendCard file is exporting a variable and that variable is referencing the anonymous function.

You have two options here. If you want to do this in a typed way you can refactor your module to be typed (option 1) or you can import the anonymous function and add a d.ts file. See https://github.com/Microsoft/TypeScript/issues/3019 for more details. about why you need to add the file.

Option 1

Refactor the Friend card js file to be typed.

export class FriendCard {
webElement: any;
menuButton: any;
serialNumber: any;

constructor(card) {
    this.webElement = card;
    this.menuButton;
    this.serialNumber;
}



getAsWebElement = function () {
    return this.webElement;
};

clickMenuButton = function () {
    this.menuButton.click();
};

setSerialNumber = function (numberOfElements) {
    this.serialNumber = numberOfElements + 1;
    this.menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i'));
};

deleteFriend = function () {
    element(by.css('[ng-click="deleteFriend(person);"]')).click();
    element(by.css('[ng-click="confirm()"]')).click();
}
};

Option 2

You can import the anonymous function

 import * as FriendCard from module("./FriendCardJs");

There are a few options for a d.ts file definition. This answer seems to be the most complete: How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

Is there a way to create and run javascript in Chrome?

Open a basic text editor and type out your html. Save it as .html If you type in file:///C:/ into the address bar you can then navigate to your chosen file and run it. If you want to open a file that is on a server type in file:/// and instead of C:/ the first letter of the server followed by :/.

UICollectionView spacing margins

You can use the collectionView:layout:insetForSectionAtIndex: method for your UICollectionView or set the sectionInset property of the UICollectionViewFlowLayout object attached to your UICollectionView:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(top, left, bottom, right);
}

or

UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[aFlowLayout setSectionInset:UIEdgeInsetsMake(top, left, bottom, right)];

Updated for Swift 5

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
       return UIEdgeInsets(top: 25, left: 15, bottom: 0, right: 5)
    }

How to grant remote access to MySQL for a whole subnet?

MySQL 8.0.23 onwards now support CIDR notation also.

So, basically:

-- CIDR Notation
GRANT ... TO 'user'@'192.168.1.0/24' IDENTIFIED BY ...

-- Netmask Notation
GRANT ... TO 'user'@'192.168.1.0/255.255.255.0' IDENTIFIED BY ...

Write to UTF-8 file in Python

I use the file *nix command to convert a unknown charset file in a utf-8 file

# -*- encoding: utf-8 -*-

# converting a unknown formatting file in utf-8

import codecs
import commands

file_location = "jumper.sub"
file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location)

file_stream = codecs.open(file_location, 'r', file_encoding)
file_output = codecs.open(file_location+"b", 'w', 'utf-8')

for l in file_stream:
    file_output.write(l)

file_stream.close()
file_output.close()

Pretty-print a Map in Java

Since java 8 there is easy way to do it with Lambda:

yourMap.keySet().forEach(key -> {
    Object obj = yourMap.get(key);
    System.out.println( obj);
}

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

Properly close mongoose's connection once you're done

The other answer didn't work for me. I had to use mongoose.disconnect(); as stated in this answer.

Django error - matching query does not exist

You can use this:

comment = Comment.objects.filter(pk=comment_id)

iOS application: how to clear notifications?

Just to expand on pcperini's answer. As he mentions you will need to add the following code to your application:didFinishLaunchingWithOptions: method;

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

You Also need to increment then decrement the badge in your application:didReceiveRemoteNotification: method if you are trying to clear the message from the message centre so that when a user enters you app from pressing a notification the message centre will also clear, ie;

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

SQL Not Like Statement not working

I just came across the same issue, and solved it, but not before I found this post. And seeing as your question wasn't really answered, here's my solution (which will hopefully work for you, or anyone else searching for the same thing I did;

Instead of;

... AND WPP.COMMENT NOT LIKE '%CORE%' ...

Try;

... AND NOT WPP.COMMENT LIKE '%CORE%' ...

Basically moving the "NOT" the other side of the field I was evaluating worked for me.

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Run vmware as administrator in windows or as root in linux. Then ctrl+P to open preferences. then on shared vms. You can see a port number 443 by default. This is conflicting with apache that is why it is not starting. Change it to some other value say 8443. Then try to start apache it will run.

The term 'ng' is not recognized as the name of a cmdlet

I resolved by following the below steps

1.Right click on command Prompt 2.Run as administrator 3.type npm install -g @angular/cli

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;
showInventory(p);  

I'm guessing you have something like this:

int main()
{
   player player;
   toDo();
}

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
{
   player p;
   toDo(p);
}

and

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}

Swift: Display HTML data in a label or textView

Try this:

let label : UILable! = String.stringFromHTML("html String")

func stringFromHTML( string: String?) -> String
    {
        do{
            let str = try NSAttributedString(data:string!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true
                )!, options:[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSNumber(unsignedLong: NSUTF8StringEncoding)], documentAttributes: nil)
            return str.string
        } catch
        {
            print("html error\n",error)
        }
        return ""
    }

Hope its helpful.

How to "scan" a website (or page) for info, and bring it into my program?

Look into the cURL library. I've never used it in Java, but I'm sure there must be bindings for it. Basically, what you'll do is send a cURL request to whatever page you want to 'scrape'. The request will return a string with the source code to the page. From there, you will use regex to parse whatever data you want from the source code. That's generally how you are going to do it.

Remove first 4 characters of a string with PHP

function String2Stars($string='',$first=0,$last=0,$rep='*'){
  $begin  = substr($string,0,$first);
  $middle = str_repeat($rep,strlen(substr($string,$first,$last)));
  $end    = substr($string,$last);
  $stars  = $begin.$middle.$end;
  return $stars;
}

example

$string = 'abcdefghijklmnopqrstuvwxyz';
echo String2Stars($string,5,-5);   // abcde****************vwxyz

.ssh/config file for windows (git)

You can use multiple ssh keys on Windows 10 and specify the type of access allowed.

Assuming you have created the ssh secure keys already and they were stored in C:\Users\[User]\.ssh

  1. Open the folder C:\Users\[User]\.ssh

  2. Create the file config (no file extension)

  3. Open the file in a text editor like Notepad, and add these configuration details for the first remote host and user. Keep both CMD and BASH paths or only pick one format. Then copy-and-paste below it for the other host/user combinations and amend as required. Save the file.

    Host [git.domain.com]
    User [user]
    Port [number]
    IdentitiesOnly=yes
    PreferredAuthentications publickey
    PasswordAuthentication no
    # CMD
    IdentityFile C:\Users\[User]\.ssh\[name_of_PRIVATE_key_file]
    # BASH
    IdentityFile /c/Users/[User]/.ssh/[name_of_PRIVATE_key_file]
    
  4. Testing

  • Using Bash (Git for Windows)
    $ ssh -T git@[git.domain.com]
    Welcome to GitLab, @[User]!
    
  • Using Commandline (requires activation of Win 10 OpenSSH Client)
    C:\Users\[User]>ssh -T git@[git.domain.com]
    Welcome to GitLab, @[User]!
    
  1. For troubleshooting use ssh -Tv git@[git.domain.com] (or -Tvv or -Tvvv for higher verbosity levels).

How can I close a login form and show the main form without my application closing?

I would do this the other way round.

In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.

EDIT Code sample(s)

private void MainForm_Load(object sender, EventArgs e)
{
    this.Hide();

    LogonForm logon = new LogonForm();

    if (logon.ShowDialog() != DialogResult.OK)
    {
        //Handle authentication failures as necessary, for example:
        Application.Exit();
    }
    else
    {
        this.Show();
    }
}

Another solution would be to show the LogonForm from the Main method in program.cs, something like this:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    LogonForm logon = new LogonForm();

    Application.Run(logon);

    if (logon.LogonSuccessful)
    {
        Application.Run(new MainForm());
    }
}

In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials

Remove whitespaces inside a string in javascript

You can use

"Hello World ".replace(/\s+/g, '');

trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.

If you change the replacement empty string to '$', the difference becomes much clearer:

var string= '  Q  W E   R TY ';
console.log(string.replace(/\s/g, '$'));  // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#

Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

Order by multiple columns with Doctrine

The comment for orderBy source code notes: Keys are field and values are the order, being either ASC or DESC.. So you can do orderBy->(['field' => Criteria::ASC]).

Sending Windows key using SendKeys

download InputSimulator from nuget package.

then write this:

        var simu = new InputSimulator();
        simu.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);

in my case to create new vertial desktop, 3 keys needed and code like this(windows key + ctrl + D):

        simu.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL }, VirtualKeyCode.VK_D);

Add numpy array as column to Pandas data frame

import numpy as np
import pandas as pd
import scipy.sparse as sparse

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)

yields

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

How do I set up access control in SVN?

You can use svn+ssh:, and then it's based on access control to the repository at the given location.

This is how I host a project group repository at my uni, where I can't set up anything else. Just having a directory that the group owns, and running svn-admin (or whatever it was) in there means that I didn't need to do any configuration.

android:drawableLeft margin and/or padding

You can use android:drawableLeft="@drawable/your_icon" to set the drawable to be shown on the left side. In order to set a padding for the drawable you should use the android:paddingLeft or android:paddingRight to set the left/right padding respectively.

android:paddingRight="10dp"
android:paddingLeft="20dp"
android:drawableRight="@drawable/ic_app_manager"

Sending message through WhatsApp

Tested on Marshmallow S5 and it works!

    Uri uri = Uri.parse("smsto:" + "phone number with country code");
    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent); 

This will open a direct chat with a person, if whatsapp not installed this will throw exception, if phone number not known to whatsapp they will offer to send invite via sms or simple sms message

How to get a reversed list view on a list in Java?

For small sized list we can create LinkedList and then can make use of descending iterator as:

List<String> stringList = new ArrayList<>(Arrays.asList("One", "Two", "Three"));
stringList.stream().collect(Collectors.toCollection(LinkedList::new))
         .descendingIterator().
         forEachRemaining(System.out::println); // Three, Two, One
System.out.println(stringList); // One, Two, Three

How to test code dependent on environment variables using JUnit?

Well you can use the setup() method to declare the different values of your env. variables in constants. Then use these constants in the tests methods used to test the different scenario.

How to change css property using javascript

This is really easy using jQuery.

For instance:

$(".left").mouseover(function(){$(".left1").show()});
$(".left").mouseout(function(){$(".left1").hide()});

I've update your fiddle: http://jsfiddle.net/TqDe9/2/

Unsupported major.minor version 52.0

If you have a problem in Android Studio and you have installed Android N, change the Android rendering version with an older one and the problem will disappear.

Enter image description here

How to add a column in TSQL after a specific column?

You should be able to do this if you create the column using the GUI in Management Studio. I believe Management studio is actually completely recreating the table, which is why this appears to happen.

As others have mentioned, the order of columns in a table doesn't matter, and if it does there is something wrong with your code.

Searching if value exists in a list of objects using Linq

Another possibility

if (list.Count(customer => customer.Firstname == "John") > 0) {
 //bla
}

Jquery post, response in new window

Use the write()-Method of the Popup's document to put your markup there:

$.post(url, function (data) {
    var w = window.open('about:blank');
    w.document.open();
    w.document.write(data);
    w.document.close();
});

How to Access Hive via Python?

I believe the easiest way is to use PyHive.

To install you'll need these libraries:

pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive

Please note that although you install the library as PyHive, you import the module as pyhive, all lower-case.

If you're on Linux, you may need to install SASL separately before running the above. Install the package libsasl2-dev using apt-get or yum or whatever package manager for your distribution. For Windows there are some options on GNU.org, you can download a binary installer. On a Mac SASL should be available if you've installed xcode developer tools (xcode-select --install in Terminal)

After installation, you can connect to Hive like this:

from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")

Now that you have the hive connection, you have options how to use it. You can just straight-up query:

cursor = conn.cursor()
cursor.execute("SELECT cool_stuff FROM hive_table")
for result in cursor.fetchall():
  use_result(result)

...or to use the connection to make a Pandas dataframe:

import pandas as pd
df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn)

SQL Server : Transpose rows to columns

Another option that may be suitable in this situation is using XML

The XML option to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation. 

The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).

Vertical expansion

Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.

Horizontal expansion

Unlike the PIVOT, newly added documents can be displayed without altering the script.

Performance breakdown

In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.

You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

How do you deploy Angular apps?

If you deploy your application in Apache (Linux server) so you can follow following steps : Follow following steps :

Step 1: ng build --prod --env=prod

Step 2. (Copy dist into server) then dist folder created, copy dist folder and deploy it in root directory of server.

Step 3. Creates .htaccess file in root folder and paste this in the .htaccess

 <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

How to convert Strings to and from UTF8 byte arrays in Java

I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).

Replace the single quote (') character from a string

Do you mean like this?

>>> mystring = "This isn't the right place to have \"'\" (single quotes)"
>>> mystring
'This isn\'t the right place to have "\'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'

C++ - Decimal to binary converting

DECIMAL TO BINARY NO ARRAYS USED *made by Oya:

I'm still a beginner, so this code will only use loops and variables xD...

Hope you like it. This can probably be made simpler than it is...

    #include <iostream>
    #include <cmath>
    #include <cstdlib>

    using namespace std;

    int main()
    {
        int i;
        int expoentes; //the sequence > pow(2,i) or 2^i
        int decimal; 
        int extra; //this will be used to add some 0s between the 1s
        int x = 1;

        cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
        cout << "\n\nWARNING: Only works until ~1.073 millions\n";
        cout << "     To exit, enter a negative number\n\n";

        while(decimal >= 0){
            cout << "\n----- // -----\n\n";
            cin >> decimal;
            cout << "\n";

            if(decimal == 0){
                cout << "0";
            }
            while(decimal >= 1){
                i = 0;
                expoentes = 1;
                while(decimal >= expoentes){
                    i++;
                    expoentes = pow(2,i);
                }
                x = 1;
                cout << "1";
                decimal -= pow(2,i-x);
                extra = pow(2,i-1-x);
                while(decimal < extra){
                    cout << "0";
                    x++;
                    extra = pow(2,i-1-x);
                }
            }
        }
        return 0;
    }

How does String substring work in Swift

Came across this fairly short and simple way of achieving this.

var str = "Hello, World"
let arrStr = Array(str)
print(arrStr[0..<5]) //["H", "e", "l", "l", "o"]
print(arrStr[7..<12]) //["W", "o", "r", "l", "d"]
print(String(arrStr[0..<5])) //Hello
print(String(arrStr[7..<12])) //World

Access files stored on Amazon S3 through web browser

I had the same problem and I fixed it by using the

  1. new context menu "Make Public".
  2. Go to https://console.aws.amazon.com/s3/home,
  3. select the bucket and then for each Folder or File (or multiple selects) right click and
  4. "make public"

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

How do I load an org.w3c.dom.Document from XML in a string?

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

How to delete images from a private docker registry?

The current v2 registry now supports deleting via DELETE /v2/<name>/manifests/<reference>

See: https://github.com/docker/distribution/blob/master/docs/spec/api.md#deleting-an-image

Working usage: https://github.com/byrnedo/docker-reg-tool

Edit: The manifest <reference> above can be retrieved from requesting to

GET /v2/<name>/manifests/<tag>

and checking the Docker-Content-Digest header in the response.

Edit 2: You may have to run your registry with the following env set:

REGISTRY_STORAGE_DELETE_ENABLED="true"

Edit3: You may have to run garbage collection to free this disk space: https://docs.docker.com/registry/garbage-collection/

android set button background programmatically

Further from @finnmglas, the Java answer as of 2021 is:

    if (Build.VERSION.SDK_INT >= 29)
        btn.getBackground().setColorFilter(new BlendModeColorFilter(color, BlendMode.MULTIPLY));
    else
        btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);

Is it better to use path() or url() in urls.py for django 2.0?

Path is a new feature of Django 2.0. Explained here : https://docs.djangoproject.com/en/2.0/releases/2.0/#whats-new-2-0

Look like more pythonic way, and enable to not use regular expression in argument you pass to view... you can ue int() function for exemple.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

Jquery how to find an Object by attribute in an Array

Use the Underscore.js findWhere function (http://underscorejs.org/#findWhere):

var purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

var daily = _.findWhere(purposeObjects, {purpose: 'daily'});

daily would equal:

{"purpose":"daily"}

Here's a fiddle: http://jsfiddle.net/spencerw/oqbgc21x/

To return more than one (if you had more in your array) you could use _.where(...)

Sending JSON to PHP using ajax

I know it's been a while, but just in case someone still needs it:

The JSON object I need to pass:

0:{CommunityId: 509, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}
1:{CommunityId: 510, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}

The Ajax code:

data: JSON.stringify(The-data-shows-above),
type: 'POST',
datatype: 'JSON',
contentType: "application/json; charset=utf-8"

And the PHP side:

json_decode(file_get_contents("php://input"));

It works for me, hope it can help!

Clearing content of text file using php

This would truncate the file:

$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);

In clear.php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER'] value.

C++ String array sorting

We can sort() function to sort string array.

Procedure :

  1. At first determine the size string array.

  2. use sort function . sort(array_name, array_name+size)

  3. Iterate through string array/


Code Snippet

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);

    string name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};

    int len = sizeof(name)/sizeof(name[0]);

    sort(name, name+len);

    for(string n: name)
    {
         cout<<n<<" ";
    }
    cout<<endl;

    return 0;
}

Delete all items from a c++ std::vector

If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)

#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>

struct foo
{
    foo( const int i_x ) : d_x( i_x )
    {
        std::cout << "foo::foo " << d_x << std::endl;
    }

    ~foo()
    {
        std::cout << "foo::~foo " << d_x << std::endl;
    }

    int d_x;
};

typedef boost::shared_ptr< foo > smart_foo_t;

int main()
{
    std::vector< smart_foo_t > foos;
    for ( int i = 0; i < 10; ++i )
    {
        smart_foo_t f( new foo( i ) );
        foos.push_back( f );
    }

    foos.clear();

    return 0;
}

Regex Named Groups in Java

For people coming to this late: Java 7 adds named groups. Matcher.group(String groupName) documentation.

How can I deploy an iPhone application from Xcode to a real iPhone device?

Solution posted by Cawas works perfectly with XCode4, too. However, there are some changes to IDE's UI, so you need to make some research to find Run Script :)

In the Project Navigator view click the root item of the project, then in the middle window select Target, then click Build Phases tab and at the bottom you'll see Add Build Phase button, click and select Add Run Script, then paste "codesign" script posted by Cawas.

How to use java.net.URLConnection to fire and handle HTTP requests?

I suggest you take a look at the code on kevinsawicki/http-request, its basically a wrapper on top of HttpUrlConnection it provides a much simpler API in case you just want to make the requests right now or you can take a look at the sources (it's not too big) to take a look at how connections are handled.

Example: Make a GET request with content type application/json and some query parameters:

// GET http://google.com?q=baseball%20gloves&size=100
String response = HttpRequest.get("http://google.com", true, "q", "baseball gloves", "size", 100)
        .accept("application/json")
        .body();
System.out.println("Response was: " + response);

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Run this code It will open google print service popup.

function openPrint(x) {

   if (x > 0) { 
       openPrint(--x); print(x); openPrint(--x);
   }

}

Try it on console where x is integer .

openPrint(1);   // Will open Chrome Print Popup Once
openPrint(2);   // Will open Chrome Print Popup Twice after 1st close and so on

Thanks

How do I get the current absolute URL in Ruby on Rails?

Rails 4.0

you can use request.original_url, output will be as given below example

get "/articles?page=2"

request.original_url # => "http://www.example.com/articles?page=2"

Get value from hashmap based on key to JSTL

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

Use of True, False, and None as return values in Python functions

In the examples in PEP 8 (Style Guide for Python Code) document, I have seen that foo is None or foo is not None are being used instead of foo == None or foo != None.

Also using if boolean_value is recommended in this document instead of if boolean_value == True or if boolean_value is True. So I think if this is the official Python way. We Python guys should go on this way, too.

'NoneType' object is not subscriptable?

list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]

def printer(*lists):
    for _list in lists:
        for ele in _list:
            print(ele, end = ", ")
        print()

printer(list1, list2, list3)

Appending a vector to a vector

std::copy (b.begin(), b.end(), std::back_inserter(a));

This can be used in case the items in vector a have no assignment operator (e.g. const member).

In all other cases this solution is ineffiecent compared to the above insert solution.

How to change the project in GCP using CLI commands

gcloud config set project my-project

You may also set the environment variable $CLOUDSDK_CORE_PROJECT.

bash: pip: command not found

CentOS 7 users can just use:

yum install python-pip

Also recommend using virtualenv if you're using pip. It can be added in the same way:

yum install python-virtualenv

What is the best way to check for Internet connectivity using .NET?

Another option is the Network List Manager API which is available for Vista and Windows 7. MSDN article here. In the article is a link to download code samples which allow you to do this:

AppNetworkListUser nlmUser = new AppNetworkListUser();
Console.WriteLine("Is the machine connected to internet? " + nlmUser.NLM.IsConnectedToInternet.ToString());

Be sure to add a reference to Network List 1.0 Type Library from the COM tab... which will show up as NETWORKLIST.

What's the difference between `raw_input()` and `input()` in Python 3?

In Python 2, raw_input() returns a string, and input() tries to run the input as a Python expression.

Since getting a string was almost always what you wanted, Python 3 does that with input(). As Sven says, if you ever want the old behaviour, eval(input()) works.

Plotting time-series with Date labels on x-axis

I like ggplot too.

Here's one example:

df1 = data.frame(
date_id = c('2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04'),          
nation = c('China', 'USA', 'China', 'USA'), 
value = c(4.0, 5.0, 6.0, 5.5))

ggplot(df1, aes(date_id, value, group=nation, colour=nation))+geom_line()+xlab(label='dates')+ylab(label='value')

enter image description here

How does Tomcat locate the webapps directory?

It can be changed in the $CATALINA_BASE/conf/server.xml in the <Host />. See the Tomcat documentation, specifically the section in regards to the Host container:

Tomcat 6 Configuration

Tomcat 7 Configuration

The default is webapps relative to the $CATALINA_BASE. An absolute pathname can be used.

Hope that helps.

How can I throw a general exception in Java?

Well, there are lots of exceptions to throw, but here is how you throw an exception:

throw new IllegalArgumentException("INVALID");

Also, yes, you can create your own custom exceptions.

A note about exceptions. When you throw an exception (like above) and you catch the exception: the String that you supply in the exception can be accessed throw the getMessage() method.

try{
    methodThatThrowsException();
}catch(IllegalArgumentException e)
{
  e.getMessage();
}

MySQL - select data from database between two dates

SELECT users.* FROM users WHERE created_at BETWEEN '2011-12-01' AND '2011-12-07';

Owl Carousel, making custom navigation

Complete tutorial here

Demo link

enter image description here

JavaScript

$('.owl-carousel').owlCarousel({
    margin: 10,
    nav: true,
    navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
    responsive: {
        0: {
            items: 1
        },
        600: {
            items: 3
        },
        1000: {
            items: 5
        }
    }
});

CSS Style for navigation

.owl-carousel .nav-btn{
  height: 47px;
  position: absolute;
  width: 26px;
  cursor: pointer;
  top: 100px !important;
}

.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}

.owl-carousel .prev-slide{
  background: url(nav-icon.png) no-repeat scroll 0 0;
  left: -33px;
}
.owl-carousel .next-slide{
  background: url(nav-icon.png) no-repeat scroll -24px 0px;
  right: -33px;
}
.owl-carousel .prev-slide:hover{
 background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}   

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

To speed things up, I would take advantage of the fact that you are not asked to find an arbitrary image/object, but specifically one with the Coca-Cola logo. This is significant because this logo is very distinctive, and it should have a characteristic, scale-invariant signature in the frequency domain, particularly in the red channel of RGB. That is to say, the alternating pattern of red-to-white-to-red encountered by a horizontal scan line (trained on a horizontally aligned logo) will have a distinctive "rhythm" as it passes through the central axis of the logo. That rhythm will "speed up" or "slow down" at different scales and orientations, but will remain proportionally equivalent. You could identify/define a few dozen such scanlines, both horizontally and vertically through the logo and several more diagonally, in a starburst pattern. Call these the "signature scan lines."

Signature scan line

Searching for this signature in the target image is a simple matter of scanning the image in horizontal strips. Look for a high-frequency in the red-channel (indicating moving from a red region to a white one), and once found, see if it is followed by one of the frequency rhythms identified in the training session. Once a match is found, you will instantly know the scan-line's orientation and location in the logo (if you keep track of those things during training), so identifying the boundaries of the logo from there is trivial.

I would be surprised if this weren't a linearly-efficient algorithm, or nearly so. It obviously doesn't address your can-bottle discrimination, but at least you'll have your logos.

(Update: for bottle recognition I would look for coke (the brown liquid) adjacent to the logo -- that is, inside the bottle. Or, in the case of an empty bottle, I would look for a cap which will always have the same basic shape, size, and distance from the logo and will typically be all white or red. Search for a solid color eliptical shape where a cap should be, relative to the logo. Not foolproof of course, but your goal here should be to find the easy ones fast.)

(It's been a few years since my image processing days, so I kept this suggestion high-level and conceptual. I think it might slightly approximate how a human eye might operate -- or at least how my brain does!)

Full Screen DialogFragment in Android

Try to use setStyle() in onCreate and override onCreateDialog make dialog without title

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme);        
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);        
    return dialog;
}

or just override onCreate() and setStyle fellow the code.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);        
}

JavaScript Array to Set

If you start out with:

let array = [
    {name: "malcom", dogType: "four-legged"},
    {name: "peabody", dogType: "three-legged"},
    {name: "pablo", dogType: "two-legged"}
];

And you want a set of, say, names, you would do:

let namesSet = new Set(array.map(item => item.name));

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';


export default class App extends Component {
  render() {
    return (
       <View>// you need to wrap the two Views an another View
          <View style={styles.box1}></View>
          <View style={styles.box2}></View>
       </View> 
    );
  }
}

const styles = StyleSheet.create({
  box1:{
    height:100,
    width:100,
    backgroundColor:'red'
  },
  box2:{
    height:100,
    width:100,
    backgroundColor:'green',
    position: 'absolute',
    top:10,
    left:30

  },
});

How do I fetch lines before/after the grep result in bash?

The way to do this is near the top of the man page

grep -i -A 10 'error data'

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

it's not exact output that you wanted but maybe something like this will do. Parent cmp:

<table>
  <item *ngFor="#i of items" [data]="i"></item>
</table>

Child cmp

import {Component} from 'angular2/core';

@Component({
  selector: `item`,
  inputs: ['data'],
  template: `
    <tr><td>{{data.name}}</td></tr>
    <tr *ngFor="#i of data.items">
      <td><h1>{{i}}</h1></td>
    </tr>
  `
})
export default class Item {


}

Counting the number of True Booleans in a Python List

Just for completeness' sake (sum is usually preferable), I wanted to mention that we can also use filter to get the truthy values. In the usual case, filter accepts a function as the first argument, but if you pass it None, it will filter for all "truthy" values. This feature is somewhat surprising, but is well documented and works in both Python 2 and 3.

The difference between the versions, is that in Python 2 filter returns a list, so we can use len:

>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
[True, True, True]
>>> len(filter(None, bool_list))
3

But in Python 3, filter returns an iterator, so we can't use len, and if we want to avoid using sum (for any reason) we need to resort to converting the iterator to a list (which makes this much less pretty):

>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
<builtins.filter at 0x7f64feba5710>
>>> list(filter(None, bool_list))
[True, True, True]
>>> len(list(filter(None, bool_list)))
3

What is the correct way to write HTML using Javascript?

Use jquery, look how easy it is:

    var a = '<h1> this is some html </h1>';
    $("#results").html(a);

       //html
    <div id="results"> </div>

MySQL Select all columns from one table and some from another table

Just use the table name:

SELECT myTable.*, otherTable.foo, otherTable.bar...

That would select all columns from myTable and columns foo and bar from otherTable.

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

Can't bind to 'ngModel' since it isn't a known property of 'input'

Import FormModule in file app.module

import { FormsModule } from '@angular/forms'; [...] @NgModule({ imports: [ [...] FormsModule ], [...] })

Find the directory part (minus the filename) of a full path in access 97

That's about it. There is no magic built-in function...

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

Google Maps API Multiple Markers with Infowindows

You could use a closure. Just modify your code like this:

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        infowindow.setContent(content);
        infowindow.open(map,marker);
    };
})(marker,content,infowindow));  

Here is the DEMO

Convert string to List<string> in one line?

Split a string delimited by characters and return all non-empty elements.

var names = ",Brian,Joe,Chris,,,";
var charSeparator = ",";
var result = names.Split(charSeparator, StringSplitOptions.RemoveEmptyEntries);

https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8

How to add a ScrollBar to a Stackpanel

Stackpanel doesn't have built in scrolling mechanism but you can always wrap the StackPanel in a ScrollViewer

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <StackPanel ... />
</ScrollViewer>

How to call multiple JavaScript functions in onclick event?

onclick="doSomething();doSomethingElse();"

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

ipad safari: disable scrolling, and bounce effect?

Try this JS solution that toggles webkitOverflowScrolling style. The trick here is that this style is off, mobile Safari goes to ordinary scrolling and prevents over-bounce — alas, it is not able to cancel ongoing drag. This complex solution also tracks onscroll as bounce over the top makes scrollTop negative that may be tracked. This solution was tested on iOS 12.1.1 and has single drawback: while accelerating the scroll single over-bounce still happens as resetting the style may not cancel it immediately.

function preventScrollVerticalBounceEffect(container) {
  setTouchScroll(true) //!: enable before the first scroll attempt

  container.addEventListener("touchstart", onTouchStart)
  container.addEventListener("touchmove", onTouch, { passive: false })
  container.addEventListener("touchend", onTouchEnd)
  container.addEventListener("scroll", onScroll)

  function isTouchScroll() {
    return !!container.style.webkitOverflowScrolling
  }

  let prevScrollTop = 0, prevTouchY, opid = 0

  function setTouchScroll(on) {
    container.style.webkitOverflowScrolling = on ? "touch" : null

    //Hint: auto-enabling after a small pause makes the start
    // smoothly accelerated as required. After the pause the
    // scroll position is settled, and there is no delta to
    // make over-bounce by dragging the finger. But still,
    // accelerated content makes short single over-bounce
    // as acceleration may not be off instantly.

    const xopid = ++opid
    !on && setTimeout(() => (xopid === opid) && setTouchScroll(true), 250)

    if(!on && container.scrollTop < 16)
      container.scrollTop = 0
    prevScrollTop = container.scrollTop
  }

  function isBounceOverTop() {
    const dY = container.scrollTop - prevScrollTop
    return dY < 0 && container.scrollTop < 16
  }

  function isBounceOverBottom(touchY) {
    const dY = touchY - prevTouchY

    //Hint: trying to bounce over the bottom, the finger moves
    // up the screen, thus Y becomes smaller. We prevent this.

    return dY < 0 && container.scrollHeight - 16 <=
      container.scrollTop + container.offsetHeight
  }

  function onTouchStart(e) {
    prevTouchY = e.touches[0].pageY
  }

  function onTouch(e) {
    const touchY = e.touches[0].pageY

    if(isBounceOverBottom(touchY)) {
      if(isTouchScroll())
        setTouchScroll(false)
      e.preventDefault()
    }

    prevTouchY = touchY
  }

  function onTouchEnd() {
    prevTouchY = undefined
  }

  function onScroll() {
    if(isTouchScroll() && isBounceOverTop()) {
      setTouchScroll(false)
    }
  }
}

Adding blur effect to background in swift

You can make an extension of UIImageView.

Swift 2.0

import Foundation
import UIKit

extension UIImageView
{
    func makeBlurImage(targetImageView:UIImageView?)
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = targetImageView!.bounds

        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
        targetImageView?.addSubview(blurEffectView)
    }
}

Usage:

override func viewDidLoad()
{
    super.viewDidLoad()

    let sampleImageView = UIImageView(frame: CGRectMake(0, 200, 300, 325))
    let sampleImage:UIImage = UIImage(named: "ic_120x120")!
    sampleImageView.image =  sampleImage

    //Convert To Blur Image Here
    sampleImageView.makeBlurImage(sampleImageView)

    self.view.addSubview(sampleImageView)
}

Swift 3 Extension

import Foundation
import UIKit

extension UIImageView
{
    func addBlurEffect()
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds

        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
        self.addSubview(blurEffectView)
    }
}

Usage:

yourImageView.addBlurEffect()

Addendum:

extension UIView {
  
  /// Remove UIBlurEffect from UIView
  func removeBlurEffect() {
    let blurredEffectViews = self.subviews.filter{$0 is UIVisualEffectView}
    blurredEffectViews.forEach{ blurView in
      blurView.removeFromSuperview()
    }
  }

Swift 5.0:

import UIKit


extension UIImageView {
    func applyBlurEffect() {
        let blurEffect = UIBlurEffect(style: .light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(blurEffectView)
    }
}

How to get date in BAT file

Locale-independent one liner to get any date format you like. I use it to generate archive names. Back quote option is needed because PowerShell command line is using single quotes.

:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Get formatted yesterday date.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).AddDays^(-1^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Show file name with the date.
echo Archive.%DTime%.zip

How to find the number of days between two dates

DECLARE @Firstdate DATE='2016-04-01',
 @LastDate DATE=GETDATE(),/*get today date*/
 @resultDay int=null

SET @resultDay=(SELECT DATEDIFF(d, @Firstdate, @LastDate))
PRINT @resultDay

Can I dispatch an action in reducer?

redux-loop takes a cue from Elm and provides this pattern.

Get list of all input objects using JavaScript, without accessing a form object

(See update at end of answer.)

You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it:

var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

There I've used it on the document, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:

var container, inputs, index;

// Get the container element
container = document.getElementById('container');

// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

...but you've said you don't want to use the parent form, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).


Update: getElementsByTagName is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input elements?

That's where the useful querySelectorAll comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:

var checkboxes = document.querySelectorAll("input[type=checkbox]");

You can also use it at the element level. For instance, if we have a div element in our element variable, we can find all of the spans with the class foo that are inside that div like this:

var fooSpans = element.querySelectorAll("span.foo");

querySelectorAll and its cousin querySelector (which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.

Get list of databases from SQL Server

In SQL Server 2008 R2 this works:

select name 
from master.sys.databases 
where owner_sid > 1;

And list only databases created by user(s).

How to get the previous URL in JavaScript?

Those of you using Node.js and Express can set a session cookie that will remember the current page URL, thus allowing you to check the referrer on the next page load. Here's an example that uses the express-session middleware:

//Add me after the express-session middleware    
app.use((req, res, next) => {
    req.session.referrer = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});

You can then check for the existance of a referrer cookie like so:

if ( req.session.referrer ) console.log(req.session.referrer);

Do not assume that a referrer cookie always exists with this method as it will not be available on instances where the previous URL was another website, the session was cleaned or was just created (first-time website load).

git checkout master error: the following untracked working tree files would be overwritten by checkout

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

Maven error: Not authorized, ReasonPhrase:Unauthorized

I have recently encountered this problem. Here are the steps to resolve

  1. Check the servers section in the settings.xml file.Is username and password correct?

_x000D_
_x000D_
<servers>_x000D_
  <server>_x000D_
    <id>serverId</id>_x000D_
    <username>username</username>_x000D_
    <password>password</password>_x000D_
  </server>_x000D_
</servers>
_x000D_
_x000D_
_x000D_

  1. Check the repository section in the pom.xml file.The id of the server tag should be the same as the id of the repository tag.

_x000D_
_x000D_
<repositories>_x000D_
 <repository>_x000D_
   <id>serverId</id>  _x000D_
   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
 </repository>_x000D_
</repositories>
_x000D_
_x000D_
_x000D_

  1. If the repository tag is not configured in the pom.xml file, look in the settings.xml file.

_x000D_
_x000D_
<profiles>_x000D_
 <profile>_x000D_
   <repositories>_x000D_
     <repository>_x000D_
      <id>serverId</id>_x000D_
      <name>aliyun</name>_x000D_
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
     </repository>_x000D_
   </repositories>_x000D_
 </profile>_x000D_
</profiles>
_x000D_
_x000D_
_x000D_

Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.

How to configure Fiddler to listen to localhost?

The Light,

You can configure the process acting as the client to use fiddler as a proxy.

Fiddler sets itself up as a proxy conveniently on 127.0.0.1:8888, and by default overrides the system settings under Internet Options in the Control Panel (if you've configured any) such that all traffic from the common protocols (http, https, and ftp) goes to 127.0.0.1:8888 before leaving your machine.

Now these protocols are often from common processes such as browsers, and so are easily picked up by fiddler. However, in your case, the process initiating the requests is probably not a browser, but one for a programming language like php.exe, or java.exe, or whatever language you are using.

If, say, you're using php, you can leverage curl. Ensure that the curl module is enabled, and then right before your code that invokes the request, include:

curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');

Hope this helps. You can also always lookup stuff like so from the fiddler documentation for a basis for you to build upon e.g. http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigurePHPcURL

File content into unix variable with newlines

Just if someone is interested in another option:

content=( $(cat test.txt) )

a=0
while [ $a -le ${#content[@]} ]
do
        echo ${content[$a]}
        a=$[a+1]
done

Eclipse - Unable to install breakpoint due to missing line number attributes

Since I have 6 different versions of Java installed, I had to change my default JDK compliance to match that of the Java version I wanted to use. Eclipse by default had compiler compliance level set to Java 1.7 when everything was built/compiled using Java 1.6.

So all I did was

  1. In eclipse menu, go to Window->Preferences->Java->Compiler
  2. Under JDK Compliance, I changed Compiler compliance level from 1.7 to 1.6

Now Eclipse doesn't complain about the "Unable to insert breakpoint Absent Line Number Information" anymore and the debugging breakpoints actually work!!!

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Please Try, if use "extends AppCompatActivity" and present actionbar.

 ActionBar eksinbar=getSupportActionBar();
if (eksinbar != null) {
    eksinbar.setDisplayHomeAsUpEnabled(true);
    eksinbar.setHomeAsUpIndicator(R.mipmap.imagexxx);
}

Adding items to end of linked list

The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().

Node.java

package in.datastructure.java.LinkedList;

/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
    int data;
    Node next;

    Node (int data){
       this.data = data;
    }
    public String toString(){
      return this.data+"--"+ this.next;
    }
}

LinkedList.java

package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;

public class LinkedList {

    Node head;
    Node lastx;
    /**
     * @description To append node at end looping all nodes from head
     * @param data
     */
    public void addLast(int data){

        if(head == null){
            head = new Node(data);
            return;
        }
        Node last = head;
        while(last.next != null) {
            last = last.next;
        }
        last.next = new Node(data);
    }


    /**
     * @description This keep track on last node and append to it
     * @param data
     */
    public void addLastx(int data){

        if(head == null){
            head = new Node(data);
            lastx = head;
            return;
        }
        if(lastx.next == null){
            lastx.next = new Node(data);
            lastx = lastx.next;
        }

    }

    public String toString(){
        ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
        Node current = head;
        while(current.next != null) {
            arrayList.add(current.data);
            current = current.next;
        }
        if(current.next == null) {
            arrayList.add(current.data);
        }
        return arrayList.toString();
    }


    public static void main(String[] args) {
        LinkedList ll = new LinkedList();
        /**
         * @description Checking the code optimization of append code
         */
        Date startTime = new Date();
        for (int i = 0 ; i < 100000 ; i++){
            ll.addLastx(i);
        }
        Date endTime = new Date();
        System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
        System.out.println(ll.toString());
    }

}

How to change the Push and Pop animations in a navigation based app

Remember that in Swift, extension are definitely your friends!

public extension UINavigationController {

    /**
     Pop current view controller to previous view controller.

     - parameter type:     transition animation type.
     - parameter duration: transition animation duration.
     */
    func pop(transitionType type: String = kCATransitionFade, duration: CFTimeInterval = 0.3) {
        self.addTransition(transitionType: type, duration: duration)
        self.popViewControllerAnimated(false)
    }

    /**
     Push a new view controller on the view controllers's stack.

     - parameter vc:       view controller to push.
     - parameter type:     transition animation type.
     - parameter duration: transition animation duration.
     */
    func push(viewController vc: UIViewController, transitionType type: String = kCATransitionFade, duration: CFTimeInterval = 0.3) {
        self.addTransition(transitionType: type, duration: duration)
        self.pushViewController(vc, animated: false)
    }

    private func addTransition(transitionType type: String = kCATransitionFade, duration: CFTimeInterval = 0.3) {
        let transition = CATransition()
        transition.duration = duration
        transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        transition.type = type
        self.view.layer.addAnimation(transition, forKey: nil)
    }

}

Create a OpenSSL certificate on Windows

If you're on windows and using apache, maybe via WAMP or the Drupal stack installer, you can additionally download the git for windows package, which includes many useful linux command line tools, one of which is openssl.

The following command creates the self signed certificate and key needed for apache and works fine in windows:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt

Call two functions from same onclick

You can call the functions from inside another function

<input id ="btn" type="button" value="click" onclick="todo()"/>

function todo(){
pay(); cls();
}

how to force maven to update local repo

Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.

Press CTRL+Shift+A to open up the Actions menu. Type Maven and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Determine which MySQL configuration file is being used

If you are on Windows, you can use Sysinternals procmon. Open it and configure filter setting like this, then click "Add". Now procmon will monitor mysqld.

enter image description here

Now start your mysql server as normal. Procmon will capture mysql's background operations. Search "my." in the procmon result pane and you will find something like the following:

enter image description here

It's clear that mysql searches a list of configuration files in turn. In my case it found C:\mysql-5.7.19-winx64\my.cnf successfully so it's using this one.

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

How to see full query from SHOW PROCESSLIST

If one want to keep getting updated processes (on the example, 2 seconds) on a shell session without having to manually interact with it use:

watch -n 2 'mysql -h 127.0.0.1 -P 3306 -u some_user -psome_pass some_database -e "show full processlist;"'

The only bad thing about the show [full] processlist is that you can't filter the output result. On the other hand, issuing the SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST open possibilities to remove from the output anything you don't want to see:

SELECT * from INFORMATION_SCHEMA.PROCESSLIST
WHERE DB = 'somedatabase'
AND COMMAND <> 'Sleep'
AND HOST NOT LIKE '10.164.25.133%' \G

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

How do I use a third-party DLL file in Visual Studio C++?

You only need to use LoadLibrary if you want to late bind and only resolve the imported functions at runtime. The easiest way to use a third party dll is to link against a .lib.


In reply to your edit:

Yes, the third party API should consist of a dll and/or a lib that contain the implementation and header files that declares the required types. You need to know the type definitions whichever method you use - for LoadLibrary you'll need to define function pointers, so you could just as easily write your own header file instead. Basically, you only need to use LoadLibrary if you want late binding. One valid reason for this would be if you aren't sure if the dll will be available on the target PC.

How can I restart a Java application?

Windows

public void restartApp(){

    // This launches a new instance of application dirctly, 
    // remember to add some sleep to the start of the cmd file to make sure current instance is
    // completely terminated, otherwise 2 instances of the application can overlap causing strange
    // things:)

    new ProcessBuilder("cmd","/c start /min c:/path/to/script/that/launches/my/application.cmd ^& exit").start();
    System.exit(0);
}

/min to start script in minimized window

^& exit to close cmd window after finish

a sample cmd script could be

@echo off
rem add some sleep (e.g. 10 seconds) to allow the preceding application instance to release any open resources (like ports) and exit gracefully, otherwise the new instance could fail to start
sleep 10   
set path=C:\someFolder\application_lib\libs;%path%
java -jar application.jar

sleep 10 sleep for 10 seconds

Remove element by id

You can simply use

document.getElementById("elementID").outerHTML="";

It works in all browsers, even on Internet Explorer.

How to synchronize or lock upon variables in Java?

If on another occasion you're synchronising a Collection rather than a String, perhaps you're be iterating over the collection and are worried about it mutating, Java 5 offers:

CSS float right not working correctly

Here is one way of doing it.

If you HTML looks like this:

<div>Contact Details
    <button type="button" class="edit_button">My Button</button>
</div>

apply the following CSS:

div {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: gray;
    overflow: auto;
}
.edit_button {
    float: right;
    margin: 0 10px 10px 0; /* for demo only */
}

The trick is to apply overflow: auto to the div, which starts a new block formatting context. The result is that the floated button is enclosed within the block area defined by the div tag.

You can then add margins to the button if needed to adjust your styling.

In the original HTML and CSS, the floated button was out of the content flow so the border of the div would be positioned with respect to the in-flow text, which does not include any floated elements.

See demo at: http://jsfiddle.net/audetwebdesign/AGavv/

What is the MySQL JDBC driver connection string?

it's depends on what service you're using.

if you use MySQL Workbench it wold be some thing like this :

jdbc:mysql://"host":"port number"/

String url = "jdbc:mysql://localhost:3306/";

And of course it will be different if you using SSL/SSH.

For more information follow the official link of Jetbriens (intelliJ idea) :

Connecting to a database #

https://www.jetbrains.com/help/idea/connecting-to-a-database.html


Configuring database connections #

https://www.jetbrains.com/help/idea/configuring-database-connections.html

How to change the time format (12/24 hours) of an <input>?

HTML5 Time Input

This one is the simplest of the date/time related types, allowing the user to select a time on a 24/12 hour clock, usually depending on the user's OS locale configuration. The value returned is in 24h hours:minutes format, which will look something like 14:30.

More details, including the appearance for each browser, can be found on MDN.

_x000D_
_x000D_
<input type="time" name="time" />
_x000D_
_x000D_
_x000D_

How to resize image automatically on browser width resize but keep same height?

It is an old question but i want to add that if you want to resize image according to viewport size only with css; you can use viewport units "vh (viewport height) or vw (viewport width)".

.img {
width: 100vw;
height: 100vh;
}

See browser supports

Simple PHP form: Attachment to email (code golf)

I haven't tested the email part of this (my test box does not send email) but I think it will work.

<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s

{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>

How to pass a value from one jsp to another jsp page?

Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp' Make three hidden text boxes and a button that is click automatically(using javascript). //Code to written in 'show.jsp'

<body>
<form action="display.jsp" method="post">
 <input type="hidden" name="u1" value="<%=u1%>"/>
 <input type="hidden" name="u2" value="<%=u2%>" />
 <input type="hidden" name="u3" value="<%=u3%>" />
 <button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
  <script type="text/javascript">
     document.getElementById("qq").click();
  </script>
</body>

// Code to be written in 'display.jsp'

 <% String u1 = request.getParameter("u1").toString();
    String u2 = request.getParameter("u2").toString();
    String u3 = request.getParameter("u3").toString();
 %>

If you want to use these variables of servlets in javascript then simply write

<script type="text/javascript">
 var a=<%=u1%>;
</script>

Hope it helps :)

How can I check for IsPostBack in JavaScript?

Server-side, write:

if(IsPostBack)
{
   // NOTE: the following uses an overload of RegisterClientScriptBlock() 
   // that will surround our string with the needed script tags 
   ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}

Then, in your script which runs for the onLoad, check for the existence of that variable:

if(isPostBack) {
   // do your thing
}

You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.

Calculate logarithm in python

From the documentation:

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

But the log10 is made available as math.log10(), which does not resort to log division if possible.

HTTP POST using JSON in Java

Here is what you need to do:

  1. Get the Apache HttpClient, this would enable you to make the required request
  2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded
  3. Create a StringEntity that you will pass JSON to it
  4. Execute the call

The code roughly looks like (you will still need to debug it and make it work):

// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
    // @Deprecated httpClient.getConnectionManager().shutdown(); 
}

How can I dynamically add items to a Java array?

In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.

package simplejava;

import java.util.Arrays;

/**
 *
 * @author sashant
 */
public class SimpleJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        try{
            String[] transactions;
            transactions = new String[10];

            for(int i = 0; i < transactions.length; i++){
                transactions[i] = "transaction - "+Integer.toString(i);            
            }

            System.out.println(Arrays.toString(transactions));

        }catch(Exception exc){
            System.out.println(exc.getMessage());
            System.out.println(Arrays.toString(exc.getStackTrace()));
        }
    }

}

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Django Admin - change header 'Django administration' text

A simple complete solution in Django 1.8.3 based on answers in this question.

In settings.py add:

ADMIN_SITE_HEADER = "My shiny new administration"

In urls.py add:

from django.conf import settings
admin.site.site_header = settings.ADMIN_SITE_HEADER

C: What is the difference between ++i and i++?

The reason ++i can be slightly faster than i++ is that i++ can require a local copy of the value of i before it gets incremented, while ++i never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this.

I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use ++i.

How to disable PHP Error reporting in CodeIgniter?

Change CI index.php file to:

if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

if (defined('ENVIRONMENT')){
    switch (ENVIRONMENT){
        case 'development':
            error_reporting(E_ALL);
        break;

        case 'testing':
        case 'production':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:

$db['default']['db_debug'] = FALSE; 

Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html

$active_group = 'development';


$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;

$db['development']['db_debug'] = TRUE;

$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;



$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;

$db['production']['db_debug'] = FALSE;

$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;

SQL Server 2005 How Create a Unique Constraint?

I also found you can do this via, the database diagrams.

By right clicking the table and selecting Indexes/Keys...

Click the 'Add' button, and change the columns to the column(s) you wish make unique.

Change Is Unique to Yes.

Click close and save the diagram, and it will add it to the table.

LINQ - Full Outer Join

I really hate these linq expressions, this is why SQL exists:

select isnull(fn.id, ln.id) as id, fn.firstname, ln.lastname
   from firstnames fn
   full join lastnames ln on ln.id=fn.id

Create this as sql view in database and import it as entity.

Of course, (distinct) union of left and right joins will make it too, but it is stupid.

Best way to check if object exists in Entity Framework?

Best way to do it

Regardless of what your object is and for what table in the database the only thing you need to have is the primary key in the object.

C# Code

var dbValue = EntityObject.Entry(obj).GetDatabaseValues();
if (dbValue == null)
{
   Don't exist
}

VB.NET Code

Dim dbValue = EntityObject.Entry(obj).GetDatabaseValues()
If dbValue Is Nothing Then
   Don't exist
End If

JavaScript Promises - reject vs. throw

Another important fact is that reject() DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.

Example:

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  throw "err";_x000D_
  console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

vs

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  reject(); // resolve() behaves similarly_x000D_
  console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

Sorting a Dictionary in place with respect to keys

Take a look at SortedDictionary, there's even a constructor overload so you can pass in your own IComparable for the comparisons.

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

you are mixing mysql and mysqli

use this mysql_real_escape_string like

$username = mysql_real_escape_string($_POST['username']);

NOTE : mysql_* is deprecated use mysqli_* or PDO

How to generate UL Li list from string array using jquery?

Other variation of Abhishek Bhalani: You can use Array.map() instead of $.each()

var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
      var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
      $('<a class="ui-all">'+ i + ': ' + item.name + '<a/>')
        .appendTo(li);
    });

How do I get a list of folders and sub folders without the files?

I used dir /s /b /o:n /a:d, and it worked perfectly, just make sure you let the file finish writing, or you'll have an incomplete list.

Using continue in a switch statement

Switch is not considered as loop so you cannot use Continue inside a case statement in switch...

Subtract days, months, years from a date in JavaScript

I'd recommend using the MomentJS libraries. They make all interactions with Dates a lot simpler.

If you use Moment, your code would be as simple as this:

var today = moment();
var nextMonth = today.add('month', 1);
// note that both variables `today` and `nextMonth` refer to 
// the next month at this point, because `add` mutates in-place

You can find MomentJS here: http://momentjs.com/

UPDATE:

In JavaScript, the Date.getDate() function returns the current day of the month from 1-31. You are subtracting 6 from this number, and it is currently the 3rd of the month. This brings the value to -3.

How to get hex color value rather than RGB value?

color class taken from bootstrap color picker

// Color object
var Color = function(val) {
    this.value = {
        h: 1,
        s: 1,
        b: 1,
        a: 1
    };
    this.setColor(val);
};

Color.prototype = {
    constructor: Color,

    //parse a string to HSB
    setColor: function(val){
        val = val.toLowerCase();
        var that = this;
        $.each( CPGlobal.stringParsers, function( i, parser ) {
            var match = parser.re.exec( val ),
            values = match && parser.parse( match ),
            space = parser.space||'rgba';
            if ( values ) {
                if (space === 'hsla') {
                    that.value = CPGlobal.RGBtoHSB.apply(null, CPGlobal.HSLtoRGB.apply(null, values));
                } else {
                    that.value = CPGlobal.RGBtoHSB.apply(null, values);
                }
                return false;
            }
        });
    },

    setHue: function(h) {
        this.value.h = 1- h;
    },

    setSaturation: function(s) {
        this.value.s = s;
    },

    setLightness: function(b) {
        this.value.b = 1- b;
    },

    setAlpha: function(a) {
        this.value.a = parseInt((1 - a)*100, 10)/100;
    },

    // HSBtoRGB from RaphaelJS
    // https://github.com/DmitryBaranovskiy/raphael/
    toRGB: function(h, s, b, a) {
        if (!h) {
            h = this.value.h;
            s = this.value.s;
            b = this.value.b;
        }
        h *= 360;
        var R, G, B, X, C;
        h = (h % 360) / 60;
        C = b * s;
        X = C * (1 - Math.abs(h % 2 - 1));
        R = G = B = b - C;

        h = ~~h;
        R += [C, X, 0, 0, X, C][h];
        G += [X, C, C, X, 0, 0][h];
        B += [0, 0, X, C, C, X][h];
        return {
            r: Math.round(R*255),
            g: Math.round(G*255),
            b: Math.round(B*255),
            a: a||this.value.a
        };
    },

    toHex: function(h, s, b, a){
        var rgb = this.toRGB(h, s, b, a);
        return '#'+((1 << 24) | (parseInt(rgb.r) << 16) | (parseInt(rgb.g) << 8) | parseInt(rgb.b)).toString(16).substr(1);
    },

    toHSL: function(h, s, b, a){
        if (!h) {
            h = this.value.h;
            s = this.value.s;
            b = this.value.b;
        }
        var H = h,
        L = (2 - s) * b,
        S = s * b;
        if (L > 0 && L <= 1) {
            S /= L;
        } else {
            S /= 2 - L;
        }
        L /= 2;
        if (S > 1) {
            S = 1;
        }
        return {
            h: H,
            s: S,
            l: L,
            a: a||this.value.a
        };
    }
};

how to use

var color = new Color("RGB(0,5,5)");
color.toHex()

JavaScript DOM: Find Element Index In Container

Array.prototype.indexOf.call(this.parentElement.children, this);

Or use let statement.

Javascript, viewing [object HTMLInputElement]

change:

$("input:text").change(function() {
    var value=$("input:text").val();
    alert(value);
});

to

$("input:text").change(function() {
    var value=$("input[type=text].selector").val();
    alert(value);
});

note: selector:id,class..

Is there a NumPy function to return the first index of something in an array?

If you need the index of the first occurrence of only one value, you can use nonzero (or where, which amounts to the same thing in this case):

>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6

If you need the first index of each of many values, you could obviously do the same as above repeatedly, but there is a trick that may be faster. The following finds the indices of the first element of each subsequence:

>>> nonzero(r_[1, diff(t)[:-1]])
(array([0, 3, 5, 6, 7, 8]),)

Notice that it finds the beginning of both subsequence of 3s and both subsequences of 8s:

[1, 1, 1, 2, 2, 3, 8, 3, 8, 8]

So it's slightly different than finding the first occurrence of each value. In your program, you may be able to work with a sorted version of t to get what you want:

>>> st = sorted(t)
>>> nonzero(r_[1, diff(st)[:-1]])
(array([0, 3, 5, 7]),)

How can I style a PHP echo text?

You can style it by the following way:

echo "<p style='color:red;'>" . $ip['cityName'] . "</p>";
echo "<p style='color:red;'>" . $ip['countryName'] . "</p>";

Git undo local branch delete

You can use git reflog to find the SHA1 of the last commit of the branch. From that point, you can recreate a branch using

git branch branchName <sha1>

Edit: As @seagullJS says, the branch -D command tells you the sha1, so if you haven't closed the terminal yet it becomes real easy. For example this deletes and then immediately restores a branch named master2:

user@MY-PC /C/MyRepo (master)
$ git branch -D master2
Deleted branch master2 (was 130d7ba).    <-- This is the SHA1 we need to restore it!

user@MY-PC /C/MyRepo (master)
$ git branch master2 130d7ba

Rails: update_attribute vs update_attributes

Also worth noting is that with update_attribute, the desired attribute to be updated doesn't need to be white listed with attr_accessible to update it as opposed to the mass assignment method update_attributes which will only update attr_accessible specified attributes.