Programs & Examples On #Mindtouch

Could not find the main class, program will exit

Tweaking MB's answer for windows, will get rid of the console window:

start javaw -jar squirrel-sql.jar

Does document.body.innerHTML = "" clear the web page?

Using document.body.innerHTML = ''; does work! Just saying, if using HTML (DOM or on function) you can use
document.writeln(''); but only onClick or onDoubleClick :)

How can one run multiple versions of PHP 5.x on a development LAMP server?

Note: The following method will work on windows.

An alternative method (if it is ok to run a single version of PHP at a time) is to define multiple Apache services, each of which will use a different PHP version.

First of all use conditions in the Apache configuration file:

 <ifdefine php54>
    SetEnv PHPRC C:/apache/php54/
    ScriptAlias /php/ "C:/apache/php54/"
    AddType application/x-httpd-php .php
    Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>

<ifdefine php55>
    SetEnv PHPRC C:/apache/php55/
    ScriptAlias /php/ "C:/apache/php55/"
    AddType application/x-httpd-php .php
    Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>

Now using the httpd.exe create two separate services from command line (elevated to administrator):

httpd.exe -k install -n Apache224_php54 -D php54

httpd.exe -k install -n Apache224_php55 -D php55

Now you can start one of the above services at a time (should shutdown one before starting the other).

If you have previously installed Apache as service you can remove that using below command (replace the service name with the one you have used):

apache -k uninstall -n Apache224

One further note is that I personally use a "notification area icon program" called "Seobiseu" to start and stop services as needed. I have added the two above services to it.

Empty brackets '[]' appearing when using .where

You can use the lower function:

Guide.where("lower(title)='attack'") 

As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.

How to overwrite the output directory in spark

If you are willing to use your own custom output format, you would be able to get the desired behaviour with RDD as well.

Have a look at the following classes: FileOutputFormat, FileOutputCommitter

In file output format you have a method named checkOutputSpecs, which is checking whether the output directory exists. In FileOutputCommitter you have the commitJob which is usually transferring data from the temporary directory to its final place.

I wasn't able to verify it yet (would do it, as soon as I have few free minutes) but theoretically: If I extend FileOutputFormat and override checkOutputSpecs to a method that doesn't throw exception on directory already exists, and adjust the commitJob method of my custom output committer to perform which ever logic that I want (e.g. Override some of the files, append others) than I may be able to achieve the desired behaviour with RDDs as well.

The output format is passed to: saveAsNewAPIHadoopFile (which is the method saveAsTextFile called as well to actually save the files). And the Output committer is configured at the application level.

How to pass variable from jade template file to a script file?

Here's how I addressed this (using a MEAN derivative)

My variables:

{
  NODE_ENV : development,
  ...
  ui_varables {
     var1: one,
     var2: two
  }
}

First I had to make sure that the necessary config variables were being passed. MEAN uses the node nconf package, and by default is set up to limit which variables get passed from the environment. I had to remedy that:

config/config.js:

original:

nconf.argv()
  .env(['PORT', 'NODE_ENV', 'FORCE_DB_SYNC'] ) // Load only these environment variables
  .defaults({
  store: {
    NODE_ENV: 'development'
  }
});

after modifications:

nconf.argv()
  .env('__') // Load ALL environment variables
  // double-underscore replaces : as a way to denote hierarchy
  .defaults({
  store: {
    NODE_ENV: 'development'
  }
});

Now I can set my variables like this:

export ui_varables__var1=first-value
export ui_varables__var2=second-value

Note: I reset the "heirarchy indicator" to "__" (double underscore) because its default was ":", which makes variables more difficult to set from bash. See another post on this thread.

Now the jade part: Next the values need to be rendered, so that javascript can pick them up on the client side. A straightforward way to write these values to the index file. Because this is a one-page app (angular), this page is always loaded first. I think ideally this should be a javascript include file (just to keep things clean), but this is good for a demo.

app/controllers/index.js:

'use strict';
var config = require('../../config/config');

exports.render = function(req, res) {
  res.render('index', {
    user: req.user ? JSON.stringify(req.user) : "null",
    //new lines follow:
    config_defaults : {
       ui_defaults: JSON.stringify(config.configwriter_ui).replace(/<\//g, '<\\/')  //NOTE: the replace is xss prevention
    }
  });
};

app/views/index.jade:

extends layouts/default

block content
  section(ui-view)
    script(type="text/javascript").
    window.user = !{user};
    //new line here
    defaults = !{config_defaults.ui_defaults};

In my rendered html, this gives me a nice little script:

<script type="text/javascript">
 window.user = null;         
 defaults = {"var1":"first-value","var2:"second-value"};
</script>        

From this point it's easy for angular to utilize the code.

PHP Get name of current directory

To get the names of current directory we can use getcwd() or dirname(__FILE__) but getcwd() and dirname(__FILE__) are not synonymous. They do exactly what their names are. If your code is running by referring a class in another file which exists in some other directory then these both methods will return different results.

For example if I am calling a class, from where these two functions are invoked and the class exists in some /controller/goodclass.php from /index.php then getcwd() will return '/ and dirname(__FILE__) will return /controller.

MongoDB logging all queries

if you want the queries to be logged to mongodb log file, you have to set both the log level and the profiling, like for example:

db.setLogLevel(1)
db.setProfilingLevel(2)

(see https://docs.mongodb.com/manual/reference/method/db.setLogLevel)

Setting only the profiling would not have the queries logged to file, so you can only get it from

db.system.profile.find().pretty()

In Python, how do I determine if an object is iterable?

I've been studying this problem quite a bit lately. Based on that my conclusion is that nowadays this is the best approach:

from collections.abc import Iterable   # drop `.abc` with Python 2.7 or lower

def iterable(obj):
    return isinstance(obj, Iterable)

The above has been recommended already earlier, but the general consensus has been that using iter() would be better:

def iterable(obj):
    try:
        iter(obj)
    except Exception:
        return False
    else:
        return True

We've used iter() in our code as well for this purpose, but I've lately started to get more and more annoyed by objects which only have __getitem__ being considered iterable. There are valid reasons to have __getitem__ in a non-iterable object and with them the above code doesn't work well. As a real life example we can use Faker. The above code reports it being iterable but actually trying to iterate it causes an AttributeError (tested with Faker 4.0.2):

>>> from faker import Faker
>>> fake = Faker()
>>> iter(fake)    # No exception, must be iterable
<iterator object at 0x7f1c71db58d0>
>>> list(fake)    # Ooops
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/.../site-packages/faker/proxy.py", line 59, in __getitem__
    return self._factory_map[locale.replace('-', '_')]
AttributeError: 'int' object has no attribute 'replace'

If we'd use insinstance(), we wouldn't accidentally consider Faker instances (or any other objects having only __getitem__) to be iterable:

>>> from collections.abc import Iterable
>>> from faker import Faker
>>> isinstance(Faker(), Iterable)
False

Earlier answers commented that using iter() is safer as the old way to implement iteration in Python was based on __getitem__ and the isinstance() approach wouldn't detect that. This may have been true with old Python versions, but based on my pretty exhaustive testing isinstance() works great nowadays. The only case where isinstance() didn't work but iter() did was with UserDict when using Python 2. If that's relevant, it's possible to use isinstance(item, (Iterable, UserDict)) to get that covered.

OPTION (RECOMPILE) is Always Faster; Why?

There are times that using OPTION(RECOMPILE) makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:

EXEC sp_updatestats

And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy but maybe we are just using different terms for the same thing.

When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.

In summary - I don't see any reason that OPTION(RECOMPILE) would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.

And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.

Deserialize json object into dynamic object using Json.net

I know this is old post but JsonConvert actually has a different method so it would be

var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);

Adding a caption to an equation in LaTeX

As in this forum post by Gonzalo Medina, a third way may be:

\documentclass{article}
\usepackage{caption}

\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}

\begin{document}

Some text

\begin{equ}[!ht]
  \begin{equation}
    a=b+c
  \end{equation}
\caption{Caption of the equation}
\end{equ}

Some other text
 
\end{document}

More details of the commands used from package caption: here.

A screenshot of the output of the above code:

screenshot of output

How can I make PHP display the error instead of giving me 500 Internal Server Error

Try not to go

MAMP > conf > [your PHP version] > php.ini

but

MAMP > bin > php > [your PHP version] > conf > php.ini

and change it there, it worked for me...

Simplest code for array intersection in javascript

Destructive seems simplest, especially if we can assume the input is sorted:

/* destructively finds the intersection of 
 * two arrays in a simple fashion.  
 *
 * PARAMS
 *  a - first array, must already be sorted
 *  b - second array, must already be sorted
 *
 * NOTES
 *  State of input arrays is undefined when
 *  the function returns.  They should be 
 *  (prolly) be dumped.
 *
 *  Should have O(n) operations, where n is 
 *    n = MIN(a.length, b.length)
 */
function intersection_destructive(a, b)
{
  var result = [];
  while( a.length > 0 && b.length > 0 )
  {  
     if      (a[0] < b[0] ){ a.shift(); }
     else if (a[0] > b[0] ){ b.shift(); }
     else /* they're equal */
     {
       result.push(a.shift());
       b.shift();
     }
  }

  return result;
}

Non-destructive has to be a hair more complicated, since we’ve got to track indices:

/* finds the intersection of 
 * two arrays in a simple fashion.  
 *
 * PARAMS
 *  a - first array, must already be sorted
 *  b - second array, must already be sorted
 *
 * NOTES
 *
 *  Should have O(n) operations, where n is 
 *    n = MIN(a.length(), b.length())
 */
function intersect_safe(a, b)
{
  var ai=0, bi=0;
  var result = [];

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}

TABLOCK vs TABLOCKX

Quite an old article on mssqlcity attempts to explain the types of locks:

Shared locks are used for operations that do not change or update data, such as a SELECT statement.

Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.

Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).


The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.

Argparse: Required arguments listed under "optional arguments"?

Building off of @Karl Rosaen

parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

The solution to the issue when i had this earlier today was that there was an additional set of tags bolted on the end of my Web.config. Once removed the functionality returned.

Compiling dynamic HTML strings from database

Try this below code for binding html through attr

.directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'attrs.dynamic' , function(html){
          element.html(scope.dynamic);
          $compile(element.contents())(scope);
        });
      }
    };
  });

Try this element.html(scope.dynamic); than element.html(attr.dynamic);

Android - implementing startForeground for a service?

If you want to make IntentService a Foreground Service

then you should override onHandleIntent()like this

Override
protected void onHandleIntent(@Nullable Intent intent) {


    startForeground(FOREGROUND_ID,getNotification());     //<-- Makes Foreground

   // Do something

    stopForeground(true);                                // <-- Makes it again a normal Service                         

}

How to make notification ?

simple. Here is the getNotification() Method

public Notification getNotification()
{

    Intent intent = new Intent(this, SecondActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);


    NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
    foregroundNotification.setOngoing(true);

    foregroundNotification.setContentTitle("MY Foreground Notification")
            .setContentText("This is the first foreground notification Peace")
            .setSmallIcon(android.R.drawable.ic_btn_speak_now)
            .setContentIntent(pendingIntent);


    return foregroundNotification.build();
}

Deeper Understanding

What happens when a service becomes a foreground service

This happens

enter image description here

What is a foreground Service ?

A foreground service,

  • makes sure that user is actively aware of that something is going on in the background by providing the notification.

  • (most importantly) is not killed by System when it runs low on memory

A use case of foreground service

Implementing song download functionality in a Music App

Cloning specific branch

You can use the following flags --single-branch && --depth to download the specific branch and to limit the amount of history which will be downloaded.

You will clone the repo from a certain point in time and only for the given branch

git clone -b <branch> --single-branch <url> --depth <number of commits>

--[no-]single-branch


Clone only the history leading to the tip of a single branch, either specified by the --branch option or the primary branch remote’s HEAD points at.

Further fetches into the resulting repository will only update the remote-tracking branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when --single-branch clone was made, no remote-tracking branch is created.


--depth

Create a shallow clone with a history truncated to the specified number of commits

Ignore outliers in ggplot2 boxplot

Ipaper::geom_boxplot2 is just what you want.

# devtools::install_github('kongdd/Ipaper')
library(Ipaper)
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy))
p + geom_boxplot2(width = 0.8, width.errorbar = 0.5)

enter image description here

How to set width and height dynamically using jQuery

or use this syntax:

$("#mainTable").css("width", "100px");
$("#mainTable").css("height", "200px");

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)

How to ignore the first line of data when processing CSV data?

Well, my mini wrapper library would do the job as well.

>>> import pyexcel as pe
>>> data = pe.load('all16.csv', name_columns_by_row=0)
>>> min(data.column[1])

Meanwhile, if you know what header column index one is, for example "Column 1", you can do this instead:

>>> min(data.column["Column 1"])

How to focus on a form input text field on page load using jQuery?

You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.

<input type="text" name="some_field" autofocus>

Note this will not work on IE9 and lower.

How do I perform an insert and return inserted identity with Dapper?

It does support input/output parameters (including RETURN value) if you use DynamicParameters, but in this case the simpler option is simply:

var id = connection.QuerySingle<int>( @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() as int)", new { Stuff = mystuff});

Note that on more recent versions of SQL Server you can use the OUTPUT clause:

var id = connection.QuerySingle<int>( @"
INSERT INTO [MyTable] ([Stuff])
OUTPUT INSERTED.Id
VALUES (@Stuff);", new { Stuff = mystuff});

Convert nullable bool? to bool

The easiest way is to use the null coalescing operator: ??

bool? x = ...;
if (x ?? true) { 

}

The ?? with nullable values works by examining the provided nullable expression. If the nullable expression has a value the it's value will be used else it will use the expression on the right of ??

Describe table structure

select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='<Table Name>'

You can get details like column datatype and size by this query

Regular expression to match a line that doesn't contain a word

Answer:

^((?!hede).)*$

Explanation:

^the beginning of the string, ( group and capture to \1 (0 or more times (matching the most amount possible)),
(?! look ahead to see if there is not,

hede your string,

) end of look-ahead, . any character except \n,
)* end of \1 (Note: because you are using a quantifier on this capture, only the LAST repetition of the captured pattern will be stored in \1)
$ before an optional \n, and the end of the string

Can I pass a JavaScript variable to another browser window?

Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.

I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.

getch and arrow codes

Try this...

I am in Windows 7 with Code::Blocks

while (true)
{
    char input;
    input = getch();

    switch(input)
    {
    case -32: //This value is returned by all arrow key. So, we don't want to do something.
        break;
    case 72:
        printf("up");
        break;
    case 75:
        printf("left");
        break;
    case 77:
        printf("right");
        break;
    case 80:
        printf("down");
        break;
    default:
        printf("INVALID INPUT!");
        break;
    }
}

Delete duplicate elements from an array

var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];

function squash(arr){
    var tmp = [];
    for(var i = 0; i < arr.length; i++){
        if(tmp.indexOf(arr[i]) == -1){
        tmp.push(arr[i]);
        }
    }
    return tmp;
}

console.log(squash(arr));

Working Example http://jsfiddle.net/7Utn7/

Compatibility for indexOf on old browsers

ModelState.AddModelError - How can I add an error that isn't for a property?

You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.

As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using

<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>

and

ModelState.AddModelError("Email", Resources.EmailInUse);

How to get CPU temperature?

It's depends on if your computer support WMI. My computer can't run this WMI demo too.

But I successfully get the CPU temperature via Open Hardware Monitor. Add the Openhardwaremonitor reference in Visual Studio. It's easier. Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
   class Program
   {
       public class UpdateVisitor : IVisitor
       {
           public void VisitComputer(IComputer computer)
           {
               computer.Traverse(this);
           }
           public void VisitHardware(IHardware hardware)
           {
               hardware.Update();
               foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
           }
           public void VisitSensor(ISensor sensor) { }
           public void VisitParameter(IParameter parameter) { }
       }
       static void GetSystemInfo()
       {
           UpdateVisitor updateVisitor = new UpdateVisitor();
           Computer computer = new Computer();
           computer.Open();
           computer.CPUEnabled = true;
           computer.Accept(updateVisitor);
           for (int i = 0; i < computer.Hardware.Length; i++)
           {
               if (computer.Hardware[i].HardwareType == HardwareType.CPU)
               {
                   for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                   {
                       if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                               Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
                   }
               }
           }
           computer.Close();
       }
       static void Main(string[] args)
       {
           while (true)
           {
               GetSystemInfo();
           }
       }
   }
}

You need to run this demo as administrator.

You can see the tutorial here: http://www.lattepanda.com/topic-f11t3004.html

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

How to compile or convert sass / scss to css with node-sass (no Ruby)?

I picked node-sass implementer for libsass because it is based on node.js.

Installing node-sass

  • (Prerequisite) If you don't have npm, install Node.js first.
  • $ npm install -g node-sass installs node-sass globally -g.

This will hopefully install all you need, if not read libsass at the bottom.

How to use node-sass from Command line and npm scripts

General format:

$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css

Examples:

  1. $ node-sass my-styles.scss my-styles.css compiles a single file manually.
  2. $ node-sass my-sass-folder/ -o my-css-folder/ compiles all the files in a folder manually.
  3. $ node-sass -w sass/ -o css/ compiles all the files in a folder automatically whenever the source file(s) are modified. -w adds a watch for changes to the file(s).

More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.

You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.

  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • Add "sass": "node-sass -w sass/ -o css/" to scripts in package.json file. It should look something like this:
"scripts": {
    "test" : "bla bla bla",
    "sass": "node-sass -w sass/ -o css/"
 }
  • $ npm run sass will compile your files.

How to use with gulp

  • $ npm install -g gulp installs Gulp globally.
  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • $ npm install --save-dev gulp installs Gulp locally. --save-dev adds gulp to devDependencies in package.json.
  • $ npm install gulp-sass --save-dev installs gulp-sass locally.
  • Setup gulp for your project by creating a gulpfile.js file in your project root folder with this content:
'use strict';
var gulp = require('gulp');

A basic example to transpile

Add this code to your gulpfile.js:

var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
  gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

$ gulp sass runs the above task which compiles .scss file(s) in the sass folder and generates .css file(s) in the css folder.

To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js:

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

All is set now! Just run the watch task:

$ gulp sass:watch

How to use with Node.js

As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.

What about libsass?

Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:

LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.

How to use executables from a package installed locally in node_modules?

Use npm-run.

From the readme:

npm-run

Find & run local executables from node_modules

Any executable available to an npm lifecycle script is available to npm-run.

Usage

$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable 

Installation

$ npm install -g npm-run

VBA using ubound on a multidimensional array

In addition to the already excellent answers, also consider this function to retrieve both the number of dimensions and their bounds, which is similar to John's answer, but works and looks a little differently:

Function sizeOfArray(arr As Variant) As String
    Dim str As String
    Dim numDim As Integer

    numDim = NumberOfArrayDimensions(arr)
    str = "Array"

    For i = 1 To numDim
        str = str & "(" & LBound(arr, i) & " To " & UBound(arr, i)
        If Not i = numDim Then
            str = str & ", "
        Else
            str = str & ")"
        End If
    Next i

    sizeOfArray = str
End Function


Private Function NumberOfArrayDimensions(arr As Variant) As Integer
' By Chip Pearson
' http://www.cpearson.com/excel/vbaarrays.htm
Dim Ndx As Integer
Dim Res As Integer
On Error Resume Next
' Loop, increasing the dimension index Ndx, until an error occurs.
' An error will occur when Ndx exceeds the number of dimension
' in the array. Return Ndx - 1.
    Do
        Ndx = Ndx + 1
        Res = UBound(arr, Ndx)
    Loop Until Err.Number <> 0
NumberOfArrayDimensions = Ndx - 1
End Function

Example usage:

Sub arrSizeTester()
    Dim arr(1 To 2, 3 To 22, 2 To 9, 12 To 18) As Variant
    Debug.Print sizeOfArray(arr())
End Sub

And its output:

Array(1 To 2, 3 To 22, 2 To 9, 12 To 18)

CSS container div not getting height

You are floating the children which means they "float" in front of the container. In order to take the correct height, you must "clear" the float

The div style="clear: both" clears the floating an gives the correct height to the container. see http://css.maxdesign.com.au/floatutorial/clear.htm for more info on floats.

eg.

<div class="c">
    <div class="l">

    </div>
    <div class="m">
        World
    </div>
    <div style="clear: both" />
</div>

Bootstrap center heading

Bootstrap comes with many pre-build classes and one of them is class="text-left". Please call this class whenever needed. :-)

Spring Boot @autowired does not work, classes in different package

When you use @SpringBootApplication annotation in for example package

com.company.config

it will automatically make component scan like this:

@ComponentScan("com.company.config") 

So it will NOT scan packages like com.company.controller etc.. Thats why you have to declare your @SpringBootApplication in package one level prior to your normal packages like this: com.company OR use scanBasePackages property, like this:

@SpringBootApplication(scanBasePackages = { "com.company" })

OR componentScan:

@SpringBootApplication
@ComponentScan("com.company")


Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

What are OLTP and OLAP. What is the difference between them?

oltp- mostly used for business transaction.used to collect business data.In sql we use insert,update and delete command for retrieving small source of data.like wise they are highly normalised.... OLTP Mostly used for maintaining the data integrity.

olap- mostly use for reporting,data mining and business analytic purpose. for the large or bulk data.deliberately it is de-normalised. it stores Historical data..

How to create a Date in SQL Server given the Day, Month and Year as Integers

CREATE DATE USING MONTH YEAR IN SQL::

DECLARE @FromMonth int=NULL,
@ToMonth int=NULL,
@FromYear int=NULL,
@ToYear int=NULL

/**Region For Create Date**/
        DECLARE @FromDate DATE=NULL
        DECLARE @ToDate DATE=NULL

    SET @FromDate=DateAdd(day,0, DateAdd(month, @FromMonth - 1,DateAdd(Year, @FromYear-1900, 0)))
    SET @ToDate=DateAdd(day,-1, DateAdd(month, @ToMonth - 0,DateAdd(Year, @ToYear-1900, 0)))
/**Region For Create Date**/

How to change Tkinter Button state from disabled to normal?

This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?

import tkinter

class App(object):
    def __init__(self):
        self.tree = None
        self._setup_widgets()

    def _setup_widgets(self):
        butts = tkinter.Button(text = "add line", state="disabled")
        butts.grid()

def main():  
    root = tkinter.Tk()
    app = App()
    root.mainloop()

if __name__ == "__main__":
    main()

Curl error: Operation timed out

Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.

If you are running the script through browser, then set the set_time_limit to zero for infinite seconds.

set_time_limit(0);

Increase the curl's operation time limit using this option CURLOPT_TIMEOUT

curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds

It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

Found shared references to a collection org.hibernate.HibernateException

I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.

Short version

Check that your @Embedded Id of container has no possible collisions.

Long version

When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.

For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.

So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.

Example

Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).

@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
    private Set<Loan> loans;

    @Embedded
    private AccountId accountId;

    ...
}

@Embeddable
public class AccountId {
    @Column(name = "X")
    private Long x;
    
    @Column(name = "BRANCH")
    private String branchId;
    
    @Column(name = "Z")
    private String z;

    ...
}

Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;

It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.

According to @NotFound(action = NotFoundAction.IGNORE) if value is not present in related table, Hibernate will load null value for the property.

If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.

So two CollectionKey objects will be equal and will have same hashCode for different Accounts.

result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
 role = "Account.loans"
 key = {Account@26451} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
 role = "Account.loans"
 key = {Account@35225} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

Because of this, Hibernate will load same PesistentSet for two entities.

PowerShell - Start-Process and Cmdline Switches

Warning

If you run PowerShell from a cmd.exe window created by Powershell, the 2nd instance no longer waits for jobs to complete.

cmd>  PowerShell
PS> Start-Process cmd.exe -Wait 

Now from the new cmd window, run PowerShell again and within it start a 2nd cmd window: cmd2> PowerShell

PS> Start-Process cmd.exe -Wait
PS>   

The 2nd instance of PowerShell no longer honors the -Wait request and ALL background process/jobs return 'Completed' status even thou they are still running !

I discovered this when my C# Explorer program is used to open a cmd.exe window and PS is run from that window, it also ignores the -Wait request. It appears that any PowerShell which is a 'win32 job' of cmd.exe fails to honor the wait request.

I ran into this with PowerShell version 3.0 on windows 7/x64

How to convert std::string to LPCWSTR in C++ (Unicode)

string  myMessage="helloworld";
int len;
int slength = (int)myMessage.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0); 
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
std::wstring r(buf);
 std::wstring stemp = r.C_str();
LPCWSTR result = stemp.c_str();

Async always WaitingForActivation

The reason is your result assigned to the returning Task which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:

var task = Task.Run(() =>
        {
            for (int i = 10; i < 432543543; i++)
            {
                // just for a long job
                double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
            }
           return "Foo Completed.";

        });

        while (task.Status != TaskStatus.RanToCompletion)
        {
            Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);

        }

        Console.WriteLine("Result: {0}", task.Result);
        Console.WriteLine("Finished.");
        Console.ReadKey(true);

The output:

enter image description here

Consider this for better explanation: You have a Foo method,let's say it Task A, and you have a Task in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task which is Task A, because Task B doesn't return a Task, it returns a string. Consider this:

If you define your result like this:

Task result = Foo(5);

You won't get any error.But if you define it like this:

string result = Foo(5);

You will get:

Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'

But if you add an await keyword:

string result = await Foo(5);

Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:

private static async Task<string> Foo(int seconds)
{
    await Task.Run(() =>
        {
            for (int i = 0; i < seconds; i++)
            {
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
                Task.Delay(TimeSpan.FromSeconds(1)).Wait();
            }

            // in here don't return anything
        });

   return await Task.Run(() =>
        {
            for (int i = 0; i < seconds; i++)
            {
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
                Task.Delay(TimeSpan.FromSeconds(1)).Wait();
            }

            return "Foo Completed.";
        });
}

And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.

How do I make a fully statically linked .exe with Visual Studio Express 2005?

My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):

  1. Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".

  2. Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"

Not sure why both were needed. I used this to remove a dependency on glut32.dll.

Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.

Cmake doesn't find Boost

This can also happen if CMAKE_FIND_ROOT_PATH is set as different from BOOST_ROOT. I faced the same issue that in spite of setting BOOST_ROOT, I was getting the error. But for cross compiling for ARM I was using Toolchain-android.cmake in which I had (for some reason):

set(BOOST_ROOT "/home/.../boost")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --sysroot=${SYSROOT}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --sysroot=${SYSROOT} -I${SYSROOT}/include/libcxx")
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
set(CMAKE_FIND_ROOT_PATH "${SYSROOT}")

CMAKE_FIND_ROOT_PATH seems to be overriding BOOST_ROOT which was causing the issue.

How to remove leading zeros using C#

Using the following will return a single 0 when input is all 0.

string s = "0000000"
s = int.Parse(s).ToString();

jQuery detect if textarea is empty

Here is my working code

function emptyTextAreaCheck(textarea, submitButtonClass) {
        if(!submitButtonClass)
            submitButtonClass = ".transSubmit";

            if($(textarea).val() == '') {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            }

        $(textarea).live('focus keydown keyup', function(){
            if($(this).val().length == 0) {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            } else {
                $('.disabled_button').addClass('transSubmit').css({
                    'cursor':'pointer'
                }).removeClass('disabled_button');
            }
        });
    }

Copy table from one database to another

Another method that can be used to copy tables from the source database to the destination one is the SQL Server Export and Import wizard, which is available in SQL Server Management Studio.

You have the choice to export from the source database or import from the destination one in order to transfer the data.

This method is a quick way to copy tables from the source database to the destination one, if you arrange to copy tables having no concern with the tables’ relationships and orders.

When using this method, the tables’ indexes and keys will not be transferred. If you are interested in copying it, you need to generate scripts for these database objects.

If these are Foreign Keys, connecting these tables together, you need to export the data in the correct order, otherwise the export wizard will fail.

Feel free to read more about this method, as well as about some more methods (including generate scripts, SELECT INTO and third party tools) in this article: https://www.sqlshack.com/how-to-copy-tables-from-one-database-to-another-in-sql-server/

convert a list of objects from one type to another using lambda expression

We will consider first List type is String and want to convert it to Integer type of List.

List<String> origList = new ArrayList<>(); // assume populated

Add values in the original List.

origList.add("1");
origList.add("2");
    origList.add("3");
    origList.add("4");
    origList.add("8");

Create target List of Integer Type

List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());

Print List values using forEach:

    targetLambdaList.forEach(System.out::println);

Use a loop to plot n charts Python

Here are two examples of how to generate graphs in separate windows (frames), and, an example of how to generate graphs and save them into separate graphics files.

Okay, first the on-screen example. Notice that we use a separate instance of plt.figure(), for each graph, with plt.plot(). At the end, we have to call plt.show() to put it all on the screen.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace( 0,10 )

for n in range(3):
    y = np.sin( x+n )
    plt.figure()
    plt.plot( x, y )

plt.show()

Another way to do this, is to use plt.show(block=False) inside the loop:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace( 0,10 )

for n in range(3):
    y = np.sin( x+n )
    plt.figure()
    plt.plot( x, y )
    plt.show( block=False )

Now, let's generate the graphs and instead, write them each to a file. Here we replace plt.show(), with plt.savefig( filename ). The difference from the previous example is that we don't have to account for ''blocking'' at each graph. Note also, that we number the file names. Here we use %03d so that we can conveniently have them in number order afterwards.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace( 0,10 )

for n in range(3):
    y = np.sin( x+n )
    plt.figure()
    plt.plot( x, y )
    plt.savefig('myfilename%03d.png'%(n))

test attribute in JSTL <c:if> tag

The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:

<c:if test="true">
    <li>user</li>
</c:if>

and then the c:if tag would be executed.

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

PowerShell script to return versions of .NET Framework on a machine?

Added v4.8 support to the script:

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?![SW])\p{L}'} |
Select PSChildName, Version, Release, @{
  name="Product"
  expression={
      switch -regex ($_.Release) {
        "378389" { [Version]"4.5" }
        "378675|378758" { [Version]"4.5.1" }
        "379893" { [Version]"4.5.2" }
        "393295|393297" { [Version]"4.6" }
        "394254|394271" { [Version]"4.6.1" }
        "394802|394806" { [Version]"4.6.2" }
        "460798|460805" { [Version]"4.7" }
        "461308|461310" { [Version]"4.7.1" }
        "461808|461814" { [Version]"4.7.2" }
        "528040|528049" { [Version]"4.8" }
        {$_ -gt 528049} { [Version]"Undocumented version (> 4.8), please update script" }
      }
    }
}

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

In OS X Lion, LANG is not set to UTF-8, how to fix it?

if you have zsh installed you can also update ~/.zprofile with

if [[ -z "$LC_ALL" ]]; then
  export LC_ALL='en_US.UTF-8'
fi

and check the output using the locale cmd as show above

? locale                                                                                                                                           
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"

Disable cross domain web security in Firefox

For anyone finding this question while using Nightwatch.js (1.3.4), there's an acceptInsecureCerts: true setting in the config file:

_x000D_
_x000D_
firefox: {_x000D_
      desiredCapabilities: {_x000D_
        browserName: 'firefox',_x000D_
        alwaysMatch: {_x000D_
          // Enable this if you encounter unexpected SSL certificate errors in Firefox_x000D_
          acceptInsecureCerts: true,_x000D_
          'moz:firefoxOptions': {_x000D_
            args: [_x000D_
              // '-headless',_x000D_
              // '-verbose'_x000D_
            ],_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    },
_x000D_
_x000D_
_x000D_

varbinary to string on SQL Server

Try this

SELECT CONVERT(varchar(5000), yourvarbincolumn, 0)

IE 8: background-size fix

As posted by 'Dan' in a similar thread, there is a possible fix if you're not using a sprite:

How do I make background-size work in IE?

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

However, this scales the entire image to fit in the allocated area. So if your using a sprite, this may cause issues.

Caution
The filter has a flaw, any links inside the allocated area are no longer clickable.

Guid is all 0's (zeros)?

Can't tell you how many times this has caught. me.

Guid myGuid = Guid.NewGuid(); 

Strip out HTML and Special Characters

Remove all special character don't give space write in single line

trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', 
urldecode(html_entity_decode(strip_tags($string))))));

Python SQLite: database is locked

I had this problem while working with Pycharm and with a database that was originally given to me by another user.

So, this is how I solve it in my case:

  1. Closed all tabs in Pycharm that operate with the problematic database.
  2. Stop all running processes from the red square botton in the top right corner of Pycharm.
  3. Delete the problematic database from the directory.
  4. Upload again the original database. And it worked again.

How can I change the default Mysql connection timeout when connecting through python?

You change default value in MySQL configuration file (option connect_timeout in mysqld section) -

[mysqld]
connect_timeout=100

If this file is not accessible for you, then you can set this value using this statement -

SET GLOBAL connect_timeout=100;

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

If you came here searching OpenID Connect (OIDC): OAuth 2.0 != OIDC

I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)

OAuth 2.0 Access Tokens##

For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)

For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).

OIDC ID Tokens##

OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud claim in ID Tokens. (openid-connect-core-1.0)

aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.

furthermore OIDC specifies the azp claim that is used in conjunction with aud when aud has more than one value.

azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.

T-SQL loop over query results

try this:

declare @i tinyint = 0,
    @count tinyint,
    @id int,
    @name varchar(max)

select @count = count(*) from table
while (@i < @count)
begin
    select @id = id, @name = name from table
    order by nr asc offset @i rows fetch next 1 rows only

    exec stored_proc @varName = @id, @otherVarName = 'test', @varForName = @name

    set @i = @i + 1
end

How to use phpexcel to read data and insert into database?

Inci framework you can do download like so:

function clubDownload($clubname)
{

    $this->load->library("excel");

    $object = new PHPExcel();
    $object->setActiveSheetIndex(0);
    $this->load->model('Members_student_model');
    $query = $this->db->query("SELECT * FROM student WHERE $clubname!=''  order by id desc");
    $resultdatanew=$query->result_array();
    $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;

    $object->getActiveSheet()->getStyle("A1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("B1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');


    $object->getActiveSheet()->getStyle("C1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("D1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');


    $object->getActiveSheet()->getStyle("E1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("F1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');
    $object->getActiveSheet()->getStyle("G1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');

    $object->getActiveSheet()->getStyle("H1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');
    $object->getActiveSheet()->getStyle("I1")->getFont()->setBold(true)
                            ->setName('Verdana')
                            ->setSize(10)
                            ->getColor()->setRGB('330000');
    $headerStyle = array(
                'fill' => array(
                        'type' => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb'=>'CCE5FF'),
                ),
                'font' => array(
                        'bold' => true,
                )
        );

    $object->getActiveSheet()->getStyle('A1:'.'I1')->applyFromArray($headerStyle);
    $table_columns = array("id", "studentid", "passport", "lastname", "firstname","university","commencing",$clubname,"added_date");
    $column = 0;
    foreach($table_columns as $field)
    {
    $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
    $column++;
    }
    $excel_row = 2;




    foreach($resultdatanew as $row)
    {


                $id=$row['id'];
                $studentid=$row['studentid'];
                $passport=$row['passport'];
                $lastname=$row['last_name'];
                $firstname=$row['first_name'];
                $passport=$row['university'];
                $commencing=$row['commencing'];
                $email_id=$row['email_id'];
                $added_date=$row['added_date'];


                $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$id);

                $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $studentid);
                $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $passport);
                $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $lastname);
                $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $firstname);
                $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $passport);
                $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row,  $commencing);
                $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $email_id);
                $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $added_date);


                $excel_row++;
}

$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="club' .$clubname.'-'.date('Y-m-d') . '.xls');
$object_writer->save('php://output');

sorting a vector of structs

Use a comparison function:

bool compareByLength(const data &a, const data &b)
{
    return a.word.size() < b.word.size();
}

and then use std::sort in the header #include <algorithm>:

std::sort(info.begin(), info.end(), compareByLength);

How to fill a Javascript object literal with many static key/value pairs efficiently?

In ES2015 a.k.a ES6 version of JavaScript, a new datatype called Map is introduced.

let map = new Map([["key1", "value1"], ["key2", "value2"]]);
map.get("key1"); // => value1

check this reference for more info.

align divs to the bottom of their container

The way I solved this was using flexbox. By using flexbox to layout the contents of your container div, you can have flexbox automatically distribute free space to an item above the one you want to have "stick to the bottom".

For example, say this is your container div with some other block elements inside it, and that the blue box (third one down) is a paragraph and the purple box (last one) is the one you want to have "stick to the bottom".

enter image description here

By setting this layout up with flexbox, you can set flex-grow: 1; on just the paragraph (blue box) and, if it is the only thing with flex-grow: 1;, it will be allocated ALL of the remaining space, pushing the element(s) after it to the bottom of the container like this:

enter image description here

(apologies for the terrible, quick-and-dirty graphics)

PHPMyAdmin Default login password

Default is:

Username: root

Password: [null]

The Password is set to 'password' in some versions.

How do you use https / SSL on localhost?

It is easy to create a self-signed certificate, import it, and bind it to your website.

1.) Create a self-signed certificate:

Run the following 4 commands, one at a time, from an elevated Command Prompt:

cd C:\Program Files (x86)\Windows Kits\8.1\bin\x64

makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.3 -sv localhost.pvk localhost.cer

cert2spc localhost.cer localhost.spc

pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx

2.) Import certificate to Trusted Root Certification Authorities store:

start --> run --> mmc.exe --> Certificates plugin --> "Trusted Root Certification Authorities" --> Certificates

Right-click Certificates --> All Tasks --> Import Find your "localhost" Certificate at C:\Program Files (x86)\Windows Kits\8.1\bin\x64\

3.) Bind certificate to website:

start --> (IIS) Manager --> Click on your Server --> Click on Sites --> Click on your top level site --> Bindings

Add or edit a binding for https and select the SSL certificate called "localhost".

4.) Import Certificate to Chrome:

Chrome Settings --> Manage Certificates --> Import .pfx certificate from C:\certificates\ folder

Test Certificate by opening Chrome and navigating to https://localhost/

Auto refresh page every 30 seconds

Just a simple line of code in the head section can refresh the page

<meta http-equiv="refresh" content="30">

although its not a javascript function, its the simplest way to accomplish the above task hopefully.

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the difference between an argument and a parameter?

Logically speaking,we're actually talking about the same thing. But I think a simple metaphor would be helpful to solve this dilemma.

If the metaphors can be called various connection point we can equate them to plug points on a wall. In this case we can consider parameters and arguments as follows;

Parameters are the sockets of the plug-point which may take various different shapes. But only certain types of plugs fit them.
Arguments will be the actual plugs that would be plugged into the plug points/sockets to activate certain equipments.

Map HTML to JSON

I got few links sometime back while reading on ExtJS full framework in itself is JSON.

http://www.thomasfrank.se/xml_to_json.html

http://camel.apache.org/xmljson.html

online XML to JSON converter : http://jsontoxml.utilities-online.info/

UPDATE BTW, To get JSON as added in question, HTML need to have type & content tags in it too like this or you need to use some xslt transformation to add these elements while doing JSON conversion

<?xml version="1.0" encoding="UTF-8" ?>
<type>div</type>
<content>
    <type>span</type>
    <content>Text2</content>
</content>
<content>Text2</content>

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

Android changing Floating Action Button color

The FAB is colored based on your colorAccent.

<style name="AppTheme" parent="Base.Theme.AppCompat.Light">
    <item name="colorAccent">@color/accent</item>
</style>

Wait until boolean value changes it state

Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.

Integer any = new Integer(0);

public synchronized boolean waitTillChange() {
    any.wait();
    return true;
}

public synchronized void change() {
    any.notify();
}

Is there a constraint that restricts my generic method to numeric types?

Probably the closest you can do is

static bool IntegerFunction<T>(T value) where T: struct

Not sure if you could do the following

static bool IntegerFunction<T>(T value) where T: struct, IComparable
, IFormattable, IConvertible, IComparable<T>, IEquatable<T>

For something so specific, why not just have overloads for each type, the list is so short and it would possibly have less memory footprint.

How to get the date 7 days earlier date from current date in Java

Java now has a pretty good built-in date library, java.time bundled with Java 8.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Foo {
    public static void main(String[] args) {

        DateTimeFormatter format =
            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime then = now.minusDays(7);

        System.out.println(String.format(
            "Now:  %s\nThen: %s",
            now.format(format),
            then.format(format)
        ));
        /*
            Example output:
                Now:  2014-05-09T14:51:48Z
                Then: 2014-05-02T14:51:48Z
         */
    }
}

Get the second largest number in a list in linear time

If you do not mind using numpy (import numpy as np):

np.partition(numbers, -2)[-2]

gives you the 2nd largest element of the list with a guaranteed worst-case O(n) running time.

The partition(a, kth) methods returns an array where the kth element is the same it would be in a sorted array, all elements before are smaller, and all behind are larger.

How to add/update an attribute to an HTML element using JavaScript?

What do you want to do with the attribute? Is it an html attribute or something of your own?

Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

How to fix 'android.os.NetworkOnMainThreadException'?

NOTE : AsyncTask was deprecated in API level 30.
https://developer.android.com/reference/android/os/AsyncTask

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:

class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected RSSFeed doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader xmlreader = parser.getXMLReader();
            RssHandler theRSSHandler = new RssHandler();
            xmlreader.setContentHandler(theRSSHandler);
            InputSource is = new InputSource(url.openStream());
            xmlreader.parse(is);

            return theRSSHandler.getFeed();
        } catch (Exception e) {
            this.exception = e;

            return null;
        } finally {
            is.close();
        }
    }

    protected void onPostExecute(RSSFeed feed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

How to execute the task:

In MainActivity.java file you can add this line within your oncreate() method

new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>

window.location.href and window.open () methods in JavaScript

  • window.open will open a new browser with the specified URL.

  • window.location.href will open the URL in the window in which the code is called.

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties.

Extracting date from a string in Python

If you know the position of the date object in the string (for example in a log file), you can use .split()[index] to extract the date without fully knowing the format.

For example:

>>> string = 'monkey 2010-07-10 love banana'
>>> date = string.split()[1]
>>> date
'2010-07-10'

HTML/JavaScript: Simple form validation on submit

HTML Form Element Validation

Run Function

<script>
    $("#validationForm").validation({
         button: "#btnGonder",
         onSubmit: function () {
             alert("Submit Process");
         },
         onCompleted: function () {
             alert("onCompleted");
         },
         onError: function () {
             alert("Error Process");
         }
    });
</script>

Go to example and download https://github.com/naimserin/Validation.

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

#temp is materalized and CTE is not.

CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.

The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.

The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

What is ADT? (Abstract Data Type)

An abstract data type, sometimes abbreviated ADT, is a logical description of how we view the data and the operations that are allowed without regard to how they will be implemented. This means that we are concerned only with what the data is representing and not with how it will eventually be constructed.

https://runestone.academy/runestone/books/published/pythonds/Introduction/WhyStudyDataStructuresandAbstractDataTypes.html

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

Get class labels from Keras functional model

UPDATE: This is no longer valid for newer Keras versions. Please use argmax() as in the answer from Emilia Apostolova.

The functional API models have just the predict() function which for classification would return the class probabilities. You can then select the most probable classes using the probas_to_classes() utility function. Example:

y_proba = model.predict(x)
y_classes = keras.np_utils.probas_to_classes(y_proba)

This is equivalent to model.predict_classes(x) on the Sequential model.

The reason for this is that the functional API support more general class of tasks where predict_classes() would not make sense.

More info: https://github.com/fchollet/keras/issues/2524

"Unmappable character for encoding UTF-8" error

I'm in the process of setting up a CI build server on a Linux box for a legacy system started in 2000. There is a section that generates a PDF that contains non-UTF8 characters. We are in the final steps of a release, so I cannot replace the characters giving me grief, yet for Dilbertesque reasons, I cannot wait a week to solve this issue after the release. Fortunately, the "javac" command in Ant has an "encoding" parameter.

 <javac destdir="${classes.dir}" classpathref="production-classpath" debug="on"
     includeantruntime="false" source="${java.level}" target="${java.level}"

     encoding="iso-8859-1">

     <src path="${production.dir}" />
 </javac>

How to export a Hive table into a CSV file?

This is a much easier way to do it within Hive's SQL:

set hive.execution.engine=tez;
set hive.merge.tezfiles=true;
set hive.exec.compress.output=false;

INSERT OVERWRITE DIRECTORY '/tmp/job/'
ROW FORMAT DELIMITED
FIELDS TERMINATED by ','
NULL DEFINED AS ''
STORED AS TEXTFILE
SELECT * from table;

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem

Angular ui-grid dynamically calculate height of the grid

UPDATE:

The HTML was requested so I've pasted it below.

<div ui-grid="gridOptions" class="my-grid"></div>

ORIGINAL:

We were able to adequately solve this problem by using responsive CSS (@media) that sets the height and width based on screen real estate. Something like (and clearly you can add more based on your needs):

@media (min-width: 1024px) {
  .my-grid {
    width: 772px;
  }
}

@media (min-width: 1280px) {
  .my-grid {
    width: 972px;
  }
}

@media (min-height: 768px) {
  .my-grid {
    height: 480px;
  }
}

@media (min-height: 900px) {
  .my-grid {
    height: 615px;
  }
}

The best part about this solution is that we need no resize event handling to monitor for grid size changes. It just works.

Visualizing decision tree in scikit-learn

Simple way founded here with pydotplus (graphviz must be installed):

from IPython.display import Image  
from sklearn import tree
import pydotplus # installing pyparsing maybe needed

...

dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())

What do &lt; and &gt; stand for?

&lt; Less than: <

&gt; Greater than: >

Laravel Checking If a Record Exists

In laravel eloquent, has default exists() method, refer followed example.

if(User::where('id', $user_id )->exists()){ // your code... }

How do I get monitor resolution in Python?

For Linux, you can use this:

import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk

s = Gdk.Screen.get_default()
screen_width = s.get_width()
screen_height = s.get_height()
print(screen_width)
print(screen_height)

Need to get a string after a "word" in a string in c#

add this code to your project

  public static class Extension {
        public static string TextAfter(this string value ,string search) {
            return  value.Substring(value.IndexOf(search) + search.Length);
        }
  }

then use

"code : string text ".TextAfter(":")

Static variable inside of a function in C

Output: 6,7

Reason

The declaration of x is inside foo but the x=5 initialization takes place outside of foo!

What we need to understand here is that

static int x = 5;

is not the same as

static int x;
x = 5;

Other answers have used the important words here, scope and lifetime, and pointed out that the scope of x is from the point of its declaration in the function foo to the end of the function foo. For example I checked by moving the declaration to the end of the function, and that makes x undeclared at the x++; statement.

So the static int x (scope) part of the statement actually applies where you read it, somewhere INSIDE the function and only from there onwards, not above it inside the function.

However the x = 5 (lifetime) part of the statement is initialization of the variable and happening OUTSIDE of the function as part of the program loading. Variable x is born with a value of 5 when the program loads.

I read this in one of the comments: "Also, this doesn't address the really confusing part, which is the fact that the initializer is skipped on subsequent calls." It is skipped on all calls. Initialization of the variable is outside of the function code proper.

The value of 5 is theoretically set regardless of whether or not foo is called at all, although a compiler might optimize the function away if you don't call it anywhere. The value of 5 should be in the variable before foo is ever called.

Inside of foo, the statement static int x = 5; is unlikely to be generating any code at all.

I found the address x uses when I put a function foo into a program of mine, and then (correctly) guessed that the same location would be used if I ran the program again. The partial screen capture below shows that x has the value 5 even before the first call to foo.

Break Point before first call to foo

Resolve host name to an ip address

This is hard to answer without more detail about the network architecture. Some things to investigate are:

  • Is it possible that client and/or server is behind a NAT device, a firewall, or similar?
  • Is any of the IP addresses involved a "local" address, like 192.168.x.y or 10.x.y.z?
  • What are the host names, are they "real" DNS:able names or something more local and/or Windows-specific?
  • How does the client look up the server? There must be a place in code or config data that holds the host name, simply try using the IP there instead if you want to avoid the lookup.

What is an .inc and why use it?

This is a convention that programmer usually use to identify different file names for include files. So that if the other developers is working on their code, he can easily identify why this file is there and what is purpose of this file by just seeing the name of the file.

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Remove this line from your code:

console.info(JSON.parse(scatterSeries));

Inserting data into a temporary table

INSERT INTO #TempTable (ID, Date, Name) 
SELECT id, date, name 
FROM physical_table

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How do I check the difference, in seconds, between two dates?

Another approach is to use timestamp values:

end_time.timestamp() - start_time.timestamp()

keytool error bash: keytool: command not found

This worked for me

sudo apt install openjdk-8-jre-headless

Formatting PowerShell Get-Date inside string

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:

$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u") 

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

remove white space from the end of line in linux

Try using

cat kb.txt | sed -e 's/\s$//g'

How can I check that two objects have the same set of property names?

You can serialize simple data to check for equality:

data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)

This will give you something like

'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'

As a function...

function compare(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);

EDIT

If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section

EDIT 2

If you just want to check keys...

function compareKeys(a, b) {
  var aKeys = Object.keys(a).sort();
  var bKeys = Object.keys(b).sort();
  return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}

should do it.

"starting Tomcat server 7 at localhost has encountered a prob"

Hey i got the solution recently... Just copy the "ROOT" folder FROM C:\Program Files\ Apache Software Foundation\ Tomcat 7.0\ webapps \ TO your_Workspace\ .metadata\ .plugins\ org.eclipse.wst.server.core\ tmp0 \wtpwebapps\ and over write it when asked..

This is needed because eclipse forgets to copy that root folder to its workspace.. Just right click on Apache tomcat 7.0 in servers tab and observe that in location will be workspace metadata by default example:"location:[workspace metadata]". Therefore it will find the root folder which has the welcome page in it and the 404 page not found error will be displayed. Thankyou ..

How to get access to HTTP header information in Spring MVC REST controller?

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...
}

Boolean vs boolean in Java

One observation: (though this can be thought of side effect)

boolean being a primitive can either say yes or no.

Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

Model backing a DB Context has changed; Consider Code First Migrations

This happens when your table structure and model class no longer in sync. You need to update the table structure according to the model class or vice versa -- this is when your data is important and must not be deleted. If your data structure has changed and the data isn't important to you, you can use the DropCreateDatabaseIfModelChanges feature (formerly known as 'RecreateDatabaseIfModelChanges' feature) by adding the following code in your Global.asax.cs:

Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());

Run your application again.

As the name implies, this will drop your database and recreate according to your latest model class (or classes) -- provided you believe the table structure definitions in your model classes are the most current and latest; otherwise change the property definitions of your model classes instead.

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

Open Android Studio then go to gradle.properties file and change the last line to

org.gradle.jvmargs=-Xmx1024m.

And then press try again

WHERE clause on SQL Server "Text" data type

You can't compare against text with the = operator, but instead must used one of the comparison functions listed here. Also note the large warning box at the top of the page, it's important.

What exactly is Python's file.flush() doing?

Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.

Explanation of BASE terminology

  • Basic Availability: The database appears to work most of the time.

  • Soft State: Stores don’t have to be write-consistent or mutually consistent all the time.

  • Eventual consistency: Data should always be consistent, with regards how any number of changes are performed.

Python 3 turn range to a list

In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.

If I was to be the designer of Python3, I will:

  1. use irange to return a sequence iterator
  2. use lrange to return a sequence list
  3. use range to return either a sequence iterator (if the number of elements is large, e.g., range(9999999) or a sequence list (if the number of elements is small, e.g., range(10))

That should be optimal.

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

Python String and Integer concatenation

Concatenation of a string and integer is simple: just use

abhishek+str(2)

Splitting a string into chunks of a certain size

I think this is an straight forward answer:

public static IEnumerable<string> Split(this string str, int chunkSize)
    {
        if(string.IsNullOrEmpty(str) || chunkSize<1)
            throw new ArgumentException("String can not be null or empty and chunk size should be greater than zero.");
        var chunkCount = str.Length / chunkSize + (str.Length % chunkSize != 0 ? 1 : 0);
        for (var i = 0; i < chunkCount; i++)
        {
            var startIndex = i * chunkSize;
            if (startIndex + chunkSize >= str.Length)
                yield return str.Substring(startIndex);
            else
                yield return str.Substring(startIndex, chunkSize);
        }
    }

And it covers edge cases.

how to parse xml to java object?

JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,

<customer id="100">
    <age>29</age>
    <name>mkyong</name>
</customer>

Create necessary model class(es):

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

Try to unmarshal:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));

Check results, fix bugs!

Get only the date in timestamp in mysql

You can use date(t_stamp) to get only the date part from a timestamp.

You can check the date() function in the docs

DATE(expr)

Extracts the date part of the date or datetime expression expr.

mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'

How to get build time stamp from Jenkins build variables?

NOTE: This changed in Jenkins 1.597, Please see here for more info regarding the migration

You should be able to view all the global environment variables that are available during the build by navigating to https://<your-jenkins>/env-vars.html.

Replace https://<your-jenkins>/ with the URL you use to get to Jenkins webpage (for example, it could be http://localhost:8080/env-vars.html).

One of the environment variables is :

BUILD_ID
    The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)

If you use jenkins editable email notification, you should be able to use ${ENV, var="BUILD_ID"} in the subject line of your email.

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

Replacing objects in array

If you don't care about the order of the array, then you may want to get the difference between arr1 and arr2 by id using differenceBy() and then simply use concat() to append all the updated objects.

var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();

_x000D_
_x000D_
var arr1 = [{_x000D_
  id: '124',_x000D_
  name: 'qqq'_x000D_
}, {_x000D_
  id: '589',_x000D_
  name: 'www'_x000D_
}, {_x000D_
  id: '45',_x000D_
  name: 'eee'_x000D_
}, {_x000D_
  id: '567',_x000D_
  name: 'rrr'_x000D_
}]_x000D_
_x000D_
var arr2 = [{_x000D_
  id: '124',_x000D_
  name: 'ttt'_x000D_
}, {_x000D_
  id: '45',_x000D_
  name: 'yyy'_x000D_
}];_x000D_
_x000D_
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How can I use a C++ library from node.js?

You can use a node.js extension to provide bindings for your C++ code. Here is one tutorial that covers that:

http://syskall.com/how-to-write-your-own-native-nodejs-extension

How to get a substring between two strings in PHP?

Try this, Its work for me, get data between test word.

$str = "Xdata test HD01 test 1data";  
$result = explode('test',$str);   
print_r($result);
echo $result[1];

ICommand MVVM implementation

I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.

Teaser:

public class SampleViewModel: BaseViewModelStub
{
    public string Name { get; set; }

    [UiCommand]
    public void HelloWorld()
    {
        MessageBox.Show("Hello World!");
    }

    [UiCommand]
    public void Print()
    {
        MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
    }

    public bool CanPrint()
    {
        return !String.IsNullOrEmpty(Name);
    }
}

}

UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.

Unfortunately MyApp has stopped. How can I solve this?

Let me share a basic Logcat analysis for when you meet a Force Close (when the app stops working).

DOCS

The basic tool from Android to collect/analyze logs is the logcat.

HERE is the Android's page about logcat

If you use android Studio, you can also check this LINK.

Capturing

Basically, you can MANUALLY capture logcat with the following command (or just check AndroidMonitor window in AndroidStudio):

adb logcat

There's a lot of parameters you can add to the command which helps you to filter and display the message that you want... This is personal... I always use the command below to get the message timestamp:

adb logcat -v time

You can redirect the output to a file and analyze it in a Text Editor.

Analyzing

If you app is Crashing, you'll get something like:

07-09 08:29:13.474 21144-21144/com.example.khan.abc D/AndroidRuntime: Shutting down VM
07-09 08:29:13.475 21144-21144/com.example.khan.abc E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.khan.abc, PID: 21144
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.onBackPressed()' on a null object reference
     at com.example.khan.abc.AudioFragment$1.onClick(AudioFragment.java:125)
     at android.view.View.performClick(View.java:4848)
     at android.view.View$PerformClick.run(View.java:20262)
     at android.os.Handler.handleCallback(Handler.java:815)
     at android.os.Handler.dispatchMessage(Handler.java:104)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5631)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
07-09 08:29:15.195 21144-21144/com.example.khan.abc I/Process: Sending signal. PID: 21144 SIG: 9

This part of the log shows you a lot of information:

  • When the issue happened: 07-09 08:29:13.475

It is important to check when the issue happened... You may find several errors in a log... you must be sure that you are checking the proper messages :)

  • Which app crashed: com.example.khan.abc

This way, you know which app crashed (to be sure that you are checking the logs about your message)

  • Which ERROR: java.lang.NullPointerException

A NULL Pointer Exception error

  • Detailed info about the error: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.onBackPressed()' on a null object reference

You tried to call method onBackPressed() from a FragmentActivity object. However, that object was null when you did it.

  • Stack Trace: Stack Trace shows you the method invocation order... Sometimes, the error happens in the calling method (and not in the called method).

    at com.example.khan.abc.AudioFragment$1.onClick(AudioFragment.java:125)

Error happened in file com.example.khan.abc.AudioFragment.java, inside onClick() method at line: 125 (stacktrace shows the line that error happened)

It was called by:

at android.view.View.performClick(View.java:4848)

Which was called by:

at android.view.View$PerformClick.run(View.java:20262)

which was called by:

at android.os.Handler.handleCallback(Handler.java:815)

etc....

Overview

This was just an overview... Not all logs are simple but the error gives specific problem and verbose shows up all problem ... It is just to share the idea and provide entry-level information to you...

I hope I could help you someway... Regards

How to conclude your merge of a file?

I had the same error and i did followed article found on google solves my issue. You have not concluded your merge

What is a typedef enum in Objective-C?

The Typedef is a Keyword in C and C++. It is used to create new names for basic data types (char, int, float, double, struct & enum).

typedef enum {
    kCircle,
    kRectangle,
    kOblateSpheroid
} ShapeType;

Here it creates enumerated data type ShapeType & we can write new names for enum type ShapeType as given below

ShapeType shape1; 
ShapeType shape2; 
ShapeType shape3;

Checking if a key exists in a JS object

You can try this:

const data = {
  name : "Test",
  value: 12
}

if("name" in data){
  //Found
}
else {
  //Not found
}

Special characters like @ and & in cURL POST data

cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com

python pandas: apply a function with arguments to a series

You can pass any number of arguments to the function that apply is calling through either unnamed arguments, passed as a tuple to the args parameter, or through other keyword arguments internally captured as a dictionary by the kwds parameter.

For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.

s = pd.Series(np.random.randint(0,10, 10))
s

0    5
1    3
2    1
3    1
4    6
5    0
6    3
7    4
8    9
9    6
dtype: int64

s.apply(lambda x: x >= 3 and x <= 6)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7     True
8    False
9     True
dtype: bool

This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.

def between(x, low, high):
    return x >= low and x =< high

We can replicate the output of the first function by passing unnamed arguments to args:

s.apply(between, args=(3,6))

Or we can use the named arguments

s.apply(between, low=3, high=6)

Or even a combination of both

s.apply(between, args=(3,), high=6)

NodeJS / Express: what is "app.use"?

app.use is Application level middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

you can use to check all requests, for example, you want to check token/access token you need to write a middleware by using app.use to check the token in the request.

This example shows a middleware function with no mount path. The function is executed every time the app receives a request.

var app = express()

app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

reference from https://expressjs.com/en/guide/using-middleware.html

Download & Install Xcode version without Premium Developer Account

Yes,
You can download Xcode with/without Paid (Premium) Apple Developer Account from below links.

Xcode 11

Xcode 10


For non-premium account/apple id: (Download Xcode 10 without Paid (Premium) Apple Developer Account from below link)

Apple Download Portal

Look at here: How to install & set command line tool


See here for older versions of Xcode (Which may need to authenticate your apple account):

ECMAScript 6 arrow function that returns an object

ES6 Arrow Function returns an Object

the right ways

  1. normal function return an object

const getUser = user => {return { name: user.name, age: user.age };};

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

  1. (js expressions )

const getUser = user => ({ name: user.name, age: user.age });

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

explain

image

refs

https://github.com/lydiahallie/javascript-questions/issues/220

https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript

Creating an empty file in C#

File.WriteAllText("path", String.Empty);

or

File.CreateText("path").Close();

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

Check: key = undef !!!

You got also the warn message:

Each child in a list should have a unique "key" prop.

if your code is complete right, but if on

<MyComponent key={someValue} />

someValue is undefined!!! Please check this first. You can save hours.

Set initial focus in an Android application

@Someone Somewhere I used this to clear focus:

editText.clearFocus();

and it helps

mysql: SOURCE error 2?

If you are using vagrant ensure that the file is on the server and then use the path to the file. e.g if the file is stored in the public folder you will have

sql> source /var/www/public/xxx.sql

Where xxx is the name of the file

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.

ORA-00932: inconsistent datatypes: expected - got CLOB

You can't put a CLOB in the WHERE clause. From the documentation:

Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data.

If your values are always less than 4k, you can use:

UPDATE IMS_TEST 
   SET TEST_Category           = 'just testing'  
 WHERE to_char(TEST_SCRIPT)    = 'something'
   AND ID                      = '10000239';

It is strange to search by a CLOB anyways.. could you not just search by the ID column?

How to make node.js require absolute? (instead of relative)

Here is the actual way I'm doing for more than 6 months. I use a folder named node_modules as my root folder in the project, in this way it will always look for that folder from everywhere I call an absolute require:

  • node_modules
    • myProject
      • index.js I can require("myProject/someFolder/hey.js") instead of require("./someFolder/hey.js")
      • someFolder which contains hey.js

This is more useful when you are nested into folders and it's a lot less work to change a file location if is set in absolute way. I only use 2 the relative require in my whole app.

What is (x & 1) and (x >>= 1)?

It is similar to x = (x >> 1).

(operand1)(operator)=(operand2)  implies(=>)  (operand1)=(operand1)(operator)(operand2) 

It shifts the binary value of x by one to the right.

E.g.

int x=3;    // binary form (011) 
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
            // x=1, binary form (001)

C# event with custom arguments

public enum MyEvents
{
    Event1
}

public class CustomEventArgs : EventArgs
{
    public MyEvents MyEvents { get; set; }
}


private EventHandler<CustomEventArgs> onTrigger;

public event EventHandler<CustomEventArgs> Trigger
{
    add
    {
        onTrigger += value;
    }
    remove
    {
        onTrigger -= value;
    }
}

protected void OnTrigger(CustomEventArgs e)
{
    if (onTrigger != null)
    {
        onTrigger(this, e);
    }
}

How do I pass a string into subprocess.Popen (using the stdin argument)?

Beware that Popen.communicate(input=s)may give you trouble ifsis too big, because apparently the parent process will buffer it before forking the child subprocess, meaning it needs "twice as much" used memory at that point (at least according to the "under the hood" explanation and linked documentation found here). In my particular case,swas a generator that was first fully expanded and only then written tostdin so the parent process was huge right before the child was spawned, and no memory was left to fork it:

File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory

How to create Password Field in Model Django

Use widget as PasswordInput

from django import forms
class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = User

Definition of a Balanced Tree

There's no difference between these two things. Think about it.

Let's take a simpler definition, "A positive number is even if it is zero or that number minus two is even." Does this say 8 is even if 6 is even? Or does this say 8 is even if 6, 4, 2, and 0 are even?

There's no difference. If it says 8 is even if 6 is even, it also says 6 is even if 4 is even. And thus it also says 4 is even if 2 is even. And thus it says 2 is even if 0 is even. So if it says 8 is even if 6 is even, it (indirectly) says 8 is even if 6, 4, 2, and 0 are even.

It's the same thing here. Any indirect sub-tree can be found by a chain of direct sub-trees. So even if it only applies directly to direct sub-trees, it still applies indirectly to all sub-trees (and thus all nodes).

Autonumber value of last inserted row - MS Access / VBA

Both of the examples immediately above didn't work for me. Opening a recordset on the table and adding a record does work to add the record, except:

myLong = CLng(rs!AutoNumberField)

returns Null if put between rs.AddNew and rs.Update. If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value. Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.

myLong = DLookup("AutoNumberField","TableName","SomeCriteria")

will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.

How to provide animation when calling another activity in Android?

Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.

How can I have Github on my own server?

There are some open source alternatives:

How to do joins in LINQ on multiple fields in single join

Declare a Class(Type) to hold the elements you want to join. In the below example declare JoinElement

 public class **JoinElement**
{
    public int? Id { get; set; }
    public string Name { get; set; }

}

results = from course in courseQueryable.AsQueryable()
                  join agency in agencyQueryable.AsQueryable()
                   on new **JoinElement**() { Id = course.CourseAgencyId, Name = course.CourseDeveloper } 
                   equals new **JoinElement**() { Id = agency.CourseAgencyId, Name = "D" } into temp1

How to debug ORA-01775: looping chain of synonyms?

Step 1) See what Objects exist with the name:

select * from all_objects where object_name = upper('&object_name');

It could be that a Synonym exists but no Table?


Step 2) If that's not the problem, investigate the Synonym:

select * from all_synonyms where synonym_name = upper('&synonym_name');

It could be that an underlying Table or View to that Synonym is missing?

performSelector may cause a leak because its selector is unknown

Because you are using ARC you must be using iOS 4.0 or later. This means you could use blocks. If instead of remembering the selector to perform you instead took a block, ARC would be able to better track what is actually going on and you wouldn't have to run the risk of accidentally introducing a memory leak.

Jquery each - Stop loop and return object

Because when you use a return statement inside an each loop, a "non-false" value will act as a continue, whereas false will act as a break. You will need to return false from the each function. Something like this:

function findXX(word) {
    var toReturn; 
    $.each(someArray, function(i) {
        $('body').append('-> '+i+'<br />');
        if(someArray[i] == word) {
            toReturn = someArray[i];
            return false;
        }   
    }); 
    return toReturn; 
}

From the docs:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

How to switch Python versions in Terminal?

I have followed the below steps in Macbook.

  1. Open terminal
  2. type nano ~/.bash_profile and enter
  3. Now add the line alias python=python3
  4. Press CTRL + o to save it.
  5. It will prompt for file name Just hit enter and then press CTRL + x.
  6. Now check python version by using the command : python --version

SQL MERGE statement to update data

Assuming you want an actual SQL Server MERGE statement:

MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
    ON target.webmeterID = source.webmeterID
    AND target.DateTime = source.DateTime
WHEN MATCHED THEN 
    UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
    INSERT (webmeterID, DateTime, kWh)
    VALUES (source.webmeterID, source.DateTime, source.kWh);

If you also want to delete records in the target that aren't in the source:

MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
    ON target.webmeterID = source.webmeterID
    AND target.DateTime = source.DateTime
WHEN MATCHED THEN 
    UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
    INSERT (webmeterID, DateTime, kWh)
    VALUES (source.webmeterID, source.DateTime, source.kWh)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;

Because this has become a bit more popular, I feel like I should expand this answer a bit with some caveats to be aware of.

First, there are several blogs which report concurrency issues with the MERGE statement in older versions of SQL Server. I do not know if this issue has ever been addressed in later editions. Either way, this can largely be worked around by specifying the HOLDLOCK or SERIALIZABLE lock hint:

MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
[...]

You can also accomplish the same thing with more restrictive transaction isolation levels.

There are several other known issues with MERGE. (Note that since Microsoft nuked Connect and didn't link issues in the old system to issues in the new system, these older issues are hard to track down. Thanks, Microsoft!) From what I can tell, most of them are not common problems or can be worked around with the same locking hints as above, but I haven't tested them.

As it is, even though I've never had any problems with the MERGE statement myself, I always use the WITH (HOLDLOCK) hint now, and I prefer to use the statement only in the most straightforward of cases.

How to escape special characters in building a JSON string?

May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..

JSON.parse("\"'\"")

How to disable all <input > inside a form with jQuery?

Above example is technically incorrect. Per latest jQuery, use the prop() method should be used for things like disabled. See their API page.

To disable all form elements inside 'target', use the :input selector which matches all input, textarea, select and button elements.

$("#target :input").prop("disabled", true);

If you only want the elements, use this.

$("#target input").prop("disabled", true);

Use of *args and **kwargs

*args and **kwargs are special-magic features of Python. Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:

def sumFunction(*args):
  result = 0
  for x in args:
    result += x
  return result

and use it like: sumFunction(3,4,6,3,6,8,9).

**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.

def someFunction(**kwargs):
  if 'text' in kwargs:
    print kwargs['text']

Calling someFunction(text="foo") will print foo.

Gson: Directly convert String to JsonObject (no POJO)

I believe this is a more easy approach:

public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{

    public JsonElement serialize(HibernateProxy object_,
        Type type_,
        JsonSerializationContext context_) {
        return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
        // that will convert enum object to its ordinal value and convert it to json element

    }

    public static <T> T initializeAndUnproxy(T entity) {
        if (entity == null) {
            throw new 
               NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(entity);
        if (entity instanceof HibernateProxy) {
            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                    .getImplementation();
        }
        return entity;
    }
}

And then you will be able to call it like this:

Gson gson = new GsonBuilder()
        .registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
        .create();

This way all the hibernate objects will be converted automatically.

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:

#!/usr/bin/perl

use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.

=cut

print "Multi Line Comment Example \n";

How can I add a new column and data to a datatable that already contains data?

Just keep going with your code - you're on the right track:

//call SQL helper class to get initial data 
DataTable dt = sql.ExecuteDataTable("sp_MyProc");

dt.Columns.Add("NewColumn", typeof(System.Int32));

foreach(DataRow row in dt.Rows)
{
    //need to set value to NewColumn column
    row["NewColumn"] = 0;   // or set it to some other value
}

// possibly save your Dataset here, after setting all the new values

Border around each cell in a range

You only need a single line of code to set the border around every cell in the range:

Range("A1:F20").Borders.LineStyle = xlContinuous

It's also easy to apply multiple effects to the border around each cell.

For example:

Sub RedOutlineCells()
    Dim rng As Range

    Set rng = Range("A1:F20")

    With rng.Borders
        .LineStyle = xlContinuous
        .Color = vbRed
        .Weight = xlThin
    End With
End Sub

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

Iterating through populated rows

For the benefit of anyone searching for similar, see worksheet .UsedRange,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

How to compare Boolean?

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

flow 2 columns of text automatically with CSS

Use CSS3

.container {
   -webkit-column-count: 2;
      -moz-column-count: 2;
           column-count: 2;

   -webkit-column-gap: 20px;
      -moz-column-gap: 20px;
           column-gap: 20px;
}

Browser Support

  • Chrome 4.0+ (-webkit-)
  • IE 10.0+
  • Firefox 2.0+ (-moz-)
  • Safari 3.1+ (-webkit-)
  • Opera 15.0+ (-webkit-)

iFrame onload JavaScript event

Update

As of jQuery 3.0, the new syntax is just .on:

see this answer here and the code:

$('iframe').on('load', function() {
    // do stuff 
});

How do I escape the wildcard/asterisk character in bash?

SHORT ANSWER

Like others have said - you should always quote the variables to prevent strange behaviour. So use echo "$foo" in instead of just echo $foo.

LONG ANSWER

I do think this example warrants further explanation because there is more going on than it might seem on the face of it.

I can see where your confusion comes in because after you ran your first example you probably thought to yourself that the shell is obviously doing:

  1. Parameter expansion
  2. Filename expansion

So from your first example:

me$ FOO="BAR * BAR"
me$ echo $FOO

After parameter expansion is equivalent to:

me$ echo BAR * BAR

And after filename expansion is equivalent to:

me$ echo BAR file1 file2 file3 file4 BAR

And if you just type echo BAR * BAR into the command line you will see that they are equivalent.

So you probably thought to yourself "if I escape the *, I can prevent the filename expansion"

So from your second example:

me$ FOO="BAR \* BAR"
me$ echo $FOO

After parameter expansion should be equivalent to:

me$ echo BAR \* BAR

And after filename expansion should be equivalent to:

me$ echo BAR \* BAR

And if you try typing "echo BAR \* BAR" directly into the command line it will indeed print "BAR * BAR" because the filename expansion is prevented by the escape.

So why did using $foo not work?

It's because there is a third expansion that takes place - Quote Removal. From the bash manual quote removal is:

After the preceding expansions, all unquoted occurrences of the characters ‘\’, ‘'’, and ‘"’ that did not result from one of the above expansions are removed.

So what happens is when you type the command directly into the command line, the escape character is not the result of a previous expansion so BASH removes it before sending it to the echo command, but in the 2nd example, the "\*" was the result of a previous Parameter expansion, so it is NOT removed. As a result, echo receives "\*" and that's what it prints.

Note the difference between the first example - "*" is not included in the characters that will be removed by Quote Removal.

I hope this makes sense. In the end the conclusion in the same - just use quotes. I just thought I'd explain why escaping, which logically should work if only Parameter and Filename expansion are at play, didn't work.

For a full explanation of BASH expansions, refer to:

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions

Print the data in ResultSet along with column names

Have a look at the documentation. You made the following mistakes. Firstly, ps.executeQuery() doesn't have any parameters. Instead you passed the SQL query into it.

Secondly, regarding the prepared statement, you have to use the ? symbol if want to pass any parameters. And later bind it using

setXXX(index, value) 

Here xxx stands for the data type.

How to set only time part of a DateTime variable in C#

date = new DateTime(date.year, date.month, date.day, HH, MM, SS);

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

MySQL Insert query doesn't work with WHERE clause

Insert query doesn't support where keyword*

Conditions apply because you can use where condition for sub-select statements. You can perform complicated inserts using sub-selects.

For example:

INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';

By placing a "select" in the insert statement, you can perform multiples inserts quickly.

With this type of insert, you may wish to check for the number of rows being inserted. You can determine the number of rows that will be inserted by running the following SQL statement before performing the insert.

SELECT count(*)
FROM customers
WHERE city = 'Newark';

You can make sure that you do not insert duplicate information by using the EXISTS condition.

For example, if you had a table named clients with a primary key of client_id, you could use the following statement:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);

This statement inserts multiple records with a subselect.

If you wanted to insert a single record, you could use the following statement:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);

The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.

See also How to insert with where clause

Sending email with PHP from an SMTP server

<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "[email protected]");

$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = [email protected]";

$headers = "From: [email protected]";

mail("[email protected]", "Testing", $message, $headers);
echo "Check your email now....&lt;BR/>";
?>

or, for more details, read on.

installing vmware tools: location of GCC binary?

to avoid the problem with CDROM: sudo nano /etc/apt/sources.list

find your cdrom and comment it with #

save the changes: "cntrl + o", than exit the file: "cntrl + x"

and try to install again

What is a C++ delegate?

You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.


Option 1 : functors:

A function object may be created by implementing operator()

struct Functor
{
     // Normal class/struct members

     int operator()(double d) // Arbitrary return types and parameter list
     {
          return (int) d + 1;
     }
};

// Use:
Functor f;
int i = f(3.14);

Option 2: lambda expressions (C++11 only)

// Syntax is roughly: [capture](parameter list) -> return type {block}
// Some shortcuts exist
auto func = [](int i) -> double { return 2*i/1.15; };
double d = func(1);

Option 3: function pointers

int f(double d) { ... }
typedef int (*MyFuncT) (double d);
MyFuncT fp = &f;
int a = fp(3.14);

Option 4: pointer to member functions (fastest solution)

See Fast C++ Delegate (on The Code Project).

struct DelegateList
{
     int f1(double d) { }
     int f2(double d) { }
};

typedef int (DelegateList::* DelegateType)(double d);

DelegateType d = &DelegateList::f1;
DelegateList list;
int a = (list.*d)(3.14);

Option 5: std::function

(or boost::function if your standard library doesn't support it). It is slower, but it is the most flexible.

#include <functional>
std::function<int(double)> f = [can be set to about anything in this answer]
// Usually more useful as a parameter to another functions

Option 6: binding (using std::bind)

Allows setting some parameters in advance, convenient to call a member function for instance.

struct MyClass
{
    int DoStuff(double d); // actually a DoStuff(MyClass* this, double d)
};

std::function<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
// auto f = std::bind(...); in C++11

Option 7: templates

Accept anything as long as it matches the argument list.

template <class FunctionT>
int DoSomething(FunctionT func)
{
    return func(3.14);
}

How to calculate cumulative normal distribution?

Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with mean and std (which is sqr(var)) and you want to calculate:

from scipy.stats import norm

# cdf(x < val)
print norm.cdf(val, m, s)

# cdf(x > val)
print 1 - norm.cdf(val, m, s)

# cdf(v1 < x < v2)
print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)

Read more about cdf here and scipy implementation of normal distribution with many formulas here.

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

Select Pandas rows based on list index

For large datasets, it is memory efficient to read only selected rows via the skiprows parameter.

Example

pred = lambda x: x not in [1, 3]
pd.read_csv("data.csv", skiprows=pred, index_col=0, names=...)

This will now return a DataFrame from a file that skips all rows except 1 and 3.


Details

From the docs:

skiprows : list-like or integer or callable, default None

...

If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lambda x: x in [0, 2]

This feature works in version pandas 0.20.0+. See also the corresponding issue and a related post.

How to create an Observable from static data similar to http one in Angular?

This is how you can create a simple observable for static data.

let observable = Observable.create(observer => {
  setTimeout(() => {
    let users = [
      {username:"balwant.padwal",city:"pune"},
      {username:"test",city:"mumbai"}]

    observer.next(users); // This method same as resolve() method from Angular 1
    console.log("am done");
    observer.complete();//to show we are done with our processing
    // observer.error(new Error("error message"));
  }, 2000);

})

to subscribe to it is very easy

observable.subscribe((data)=>{
  console.log(data); // users array display
});

I hope this answer is helpful. We can use HTTP call instead static data.

IE6/IE7 css border on select element

I've worked around the inability to put a border on the select in IE7 (IE8 in compatibility mode)

By giving it a border as wel as a padding, it looks like something....

Not everything, but it's start...

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Limit the length of a string with AngularJS

The simplest solution I found for simply limiting the string length was {{ modal.title | slice:0:20 }}, and then borrowing from @Govan above you can use {{ modal.title.length > 20 ? '...' : ''}} to add the suspension points if the string is longer than 20, so the final result is simply:

{{ modal.title | slice:0:20 }}{{ modal.title.length > 20 ? '...' : ''}}

https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html