Programs & Examples On #Importerror

Refers to errors that result from attempting to import a module or library into one's code

ImportError: cannot import name main when running pip --version command in windows7 32 bit

A simple solution that works with Ubuntu, but may fix the problem on windows too:

Just call

pip install --upgrade pip

ImportError: DLL load failed: %1 is not a valid Win32 application

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

"ImportError: No module named" when trying to run Python script

This is probably caused by different python versions installed on your system, i.e. python2 or python3.

Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x. E.g. you should see version information like below:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Then run the example.py script with below command

$ python3 example.py

Python error "ImportError: No module named"

I've found that changing the name (via GUI) of aliased folders (Mac) can cause issues with loading modules. If the original folder name is changed, remake the symbolic link. I'm unsure how prevalent this behavior may be, but it was frustrating to debug.

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Verify if cv2.so did compile, should be placed in: /usr/local/lib/python2.7/site-packages Then export that path like this

export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH

Same as in the answer here

ImportError: No Module Named bs4 (BeautifulSoup)

I have been searching far and wide in the internet.

I'm using Python 3.6 and MacOS. I have uninstalled and installed with pip3 install bs4 but that didn't work. It seems like python is not able to detect or search the bs4 module.

This is what worked: python3 -m pip install bs4

The -m option allows you to add a module name.

https://docs.python.org/3/using/cmdline.html

How to fix "Attempted relative import in non-package" even with __init__.py

To elaborate on Ignacio Vazquez-Abrams's answer:

The Python import mechanism works relative to the __name__ of the current file. When you execute a file directly, it doesn't have its usual name, but has "__main__" as its name instead. So relative imports don't work.

You can, as Igancio suggested, execute it using the -m option. If you have a part of your package that is meant to be run as a script, you can also use the __package__ attribute to tell that file what name it's supposed to have in the package hierarchy.

See http://www.python.org/dev/peps/pep-0366/ for details.

ImportError: No module named 'bottle' - PyCharm

In some cases no "No module ..." can appear even on local files. In such cases you just need to mark appropriate directories as "source directories":

Mark as source lib directory

"ImportError: no module named 'requests'" after installing with pip

if it works when you do :

python
>>> import requests

then it might be a mismatch between a previous version of python on your computer and the one you are trying to use

in that case : check the location of your working python:

which python And get sure it is matching the first line in your python code

#!<path_from_which_python_command>

ImportError: No module named six

I did the following to solve the mentioned problem. I got the mentioned problem when I was trying to run the built exe, even I successfully built the exe using pyinstaller. I did this on Windows 10.

  1. go to https://pypi.org/project/six/#files
  2. download "six-1.14.0.tar.gz (33.9 kB)"
  3. unzip it, copy and paste "six.py" into your source directory.
  4. import "six" module into your source code (import six)
  5. run source script.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

May be the problem is with your python-opencv version. It's better to downgrade your version to 3.3.0.9 which does not include any GUI dependencies. Same question was found on GitHub here the link to the answer.

ImportError: Cannot import name X

Don't see this one here yet - this is incredibly stupid, but make sure you're importing the correct variable/function.

I was getting this error

ImportError: cannot import name IMPLICIT_WAIT

because my variable was actually IMPLICIT_TIMEOUT.

when I changed my import to use the correct name, I no longer got the error ???

Python ImportError: No module named wx

Download the .whl file from this link.

The name of the file is: wxPython-3.0.2.0-cp27-none-win32.whl for Windows 32 bit and python 2.7 and wxPython-3.0.2.0-cp27-none-win_amd64.whl for Windows 64 bit and python 2.7.

Then in the command prompt: pip install location-of-the-above-saved-file

Why can't Python import Image from PIL?

I had the same problem, pillow was installed with an environment.yml in anaconda

I am quickly learning that pip and setuptools must always be up to date or I will have problems. Always update these tools before installing packages.For any package import problem uninstall the package upgrade the listed tools(maybe even your base environment) and reinstall.

conda uninstall pillow
python -m pip install pip --upgrade
pip install setuptools --upgrade
pip install pillow

If using Anaconda, from the base environment first run the following before installing packages/environments:

conda update conda

Updating the base env is not required to fix this issue but is a good practice to avoid similar problems

@theeastcoastwest touched on the pip upgrade in their answer but I felt more information was needed

Importing files from different folder

First import sys in name-file.py

 import sys

Second append the folder path in name-file.py

sys.path.insert(0, '/the/folder/path/name-package/')

Third Make a blank file called __ init __.py in your subdirectory (this tells Python it is a package)

  • name-file.py
  • name-package
    • __ init __.py
    • name-module.py

Fourth import the module inside the folder in name-file.py

from name-package import name-module

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

change PYTHONHOME to the parent folder of the bin file of python, like /usr,which is the parent folder of /usr/bin.

Error in MySQL when setting default value for DATE or DATETIME

I got into a situation where the data was mixed between NULL and 0000-00-00 for a date field. But I did not know how to update the '0000-00-00' to NULL, because

 update my_table set my_date_field=NULL where my_date_field='0000-00-00'

is not allowed any more. My workaround was quite simple:

update my_table set my_date_field=NULL where my_date_field<'1000-01-01'

because all the incorrect my_date_field values (whether correct dates or not) were from before this date.

How to open .SQLite files

My favorite:

https://inloop.github.io/sqlite-viewer/

No installation needed. Just drop the file.

global variable for all controller and views

Most popular answers here with BaseController didn't worked for me on Laravel 5.4, but they have worked on 5.3. No idea why.

I have found a way which works on Laravel 5.4 and gives variables even for views which are skipping controllers. And, of course, you can get variables from the database.

add in your app/Providers/AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Using view composer to set following variables globally
        view()->composer('*',function($view) {
            $view->with('user', Auth::user());
            $view->with('social', Social::all()); 
            // if you need to access in controller and views:
            Config::set('something', $something); 
        });
    }
}

credit: http://laraveldaily.com/global-variables-in-base-controller/

Run PHP Task Asynchronously

It's a great idea to use cURL as suggested by rojoca.

Here is an example. You can monitor text.txt while the script is running in background:

<?php

function doCurl($begin)
{
    echo "Do curl<br />\n";
    $url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $url = preg_replace('/\?.*/', '', $url);
    $url .= '?begin='.$begin;
    echo 'URL: '.$url.'<br>';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    echo 'Result: '.$result.'<br>';
    curl_close($ch);
}


if (empty($_GET['begin'])) {
    doCurl(1);
}
else {
    while (ob_get_level())
        ob_end_clean();
    header('Connection: close');
    ignore_user_abort();
    ob_start();
    echo 'Connection Closed';
    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush();
    flush();

    $begin = $_GET['begin'];
    $fp = fopen("text.txt", "w");
    fprintf($fp, "begin: %d\n", $begin);
    for ($i = 0; $i < 15; $i++) {
        sleep(1);
        fprintf($fp, "i: %d\n", $i);
    }
    fclose($fp);
    if ($begin < 10)
        doCurl($begin + 1);
}

?>

How to put a link on a button with bootstrap?

You can call a function on click event of button.

<input type="button" class="btn btn-info" value="Input Button" onclick=" relocate_home()">

<script>
function relocate_home()
{
     location.href = "www.yoursite.com";
} 
</script>

OR Use this Code

<a href="#link" class="btn btn-info" role="button">Link Button</a>

Auto expand a textarea using jQuery

Let's say you're trying to accomplish this using Knockout... here's how:

In page:

<textarea data-bind="event: { keyup: $root.GrowTextArea }"></textarea>

In view model:

self.GrowTextArea = function (data, event) {
    $('#' + event.target.id).height(0).height(event.target.scrollHeight);
}

This should work even if you have multiple textareas created by a Knockout foreach like I do.

$watch'ing for data changes in an Angular directive

Because if you want to trigger your data with deep of it,you have to pass 3th argument true of your listener.By default it's false and it meens that you function will trigger,only when your variable will change not it's field.

Syntax behind sorted(key=lambda: ...)

Just to rephrase, the key (Optional. A Function to execute to decide the order. Default is None) in sorted functions expects a function and you use lambda.

To define lambda, you specify the object property you want to sort and python's built-in sorted function will automatically take care of it.

If you want to sort by multiple properties then assign key = lambda x: (property1, property2).

To specify order-by, pass reverse= true as the third argument(Optional. A Boolean. False will sort ascending, True will sort descending. Default is False) of sorted function.

Read a text file line by line in Qt

Use this code:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}

break statement in "if else" - java

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

Link to the issue number on GitHub within a commit message

One of my first projects as a programmer was a gem called stagecoach that (among other things) allowed the automatic adding of a github issue number to every commit message on a branch, which is a part of the question that hasn't really been answered.

Essentially when creating a branch you'd use a custom command (something like stagecoach -b <branch_name> -g <issue_number>), and the issue number would then be assigned to that branch in a yml file. There was then a commit hook that appended the issue number to the commit message automatically.

I wouldn't recommend it for production use as at the time I'd only been programming for a few months and I no longer maintain it, but it may be of interest to somebody.

Parse usable Street Address, City, State, Zip from a string

I've done a lot of work on this kind of parsing. Because there are errors you won't get 100% accuracy, but there are a few things you can do to get most of the way there, and then do a visual BS test. Here's the general way to go about it. It's not code, because it's pretty academic to write it, there's no weirdness, just lots of string handling.

(Now that you've posted some sample data, I've made some minor changes)

  1. Work backward. Start from the zip code, which will be near the end, and in one of two known formats: XXXXX or XXXXX-XXXX. If this doesn't appear, you can assume you're in the city, state portion, below.
  2. The next thing, before the zip, is going to be the state, and it'll be either in a two-letter format, or as words. You know what these will be, too -- there's only 50 of them. Also, you could soundex the words to help compensate for spelling errors.
  3. before that is the city, and it's probably on the same line as the state. You could use a zip-code database to check the city and state based on the zip, or at least use it as a BS detector.
  4. The street address will generally be one or two lines. The second line will generally be the suite number if there is one, but it could also be a PO box.
  5. It's going to be near-impossible to detect a name on the first or second line, though if it's not prefixed with a number (or if it's prefixed with an "attn:" or "attention to:" it could give you a hint as to whether it's a name or an address line.

I hope this helps somewhat.

How to trigger jQuery change event in code

for me $('#element').val('...').change() is the best way.

docker entrypoint running bash script gets "permission denied"

This is an old question asked two years prior to my answer, I am going to post what worked for me anyways.

In my working directory I have two files: Dockerfile & provision.sh

Dockerfile:

FROM centos:6.8

# put the script in the /root directory of the container
COPY provision.sh /root

# execute the script inside the container
RUN /root/provision.sh

EXPOSE 80

# Default command
CMD ["/bin/bash"]

provision.sh:

#!/usr/bin/env bash

yum upgrade

I was able to make the file in the docker container executable by setting the file outside the container as executable chmod 700 provision.sh then running docker build . .

Sort a list of tuples by 2nd item (integer value)

For a lambda-avoiding method, first define your own function:

def MyFn(a):
    return a[1]

then:

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=MyFn)

How to find the date of a day of the week from a date using PHP?

<?php echo date("H:i", time()); ?>
<?php echo $days[date("l", time())] . date(", d.m.Y", time()); ?>

Simple, this should do the trick

Is there a MySQL option/feature to track history of changes to records?

You could create triggers to solve this. Here is a tutorial to do so (archived link).

Setting constraints and rules in the database is better than writing special code to handle the same task since it will prevent another developer from writing a different query that bypasses all of the special code and could leave your database with poor data integrity.

For a long time I was copying info to another table using a script since MySQL didn’t support triggers at the time. I have now found this trigger to be more effective at keeping track of everything.

This trigger will copy an old value to a history table if it is changed when someone edits a row. Editor ID and last mod are stored in the original table every time someone edits that row; the time corresponds to when it was changed to its current form.

DROP TRIGGER IF EXISTS history_trigger $$

CREATE TRIGGER history_trigger
BEFORE UPDATE ON clients
    FOR EACH ROW
    BEGIN
        IF OLD.first_name != NEW.first_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'first_name',
                        NEW.first_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

        IF OLD.last_name != NEW.last_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'last_name',
                        NEW.last_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

    END;
$$

Another solution would be to keep an Revision field and update this field on save. You could decide that the max is the newest revision, or that 0 is the most recent row. That's up to you.

Check if one date is between two dates

Try what's below. It will help you...

Fiddle : http://jsfiddle.net/RYh7U/146/

Script :

if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
    alert("Availed");
else
    alert("Not Availed");

function dateCheck(from,to,check) {

    var fDate,lDate,cDate;
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);

    if((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

How do you find the current user in a Windows environment?

In a standard context, each connected user holds an explorer.exe process: The command [tasklist /V|find "explorer"] returns a line that contains the explorer.exe process owner's, with an adapted regex it is possible to obtain the required value. This also runs perfectly under Windows 7.

In rare cases explorer.exe is replaced by another program, the find filter can be adapted to match this case. If the command return an empty line then it is likely that no user is logged on. With Windows 7 it is also possible to run [query session|find ">"].

How to revert to origin's master branch's version of file

Assuming you did not commit the file, or add it to the index, then:

git checkout -- filename

Assuming you added it to the index, but did not commit it, then:

git reset HEAD filename
git checkout -- filename

Assuming you did commit it, then:

git checkout origin/master filename

Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):

git reset --hard origin/master

How can I check file size in Python?

You need the st_size property of the object returned by os.stat. You can get it by either using pathlib (Python 3.4+):

>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564

or using os.stat:

>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564

Output is in bytes.

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

Simpler way (if your only keyword is "code" ) may be:

string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();

Proper MIME type for OTF fonts

There are a number of font formats that one can set MIME types for, on both Apache and IIS servers. I've traditionally had luck with the following:

svg   as "image/svg+xml"                  (W3C: August 2011)
ttf   as "application/x-font-ttf"         (IANA: March 2013)
      or "application/x-font-truetype"
otf   as "application/x-font-opentype"    (IANA: March 2013)
woff  as "application/font-woff"          (IANA: January 2013)
woff2 as "application/font-woff2"         (W3C W./E.Draft: May 2014/March 2016)
eot   as "application/vnd.ms-fontobject"  (IANA: December 2005)
sfnt  as "application/font-sfnt"          (IANA: March 2013) 

According to the Internet Engineering Task Force who maintain the initial document regarding Multipurpose Internet Mail Extensions (MIME types) here: http://tools.ietf.org/html/rfc2045#section-5 ... it says in specifics:

"It is expected that additions to the larger set of supported types can generally be accomplished by the creation of new subtypes of these initial types. In the future, more top-level types may be defined only by a standards-track extension to this standard. If another top-level type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid a potential conflict with a future official name."

As it were, and over time, additional MIME types get added as standards are created and accepted, therefor we see examples of vendor specific MIME types such as vnd.ms-fontobject and the like.

UPDATE August 16, 2013: WOFF was formally registered at IANA on January 3, 2013 and Webkit has been updated on March 5, 2013 and browsers that are sourcing this update in their latest versions will start issuing warnings about the server MIME types with the old x-font-woff declaration. Since the warnings are only annoying I would recommend switching to the approved MIME type right away. In an ideal world, the warnings will resolve themselves in time.

UPDATE February 26, 2015: WOFF2 is now in the W3C Editor's Draft with the proposed mime-type. It should likely be submitted to IANA in the next year (possibly by end of 2016) following more recent progress timelines. As well SFNT, the scalable/spline container font format used in the backbone table reference of Google Web Fonts with their sfntly java library and is already registered as a mime type with IANA and could be added to this list as well dependent on individual need.

UPDATE October 4, 2017: We can follow the progression of the WOFF2 format here with a majority of modern browsers supporting the format successfully. As well, we can follow the IETF's "font" Top-Level Media Type request for comments (RFC) tracker and document regarding the latest set of proposed font types for approval.


For those wishing to embed the typeface in the proper order in your CSS please visit this article. But again, I've had luck with the following order:

@font-face {
    font-family: 'my-web-font';
    src: url('webfont.eot');
    src: url('webfont.eot?#iefix') format('embedded-opentype'),
         url('webfont.woff2') format('woff2'),
         url('webfont.woff') format('woff'),
         url('webfont.ttf') format('truetype'),
         url('webfont.svg#webfont') format('svg');
    font-weight: normal;
    font-style: normal;
}

For Subversion auto-properties, these can be listed as:

# Font formats
svg   = svn:mime-type=image/svg+xml
ttf   = svn:mime-type=application/x-font-ttf
otf   = svn:mime-type=application/x-font-opentype
woff  = svn:mime-type=application/font-woff
woff2 = svn:mime-type=application/font-woff2
eot   = svn:mime-type=application/vnd.ms-fontobject
sfnt  = svn:mime-type=application/font-sfnt

Facebook database design?

Keep a friend table that holds the UserID and then the UserID of the friend (we will call it FriendID). Both columns would be foreign keys back to the Users table.

Somewhat useful example:

Table Name: User
Columns:
    UserID PK
    EmailAddress
    Password
    Gender
    DOB
    Location

TableName: Friends
Columns:
    UserID PK FK
    FriendID PK FK
    (This table features a composite primary key made up of the two foreign 
     keys, both pointing back to the user table. One ID will point to the
     logged in user, the other ID will point to the individual friend
     of that user)

Example Usage:

Table User
--------------
UserID EmailAddress Password Gender DOB      Location
------------------------------------------------------
1      [email protected]  bobbie   M      1/1/2009 New York City
2      [email protected]  jonathan M      2/2/2008 Los Angeles
3      [email protected]  joseph   M      1/2/2007 Pittsburgh

Table Friends
---------------
UserID FriendID
----------------
1      2
1      3
2      3

This will show that Bob is friends with both Jon and Joe and that Jon is also friends with Joe. In this example we will assume that friendship is always two ways, so you would not need a row in the table such as (2,1) or (3,2) because they are already represented in the other direction. For examples where friendship or other relations aren't explicitly two way, you would need to also have those rows to indicate the two-way relationship.

Angular 2 - innerHTML styling

The simple solution you need to follow is

import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer){}

transformYourHtml(htmlTextWithStyle) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

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

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

How to download PDF automatically using js?

  1. for second point, get a full path to pdf file into some java variable. e.g. http://www.domain.com/files/filename.pdf

e.g. you're using php and $filepath contains pdf file path.

so you can write javascript like to to emulate download dialog box.

<script language="javascript">
    window.location.href = '<?php echo $filepath; ?>';
</script

Above code sends browser to pdf file by its url "http://www.domain.com/files/filename.pdf". So at last, browser will show download dialog box to where to save this file on your machine.

Ignore Typescript Errors "property does not exist on value of type"

There are several ways to handle this problem. If this object is related to some external library, the best solution would be to find the actual definitions file (great repository here) for that library and reference it, e.g.:

/// <reference path="/path/to/jquery.d.ts" >

Of course, this doesn't apply in many cases.

If you want to 'override' the type system, try the following:

declare var y;

This will let you make any calls you want on var y.

Is there a C++ decompiler?

Yes, but none of them will manage to produce readable enough code to worth the effort. You will spend more time trying to read the decompiled source with assembler blocks inside, than rewriting your old app from scratch.

How do I convert a column of text URLs into active hyperlinks in Excel?

Easiest way here

  • Highlight the whole column
  • click ''insert''
  • click ''Hyperlink''
  • click ''place in this document''
  • click ok
  • thats all

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Your problem is in this line: Message messageObject = new Message ();
This error says that the Message class is not known at compile time.

So you need to import the Message class.

Something like this:

import package1.package2.Message;

Check this out.

http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

How to enter special characters like "&" in oracle database?

you can simply escape & by following a dot. try this:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');

How to negate 'isblank' function

I suggest:

=not(isblank(A1))  

which returns TRUE if A1 is populated and FALSE otherwise. Which compares with:

=isblank(A1)  

which returns TRUE if A1 is empty and otherwise FALSE.

position fixed is not working

Another cause could be a parent container that contains the CSS animation property. That's what it was for me.

What is %timeit in python?

Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

CSS for the "down arrow" on a <select> element?

You would need to create your own dropdown using hidden divs and a hidden input element to record which option was "selected". My guess is that @Jan Hancic's link he posted is probably what you're looking for.

Daylight saving time and time zone best practices

In dealing with databases (in particular MySQL, but this applies to most databases), I found it hard to store UTC.

  • Databases usually work with server datetime by default (that is, CURRENT_TIMESTAMP).
  • You may not be able to change the server timezone.
  • Even if you are able to change the timezone, you may have third-party code that expects server timezone to be local.

I found it easier to just store server datetime in the database, then let the database convert the stored datetime back to UTC (that is, UNIX_TIMESTAMP()) in the SQL statements. After that you can use the datetime as UTC in your code.

If you have 100% control over the server and all code, it's probably better to change server timezone to UTC.

Generating HTML email body in C#

Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.

Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.

Node/Express file upload

ExpressJS Issue:

Most of the middleware is removed from express 4. check out: http://www.github.com/senchalabs/connect#middleware For multipart middleware like busboy, busboy-connect, formidable, flow, parted is needed.

This example works using connect-busboy middleware. create /img and /public folders.
Use the folder structure:

\server.js

\img\"where stuff is uploaded to"

\public\index.html

SERVER.JS

var express = require('express');    //Express Web Server 
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path');     //used for file path
var fs = require('fs-extra');       //File System - for file manipulation

var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));

/* ========================================================== 
Create a Route (/upload) to handle the Form submission 
(handle POST requests to /upload)
Express v4  Route definition
============================================================ */
app.route('/upload')
    .post(function (req, res, next) {

        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename) {
            console.log("Uploading: " + filename);

            //Path where image will be uploaded
            fstream = fs.createWriteStream(__dirname + '/img/' + filename);
            file.pipe(fstream);
            fstream.on('close', function () {    
                console.log("Upload Finished of " + filename);              
                res.redirect('back');           //where to go next
            });
        });
    });

var server = app.listen(3030, function() {
    console.log('Listening on port %d', server.address().port);
});

INDEX.HTML

<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
    <meta charset="UTF-8">
    <title>angular file upload</title>
</head>

<body>
        <form method='post' action='upload' enctype="multipart/form-data">
        <input type='file' name='fileUploaded'>
        <input type='submit'>
 </body>
</html>

The following will work with formidable SERVER.JS

var express = require('express');   //Express Web Server 
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path');     //used for file path
var fs =require('fs-extra');    //File System-needed for renaming file etc

var app = express();
app.use(express.static(path.join(__dirname, 'public')));

/* ========================================================== 
 bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));
 app.route('/upload')
 .post(function (req, res, next) {

  var form = new formidable.IncomingForm();
    //Formidable uploads to operating systems tmp dir by default
    form.uploadDir = "./img";       //set upload directory
    form.keepExtensions = true;     //keep file extension

    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        console.log("form.bytesReceived");
        //TESTING
        console.log("file size: "+JSON.stringify(files.fileUploaded.size));
        console.log("file path: "+JSON.stringify(files.fileUploaded.path));
        console.log("file name: "+JSON.stringify(files.fileUploaded.name));
        console.log("file type: "+JSON.stringify(files.fileUploaded.type));
        console.log("astModifiedDate: "+JSON.stringify(files.fileUploaded.lastModifiedDate));

        //Formidable changes the name of the uploaded file
        //Rename the file to its original name
        fs.rename(files.fileUploaded.path, './img/'+files.fileUploaded.name, function(err) {
        if (err)
            throw err;
          console.log('renamed complete');  
        });
          res.end();
    });
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});

What does <![CDATA[]]> in XML mean?

Note that the CDATA construct is only needed if placing text directly in the XML text file.

That is, you only need to use CDATA if hand typing or programmatically building the XML text directly.

Any text entered using a DOM processor API or SimpleXML will be automatically escaped to prevent running foul of XML content rules.

Notwithstanding that, there can be times where using CDATA can reduce the text size that would otherwise be produced with all entities encoded, such as for css in style tags or javascript in script tags, where many language constructs use characters in HTML|XML, like < and >.

Case insensitive std::string.find()

If you want “real” comparison according to Unicode and locale rules, use ICU’s Collator class.

Loop inside React JSX

Inside your render or any function and before return, you can use a variable to store JSX elements. Just like this -

const tbodyContent = [];
for (let i=0; i < numrows; i++) {
    tbodyContent.push(<ObjectRow/>);
}

Use it inside your tbody like this:

<tbody>
    {
        tbodyContent
    }
</tbody>

But I'll prefer map() over this.

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

Okay- here we go:

(In a "silverlight app": please check first that silverlight is checked in "web" in your server project "properties"- If that didnt solve it then try this beneath)

On first time do: run this first: devenv.exe /ResetSettings and 1: In top menu click on debug tag 2: click options and settings 3: In "debugging" and under "general" find "enable .net framework source stepping" 4: Tick the box. 5: And now all the symbols will be downloaded and reconfigured :)

If it happens again after the above just clear the folder where the symbols are:

1: In top menu click on debug tag 2: click options and settings 3: In "debugging" and under "symbols" find the button "empty symbol cache" and click it.

Where does Vagrant download its .box files to?

The actual .box file is deleted by Vagrant once the download and box installation is complete. As mentioned in other answers, whilst downloading, the .box file is stored as:

~/.vagrant.d/tmp/boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

where the file name is 'box' followed by a 40 byte hexadecimal hash. A temporary file on my system for example, is:

~/.vagrant.d/tmp/boxc74a85fe4af3197a744851517c6af4d4959db77f

As far as I can tell, this file is never saved with a *.box extension, which explains why the searches above failed to locate it. There are two ways to retrieve the actual box file:

  1. Download the .box file from vagrantcloud.com

    1. Find the box you're interested in on the atlas. For example, https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1
    2. Replace the domain name with vagrantcloud.com. So https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box.
    3. Add /providers/virtualbox.box to the end of that URL. So https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box
    4. Save the .box file
    5. Use the .box as you wish, for example, hosting it yourself and pointing config.vm.box_url to the URL. OR
  2. Get the .box directly from Vagrant

    This requires you to modify the ruby source to prevent Vagrant from deleting the box after successful download.

    1. Locate the box_add.rb file in your Vagrant installation directory. On my system it's located at /Applications/Vagrant/embedded/gems/gems/vagrant-1.5.2/lib/vagrant/action/builtin/box_add.rb
    2. Find the box_add function. Within the box_add function, there is a block that reads:

      ensure # Make sure we delete the temporary file after we add it, # unless we were interrupted, in which case we keep it around # so we can resume the download later. if !@download_interrupted @logger.debug("Deleting temporary box: #{box_url}") begin box_url.delete if box_url rescue Errno::ENOENT # Not a big deal, the temp file may not actually exist end end

    3. Comment this block out.
    4. Add another box using vagrant add box <boxname>.
    5. Wait for it to download. You can watch it save in the ~/.vagrant.d/tmp/ directory as a boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX file.
    6. Rename the the file to something more useful. Eg, mv boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX trusty64.box.

Why would you want this?

For me, this has been useful to retrieve the .box file so it can be hosted on local, fast infrastructure as opposed to downloading from HashiCorp's Atlas box catalog or another box provider.

This really should be part of the default Vagrant functionality as it has a very definitive use case.

Are static methods inherited in Java?

You can experience the difference in following code, which is slightly modification over your code.

class A {
    public static void display() {
        System.out.println("Inside static method of superclass");
    }
}

class B extends A {
    public void show() {
        display();
    }

    public static void display() {
        System.out.println("Inside static method of this class");
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
        // prints: Inside static method of this class
        b.display();

        A a = new B();
        // prints: Inside static method of superclass
        a.display();
    }
}

This is due to static methods are class methods.

A.display() and B.display() will call method of their respective classes.

VBA for clear value in specific range of cell and protected cell from being wash away formula

Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:

  1. Ctrl-G
  2. A1:X50 Enter
  3. Delete

Unless you have to do this very often, entering and then triggering the VBAcode is more effort.

And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.

How to use su command over adb shell?

for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.

adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""

Why is the use of alloca() not considered good practice?

Here's why:

char x;
char *y=malloc(1);
char *z=alloca(&x-y);
*z = 1;

Not that anyone would write this code, but the size argument you're passing to alloca almost certainly comes from some sort of input, which could maliciously aim to get your program to alloca something huge like that. After all, if the size isn't based on input or doesn't have the possibility to be large, why didn't you just declare a small, fixed-size local buffer?

Virtually all code using alloca and/or C99 vlas has serious bugs which will lead to crashes (if you're lucky) or privilege compromise (if you're not so lucky).

How can I get npm start at a different directory?

npm start --prefix path/to/your/app

& inside package.json add the following script

"scripts": {
   "preinstall":"cd $(pwd)"
}

pythonw.exe or python.exe?

In my experience the pythonw.exe is faster at least with using pygame.

How to create a md5 hash of a string in C?

It would appear that you should

  • Create a struct MD5context and pass it to MD5Init to get it into a proper starting condition
  • Call MD5Update with the context and your data
  • Call MD5Final to get the resulting hash

These three functions and the structure definition make a nice abstract interface to the hash algorithm. I'm not sure why you were shown the core transform function in that header as you probably shouldn't interact with it directly.

The author could have done a little more implementation hiding by making the structure an abstract type, but then you would have been forced to allocate the structure on the heap every time (as opposed to now where you can put it on the stack if you so desire).

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

how to import csv data into django models

You can use the django-csv-importer package. http://pypi.python.org/pypi/django-csv-importer/0.1.1

It works like a django model

MyCsvModel(CsvModel):
    field1 = IntegerField()
    field2 = CharField()
    etc

    class Meta:
        delimiter = ";"
        dbModel = Product

And you just have to: CsvModel.import_from_file("my file")

That will automatically create your products.

Using stored procedure output parameters in C#

I slightly modified your stored procedure (to use SCOPE_IDENTITY) and it looks like this:

CREATE PROCEDURE usp_InsertContract
    @ContractNumber varchar(7),
    @NewId int OUTPUT
AS
BEGIN
    INSERT INTO [dbo].[Contracts] (ContractNumber)
    VALUES (@ContractNumber)

    SELECT @NewId = SCOPE_IDENTITY()
END

I tried this and it works just fine (with that modified stored procedure):

// define connection and command, in using blocks to ensure disposal
using(SqlConnection conn = new SqlConnection(pvConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.usp_InsertContract", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;

    // set up the parameters
    cmd.Parameters.Add("@ContractNumber", SqlDbType.VarChar, 7);
    cmd.Parameters.Add("@NewId", SqlDbType.Int).Direction = ParameterDirection.Output;

    // set parameter values
    cmd.Parameters["@ContractNumber"].Value = contractNumber;

    // open connection and execute stored procedure
    conn.Open();
    cmd.ExecuteNonQuery();

    // read output value from @NewId
    int contractID = Convert.ToInt32(cmd.Parameters["@NewId"].Value);
    conn.Close();
}

Does this work in your environment, too? I can't say why your original code won't work - but when I do this here, VS2010 and SQL Server 2008 R2, it just works flawlessly....

If you don't get back a value - then I suspect your table Contracts might not really have a column with the IDENTITY property on it.

Is there a JavaScript function that can pad a string to get to a determined length?

1. function
var _padLeft = function(paddingString, width, replacementChar) {
    return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' ');
};

2. String prototype
String.prototype.padLeft = function(width, replacementChar) {
        return this.length >= width ? this.toString() : (replacementChar + this).padLeft(width, replacementChar || ' ');
};

3. slice
('00000' + paddingString).slice(-5)

Spring Bean Scopes

According to the documentation of Spring-Cloud-Config there is one extra scope next to the existing five. It is @RefreshScope.

This is the short description of RefreshScope:

When there is a configuration change, a Spring @Bean that is marked as @RefreshScope gets special treatment. This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance, if a DataSource has open connections when the database URL is changed via the Environment, you probably want the holders of those connections to be able to complete what they are doing. Then, the next time something borrows a connection from the pool, it gets one with the new URL.

Sometimes, it might even be mandatory to apply the @RefreshScope annotation on some beans which can be only initialized once. If a bean is "immutable", you will have to either annotate the bean with @RefreshScope or specify the classname under the property key spring.cloud.refresh.extra-refreshable.

Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call, you must invalidate its cache entry.

The RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. The /refresh endpoint exposes this functionality (over HTTP or JMX). To refresh an individual bean by name, there is also a refresh(String) method.

How to read a text file directly from Internet using Java?

Alternatively, you can use Guava's Resources object:

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);

How can I clear an HTML file input with JavaScript?

This worked for me. const clear = (event) =>{event.target.value = [ ];} clear("input_id");

add created_at and updated_at fields to mongoose schemas

As of Mongoose 4.0 you can now set a timestamps option on the Schema to have Mongoose handle this for you:

var thingSchema = new Schema({..}, { timestamps: true });

You can change the name of the fields used like so:

var thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });

http://mongoosejs.com/docs/guide.html#timestamps

import httplib ImportError: No module named httplib

I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:

apt-get install -y --no-install-recommends python

And I should not have included the --no-install-recommends flag:

apt-get install -y python

How do I start Mongo DB from Windows?

Actually windows way to use service, from the official documentation:

  • Find out where is your executable is installed, path may be like this:

    "C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe"

  • Create config file with such content (yaml format), path may be like this:

    "C:\Program Files\MongoDB\Server\3.4\mongod.cfg"

systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db
  • Execute as admin the next command (run command line as admin):
C:\...\mongod.exe --config C:\...\mongod.cfg --install

Where paths is reduced with dots, see above.

The key --install say to mongo to install itself as windows service.

Now you can start, stop, restart mongo server as usual windows service choose your favorite way from this:

  • from Control Panel -> Administration -> Services -> MongoDB
  • by command execution from command line as admin: (net start MongoDB)

Check log file specified in config file if any problems.

making a paragraph in html contain a text from a file

Here is a javascript code I have tested successfully :

    var txtFile = new XMLHttpRequest();
    var allText = "file not found";
    txtFile.onreadystatechange = function () {
        if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
            allText = txtFile.responseText;
            allText = allText.split("\n").join("<br>");
        }

        document.getElementById('txt').innerHTML = allText;
    }
    txtFile.open("GET", '/result/client.txt', true);
    txtFile.send(null);

Apache: client denied by server configuration

Apache 2.4.3 (or maybe slightly earlier) added a new security feature that often results in this error. You would also see a log message of the form "client denied by server configuration". The feature is requiring an authorized user identity to access a directory. It is turned on by DEFAULT in the httpd.conf that ships with Apache. You can see the enabling of the feature with the directive

Require all denied

This basically says to deny access to all users. To fix this problem, either remove the denied directive (or much better) add the following directive to the directories you want to grant access to:

Require all granted

as in

<Directory "your directory here">
   Order allow,deny
   Allow from all
   # New directive needed in Apache 2.4.3: 
   Require all granted
</Directory>

Difference between Apache CXF and Axis

Another advantage of CXF: it connects to web servers using NTLMV2 authentication out of the box. (used by Windows 2008 & up) Before using CXF, I hacked Axis2 to use HTTPClient V4 + JCIFS to make this possible.

How to make PopUp window in java

public class JSONPage {
    Logger log = Logger.getLogger("com.prodapt.autotest.gui.design.EditTestData");


    public static final JFrame JSONFrame = new JFrame();
    public final JPanel jPanel = new JPanel();

    JLabel IdLabel = new JLabel("JSON ID*");
    JLabel DataLabel = new JLabel("JSON Data*");
    JFormattedTextField JId = new JFormattedTextField("Auto Generated");
    JTextArea JData = new JTextArea();
    JButton Cancel = new JButton("Cancel");
    JButton Add = new JButton("Add");

    public void JsonPage() {

        JSONFrame.getContentPane().add(jPanel);
        JSONFrame.add(jPanel);
        JSONFrame.setSize(400, 250);
        JSONFrame.setResizable(false);
        JSONFrame.setVisible(false);
        JSONFrame.setTitle("Add JSON Data");
        JSONFrame.setLocationRelativeTo(null);
        jPanel.setLayout(null);

        JData.setWrapStyleWord(true);
        JId.setEditable(false);

        IdLabel.setBounds(20, 30, 120, 25);
        JId.setBounds(100, 30, 120, 25);
        DataLabel.setBounds(20, 60, 120, 25);
        JData.setBounds(100, 60, 250, 75);
        Cancel.setBounds(80, 170, 80, 30);
        Add.setBounds(280, 170, 50, 30);

        jPanel.add(IdLabel);
        jPanel.add(JId);
        jPanel.add(DataLabel);
        jPanel.add(JData);
        jPanel.add(Cancel);
        jPanel.add(Add);

        SwingUtilities.updateComponentTreeUI(JSONFrame);

        Cancel.addActionListener(new ActionListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void actionPerformed(ActionEvent e) {
                JData.setText("");
                JSONFrame.hide();
                TestCasePage.testCaseFrame.show();
            }
        });

        Add.addActionListener(new ActionListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    PreparedStatement pStatement = DAOHelper.getInstance()
                            .createJSON(
                                    ConnectionClass.getInstance()
                                            .getConnection());
                    pStatement.setString(1, null);
                    if (JData.getText().toString().isEmpty()) {
                        JOptionPane.showMessageDialog(JSONFrame,
                                "Must Enter JSON Path");
                    } else {
                        // System.out.println(eleSelectBy);
                        pStatement.setString(2, JData.getText());
                        pStatement.executeUpdate();
                        JOptionPane.showMessageDialog(JSONFrame, "!! Added !!");
                        log.info("JSON Path Added"+JData);
                        JData.setText("");
                        JSONFrame.hide();
                    }

                } catch (SQLException e1) {
                    JData.setText("");
                    log.info("Error in Adding JSON Path");
                    e1.printStackTrace();
                }
            }
        });
    }

}

Questions every good .NET developer should be able to answer?

None, really. There are probably very simple questions that the smartest people in the world do not know the answers to. Not because they are hard, but simply because they just haven't come across it. You should be looking at the whole package and the skill of the developer, not whether they can answer an arbitrary question.

If the question is easy enough to be answered in a short sentence or two, it's easy enough to just tell someone who doesn't know. You should be looking for their understanding of concepts and reasoning capability, not their ability to answer questions "every .NET developer should be able to answer."

In jQuery, how do I select an element by its name attribute?

Something like this maybe?

$("input:radio[name=theme]").click(function() { 
 ...
}); 

When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.

Regex Named Groups in Java

A bit old question but I found myself needing this also and that the suggestions above were inaduquate - and as such - developed a thin wrapper myself: https://github.com/hofmeister/MatchIt

Number of days between past date and current date in Google spreadsheet

The following seemed to work well for me:

=DATEDIF(B2, Today(), "D")

How can I parse a time string containing milliseconds in it with python?

I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

The solution if datetime doesn't support %f and without needing a try/except is:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

This works for the input string "2010-10-06 09:42:52.266000"

MySQL - UPDATE query with LIMIT

I would suggest a two step query

I'm assuming you have an autoincrementing primary key because you say your PK is (max+1) which sounds like the definition of an autioincrementing key.
I'm calling the PK id, substitute with whatever your PK is called.

1 - figure out the primary key number for column 1000.

SELECT @id:= id FROM smartmeter_usage LIMIT 1 OFFSET 1000

2 - update the table.

UPDATE smartmeter_usage.users_reporting SET panel_id = 3 
WHERE panel_id IS NULL AND id >= @id 
ORDER BY id 
LIMIT 1000

Please test to see if I didn't make an off-by-one error; you may need to add or subtract 1 somewhere.

How to change the font size on a matplotlib plot

Based on the above stuff:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)

fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)

plot = fig.add_subplot(1, 1, 1)

plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)

for label in (plot.get_xticklabels() + plot.get_yticklabels()):
    label.set_fontproperties(font)

Finding square root without using sqrt function?

Here is a very awesome code to find sqrt and even faster than original sqrt function.

float InvSqrt (float x) 
{
    float xhalf = 0.5f*x;
    int i = *(int*)&x;
    i = 0x5f375a86 - (i>>1);
    x = *(float*)&i;
    x = x*(1.5f - xhalf*x*x);
    x = x*(1.5f - xhalf*x*x);
    x = x*(1.5f - xhalf*x*x);
    x=1/x;
    return x;
}

How large should my recv buffer be when calling recv in the socket library

The answers to these questions vary depending on whether you are using a stream socket (SOCK_STREAM) or a datagram socket (SOCK_DGRAM) - within TCP/IP, the former corresponds to TCP and the latter to UDP.

How do you know how big to make the buffer passed to recv()?

  • SOCK_STREAM: It doesn't really matter too much. If your protocol is a transactional / interactive one just pick a size that can hold the largest individual message / command you would reasonably expect (3000 is likely fine). If your protocol is transferring bulk data, then larger buffers can be more efficient - a good rule of thumb is around the same as the kernel receive buffer size of the socket (often something around 256kB).

  • SOCK_DGRAM: Use a buffer large enough to hold the biggest packet that your application-level protocol ever sends. If you're using UDP, then in general your application-level protocol shouldn't be sending packets larger than about 1400 bytes, because they'll certainly need to be fragmented and reassembled.

What happens if recv gets a packet larger than the buffer?

  • SOCK_STREAM: The question doesn't really make sense as put, because stream sockets don't have a concept of packets - they're just a continuous stream of bytes. If there's more bytes available to read than your buffer has room for, then they'll be queued by the OS and available for your next call to recv.

  • SOCK_DGRAM: The excess bytes are discarded.

How can I know if I have received the entire message?

  • SOCK_STREAM: You need to build some way of determining the end-of-message into your application-level protocol. Commonly this is either a length prefix (starting each message with the length of the message) or an end-of-message delimiter (which might just be a newline in a text-based protocol, for example). A third, lesser-used, option is to mandate a fixed size for each message. Combinations of these options are also possible - for example, a fixed-size header that includes a length value.

  • SOCK_DGRAM: An single recv call always returns a single datagram.

Is there a way I can make a buffer not have a fixed amount of space, so that I can keep adding to it without fear of running out of space?

No. However, you can try to resize the buffer using realloc() (if it was originally allocated with malloc() or calloc(), that is).

Storing JSON in database vs. having a new column for each key

the drawback of the approach is exactly what you mentioned :

it makes it VERY slow to find things, since each time you need to perform a text-search on it.

value per column instead matches the whole string.

Your approach (JSON based data) is fine for data you don't need to search by, and just need to display along with your normal data.

Edit: Just to clarify, the above goes for classic relational databases. NoSQL use JSON internally, and are probably a better option if that is the desired behavior.

Oracle: how to add minutes to a timestamp?

like that very easily

i added 10 minutes to system date and always in preference use the Db server functions not custom one .

select to_char(sysdate + NUMTODSINTERVAL(10,'MINUTE'),'DD/MM/YYYY HH24:MI:SS') from dual;

What is the difference between Document style and RPC style communication?

Can some body explain me the differences between a Document style and RPC style webservices?

There are two communication style models that are used to translate a WSDL binding to a SOAP message body. They are: Document & RPC

The advantage of using a Document style model is that you can structure the SOAP body any way you want it as long as the content of the SOAP message body is any arbitrary XML instance. The Document style is also referred to as Message-Oriented style.

However, with an RPC style model, the structure of the SOAP request body must contain both the operation name and the set of method parameters. The RPC style model assumes a specific structure to the XML instance contained in the message body.

Furthermore, there are two encoding use models that are used to translate a WSDL binding to a SOAP message. They are: literal, and encoded

When using a literal use model, the body contents should conform to a user-defined XML-schema(XSD) structure. The advantage is two-fold. For one, you can validate the message body with the user-defined XML-schema, moreover, you can also transform the message using a transformation language like XSLT.

With a (SOAP) encoded use model, the message has to use XSD datatypes, but the structure of the message need not conform to any user-defined XML schema. This makes it difficult to validate the message body or use XSLT based transformations on the message body.

The combination of the different style and use models give us four different ways to translate a WSDL binding to a SOAP message.

Document/literal
Document/encoded
RPC/literal
RPC/encoded

I would recommend that you read this article entitled Which style of WSDL should I use? by Russell Butek which has a nice discussion of the different style and use models to translate a WSDL binding to a SOAP message, and their relative strengths and weaknesses.

Once the artifacts are received, in both styles of communication, I invoke the method on the port. Now, this does not differ in RPC style and Document style. So what is the difference and where is that difference visible?

The place where you can find the difference is the "RESPONSE"!

RPC Style:

package com.sample;

import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.RPC)
public interface StockPrice { 

    public String getStockPrice(String stockName); 

    public ArrayList getStockPriceList(ArrayList stockNameList); 
}

The SOAP message for second operation will have empty output and will look like:

RPC Style Response:

<ns2:getStockPriceListResponse 
       xmlns:ns2="http://sample.com/">
    <return/>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>

Document Style:

package com.sample;

import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.DOCUMENT)
public interface StockPrice {

    public String getStockPrice(String stockName);

    public ArrayList getStockPriceList(ArrayList stockNameList);
}

If we run the client for the above SEI, the output is:

123 [123, 456]

This output shows that ArrayList elements are getting exchanged between the web service and client. This change has been done only by the changing the style attribute of SOAPBinding annotation. The SOAP message for the second method with richer data type is shown below for reference:

Document Style Response:

<ns2:getStockPriceListResponse 
       xmlns:ns2="http://sample.com/">
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xsi:type="xs:string">123</return>
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xsi:type="xs:string">456</return>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>

Conclusion

  • As you would have noticed in the two SOAP response messages that it is possible to validate the SOAP response message in case of DOCUMENT style but not in RPC style web services.
  • The basic disadvantage of using RPC style is that it doesn’t support richer data types and that of using Document style is that it brings some complexity in the form of XSD for defining the richer data types.
  • The choice of using one out of these depends upon the operation/method requirements and the expected clients.

Similarly, in what way SOAP over HTTP differ from XML over HTTP? After all SOAP is also XML document with SOAP namespace. So what is the difference here?

Why do we need a standard like SOAP? By exchanging XML documents over HTTP, two programs can exchange rich, structured information without the introduction of an additional standard such as SOAP to explicitly describe a message envelope format and a way to encode structured content.

SOAP provides a standard so that developers do not have to invent a custom XML message format for every service they want to make available. Given the signature of the service method to be invoked, the SOAP specification prescribes an unambiguous XML message format. Any developer familiar with the SOAP specification, working in any programming language, can formulate a correct SOAP XML request for a particular service and understand the response from the service by obtaining the following service details.

  • Service name
  • Method names implemented by the service
  • Method signature of each method
  • Address of the service implementation (expressed as a URI)

Using SOAP streamlines the process for exposing an existing software component as a Web service since the method signature of the service identifies the XML document structure used for both the request and the response.

Detect when a window is resized using JavaScript ?

You can use .resize() to get every time the width/height actually changes, like this:

$(window).resize(function() {
  //resize just happened, pixels changed
});

You can view a working demo here, it takes the new height/width values and updates them in the page for you to see. Remember the event doesn't really start or end, it just "happens" when a resize occurs...there's nothing to say another one won't happen.


Edit: By comments it seems you want something like a "on-end" event, the solution you found does this, with a few exceptions (you can't distinguish between a mouse-up and a pause in a cross-browser way, the same for an end vs a pause). You can create that event though, to make it a bit cleaner, like this:

$(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd');
    }, 500);
});

You could have this is a base file somewhere, whatever you want to do...then you can bind to that new resizeEnd event you're triggering, like this:

$(window).bind('resizeEnd', function() {
    //do something, window hasn't changed size in 500ms
});

You can see a working demo of this approach here ?

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

How to get the browser viewport dimensions?

If you are looking for non-jQuery solution that gives correct values in virtual pixels on mobile, and you think that plain window.innerHeight or document.documentElement.clientHeight can solve your problem, please study this link first: https://tripleodeon.com/assets/2011/12/table.html

The developer has done good testing that reveals the problem: you can get unexpected values for Android/iOS, landscape/portrait, normal/high density displays.

My current answer is not silver bullet yet (//todo), but rather a warning to those who are going to quickly copy-paste any given solution from this thread into production code.

I was looking for page width in virtual pixels on mobile, and I've found the only working code is (unexpectedly!) window.outerWidth. I will later examine this table for correct solution giving height excluding navigation bar, when I have time.

Difference between $(this) and event.target?

Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:

  • For a global function, this represents the window.

  • For an object method, this represents the object instance.

  • And in an event handler, this represents the element that received the event.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown() {
            alert(this);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown();alert(this);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object Window
object HTMLParagraphElement

An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown(event) {
            var theEvent = event ? event : window.event;
            var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
            alert(event);
                    alert(locString);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown(event);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object MouseEvent
X = 982 Y = 329

How to add text to an existing div with jquery

we can do it in more easy way like by adding a function on button and on click we call that function for append.

<div id="Content">
<button id="Add" onclick="append();">Add Text</button>
</div> 
<script type="text/javascript">
function append()
{
$('<p>Text</p>').appendTo('#Content');
}
</script>

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

OPTional

It holds optional software and packages that you install that are not required for the system to run.

How can I inspect element in an Android browser?

If you want to inspect html, css or maybe you need js console in your mobile browser . You can use excelent tool eruda Using it you have the same Developer Tools on your mobile browser like in your desctop device. Dont forget to upvote :) Here is a link https://github.com/liriliri/eruda

pandas read_csv and filter columns with usecols

You have to just add the index_col=False parameter

df1 = pd.read_csv('foo.csv',
     header=0,
     index_col=False,
     names=["dummy", "date", "loc", "x"], 
     usecols=["dummy", "date", "loc", "x"],
     parse_dates=["date"])
  print df1

Need a row count after SELECT statement: what's the optimal SQL approach?

Just to add this because this is the top result in google for this question. In sqlite I used this to get the rowcount.

WITH temptable AS
  (SELECT one,two
   FROM
     (SELECT one, two
      FROM table3
      WHERE dimension=0
      UNION ALL SELECT one, two
      FROM table2
      WHERE dimension=0
      UNION ALL SELECT one, two
      FROM table1
      WHERE dimension=0)
   ORDER BY date DESC)
SELECT *
FROM temptable
LEFT JOIN
  (SELECT count(*)/7 AS cnt,
                        0 AS bonus
   FROM temptable) counter
WHERE 0 = counter.bonus

Where are the recorded macros stored in Notepad++?

If you install Notepad++ on Linux system by wine (In my case desktop Ubuntu 14.04-LTS_X64) the file "shortcuts.xml" is under :

$/home/[USER-NAME]/.wine/drive_c/users/[USER-NAME]/My Documents/.wine/drive_c/Program Files (x86)/Notepad++/shortcuts.xml

Thanks to Harrison and all that have suggestions for that isssue.

CSS: Change image src on img:hover

You can't change img tag's src attribute using CSS. Possible using Javascript onmouseover() event handler.

HTML:

<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover='hover()'/>

Javascript:

function hover() {
  document.getElementById("my-img").src = "http://dummyimage.com/100x100/eb00eb/fff";
}

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

Permutations between two lists of unequal length

Answering the question "given two lists, find all possible permutations of pairs of one item from each list" and using basic Python functionality (i.e., without itertools) and, hence, making it easy to replicate for other programming languages:

def rec(a, b, ll, size):
    ret = []
    for i,e in enumerate(a):
        for j,f in enumerate(b):
            l = [e+f]
            new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size)
            if not new_l:
                ret.append(l)
            for k in new_l:
                l_k = l + k
                ret.append(l_k)
                if len(l_k) == size:
                    ll.append(l_k)
    return ret

a = ['a','b','c']
b = ['1','2']
ll = []
rec(a,b,ll, min(len(a),len(b)))
print(ll)

Returns

[['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']]

HTML button onclick event

This example will help you:

<form>
    <input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>

You can open next page on same page by:

<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">

Find nearest latitude/longitude with an SQL query

Mysql query for search coordinates with distance limit and where condition

SELECT , ( 3959 acos( cos( radians('28.5850154') ) cos( radians(lat) ) cos( radians( lng ) - radians('77.07207489999999') ) + sin( radians('28.5850154') ) * sin( radians( lat ) ) ) ) AS distance FROM `Wo_Products` WHERE `active` = '1' HAVING distance < 5

How do you round a floating point number in Perl?

If you decide to use printf or sprintf, note that they use the Round half to even method.

foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {
    printf "$i -> %.0f\n", $i;
}
__END__
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4

How to make a .NET Windows Service start right after the installation?

I've posted a step-by-step procedure for creating a Windows service in C# here. It sounds like you're at least to this point, and now you're wondering how to start the service once it is installed. Setting the StartType property to Automatic will cause the service to start automatically after rebooting your system, but it will not (as you've discovered) automatically start your service after installation.

I don't remember where I found it originally (perhaps Marc Gravell?), but I did find a solution online that allows you to install and start your service by actually running your service itself. Here's the step-by-step:

  1. Structure the Main() function of your service like this:

    static void Main(string[] args)
    {
        if (args.Length == 0) {
            // Run your service normally.
            ServiceBase[] ServicesToRun = new ServiceBase[] {new YourService()};
            ServiceBase.Run(ServicesToRun);
        } else if (args.Length == 1) {
            switch (args[0]) {
                case "-install":
                    InstallService();
                    StartService();
                    break;
                case "-uninstall":
                    StopService();
                    UninstallService();
                    break;
                default:
                    throw new NotImplementedException();
            }
        }
    }
    
  2. Here is the supporting code:

    using System.Collections;
    using System.Configuration.Install;
    using System.ServiceProcess;
    
    private static bool IsInstalled()
    {
        using (ServiceController controller = 
            new ServiceController("YourServiceName")) {
            try {
                ServiceControllerStatus status = controller.Status;
            } catch {
                return false;
            }
            return true;
        }
    }
    
    private static bool IsRunning()
    {
        using (ServiceController controller = 
            new ServiceController("YourServiceName")) {
            if (!IsInstalled()) return false;
            return (controller.Status == ServiceControllerStatus.Running);
        }
    }
    
    private static AssemblyInstaller GetInstaller()
    {
        AssemblyInstaller installer = new AssemblyInstaller(
            typeof(YourServiceType).Assembly, null);
        installer.UseNewContext = true;
        return installer;
    }
    
  3. Continuing with the supporting code...

    private static void InstallService()
    {
        if (IsInstalled()) return;
    
        try {
            using (AssemblyInstaller installer = GetInstaller()) {
                IDictionary state = new Hashtable();
                try {
                    installer.Install(state);
                    installer.Commit(state);
                } catch {
                    try {
                        installer.Rollback(state);
                    } catch { }
                    throw;
                }
            }
        } catch {
            throw;
        }
    }
    
    private static void UninstallService()
    {
        if ( !IsInstalled() ) return;
        try {
            using ( AssemblyInstaller installer = GetInstaller() ) {
                IDictionary state = new Hashtable();
                try {
                    installer.Uninstall( state );
                } catch {
                    throw;
                }
            }
        } catch {
            throw;
        }
    }
    
    private static void StartService()
    {
        if ( !IsInstalled() ) return;
    
        using (ServiceController controller = 
            new ServiceController("YourServiceName")) {
            try {
                if ( controller.Status != ServiceControllerStatus.Running ) {
                    controller.Start();
                    controller.WaitForStatus( ServiceControllerStatus.Running, 
                        TimeSpan.FromSeconds( 10 ) );
                }
            } catch {
                throw;
            }
        }
    }
    
    private static void StopService()
    {
        if ( !IsInstalled() ) return;
        using ( ServiceController controller = 
            new ServiceController("YourServiceName")) {
            try {
                if ( controller.Status != ServiceControllerStatus.Stopped ) {
                    controller.Stop();
                    controller.WaitForStatus( ServiceControllerStatus.Stopped, 
                         TimeSpan.FromSeconds( 10 ) );
                }
            } catch {
                throw;
            }
        }
    }
    
  4. At this point, after you install your service on the target machine, just run your service from the command line (like any ordinary application) with the -install command line argument to install and start your service.

I think I've covered everything, but if you find this doesn't work, please let me know so I can update the answer.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

What is Hash and Range Primary Key?

"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:

Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.

This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.


Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.

This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:

Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false

I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.

Center image using text-align center?

Sometimes we directly add the content and images on the WordPress administrator inside the pages. When we insert the images inside the content and want to align that center. Code is displayed as:

 **<p><img src="https://abcxyz.com/demo/wp-content/uploads/2018/04/1.jpg" alt=""></p>**

In that case you can add CSS content like this:

article p img{
    margin: 0 auto;
    display: block;
    text-align: center;
    float: none;
}

Add an index (numeric ID) column to large data frame

Well, if I understand you correctly. You can do something like the following.

To show it, I first create a data.frame with your example

df <- 
scan(what = character(), sep = ",", text =
"001, 34, 3, aa.com
002, 4, 4, aa.com
034, 3, 3, aa.com
001, 12, 4, bb.com
002, 1, 3, bb.com
034, 2, 2, cc.com")

df <- as.data.frame(matrix(df, 6, 4, byrow = TRUE))
colnames(df) <- c("user_id", "number_of_logins", "number_of_images", "web")  

You can then run one of the following lines to add a column (at the end of the data.frame) with the row number as the generated user id. The second lines simply adds leading zeros.

df$generated_uid  <- 1:nrow(df)
df$generated_uid2 <- sprintf("%03d", 1:nrow(df))

If you absolutely want the generated user id to be the first column, you can add the column like so:

df <- cbind("generated_uid3" = sprintf("%03d", 1:nrow(df)), df)

or simply rearrage the columns.

Drawing a dot on HTML5 canvas

The above claim that "If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing" seems to be quite wrong - at least with Chrome 31.0.1650.57 m or depending on your definition of "lot of pixel". I would have preferred to comment directly to the respective post - but unfortunately I don't have enough stackoverflow points yet:

I think that I am drawing "a lot of pixels" and therefore I first followed the respective advice for good measure I later changed my implementation to a simple ctx.fillRect(..) for each drawn point, see http://www.wothke.ch/webgl_orbittrap/Orbittrap.htm

Interestingly it turns out the silly ctx.fillRect() implementation in my example is actually at least twice as fast as the ImageData based double buffering approach.

At least for my scenario it seems that the built-in ctx.getImageData/ctx.putImageData is in fact unbelievably SLOW. (It would be interesting to know the percentage of pixels that need to be touched before an ImageData based approach might take the lead..)

Conclusion: If you need to optimize performance you have to profile YOUR code and act on YOUR findings..

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

How to remove array element in mongodb?

If you use the Mongoose API and looking to pull a sub/child object: Read this document Don't forget to use save() when you're done editing otherwise the changes won't be saved to the database.

Smart way to truncate long strings

Text-overflow: ellipsis is the property you need. With this and an overflow:hidden with a specific width, everything surpassing that will get the three period effect at the end ... Don't forget to add whitespace:nowrap or the text will be put in multiple lines.

.wrap{
  text-overflow: ellipsis
  white-space: nowrap;
  overflow: hidden;
  width:"your desired width";
}
<p class="wrap">The string to be cut</p>

How to get Latitude and Longitude of the mobile device in android?

Here is the class LocationFinder to find the GPS location. This class will call MyLocation, which will do the business.

LocationFinder

public class LocationFinder extends Activity {

    int increment = 4;
    MyLocation myLocation = new MyLocation();

    // private ProgressDialog dialog;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intermediat);
        myLocation.getLocation(getApplicationContext(), locationResult);

        boolean r = myLocation.getLocation(getApplicationContext(),
            locationResult);

        startActivity(new Intent(LocationFinder.this,
        // Nearbyhotelfinder.class));
            GPSMyListView.class));
        finish();
    }

    public LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            // TODO Auto-generated method stub
            double Longitude = location.getLongitude();
            double Latitude = location.getLatitude();

            Toast.makeText(getApplicationContext(), "Got Location",
                Toast.LENGTH_LONG).show();

            try {
                SharedPreferences locationpref = getApplication()
                    .getSharedPreferences("location", MODE_WORLD_READABLE);
                SharedPreferences.Editor prefsEditor = locationpref.edit();
                prefsEditor.putString("Longitude", Longitude + "");
                prefsEditor.putString("Latitude", Latitude + "");
                prefsEditor.commit();
                System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    // handler for the background updating

}

MyLocation

public class MyLocation {

    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //Toast.makeText(context, gps_enabled+" "+network_enabled,     Toast.LENGTH_LONG).show();

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();


        timer1.schedule(new GetLastLocation(), 10000);
    //    Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override

        public void run() {

            //Context context = getClass().getgetApplicationContext();
             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Well, since Multipart Form Data is intended to be used for binary ( and not for text) data transmission, I believe it's bad practice to send data in encoded to String over it.

Another disadvantage is impossibility to send more complex parameters like JSON.

That said, a better option would be to send all data in binary form, that is as Data.

Say I need to send this data

let name = "Arthur"
let userIDs = [1,2,3]
let usedAge = 20

...alongside with user's picture:

let image = UIImage(named: "img")!

For that I would convert that text data to JSON and then to binary alongside with image:

//Convert image to binary
let data = UIImagePNGRepresentation(image)!

//Convert text data to binary
let dict: Dictionary<String, Any> = ["name": name, "userIDs": userIDs, "usedAge": usedAge]
userData = try? JSONSerialization.data(withJSONObject: dict)

And then, finally send it via Multipart Form Data request:

Alamofire.upload(multipartFormData: { (multiFoormData) in
        multiFoormData.append(userData, withName: "user")
        multiFoormData.append(data, withName: "picture", mimeType: "image/png")
    }, to: url) { (encodingResult) in
        ...
    }

Merge two (or more) lists into one, in C# .NET

Assuming you want a list containing all of the products for the specified category-Ids, you can treat your query as a projection followed by a flattening operation. There's a LINQ operator that does that: SelectMany.

// implicitly List<Product>
var products = new[] { CategoryId1, CategoryId2, CategoryId3 }
                     .SelectMany(id => GetAllProducts(id))
                     .ToList();

In C# 4, you can shorten the SelectMany to: .SelectMany(GetAllProducts)

If you already have lists representing the products for each Id, then what you need is a concatenation, as others point out.

How do I send email with JavaScript without opening the mail client?

You can't do it with client side script only... you could make an AJAX call to some server side code that will send an email...

How to comment/uncomment in HTML code

My view templates are generally .php files. This is what I would be using for now.

<?php // Some comment here ?>

The solution is quite similar to what @Robert suggested, works for me. Is not very clean I guess.

How do I sort a VARCHAR column in SQL server that contains numbers?

There are a few possible ways to do this.

One would be

SELECT
 ...
ORDER BY
  CASE 
    WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value) 
    ELSE 9999999 -- or something huge
  END,
  value

the first part of the ORDER BY converts everything to an int (with a huge value for non-numerics, to sort last) then the last part takes care of alphabetics.

Note that the performance of this query is probably at least moderately ghastly on large amounts of data.

Creating a "Hello World" WebSocket example

Issue

Since you are using WebSocket, spender is correct. After recieving the initial data from the WebSocket, you need to send the handshake message from the C# server before any further information can flow.

HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: websocket
Connection: Upgrade
WebSocket-Origin: example
WebSocket-Location: something.here
WebSocket-Protocol: 13

Something along those lines.

You can do some more research into how WebSocket works on w3 or google.

Links and Resources

Here is a protocol specifcation: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76#section-1.3

List of working examples:

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

You cannot supply system properties to the jarsigner.exe tool, unfortunately.

I have submitted defect 7177232, referencing @eckes' defect 7127374 and explaining why it was closed in error.

My defect is specifically about the impact on the jarsigner tool, but perhaps it will lead them to reopening the other defect and addressing the issue properly.

UPDATE: Actually, it turns out that you CAN supply system properties to the Jarsigner tool, it's just not in the help message. Use jarsigner -J-Djsse.enableSNIExtension=false

SQL SERVER: Get total days between two dates

SQL Server DateDiff

DECLARE @startdate datetime2 = '2007-05-05 12:10:09.3312722';
DECLARE @enddate datetime2 = '2009-05-04 12:10:09.3312722'; 
SELECT DATEDIFF(day, @startdate, @enddate);

How does database indexing work?

Simple Description!

The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.

Example: We have a database table called User with three columns – Name, Age and Address. Assume that the User table has thousands of rows.

Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:

SELECT * FROM User 
WHERE Name = 'John'

The database software would literally have to look at every single row in the User table to see if the Name for that row is ‘John’. This will take a long time.

This is where index helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.

How to create an index:

CREATE INDEX name_index
ON User (Name)

An index consists of column values(Eg: John) from one table, and those values are stored in a data structure.

So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!

Calculate difference between two datetimes in MySQL

If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

how to drop database in sqlite?

to delete your app database try this:

 this.deleteDatabase("databasename.db");

this will delete the database file

How to pass all arguments passed to my bash script to a function of mine?

I needed a variation on this, which I expect will be useful to others:

function diffs() {
        diff "${@:3}" <(sort "$1") <(sort "$2")
}

The "${@:3}" part means all the members of the array starting at 3. So this function implements a sorted diff by passing the first two arguments to diff through sort and then passing all other arguments to diff, so you can call it similarly to diff:

diffs file1 file2 [other diff args, e.g. -y]

EditorFor() and html properties

UPDATE: hm, obviously this won't work because model is passed by value so attributes are not preserved; but I leave this answer as an idea.

Another solution, I think, would be to add your own TextBox/etc helpers, that will check for your own attributes on model.

public class ViewModel
{
  [MyAddAttribute("class", "myclass")]
  public string StringValue { get; set; }
}

public class MyExtensions
{
  public static IDictionary<string, object> GetMyAttributes(object model)
  {
     // kind of prototype code...
     return model.GetType().GetCustomAttributes(typeof(MyAddAttribute)).OfType<MyAddAttribute>().ToDictionary(
          x => x.Name, x => x.Value);
  }
}

<!-- in the template -->
<%= Html.TextBox("Name", Model, MyExtensions.GetMyAttributes(Model)) %>

This one is easier but not as convinient/flexible.

PHP CURL DELETE request

To call GET,POST,DELETE,PUT All kind of request, i have created one common function

function CallAPI($method, $api, $data) {
    $url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    switch ($method) {
        case "GET":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            break;
    }
    $response = curl_exec($curl);
    $data = json_decode($response);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check the HTTP Status code
    switch ($httpCode) {
        case 200:
            $error_status = "200: Success";
            return ($data);
            break;
        case 404:
            $error_status = "404: API Not found";
            break;
        case 500:
            $error_status = "500: servers replied with an error.";
            break;
        case 502:
            $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
            break;
        case 503:
            $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
            break;
        default:
            $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
            break;
    }
    curl_close($curl);
    echo $error_status;
    die;
}

CALL Delete Method

$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);

CALL Post Method

$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);

CALL Get Method

$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);

CALL Put Method

$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);

Resizing SVG in html?

Here is an example of getting the bounds using svg.getBox(): https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44

At the end you get numbers that you can plug into the svg to set the viewbox properly. Then use any css on the parent div and you're done.

 // get all SVG objects in the DOM
 var svgs = document.getElementsByTagName("svg");
 var svg = svgs[0],
    box = svg.getBBox(), // <- get the visual boundary required to view all children
    viewBox = [box.x, box.y, box.width, box.height].join(" ");

    // set viewable area based on value above
    svg.setAttribute("viewBox", viewBox);

How to call on a function found on another file?

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out

What's the difference between Sender, From and Return-Path?

The official RFC which defines this specification could be found here:

http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)

2.1.2. Header Field: From

Description:  
    Mailbox of message author  
[...]  
Related information:
    Specifies the author(s) of the message; that is, the mailbox(es)
    of the person(s) or system(s) responsible for the writing of the
    message. Defined as standard by RFC 822.

2.1.3. Header Field: Sender

Description:  
    Mailbox of message sender  
[...]  
Related information:
    Specifies the mailbox of the agent responsible for the actual
    transmission of the message.  Defined as standard by RFC 822.

2.1.22. Header Field: Return-Path

Description:
    Message return path
[...]  
Related information:
    Return path for message response diagnostics. See also RFC 2821
    [17]. Defined as standard by RFC 822.

Pass variables by reference in JavaScript

Simple Object

_x000D_
_x000D_
function foo(x) {
  // Function with other context
  // Modify `x` property, increasing the value
  x.value++;
}

// Initialize `ref` as object
var ref = {
  // The `value` is inside `ref` variable object
  // The initial value is `1`
  value: 1
};

// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);

console.log(ref.value); // Prints "3"
_x000D_
_x000D_
_x000D_


Custom Object

Object rvar

_x000D_
_x000D_
/**
 * Aux function to create by-references variables
 */
function rvar(name, value, context) {
  // If `this` is a `rvar` instance
  if (this instanceof rvar) {
    // Inside `rvar` context...
    
    // Internal object value
    this.value = value;
    
    // Object `name` property
    Object.defineProperty(this, 'name', { value: name });
    
    // Object `hasValue` property
    Object.defineProperty(this, 'hasValue', {
      get: function () {
        // If the internal object value is not `undefined`
        return this.value !== undefined;
      }
    });
    
    // Copy value constructor for type-check
    if ((value !== undefined) && (value !== null)) {
      this.constructor = value.constructor;
    }
    
    // To String method
    this.toString = function () {
      // Convert the internal value to string
      return this.value + '';
    };
  } else {
    // Outside `rvar` context...
    
    // Initialice `rvar` object
    if (!rvar.refs) {
      rvar.refs = {};
    }
    
    // Initialize context if it is not defined
    if (!context) {
      context = window;
    }
    
    // Store variable
    rvar.refs[name] = new rvar(name, value, context);
    
    // Define variable at context
    Object.defineProperty(context, name, {
      // Getter
      get: function () { return rvar.refs[name]; },
      // Setter
      set: function (v) { rvar.refs[name].value = v; },
      // Can be overrided?
      configurable: true
    });

    // Return object reference
    return context[name];
  }
}

// Variable Declaration

  // Declare `test_ref` variable
  rvar('test_ref_1');

  // Assign value `5`
  test_ref_1 = 5;
  // Or
  test_ref_1.value = 5;

  // Or declare and initialize with `5`:
  rvar('test_ref_2', 5);

// ------------------------------
// Test Code

// Test Function
function Fn1 (v) { v.value = 100; }

// Declare
rvar('test_ref_number');

// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);

// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);

// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);

// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);

// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');

// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');

// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true

// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true

// Increase value
test_ref_number++;
test_ref_number.value === 101; // true

// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true

test_ref_str.value === "a"; // true

// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true 
_x000D_
_x000D_
_x000D_

Add line break within tooltips

This css will help you.

    .tooltip {
      word-break: break-all;
    }

or if you want in one line

    .tooltip-inner {
      max-width: 100%;
    }

How do I parse a string with a decimal point to a double?

I couldn't write a comment, so I write here:

double.Parse("3.5", CultureInfo.InvariantCulture) is not a good idea, because in Canada we write 3,5 instead of 3.5 and this function gives us 35 as a result.

I tested both on my computer:

double.Parse("3.5", CultureInfo.InvariantCulture) --> 3.5 OK
double.Parse("3,5", CultureInfo.InvariantCulture) --> 35 not OK

This is a correct way that Pierre-Alain Vigeant mentioned

public static double GetDouble(string value, double defaultValue)
{
    double result;

    // Try parsing in the current culture
    if (!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&
        // Then try in US english
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&
        // Then in neutral language
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out result))
    {
        result = defaultValue;
    }
    return result;
}

Lost connection to MySQL server during query?

This was happening to me with mariadb because I made a varchar(255) column a unique key.. guess that's too heavy for a unique, as the insert was timing out.

How to clear text area with a button in html using javascript?

Change in your html with adding the function on the button click

 <input type="button" value="Clear" onclick="javascript:eraseText();"> 
    <textarea id='output' rows=20 cols=90></textarea>

Try this in your js file:

function eraseText() {
    document.getElementById("output").value = "";
}

jQuery How to Get Element's Margin and Padding?

Border

I believe you can get the border width using .css('border-left-width'). You can also fetch top, right, and bottom and compare them to find the max value. The key here is that you have to specify a specific side.

Padding

See jQuery calculate padding-top as integer in px

Margin

Use the same logic as border or padding.

Alternatively, you could use outerWidth. The pseudo-code should be
margin = (outerWidth(true) - outerWidth(false)) / 2. Note that this only works for finding the margin horizontally. To find the margin vertically, you would need to use outerHeight.

Execute curl command within a Python script

Use this tool (hosted here for free) to convert your curl command to equivalent Python requests code:

Example: This,

curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' --compressed

Gets converted neatly to:

import requests

cookies = {
    'SESSID': 'ABCDEF',
}

headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Origin': 'https://www.example.com',
    'Accept-Encoding': 'gzip, deflate, br',
}

data = 'Pathfinder'

response = requests.post('https://www.example.com/', headers=headers, cookies=cookies, data=data)

Reset C int array to zero : the fastest way?

zero(myarray); is all you need in C++.

Just add this to a header:

template<typename T, size_t SIZE> inline void zero(T(&arr)[SIZE]){
    memset(arr, 0, SIZE*sizeof(T));
}

Find an object in SQL Server (cross-database)

sp_MSforeachdb 'select db_name(), * From ?..sysobjects where xtype in (''U'', ''P'') And name = ''ObjectName'''

Instead of 'ObjectName' insert object you are looking for. First column will display name of database where object is located at.

How to convert color code into media.brush?

You could use the same mechanism the XAML reading system uses: Type converters

var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;

Linux shell sort file according to the second column?

To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :

sort -k 2,2 -s orig_file > sorted_file

Loop through Map in Groovy?

When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value

Unable to find velocity template resources

I faced a similar issue. I was copying the velocity engine mail templates in wrong folder. Since JavaMailSender and VelocityEngine are declared as resources under MailService, its required to add the templates under resource folder declared for the project.

I made the changes and it worked. Put the templates as

src/main/resources/templates/<package>/sampleMail.vm

GitLab remote: HTTP Basic: Access denied and fatal Authentication

   git config --system --unset credential.helper

then enter new password for Git remote server.

Delete all rows in an HTML table

Assign an id or a class for your tbody.

document.querySelector("#tbodyId").remove();
document.querySelectorAll(".tbodyClass").remove();

You can name your id or class how you want, not necessarily #tbodyId or .tbodyClass.

How do I hide certain files from the sidebar in Visual Studio Code?

You can configure patterns to hide files and folders from the explorer and searches.

  1. Open VS User Settings (Main menu: File > Preferences > Settings). This will open the setting screen.
  2. Search for files:exclude in the search at the top.
  3. Configure the User Setting with new glob patterns as needed. In this case add this pattern node_modules/ then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic.

When you are done it should look something like this: enter image description here

If you want to directly edit the settings file: For example to hide a top level node_modules folder in your workspace:

"files.exclude": {
    "node_modules/": true
}

To hide all files that start with ._ such as ._.DS_Store files found on OSX:

"files.exclude": {
    "**/._*": true
}

You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings). Workspace settings will create a .vscode/settings.json file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.

to remove first and last element in array

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

unshift() adds a new element to the beginning of an array.
shift() removes an element from the beginning of an array.

To remove first element from an array arr , use arr.shift()
To remove last element from an array arr , use arr.pop()

Classes cannot be accessed from outside package

Do you by any chance have two PUBLICclass classes in your project, where one is public (the one of which you posted the signature here), and another one which is package visible, and you import the wrong one in your code ?

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

fatal error LNK1169: one or more multiply defined symbols found in game programming

just add /FORCE as linker flag and you're all set.

for instance, if you're working on CMakeLists.txt. Then add following line:

SET(CMAKE_EXE_LINKER_FLAGS  "/FORCE")

Detect if value is number in MySQL

I have found that this works quite well

if(col1/col1= 1,'number',col1) AS myInfo

Invert colors of an image in CSS or JavaScript

CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:

_x000D_
_x000D_
img {_x000D_
   -webkit-filter: invert(1);_x000D_
   filter: invert(1);_x000D_
   }
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
_x000D_
_x000D_

What I can do to resolve "1 commit behind master"?

Suppose currently in your branch myBranch
Do the following :-

git status

If all changes are committed

git pull origin master

If changes are not committed than

git add .

git commit -m"commit changes"

git pull origin master

Check if there are any conflicts than resolve and commit changes

git add .

git commit -m"resolved conflicts message"

And than push

git push origin myBranch

Git stash pop- needs merge, unable to refresh index

The stash has already been applied to other files.

It is only app.coffee that you have to merge manually. Afterwards just run

git reset

to unstage the changes and keep on hacking.

How can I create a two dimensional array in JavaScript?

The sanest answer seems to be

_x000D_
_x000D_
var nrows = ~~(Math.random() * 10);_x000D_
var ncols = ~~(Math.random() * 10);_x000D_
console.log(`rows:${nrows}`);_x000D_
console.log(`cols:${ncols}`);_x000D_
var matrix = new Array(nrows).fill(0).map(row => new Array(ncols).fill(0));_x000D_
console.log(matrix);
_x000D_
_x000D_
_x000D_


Note we can't directly fill with the rows since fill uses shallow copy constructor, therefore all rows would share the same memory...here is example which demonstrates how each row would be shared (taken from other answers):

// DON'T do this: each row in arr, is shared
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo'; // also modifies arr[1][0]
console.info(arr);

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

Trim whitespace from a String

In addition to answer of @gjha:

inline std::string ltrim_copy(const std::string& str)
{
    auto it = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return std::string(it, str.cend());
}

inline std::string rtrim_copy(const std::string& str)
{
    auto it = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
}

inline std::string trim_copy(const std::string& str)
{
    auto it1 = std::find_if(str.cbegin(), str.cend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    if (it1 == str.cend()) {
        return std::string();
    }
    auto it2 = std::find_if(str.crbegin(), str.crend(),
        [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
}

React js onClick can't pass value to method

Use a closure, it result in a clean solution:

<th onClick={this.handleSort(column)} >{column}</th>

handleSort function will return a function that have the value column already set.

handleSort: function(value) { 
    return () => {
        console.log(value);
    }
}

The anonymous function will be called with the correct value when the user click on the th.

Example: https://stackblitz.com/edit/react-pass-parameters-example

includes() not working in all browsers

import 'core-js/es7/array' 

into polyfill.ts worked for me.

Creating a BLOB from a Base64 string in JavaScript

The atob function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.

const byteCharacters = atob(b64Data);

Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt method for each character in the string.

const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}

You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor.

const byteArray = new Uint8Array(byteNumbers);

This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob constructor.

const blob = new Blob([byteArray], {type: contentType});

The code above works. However the performance can be improved a little by processing the byteCharacters in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.

const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

window.location = blobUrl;

Full Example:

_x000D_
_x000D_
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {_x000D_
  const byteCharacters = atob(b64Data);_x000D_
  const byteArrays = [];_x000D_
_x000D_
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
    const slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
    const byteNumbers = new Array(slice.length);_x000D_
    for (let i = 0; i < slice.length; i++) {_x000D_
      byteNumbers[i] = slice.charCodeAt(i);_x000D_
    }_x000D_
_x000D_
    const byteArray = new Uint8Array(byteNumbers);_x000D_
    byteArrays.push(byteArray);_x000D_
  }_x000D_
_x000D_
  const blob = new Blob(byteArrays, {type: contentType});_x000D_
  return blob;_x000D_
}_x000D_
_x000D_
const contentType = 'image/png';_x000D_
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
const blob = b64toBlob(b64Data, contentType);_x000D_
const blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
const img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
_x000D_
_x000D_

Generating a unique machine id

What about just using the UniqueID of the processor?

npm ERR cb() never called

For mac users (HighSierra), do not install node using brew. It'll mess up with npm. I had to uninstall node and install using the package in the main nodejs.org source : https://nodejs.org/en/

Here's a simple guide that doesn't use brew: https://coolestguidesontheplanet.com/installing-node-js-on-macos/

How do I inject a controller into another controller in AngularJS

I'd suggest the question you should be asking is how to inject services into controllers. Fat services with skinny controllers is a good rule of thumb, aka just use controllers to glue your service/factory (with the business logic) into your views.

Controllers get garbage collected on route changes, so for example, if you use controllers to hold business logic that renders a value, your going to lose state on two pages if the app user clicks the browser back button.

var app = angular.module("testApp", ['']);

app.factory('methodFactory', function () {
    return { myMethod: function () {
            console.log("methodFactory - myMethod");
    };
};

app.controller('TestCtrl1', ['$scope', 'methodFactory', function ($scope,methodFactory) {  //Comma was missing here.Now it is corrected.
    $scope.mymethod1 = methodFactory.myMethod();
}]);

app.controller('TestCtrl2', ['$scope', 'methodFactory', function ($scope, methodFactory) {
    $scope.mymethod2 = methodFactory.myMethod();
}]);

Here is a working demo of factory injected into two controllers

Also, I'd suggest having a read of this tutorial on services/factories.

How can I insert new line/carriage returns into an element.textContent?

nelek's answer is the best one posted so far, but it relies on setting the css value: white-space: pre, which might be undesirable.

I'd like to offer a different solution, which tries to tackle the real question that should've been asked here:

"How to insert untrusted text into a DOM element?"

If you trust the text, why not just use innerHTML?

domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '<br>');

should be sufficient for all the reasonable cases.

If you decided you should use .textContent instead of .innerHTML, it means you don't trust the text that you're about to insert, right? This is a reasonable concern.

For example, you have a form where the user can create a post, and after posting it, the post text is stored in your database, and later on appended to pages whenever other users visit the relevant page.

If you use innerHTML here, you get a security breach. i.e., a user can post something like

[script]alert(1);[/script]

(try to imagine that [] are <>, apparently stack overflow is appending text in unsafe ways!)

which won't trigger an alert if you use innerHTML, but it should give you an idea why using innerHTML can have issues. a smarter user would post

[img src="invalid_src" onerror="alert(1)"]

which would trigger an alert for every other user that visits the page. Now we have a problem. An even smarter user would put display: none on that img style, and make it post the current user's cookies to a cross domain site. Congratulations, all your user login details are now exposed on the internet.

So, the important thing to understand is, using innerHTML isn't wrong, it's perfect if you're just using it to build templates using only your own trusted developer code. The real question should've been "how do I append untrusted user text that has newlines to my HTML document".

This raises a question: which strategy do we use for newlines? do we use [br] elements? [p]s or [div]s?

Here is a short function that solves the problem:

function insertUntrustedText(domElement, untrustedText, newlineStrategy) {
    domElement.innerHTML = '';
    var lines = untrustedText.replace(/\r/g, '').split('\n');
    var linesLength = lines.length;
    if(newlineStrategy === 'br') {
        for(var i = 0; i < linesLength; i++) {
            domElement.appendChild(document.createTextNode(lines[i]));
            domElement.appendChild(document.createElement('br'));
        }
    }
    else {
        for(var i = 0; i < linesLength; i++) {
            var lineElement = document.createElement(newlineStrategy);
            lineElement.textContent = lines[i];
            domElement.appendChild(lineElement);
        }
    }
}

You can basically throw this somewhere in your common_functions.js file and then just fire and forget whenever you need to append any user/api/etc -> untrusted text (i.e. not-written-by-your-own-developer-team) to your html pages.

usage example:

insertUntrustedText(document.querySelector('.myTextParent'), 'line1\nline2\r\nline3', 'br');

the parameter newlineStrategy accepts only valid dom element tags, so if you want [br] newlines, pass 'br', if you want each line in a [p] element, pass 'p', etc.

How to get the current directory in a C program?

Note that getcwd(3) is also available in Microsoft's libc: getcwd(3), and works the same way you'd expect.

Must link with -loldnames (oldnames.lib, which is done automatically in most cases), or use _getcwd(). The unprefixed version is unavailable under Windows RT.

Viewing unpushed Git commits

Handy git alias for looking for unpushed commits in current branch:

alias unpushed = !GIT_CURRENT_BRANCH=$(git name-rev --name-only HEAD) && git log origin/$GIT_CURRENT_BRANCH..$GIT_CURRENT_BRANCH --oneline

What this basically does:

git log origin/branch..branch

but also determines current branch name.

Cannot make Project Lombok work on Eclipse

You not only have to add lombok.jar to the libraries, but also install it by either double-clicking the lombok jar, or from the command line run java -jar lombok.jar. That will show you a nice installer screen. Select your Eclipse installation and install.

Afterwards, you can check if the installer has correctly modified your eclipse.ini:

-vmargs
...
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar

If your Eclipse was already running, you have to Exit Eclipse and start it again. (File/Restart is not enough)

If you are starting Eclipse using a shortcut, make sure that either there are no command line arguments filled in, or manually add -javaagent:lombok.jar -Xbootclasspath/a:lombok.jar somewhere after -vmargs.

Recent editions of Lombok also add a line to the About Eclipse screen. If Lombok is active you can find a line like 'Lombok v0.11.6 "Dashing Kakapo" is installed. http://projectlombok.org/' just above the line of buttons.

If for some reason, usually related to customized eclipse builds, you need to use the full path, you can instruct the installer on the command line to do so:

java -Dlombok.installer.fullpath -jar lombok.jar

what is the difference between ajax and jquery and which one is better?

AJAX is a technique to do an XMLHttpRequest (out of band Http request) from a web page to the server and send/retrieve data to be used on the web page. AJAX stands for Asynchronous Javascript And XML. It uses javascript to construct an XMLHttpRequest, typically using different techniques on various browsers.

jQuery (website) is a javascript framework that makes working with the DOM easier by building lots of high level functionality that can be used to search and interact with the DOM. Part of the functionality of jQuery implements a high-level interface to do AJAX requests. jQuery implements this interface abstractly, shielding the developer from the complexity of multi-browser support in making the request.

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

jQuery "on create" event for dynamically-created elements

For me binding to the body does not work. Binding to the document using jQuery.bind() does.

$(document).bind('DOMNodeInserted',function(e){
             var target = e.target;
         });

Java, "Variable name" cannot be resolved to a variable

I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:

String cannot be resolved to a variable

With this Java code:

if (true)
    String my_variable = "somevalue";
    System.out.println("foobar");

You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?

Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.

If you put braces around the conditional block like this:

if (true){
    String my_variable = "somevalue"; }
    System.out.println("foobar");

Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

How do I calculate someone's age based on a DateTime type birthday?

Here is a very simple and easy to follow example.

private int CalculateAge()
{
//get birthdate
   DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
   int byear = dtBirth.Year;
   int bmonth = dtBirth.Month;
   int bday = dtBirth.Day;
   DateTime dtToday = DateTime.Now;
   int tYear = dtToday.Year;
   int tmonth = dtToday.Month;
   int tday = dtToday.Day;
   int age = tYear - byear;
   if (bmonth < tmonth)
       age--;
   else if (bmonth == tmonth && bday>tday)
   {
       age--;
   }
return age;
}

Animate element to auto height with jQuery

You can always wrap the child elements of #first and save height height of the wrapper as a variable. This might not be the prettiest or most efficient answer, but it does the trick.

Here's a fiddle where I included a reset.

but for your purposes, here's the meat & potatoes:

$(function(){
//wrap everything inside #first
$('#first').children().wrapAll('<div class="wrapper"></div>');
//get the height of the wrapper 
var expandedHeight = $('.wrapper').height();
//get the height of first (set to 200px however you choose)
var collapsedHeight = $('#first').height();
//when you click the element of your choice (a button in my case) #first will animate to height auto
$('button').click(function(){
    $("#first").animate({
        height: expandedHeight            
    })
});
});?

How can I change my Cygwin home folder after installation?

I'd like to add a correction/update to the bit about $HOME taking precedence. The home directory in /etc/passwd takes precedence over everything.

I'm a long time Cygwin user and I just did a clean install of Windows 7 x64 and Cygwin V1.126. I was going nuts trying to figure out why every time I ran ssh I kept getting:

e:\>ssh foo.bar.com
Could not create directory '/home/dhaynes/.ssh'.
The authenticity of host 'foo.bar.com (10.66.19.19)' can't be established.
...

I add the HOME=c:\users\dhaynes definition in the Windows environment but still it kept trying to create '/home/dhaynes'. I tried every combo I could including setting HOME to /cygdrive/c/users/dhaynes. Googled for the error message, could not find anything, couldn't find anything on the cygwin site. I use cygwin from cmd.exe, not bash.exe but the problem was present in both.

I finally realized that the home directory in /etc/passwd was taking precedence over the $HOME environment variable. I simple re-ran 'mkpasswd -l >/etc/passwd' and that updated the home directory, now all is well with ssh.

That may be obvious to linux types with sysadmin experience but for those of us who primarily use Windows it's a bit obscure.

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

grant remote access of MySQL database from any IP address

Assuming that the above step is completed and MySql port 3306 is free to be accessed remotely; Don't forget to bind the public ip address in the mysql config file.

For example on my ubuntu server:

#nano /etc/mysql/my.cnf

In the file, search for the [mysqld] section block and add the new bind address, in this example it is 192.168.0.116. It would look something like this

......    
.....    
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.

bind-address        = 127.0.0.1    
bind-address        = 192.168.0.116

.....    
......

you can remove th localhost(127.0.0.1) binding if you choose, but then you have to specifically give an IP address to access the server on the local machine.

Then the last step is to restart the MySql server (on ubuntu)

stop mysql

start mysql

or #/etc/init.d/mysql restart for other systems

Now the MySQL database can be accessed remotely by:

mysql -u username -h 192.168.0.116 -p

How to get the client IP address in PHP

The following is the most advanced method I have found, and I have already tried some others in the past. It is valid to ensure to get the IP address of a visitor (but please note that any hacker could falsify the IP address easily).

function get_ip_address() {

    // Check for shared Internet/ISP IP
    if (!empty($_SERVER['HTTP_CLIENT_IP']) && validate_ip($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }

    // Check for IP addresses passing through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

        // Check if multiple IP addresses exist in var
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
            $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($iplist as $ip) {
                if (validate_ip($ip))
                    return $ip;
            }
        }
        else {
            if (validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
        return $_SERVER['HTTP_X_FORWARDED'];
    if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
        return $_SERVER['HTTP_FORWARDED_FOR'];
    if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
        return $_SERVER['HTTP_FORWARDED'];

    // Return unreliable IP address since all else failed
    return $_SERVER['REMOTE_ADDR'];
}

/**
 * Ensures an IP address is both a valid IP address and does not fall within
 * a private network range.
 */
function validate_ip($ip) {

    if (strtolower($ip) === 'unknown')
        return false;

    // Generate IPv4 network address
    $ip = ip2long($ip);

    // If the IP address is set and not equivalent to 255.255.255.255
    if ($ip !== false && $ip !== -1) {
        // Make sure to get unsigned long representation of IP address
        // due to discrepancies between 32 and 64 bit OSes and
        // signed numbers (ints default to signed in PHP)
        $ip = sprintf('%u', $ip);

        // Do private network range checking
        if ($ip >= 0 && $ip <= 50331647)
            return false;
        if ($ip >= 167772160 && $ip <= 184549375)
            return false;
        if ($ip >= 2130706432 && $ip <= 2147483647)
            return false;
        if ($ip >= 2851995648 && $ip <= 2852061183)
            return false;
        if ($ip >= 2886729728 && $ip <= 2887778303)
            return false;
        if ($ip >= 3221225984 && $ip <= 3221226239)
            return false;
        if ($ip >= 3232235520 && $ip <= 3232301055)
            return false;
        if ($ip >= 4294967040)
            return false;
    }
    return true;
}

regular expression for finding 'href' value of a <a> link

I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href attribute of each links. It will match whether double or single quotes are used.

<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1

You can view a full explanation of this regex at here.

Snippet playground:

_x000D_
_x000D_
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
  console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
  Text to match:_x000D_
  <input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
  _x000D_
  <button>Match</button>_x000D_
 </label>
_x000D_
_x000D_
_x000D_

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

Check your dependencies for uses of + in the versions. Some dependency could be using com.android.support:appcompat-v7:+. This leads to problems when a new version gets released and could break features.

The solution for this would be to either use com.android.support:appcompat-v7:{compileSdkVersion}.+ or don't use + at all and use the full version (ex. com.android.support:appcompat-v7:26.1.0).

If you cannot see a line in your build.gradle files for this, run in android studio terminal to give an overview of what each dependency uses

gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath (include androidtest dependencies)

OR

gradlew -q dependencies app:dependencies --configuration debugCompileClasspath (regular dependencies for debug)

which results in something that looks close to this

------------------------------------------------------------
Project :app
------------------------------------------------------------

debugCompileClasspath - Resolved configuration for compilation for variant: debug
...
+--- com.android.support:appcompat-v7:26.1.0
|    +--- com.android.support:support-annotations:26.1.0
|    +--- com.android.support:support-v4:26.1.0 (*)
|    +--- com.android.support:support-vector-drawable:26.1.0
|    |    +--- com.android.support:support-annotations:26.1.0
|    |    \--- com.android.support:support-compat:26.1.0 (*)
|    \--- com.android.support:animated-vector-drawable:26.1.0
|         +--- com.android.support:support-vector-drawable:26.1.0 (*)
|         \--- com.android.support:support-core-ui:26.1.0 (*)
+--- com.android.support:design:26.1.0
|    +--- com.android.support:support-v4:26.1.0 (*)
|    +--- com.android.support:appcompat-v7:26.1.0 (*)
|    +--- com.android.support:recyclerview-v7:26.1.0
|    |    +--- com.android.support:support-annotations:26.1.0
|    |    +--- com.android.support:support-compat:26.1.0 (*)
|    |    \--- com.android.support:support-core-ui:26.1.0 (*)
|    \--- com.android.support:transition:26.1.0
|         +--- com.android.support:support-annotations:26.1.0
|         \--- com.android.support:support-v4:26.1.0 (*)
+--- com.android.support.constraint:constraint-layout:1.0.2
|    \--- com.android.support.constraint:constraint-layout-solver:1.0.2

(*) - dependencies omitted (listed previously)

If you have no control over changing the version, Try forcing it to use a specific version.

configurations.all {
    resolutionStrategy {
        force "com.android.support:appcompat-v7:26.1.0"
        force "com.android.support:support-v4:26.1.0"
    }
}

The force dependency may need to be different depending on what is being set to 28.0.0

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

How to use sed to replace only the first occurrence in a file?

The following command removes the first occurrence of a string, within a file. It removes the empty line too. It is presented on an xml file, but it would work with any file.

Useful if you work with xml files and you want to remove a tag. In this example it removes the first occurrence of the "isTag" tag.

Command:

sed -e 0,/'<isTag>false<\/isTag>'/{s/'<isTag>false<\/isTag>'//}  -e 's/ *$//' -e  '/^$/d'  source.txt > output.txt

Source file (source.txt)

<xml>
    <testdata>
        <canUseUpdate>true</canUseUpdate>
        <isTag>false</isTag>
        <moduleLocations>
            <module>esa_jee6</module>
            <isTag>false</isTag>
        </moduleLocations>
        <node>
            <isTag>false</isTag>
        </node>
    </testdata>
</xml>

Result file (output.txt)

<xml>
    <testdata>
        <canUseUpdate>true</canUseUpdate>
        <moduleLocations>
            <module>esa_jee6</module>
            <isTag>false</isTag>
        </moduleLocations>
        <node>
            <isTag>false</isTag>
        </node>
    </testdata>
</xml>

ps: it didn't work for me on Solaris SunOS 5.10 (quite old), but it works on Linux 2.6, sed version 4.1.5

Where in memory are my variables stored in C?

I am referring to these variables only from the C perspective.

From the perspective of the C language, all that matters is extent, scope, linkage, and access; exactly how items are mapped to different memory segments is up to the individual implementation, and that will vary. The language standard doesn't talk about memory segments at all. Most modern architectures act mostly the same way; block-scope variables and function arguments will be allocated from the stack, file-scope and static variables will be allocated from a data or code segment, dynamic memory will be allocated from a heap, some constant data will be stored in read-only segments, etc.

MySQL selecting yesterday's date

Query for the last weeks:

SELECT *
FROM dual
WHERE search_date BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE()

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Pull "pulls" the div towards the left of the browser and and Push "pushes" the div away from left of browser.

Like: enter image description here

So basically in a 3 column layout of any web page the "Main Body" appears at the "Center" and in "Mobile" view the "Main Body" appears at the "Top" of the page. This is mostly desired by everyone with 3 column layout.

<div class="container">
    <div class="row">
        <div id="content" class="col-lg-4 col-lg-push-4 col-sm-12">
        <h2>This is Content</h2>
        <p>orem Ipsum ...</p>
        </div>

        <div id="sidebar-left" class="col-lg-4  col-sm-6 col-lg-pull-4">
        <h2>This is Left Sidebar</h2>
        <p>orem Ipsum...</p>
        </div>


        <div id="sidebar-right" class="col-lg-4 col-sm-6">
        <h2>This is Right Sidebar</h2>
        <p>orem Ipsum.... </p>
        </div>
    </div>
</div>

You can view it here: http://jsfiddle.net/DrGeneral/BxaNN/1/

Hope it helps

sql insert into table with select case values

Also you can use COALESCE instead of CASE expression. Because result of concatenating anything to NULL, even itself, is always NULL

INSERT TblStuff(FullName,Address,City,Zip)
SELECT COALESCE(Fname + ' ' + Middle + ' ' + Lname, Fname + LName) AS FullName,
       COALESCE(Address1 + ', ' + Address2, Address1) AS Address, City, Zip
FROM tblImport

Demo on SQLFiddle

Programmatically set the initial view controller using Storyboards

Swift 5 or above# make route view controller by this simple code. If you are using xcode 11 or above first initialise var window: UIWindow? in AppDelegate

let rootVC = mainStoryboard.instantiateViewController(withIdentifier: "YOURCONTROLLER") as! YOURCONTROLLER

        navigationController.setNavigationBarHidden(true, animated: true)
        UIApplication.shared.windows.first?.rootViewController = UINavigationController.init(rootViewController: rootVC)
        UIApplication.shared.windows.first?.makeKeyAndVisible()

How to generate .env file for laravel?

.env files are hidden by Netbeans. To show them do this:

Tools > Options > Miscellaneous > Files

Under Files Ignored be the IDE is Ignored Files Pattern:

The default is

^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~$|^\.(?!(htaccess|git.+|hgignore)$).*$

Add env to the excluded-not-excluded bit

^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~$|^\.(?!(env|htaccess|git.+|hgignore)$).*$

Files named .env now show.

Turn a single number into single digits Python

The easiest way is to turn the int into a string and take each character of the string as an element of your list:

>>> n = 43365644 
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits)  # use the extends method if you want to add the list to another

It involves a casting operation, but it's readable and acceptable if you don't need extreme performance.

How to serve up images in Angular2?

In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png. This will work fine because browser will make request to server for that image and webpack will be able serve that image.

Dismissing a Presented View Controller

In addition to Michael Enriquez's answer, I can think of one other reason why this may be a good way to protect yourself from an undetermined state:

Say ViewControllerA presents ViewControllerB modally. But, since you may not have written the code for ViewControllerA you aren't aware of the lifecycle of ViewControllerA. It may dismiss 5 seconds (say) after presenting your view controller, ViewControllerB.

In this case, if you were simply using dismissViewController from ViewControllerB to dismiss itself, you would end up in an undefined state--perhaps not a crash or a black screen but an undefined state from your point of view.

If, instead, you were using the delegate pattern, you would be aware of the state of ViewControllerB and you can program for a case like the one I described.

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

AngularJS : The correct way of binding to a service properties

I think it's a better way to bind on the service itself instead of the attributes on it.

Here's why:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<body ng-app="BindToService">

  <div ng-controller="BindToServiceCtrl as ctrl">
    ArrService.arrOne: <span ng-repeat="v in ArrService.arrOne">{{v}}</span>
    <br />
    ArrService.arrTwo: <span ng-repeat="v in ArrService.arrTwo">{{v}}</span>
    <br />
    <br />
    <!-- This is empty since $scope.arrOne never changes -->
    arrOne: <span ng-repeat="v in arrOne">{{v}}</span>
    <br />
    <!-- This is not empty since $scope.arrTwo === ArrService.arrTwo -->
    <!-- Both of them point the memory space modified by the `push` function below -->
    arrTwo: <span ng-repeat="v in arrTwo">{{v}}</span>
  </div>

  <script type="text/javascript">
    var app = angular.module("BindToService", []);

    app.controller("BindToServiceCtrl", function ($scope, ArrService) {
      $scope.ArrService = ArrService;
      $scope.arrOne = ArrService.arrOne;
      $scope.arrTwo = ArrService.arrTwo;
    });

    app.service("ArrService", function ($interval) {
      var that = this,
          i = 0;
      this.arrOne = [];
      that.arrTwo = [];

      $interval(function () {
        // This will change arrOne (the pointer).
        // However, $scope.arrOne is still same as the original arrOne.
        that.arrOne = that.arrOne.concat([i]);

        // This line changes the memory block pointed by arrTwo.
        // And arrTwo (the pointer) itself never changes.
        that.arrTwo.push(i);
        i += 1;
      }, 1000);

    });
  </script>
</body> 

You can play it on this plunker.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

Guys in my case none of the solutions above worked.

I had to delete the files within the Project workspace:

  • .project
  • .classpath

And the folder:

  • .settings

Then I copied the ones from a similar project that was working before. This managed to fix my broken project.

Of course do not use this method before trying the previous alternatives!.

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

How to convert a list into data table

you can use this extension method and call it like this.

DataTable dt =   YourList.ToDataTable();

public static DataTable ToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

On Windows 10,

I just solved this issue by doing the following.

  1. Goto my.ini and add these 2 lines under [mysqld]

    skip-log-bin
    log_bin_trust_function_creators = 1
    
  2. restart MySQL service

Fatal error: Call to a member function prepare() on null

In ---- model: Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

Change the class ----- extends Model to class ----- extends Eloquent

How to check Elasticsearch cluster health?

PROBLEM :-

Sometimes, Localhost may not get resolved. So it tends to return an output as seen below :

# curl -XGET localhost:9200/_cluster/health?pretty

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

# curl -XGET localhost:9200/_cat/indices

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

SOLUTION :-

Guess, this error is most probably returned by Local Squid deployed in the server.

So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.

Responsive css background images

    <style> 
         * {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

#res_img {
  background: url("https://s15.postimg.org/ve2qzi01n/image_slider_1.jpg");
  width: 100%;
  height: 500px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  border: 1px solid red;
}

@media screen and (min-width:300px) and (max-width:500px) {
  #res_img {
    width: 100%;
    height: 200px;
  }
}

    </style>

<div id="res_img">
</div>

Android load from URL to Bitmap

I Prefer these one:

Creates Bitmap from InputStream and returns it:

    public static  Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
            stream.close();
        }
        catch (IOException e1) {
            e1.printStackTrace();
            System.out.println("downloadImage"+ e1.toString());
        }
        return bitmap;
    }

  // Makes HttpURLConnection and returns InputStream

 public static  InputStream getHttpConnection(String urlString)  throws IOException {

        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("downloadImage" + ex.toString());
        }
        return stream;
    }

REMEMBER :

Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. For Gingerbread and later, HttpURLConnection is the best choice.

From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below

/**     AsyncTAsk for Image Bitmap  */
    private class AsyncGettingBitmapFromUrl extends AsyncTask<String, Void, Bitmap> {


        @Override
        protected Bitmap doInBackground(String... params) {

            System.out.println("doInBackground");

            Bitmap bitmap = null;

            bitmap = AppMethods.downloadImage(params[0]);

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {

            System.out.println("bitmap" + bitmap);

        }
    }

Add vertical scroll bar to panel

Below is the code that implements custom vertical scrollbar. The important detail here is to know when scrollbar is needed by calculating how much space is consumed by the controls that you add to the panel.

panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;

// here you'd be adding controls

int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
    // this example uses textbox control
    TextBox txt = new TextBox();
    txt.Location = new System.Drawing.Point(x, y);
    // add whatever details you need for this control
    // before adding it to the panel
    panelUserInput.Controls.Add(txt);
    height = y + txt.Height;
    y += 25;
}
if (height > panelUserInput.Height)
{
    VScrollBar bar = new VScrollBar();
    bar.Dock = DockStyle.Right;
    bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value =  bar.Value; };
    bar.Top = 0;
    bar.Left = panelUserInput.Width - bar.Width;
    bar.Height = panelUserInput.Height;
    bar.Visible = true;
    panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();

// then update the form
this.PerformLayout();

Explanation of <script type = "text/template"> ... </script>

jQuery Templates is an example of something that uses this method to store HTML that will not be rendered directly (that’s the whole point) inside other HTML: http://api.jquery.com/jQuery.template/