Programs & Examples On #Mako

Mako is a template library written in Python. It provides a familiar, non-XML syntax which compiles into Python modules for maximum performance. Conceptually, Mako is an embedded Python (i.e. Python Server Page) language.

pip3: command not found

Try this if other methods do not work:

  1. brew install python3
  2. brew link --overwrite python
  3. brew postinstall python3

Uncaught TypeError: undefined is not a function while using jQuery UI

You may see if you are not loading jQuery twice somehow. Especially after your plugin JavaScript file loaded.

I has the same error and found that one of my external PHP files was loading jQuery again.

SQLite select where empty?

There are several ways, like:

where some_column is null or some_column = ''

or

where ifnull(some_column, '') = ''

or

where coalesce(some_column, '') = ''

of

where ifnull(length(some_column), 0) = 0

jQuery: go to URL with target="_blank"

Detect if a target attribute was used and contains "_blank". For mobile devices that don't like "_blank", this is a reliable alternative.

    $('.someSelector').bind('touchend click', function() {

        var url = $('a', this).prop('href');
        var target = $('a', this).prop('target');

        if(url) {
            // # open in new window if "_blank" used
            if(target == '_blank') { 
                window.open(url, target);
            } else {
                window.location = url;
            }
        }           
    });

Is a Java hashmap search really O(1)?

We've established that the standard description of hash table lookups being O(1) refers to the average-case expected time, not the strict worst-case performance. For a hash table resolving collisions with chaining (like Java's hashmap) this is technically O(1+a) with a good hash function, where a is the table's load factor. Still constant as long as the number of objects you're storing is no more than a constant factor larger than the table size.

It's also been explained that strictly speaking it's possible to construct input that requires O(n) lookups for any deterministic hash function. But it's also interesting to consider the worst-case expected time, which is different than average search time. Using chaining this is O(1 + the length of the longest chain), for example T(log n / log log n) when a=1.

If you're interested in theoretical ways to achieve constant time expected worst-case lookups, you can read about dynamic perfect hashing which resolves collisions recursively with another hash table!

How do I make a text go onto the next line if it overflows?

As long as you specify a width on the element, it should wrap itself without needing anything else.

How to create a remote Git repository from a local one?

There is an interesting difference between the two popular solutions above:

  1. If you create the bare repository like this:

    cd     /outside_of_any_repo
    mkdir  my_remote.git
    cd     my_remote.git
    git init --bare
    

and then

cd  /your_path/original_repo
git remote add origin /outside_of_any_repo/my_remote.git
git push --set-upstream origin master

Then git sets up the configuration in 'original_repo' with this relationship:

original_repo origin --> /outside_of_any_repo/my_remote.git/

with the latter as the upstream remote. And the upstream remote doesn't have any other remotes in its configuration.

  1. However, if you do it the other way around:

    (from in directory original_repo)
    cd ..
    git clone --bare original_repo  /outside_of_any_repo/my_remote.git
    

then 'my_remote.git' winds up with its configuration having 'origin' pointing back to 'original_repo' as a remote, with a remote.origin.url equating to local directory path, which might not be appropriate if it is going to be moved to a server.

While that "remote" reference is easy to get rid of later if it isn't appropriate, 'original_repo' still has to be set up to point to 'my_remote.git' as an up-stream remote (or to wherever it is going to be shared from). So technically, you can arrive at the same result with a few more steps with approach #2. But #1 seems a more direct approach to creating a "central bare shared repo" originating from a local one, appropriate for moving to a server, with fewer steps involved. I think it depends on the role you want the remote repo to play. (And yes, this is in conflict with the documentation here.)

Caveat: I learned the above (at this writing in early August 2019) by doing a test on my local system with a real repo, and then doing a file-by-file comparison between the results. But! I am still learning, so there could be a more correct way. But my tests have helped me conclude that #1 is my currently-preferred method.

jQuery .slideRight effect

If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide(), with additional arguments, as follows:

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this).hide('slide',{direction:'right'},1000);

            });
    });

JS Fiddle demo.


Without using jQuery UI, you could achieve your aim just using animate():

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this)
                    .animate(
                        {
                            'margin-left':'1000px'
                            // to move it towards the right and, probably, off-screen.
                        },1000,
                        function(){
                            $(this).slideUp('fast');
                            // once it's finished moving to the right, just 
                            // removes the the element from the display, you could use
                            // `remove()` instead, or whatever.
                        }
                        );

            });
    });

JS Fiddle demo

If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

Where is Maven Installed on Ubuntu

Ubuntu 11.10 doesn't have maven3 in repo.

Follow below step to install maven3 on ubuntu 11.10

sudo add-apt-repository ppa:natecarlson/maven3
sudo apt-get update && sudo apt-get install maven3

Open terminal: mvn3 -v

if you want mvn as a binary then execute below script:

sudo ln -s /usr/bin/mvn3 /usr/bin/mvn

I hope this will help you.

Thanks, Rajam

get UTC timestamp in python with datetime

Naïve datetime versus aware datetime

Default datetime objects are said to be "naïve": they keep time information without the time zone information. Think about naïve datetime as a relative number (ie: +4) without a clear origin (in fact your origin will be common throughout your system boundary).

In contrast, think about aware datetime as absolute numbers (ie: 8) with a common origin for the whole world.

Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4 targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp() method. (cf: http://bugs.python.org/issue1457227)

To check if your datetime dt is naïve, check dt.tzinfo, if None, then it's naïve:

datetime.now()        ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1)  ## returns naïve datetime pointing on user given time

I have naïve datetimes, what can I do ?

You must make an assumption depending on your particular context: The question you must ask yourself is: was your datetime on UTC ? or was it local time ?

  • If you were using UTC (you are out of trouble):

    import calendar
    
    def dt2ts(dt):
        """Converts a datetime object to UTC timestamp
    
        naive datetime will be considered UTC.
    
        """
    
        return calendar.timegm(dt.utctimetuple())
    
  • If you were NOT using UTC, welcome to hell.

    You have to make your datetime non-naïve prior to using the former function, by giving them back their intended timezone.

    You'll need the name of the timezone and the information about if DST was in effect when producing the target naïve datetime (the last info about DST is required for cornercases):

    import pytz     ## pip install pytz
    
    mytz = pytz.timezone('Europe/Amsterdam')             ## Set your timezone
    
    dt = mytz.normalize(mytz.localize(dt, is_dst=True))  ## Set is_dst accordingly
    

    Consequences of not providing is_dst:

    Not using is_dst will generate incorrect time (and UTC timestamp) if target datetime was produced while a backward DST was put in place (for instance changing DST time by removing one hour).

    Providing incorrect is_dst will of course generate incorrect time (and UTC timestamp) only on DST overlap or holes. And, when providing also incorrect time, occuring in "holes" (time that never existed due to forward shifting DST), is_dst will give an interpretation of how to consider this bogus time, and this is the only case where .normalize(..) will actually do something here, as it'll then translate it as an actual valid time (changing the datetime AND the DST object if required). Note that .normalize() is not required for having a correct UTC timestamp at the end, but is probably recommended if you dislike the idea of having bogus times in your variables, especially if you re-use this variable elsewhere.

    and AVOID USING THE FOLLOWING: (cf: Datetime Timezone conversion using pytz)

    dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))  ## BAD !!
    

    Why? because .replace() replaces blindly the tzinfo without taking into account the target time and will choose a bad DST object. Whereas .localize() uses the target time and your is_dst hint to select the right DST object.

OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):

Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.

By using time.mktime we can create an utc_mktime:

def utc_mktime(utc_tuple):
    """Returns number of seconds elapsed since epoch

    Note that no timezone are taken into consideration.

    utc tuple must be: (year, month, day, hour, minute, second)

    """

    if len(utc_tuple) == 6:
        utc_tuple += (0, 0, 0)
    return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))

def datetime_to_timestamp(dt):
    """Converts a datetime object to UTC timestamp"""

    return int(utc_mktime(dt.timetuple()))

You must make sure that your datetime object is created on the same timezone than the one that has created your datetime.

This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).

How to abort makefile if variable not set?

TL;DR: Use the error function:

ifndef MY_FLAG
$(error MY_FLAG is not set)
endif

Note that the lines must not be indented. More precisely, no tabs must precede these lines.


Generic solution

In case you're going to test many variables, it's worth defining an auxiliary function for that:

# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
#   1. Variable name(s) to test.
#   2. (optional) Error message to print.
check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
      $(error Undefined $1$(if $2, ($2))))

And here is how to use it:

$(call check_defined, MY_FLAG)

$(call check_defined, OUT_DIR, build directory)
$(call check_defined, BIN_DIR, where to put binary artifacts)
$(call check_defined, \
            LIB_INCLUDE_DIR \
            LIB_SOURCE_DIR, \
        library path)


This would output an error like this:

Makefile:17: *** Undefined OUT_DIR (build directory).  Stop.

Notes:

The real check is done here:

$(if $(value $1),,$(error ...))

This reflects the behavior of the ifndef conditional, so that a variable defined to an empty value is also considered "undefined". But this is only true for simple variables and explicitly empty recursive variables:

# ifndef and check_defined consider these UNDEFINED:
explicitly_empty =
simple_empty := $(explicitly_empty)

# ifndef and check_defined consider it OK (defined):
recursive_empty = $(explicitly_empty)

As suggested by @VictorSergienko in the comments, a slightly different behavior may be desired:

$(if $(value $1) tests if the value is non-empty. It's sometimes OK if the variable is defined with an empty value. I'd use $(if $(filter undefined,$(origin $1)) ...

And:

Moreover, if it's a directory and it must exist when the check is run, I'd use $(if $(wildcard $1)). But would be another function.

Target-specific check

It is also possible to extend the solution so that one can require a variable only if a certain target is invoked.

$(call check_defined, ...) from inside the recipe

Just move the check into the recipe:

foo :
    @:$(call check_defined, BAR, baz value)

The leading @ sign turns off command echoing and : is the actual command, a shell no-op stub.

Showing target name

The check_defined function can be improved to also output the target name (provided through the $@ variable):

check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
        $(error Undefined $1$(if $2, ($2))$(if $(value @), \
                required by target `$@')))

So that, now a failed check produces a nicely formatted output:

Makefile:7: *** Undefined BAR (baz value) required by target `foo'.  Stop.

check-defined-MY_FLAG special target

Personally I would use the simple and straightforward solution above. However, for example, this answer suggests using a special target to perform the actual check. One could try to generalize that and define the target as an implicit pattern rule:

# Check that a variable specified through the stem is defined and has
# a non-empty value, die with an error otherwise.
#
#   %: The name of the variable to test.
#   
check-defined-% : __check_defined_FORCE
    @:$(call check_defined, $*, target-specific)

# Since pattern rules can't be listed as prerequisites of .PHONY,
# we use the old-school and hackish FORCE workaround.
# You could go without this, but otherwise a check can be missed
# in case a file named like `check-defined-...` exists in the root 
# directory, e.g. left by an accidental `make -t` invocation.
.PHONY : __check_defined_FORCE
__check_defined_FORCE :

Usage:

foo :|check-defined-BAR

Notice that the check-defined-BAR is listed as the order-only (|...) prerequisite.

Pros:

  • (arguably) a more clean syntax

Cons:

I believe, these limitations can be overcome using some eval magic and secondary expansion hacks, although I'm not sure it's worth it.

can you host a private repository for your organization to use with npm?

A little late to the party, but NodeJS (as of ~Nov 14 I guess) supports corporate NPM repositories - you can find out more on their official site.

From a cursory glance it would appear that npmE allows fall-through mirroring of the NPM repository - that is, it will look up packages in the real NPM repository if it can't find one on your internal one. Seems very useful!

npm Enterprise is an on-premises solution for securely sharing and distributing JavaScript modules within your organization, from the team that maintains npm and the public npm registry. It's designed for teams that need:

easy internal sharing of private modules better control of development and deployment workflow stricter security around deploying open-source modules compliance with legal requirements to host code on-premises npmE is private npm

npmE is an npm registry that works with the same standard npm client you already use, but provides the features needed by larger organizations who are now enthusiastically adopting node. It's built by npm, Inc., the sponsor of the npm open source project and the host of the public npm registry.

Unfortunately, it's not free. You can get a trial, but it is commerical software. This is the not so great bit for solo developers, but if you're a solo developer, you have GitHub :-)

Using relative URL in CSS file, what location is it relative to?

In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.

For example, suppose the following rule:

body { background: url("yellow") }

is located in a style sheet designated by the URI:

http://www.example.org/style/basic.css

The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI

http://www.example.org/style/yellow

User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.

Taken from the CSS 2.1 spec.

Python code to remove HTML tags from a string

Note that this isn't perfect, since if you had something like, say, <a title=">"> it would break. However, it's about the closest you'd get in non-library Python without a really complex function:

import re

TAG_RE = re.compile(r'<[^>]+>')

def remove_tags(text):
    return TAG_RE.sub('', text)

However, as lvc mentions xml.etree is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml version:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

how to destroy bootstrap modal window completely?

With ui-router this may be an option for you. It reloads the controller on close so reinitializes the modal contents before it fires next time.

$("#myModalId").on('hidden.bs.modal', function () {
  $state.reload();  //resets the modal
});

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

quick answer is this:

sh "ls -l > commandResult"
result = readFile('commandResult').trim()

I think there exist a feature request to be able to get the result of sh step, but as far as I know, currently there is no other option.

EDIT: JENKINS-26133

EDIT2: Not quite sure since what version, but sh/bat steps now can return the std output, simply:

def output = sh returnStdout: true, script: 'ls -l'

How can I dynamically add items to a Java array?

keep a count of where you are in the primitive array

class recordStuff extends Thread
{
    double[] aListOfDoubles;
    int i = 0;

    void run()
    {
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());
    }

    void doStuff()
    {
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
        {
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
            {
                if (a[j] == a[i]) count++;
            }
            if (count > maxCount) 
            {
                maxCount = count;
                maxValue = aListOfDoubles[i];
            }
        }
        return maxValue;
    }
}

How to list active / open connections in Oracle?

The following gives you list of operating system users sorted by number of connections, which is useful when looking for excessive resource usage.

select osuser, count(*) as active_conn_count 
from v$session 
group by osuser 
order by active_conn_count desc

Redirecting to authentication dialog - "An error occurred. Please try again later"

I had tried all the answers mentioned here. But it didn't work. I had to delete and create again. I am guessing it was due to new the "Authenticated Referral". If you have added Open Graph objects which are not approved, it might give you an error.

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

One obvious thing is that you will have to remove the comma here

receipt int(10),

but the actual problem is because of the line

amount double(10) NOT NULL,

change it to

amount double NOT NULL,

socket.error: [Errno 48] Address already in use

This commonly happened use case for any developer.

It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)

function killport {
   kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
}

Usage:

killport port_number

Example:

killport 8080

chai test array equality doesn't work as expected

Try to use deep Equal. It will compare nested arrays as well as nested Json.

expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });

Please refer to main documentation site.

How do I check if an integer is even or odd?

Here is an answer in Java:

public static boolean isEven (Integer Number) {
    Pattern number = Pattern.compile("^.*?(?:[02]|8|(?:6|4))$");
    String num = Number.toString(Number);
    Boolean numbr = new Boolean(number.matcher(num).matches());
    return numbr.booleanValue();
}

How to echo out the values of this array?

The problem here is in your explode statement

//$item['date'] presumably = 20120514.  Do a print of this
$eventDate = trim($item['date']);

//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));

 //$myarray is currently = to '20'

 foreach ($myarray as $value) {
    //Now you are iterating through a string
    echo $value;
 }

Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.

How can I get href links from HTML using Python?

This is way late to answer but it will work for latest python users:

from bs4 import BeautifulSoup
import requests 


html_page = requests.get('http://www.example.com').text

soup = BeautifulSoup(html_page, "lxml")
for link in soup.findAll('a'):
    print(link.get('href'))

Don't forget to install "requests" and "BeautifulSoup" package and also "lxml". Use .text along with get otherwise it will throw an exception.

"lxml" is used to remove that warning of which parser to be used. You can also use "html.parser" whichever fits your case.

Use sed to replace all backslashes with forward slashes

sed can perform text transformations on input stream from a file or from a pipeline. Example:

echo 'C:\foo\bar.xml' | sed 's/\\/\//g'

gets

C:/foo/bar.xml

Using ResourceManager

I went through a similar issue. If you consider your "YeagerTechResources.Resources", it means that your Resources.resx is at the root folder of your project.

Be careful to include the full path eg : "project\subfolder(s)\file[.resx]" to the ResourceManager constructor.

Access HTTP response as string in Go

The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

Android : change button text and background color

Since API level 21 you can use :

android:backgroundTint="@android:color/white"

you only have to add this in your xml

Git, fatal: The remote end hung up unexpectedly

I dont think its a good idea to do that but if you have backup in ur machine.. push one more time and then try cloning repo and then remove .git from old dir and move .git from new cloned folder .. git is resolved but because of the issue some files may not upload at git. Push again all from ur back up and then pull it to ur server or the other machine where it get currupted. Right now i just did thid ... Works for me .. and take a backup of your dir before doing this.

And plz correct me if i am wrong. I also dont know what can go wrong after doing this? But this time it really works.

How to install the Six module in Python2.7

here's what six is:

pip search six
six                       - Python 2 and 3 compatibility utilities

to install:

pip install six

though if you did install python-dateutil from pip six should have been set as a dependency.

N.B.: to install pip run easy_install pip from command line.

runOnUiThread in fragment

I used this for getting Date and Time in a fragment.

private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_head_screen, container, false);

    dateTextView =  root.findViewById(R.id.dateView);
    hourTv = root.findViewById(R.id.hourView);

        Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //Calendario para obtener fecha & hora
                            Date currentTime = Calendar.getInstance().getTime();
                            SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
                            SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");

                            String currentDate = date_sdf.format(currentTime);
                            String currentHour = hour_sdf.format(currentTime);

                            dateTextView.setText(currentDate);
                            hourTv.setText(currentHour);
                        }
                    });
                }
            } catch (InterruptedException e) {
                Log.v("InterruptedException", e.getMessage());
            }
        }
    };
}

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

A different take with a simple jQuery plugin

Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.

This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.

You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.

All you have to do is to use this plugin on the client side. An Ajax request would look like this:

$.ajax({
    type: "POST",
    url: "SomeURL",
    data: $.toDictionary(yourComplexJSONobject),
    success: function() { ... },
    error: function() { ... }
});

But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.

Display date/time in user's locale format and time offset

Here's what I've used in past projects:

var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set.  again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');

How to use vertical align in bootstrap

Maybe an old topic but if someone needs further help with this do the following for example (this puts the text in middle line of image if it has larger height then the text).

HTML:

<div class="row display-table">
    <div class="col-xs-12 col-sm-4 display-cell">
        img
    </div>
    <div class="col-xs-12 col-sm-8 display-cell">
        text
    </div>
</div>

CSS:

.display-table{
    display: table;
    table-layout: fixed;
}

.display-cell{
    display: table-cell;
    vertical-align: middle;
    float: none;
}

The important thing that I missed out on was "float: none;" since it got float left from bootstrap col attributes.

Cheers!

How to set-up a favicon?

<!DOCTYPE html 
      PUBLIC "-//W3C//DTD HTML 4.01//EN"
      "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" 
      type="image/png" 
      href="http://example.com/myicon.png">
</head>
<body>
...
</body>
</html>

rel="shortcut icon" should be rel="icon"

Source: W3C

How to resize image (Bitmap) to a given size?

In MonoDroid here's how (c#)

/// <summary>
/// Graphics support for resizing images
/// </summary>
public static class Graphics
{
    public static Bitmap ScaleDownBitmap(Bitmap originalImage, float maxImageSize, bool filter)
    {
        float ratio = Math.Min((float)maxImageSize / originalImage.Width, (float)maxImageSize / originalImage.Height);
        int width = (int)Math.Round(ratio * (float)originalImage.Width);
        int height =(int) Math.Round(ratio * (float)originalImage.Height);

        Bitmap newBitmap = Bitmap.CreateScaledBitmap(originalImage, width, height, filter);
        return newBitmap;
    }

    public static Bitmap ScaleBitmap(Bitmap originalImage, int wantedWidth, int wantedHeight)
    {
        Bitmap output = Bitmap.CreateBitmap(wantedWidth, wantedHeight, Bitmap.Config.Argb8888);
        Canvas canvas = new Canvas(output);
        Matrix m = new Matrix();
        m.SetScale((float)wantedWidth / originalImage.Width, (float)wantedHeight / originalImage.Height);
        canvas.DrawBitmap(originalImage, m, new Paint());
        return output;
    }

}

HighCharts Hide Series Name from the Legend

Looks like HighChart 2.2.0 has resolved this issue. I tried it here with the same code you have, and the first series is hidden now. Could you try it with HighChart 2.2.0?

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

Android webview & localStorage

If your app use multiple webview you will still have troubles : localStorage is not correctly shared accross all webviews.

If you want to share the same data in multiple webviews the only way is to repair it with a java database and a javascript interface.

This page on github shows how to do this.

hope this help!

How to change colors of a Drawable in Android?

I know this question was ask way before Lollipop but I would like to add a nice way to do this on Android 5.+. You make an xml drawable that references the original one and set tint on it like such:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

window.location.href doesn't redirect

From this answer,

window.location.href not working

you just need to add

return false;

at the bottom of your function

Visualizing branch topology in Git

To any of these recipes (based on git log or gitk), you can add --simplify-by-decoration to collapse the uninteresting linear parts of the history. This makes much more of the topology visible at once. I can now understand large histories that would be incomprehensible without this option!

I felt the need to post this because it doesn't seem to be as well-known as it should be. It doesn't appear in most of the Stack Overflow questions about visualizing history, and it took me quite a bit of searching to find--even after I knew I wanted it! I finally found it in this Debian bug report. The first mention on Stack Overflow seems to be this answer by Antoine Pelisse.

Install a module using pip for specific python version

If you have both 2.7 and 3.x versions of python installed, then just rename the python exe file of python 3.x version to something like - "python.exe" to "python3.exe". Now you can use pip for both versions individually. If you normally type "pip install " it will consider the 2.7 version by default. If you want to install it on the 3.x version you need to call the command as "python3 -m pip install ".

Simple timeout in java

The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.

/*
 * [RollYourOwnTimeouts.java]
 *
 * Summary: How to roll your own timeouts.
 *
 * Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2016-06-28 initial version
 */
package com.mindprod.example;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static java.lang.System.*;

/**
 * How to roll your own timeouts.
 * Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2016-06-28 initial version
 * @since 2016-06-28
 */

public class RollYourOwnTimeout
    {

    private static final long MILLIS_TO_WAIT = 10 * 1000L;

    public static void main( final String[] args )
        {
        final ExecutorService executor = Executors.newSingleThreadExecutor();

        // schedule the work
        final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );

        try
            {
            // where we wait for task to complete
            final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
            out.println( "result: " + result );
            }

        catch ( TimeoutException e )
            {
            err.println( "task timed out" );
            future.cancel( true /* mayInterruptIfRunning */ );
            }

        catch ( InterruptedException e )
            {
            err.println( "task interrupted" );
            }

        catch ( ExecutionException e )
            {
            err.println( "task aborted" );
            }

        executor.shutdownNow();

        }
/**
 * dummy method to read some data from a website
 */
private static String requestDataFromWebsite()
    {
    try
        {
        // force timeout to expire
        Thread.sleep( 14_000L );
        }
    catch ( InterruptedException e )
        {
        }
    return "dummy";
    }

}

How to change XAMPP apache server port?

I had problem too. I switced Port but couldn't start on 8012.

Skype was involved becouse it had the same port - 80. And it couldn't let apache change it's port.

So just restart computer and Before turning on any other programs Open xampp first change port let's say from 80 to 8000 or 8012 on these lines in httpd.conf

Listen 80
ServerName localhost:80

Restart xampp, Start apache, check localhost.

How to add a href link in PHP?

Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.

.box{
  float:right;
}
.box a img{
  vertical-align: middle;
  border: 0px;
}

<div class="box">
    <a href="<?php echo "http://www.someotherwebsite.com"; ?>">
        <img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
    </a>
</div>

As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.

<div class="box">
    <a href="http://www.someotherwebsite.com">
        <img src="file_location/media/img/twitter.png" alt="Image Decription">
    </a>
</div>

What is a good alternative to using an image map generator?

Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.

This btw is Search Engine Optimised as well :)

Source code follows:

_x000D_
_x000D_
.image-map {
  background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  width: 272px;
  height: 92px;
  display: block;
  position: relative;
  margin-top:10px;
  float: left;
}

.image-map > a.map {
  position: absolute;
  display: block;
  border: 1px solid green;
}
_x000D_
<div class="image-map">
    <a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
    <a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
    <a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
_x000D_
_x000D_

EDIT:

After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.

Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)

However I guess the target audience for this question does not agree with me.

You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.

Vue js error: Component template should contain exactly one root element

You need to wrap all the html into one single element.

<template>
   <div>
        <div class="form-group">
            <label for="avatar" class="control-label">Avatar</label>
            <input type="file" v-on:change="fileChange" id="avatar">
            <div class="help-block">
                Help block here updated 4  ...
            </div>
        </div>

        <div class="col-md-6">
            <input type="hidden" name="avatar_id">
            <img class="avatar" title="Current avatar">
        </div>
   </div>

</template>

<script>
    export default{
        methods: {
            fileChange(){
                console.log('Test of file input change')
            }
        }
    }
</script>

Comparing boxed Long values 127 and 128

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

 For example:
    If we set java.lang.Integer.IntegerCache.high=500;
    then values from -128 to 500 will get cached and 

    Integer a=498;
    Integer b=499;
    System.out.println(a==b)

    Output will be "true".

Float and Double objects never gets cached.

Character will get cache from 0 to 127

You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

1) type cast both objects into primitive values and compare

    (long)val3 == (long)val4

2) read value of object and compare

    val3.longValue() == val4.longValue()

3) Use equals() method on object comparison.

    val3.equals(val4);  

Using the Underscore module with Node.js

The Node REPL uses the underscore variable to hold the result of the last operation, so it conflicts with the Underscore library's use of the same variable. Try something like this:

Admin-MacBook-Pro:test admin$ node
> _und = require("./underscore-min")
{ [Function]
  _: [Circular],
  VERSION: '1.1.4',
  forEach: [Function],
  each: [Function],
  map: [Function],
  inject: [Function],
  (...more functions...)
  templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
  template: [Function] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6

How can I know if a branch has been already merged into master?

Use git merge-base <commit> <commit>.

This command finds best common ancestor(s) between two commits. And if the common ancestor is identical to the last commit of a "branch" ,then we can safely assume that that a "branch" has been already merged into the master.

Here are the steps

  1. Find last commit hash on master branch
  2. Find last commit hash on a "branch"
  3. Run command git merge-base <commit-hash-step1> <commit-hash-step2>.
  4. If output of step 3 is same as output of step 2, then a "branch" has been already merged into master.

More info on git merge-base https://git-scm.com/docs/git-merge-base.

Spring's overriding bean

Question was more about XML but as annotation are more popular nowadays and it works similarly I'll show by example. Let's create class Foo:

public class Foo {
    private String name;

    public String getName() {
        return name;
    }

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

and two Configuration files (you can't create one):

@Configuration
public class Configuration1 {
    @Bean
    public Foo foo() {
        Foo foo = new Foo();
        foo.setName("configuration1");
        return foo;
    }
}

and

@Configuration
public class Configuration2 {
    @Bean
    public Foo foo() {
        Foo foo = new Foo();
        foo.setName("configuration2");
        return foo;
    }
}

and let's see what happens when calling foo.getName():

@SpringBootApplication
public class OverridingBeanDefinitionsApplication {

    public static void main(String[] args) {
        SpringApplication.run(OverridingBeanDefinitionsApplication.class, args);

        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(
                        Configuration1.class, Configuration2.class);

        Foo foo = applicationContext.getBean(Foo.class);
        System.out.println(foo.getName());
    }
}

in this example result is: configuration2. The Spring Container gets all configuration metadata sources and merges bean definitions in those sources. In this example there are two @Beans. Order in which they are fed into ApplicationContext decide. You can flip new AnnotationConfigApplicationContext(Configuration2.class, Configuration1.class); and result will be configuration1.

Onclick event to remove default value in a text input field

u can use placeholder and when u write a text on the search box placeholder will hidden. Thanks

<input placeholder="Search" type="text" />

How to convert string to float?

Use atof()

But this is deprecated, use this instead:

const char* flt = "4.0800";
float f;
sscanf(flt, "%f", &f);

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/

atof() returns 0 for both failure and on conversion of 0.0, best to not use it.

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

How to get Spinner value?

Say this is your xml with spinner entries (ie. titles) and values:

<resources>
    <string-array name="size_entries">
        <item>Small</item>
        <item>Medium</item>
        <item>Large</item>
    </string-array>

    <string-array name="size_values">
        <item>12</item>
        <item>16</item>
        <item>20</item>
    </string-array>
</resources>

and this is your spinner:

<Spinner
    android:id="@+id/size_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/size_entries" />

Then in your code to get the entries:

Spinner spinner = (Spinner) findViewById(R.id.size_spinner);
String size = spinner.getSelectedItem().toString(); // Small, Medium, Large

and to get the values:

int spinner_pos = spinner.getSelectedItemPosition();
String[] size_values = getResources().getStringArray(R.array.size_values);
int size = Integer.valueOf(size_values[spinner_pos]); // 12, 16, 20

How do you get the index of the current iteration of a foreach loop?

For interest, Phil Haack just wrote an example of this in the context of a Razor Templated Delegate (http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx)

Effectively he writes an extension method which wraps the iteration in an "IteratedItem" class (see below) allowing access to the index as well as the element during iteration.

public class IndexedItem<TModel> {
  public IndexedItem(int index, TModel item) {
    Index = index;
    Item = item;
  }

  public int Index { get; private set; }
  public TModel Item { get; private set; }
}

However, while this would be fine in a non-Razor environment if you are doing a single operation (i.e. one that could be provided as a lambda) it's not going to be a solid replacement of the for/foreach syntax in non-Razor contexts.

What are bitwise shift (bit-shift) operators and how do they work?

Bitwise operations, including bit shift, are fundamental to low-level hardware or embedded programming. If you read a specification for a device or even some binary file formats, you will see bytes, words, and dwords, broken up into non-byte aligned bitfields, which contain various values of interest. Accessing these bit-fields for reading/writing is the most common usage.

A simple real example in graphics programming is that a 16-bit pixel is represented as follows:

  bit | 15| 14| 13| 12| 11| 10| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1  | 0 |
      |       Blue        |         Green         |       Red          |

To get at the green value you would do this:

 #define GREEN_MASK  0x7E0
 #define GREEN_OFFSET  5

 // Read green
 uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;

Explanation

In order to obtain the value of green ONLY, which starts at offset 5 and ends at 10 (i.e. 6-bits long), you need to use a (bit) mask, which when applied against the entire 16-bit pixel, will yield only the bits we are interested in.

#define GREEN_MASK  0x7E0

The appropriate mask is 0x7E0 which in binary is 0000011111100000 (which is 2016 in decimal).

uint16_t green = (pixel & GREEN_MASK) ...;

To apply a mask, you use the AND operator (&).

uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;

After applying the mask, you'll end up with a 16-bit number which is really just a 11-bit number since its MSB is in the 11th bit. Green is actually only 6-bits long, so we need to scale it down using a right shift (11 - 6 = 5), hence the use of 5 as offset (#define GREEN_OFFSET 5).

Also common is using bit shifts for fast multiplication and division by powers of 2:

 i <<= x;  // i *= 2^x;
 i >>= y;  // i /= 2^y;

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

Expand a div to fill the remaining width

The solution to this is actually very easy, but not at all obvious. You have to trigger something called a "block formatting context" (BFC), which interacts with floats in a specific way.

Just take that second div, remove the float, and give it overflow:hidden instead. Any overflow value other than visible makes the block it's set on become a BFC. BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them. The net effect here is that the floated div will do its thing, then the second div will be an ordinary block, taking up all available width except that occupied by the float.

This should work across all current browsers, though you may have to trigger hasLayout in IE6 and 7. I can't recall.

Demos:

Alarm Manager Example

Here's a fairly self-contained example. It turns a button red after 5sec.

    public void SetAlarm()
    {
        final Button button = buttons[2]; // replace with a button from your own UI
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override public void onReceive( Context context, Intent _ )
            {
                button.setBackgroundColor( Color.RED );
                context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
            }
        };

        this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );

        PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
        AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));

        // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
        manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
    }

Remember though that the AlarmManager fires even when your application is not running. If you call this function and hit the Home button, wait 5 sec, then go back into your app, the button will have turned red.

I don't know what kind of behavior you would get if your app isn't in memory at all, so be careful with what kind of state you try to preserve.

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

set
{
    _subHead = value;
}

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

Formatting code snippets for blogging on Blogger

1. First, take backup of your blogger template
2. After that open your blogger template (In Edit HTML mode) & copy the all css given in this link before </b:skin> tag
3. Paste the followig code before </head> tag

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>

4. Paste the following code before </body> tag.

<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

5. Save Blogger Template.
6. Now syntax highlighting is ready to use you can use it with <pre></pre> tag.

<pre name="code">
...Your html-escaped code goes here...
</pre>

<pre name="code" class="php">
    echo "I like PHP";
</pre>

7. You can Escape your code here.
8. Here is list of supported language for <class> attribute.

html5 - canvas element - Multiple layers

No, however, you could layer multiple <canvas> elements on top of each other and accomplish something similar.

<div style="position: relative;">
 <canvas id="layer1" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="layer2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

Draw your first layer on the layer1 canvas, and the second layer on the layer2 canvas. Then when you clearRect on the top layer, whatever's on the lower canvas will show through.

Eclipse Bug: Unhandled event loop exception No more handles

I have a nvidia GPU, and if nView is enabled it happens all the time. Try to disable it.

It seems that eclipse is not very compatible with softwares that override system window management on multi screen.

Hint how to disable nView: http://nviewdesktopmanager.blogspot.com/2011/08/how-to-disable-nview-desktop-manager.html

How to join two JavaScript Objects, without using JQUERY

WORKING FIDDLE

Simplest Way with Jquery -

var finalObj = $.extend(obj1, obj2);

Without Jquery -

var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];

How to check SQL Server version

Simply use

SELECT @@VERSION

Sample output

Microsoft SQL Server 2012 - 11.0.2100.60 (X64) 
Feb 10 2012 19:39:15 
Copyright (c) Microsoft Corporation
Express Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )

Source: How to check sql server version? (Various ways explained)

How to remove jar file from local maven repository which was added with install:install-file?

While there is a maven command you can execute to do this, it's easier to just delete the files manually from the repository.

Like this on windows Documents and Settings\your username\.m2 or $HOME/.m2 on Linux

Can Android Studio be used to run standard Java projects?

It works perfect if you do File>Open... and then select pom.xml file. Be sure to change the dropdown at the top-left of the sidebar that says "Android" to "Project" to see all your files. Also I think it helps if the folder your pom.xml file is in a folder called "app/".

Disclaimer: My java project was generated by Google App Engine.

Perl: function to trim string leading and trailing whitespace

Apply: s/^\s*//; s/\s+$//; to it. Or use s/^\s+|\s+$//g if you want to be fancy.

How to change the button text of <input type="file" />?

This is an alternative solution that may be of help to you. This hides the text that appears out of the button, mixing it with the background-color of the div. Then you can give the div a title you like.

<div style="padding:10px;font-weight:bolder; background-color:#446655;color: white;margin-top:10px;width:112px;overflow: hidden;">
     UPLOAD IMAGE <input style="width:100px;color:#446655;display: inline;" type="file"  />
</div>

Extreme wait-time when taking a SQL Server database offline

Do you have any open SQL Server Management Studio windows that are connected to this DB?

Put it in single user mode, and then try again.

How can I get the concatenation of two lists in Python without modifying either one?

And if you have more than two lists to concatenate:

import operator
from functools import reduce  # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])

# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)

It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args.

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

Wait for a process to finish

There is no builtin feature to wait for any process to finish.

You could send kill -0 to any PID found, so you don't get puzzled by zombies and stuff that will still be visible in ps (while still retrieving the PID list using ps).

Variables within app.config/web.config

Inside <appSettings> you can create application keys,

<add key="KeyName" value="Keyvalue"/>

Later on you can access these values using:

ConfigurationManager.AppSettings["Keyname"]

How to count the number of set bits in a 32-bit integer?

I'm particularly fond of this example from the fortune file:

#define BITCOUNT(x)    (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255)
#define BX_(x)         ((x) - (((x)>>1)&0x77777777)
                             - (((x)>>2)&0x33333333)
                             - (((x)>>3)&0x11111111))

I like it best because it's so pretty!

Wait for shell command to complete

Either link the shell to an object, have the batch job terminate the shell object (exit) and have the VBA code continue once the shell object = Nothing?

Or have a look at this: Capture output value from a shell command in VBA?

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

The issue pointed in the comment is valid, so here is a different revision that's immune to that:

function show_alert() {
  if(!confirm("Do you really want to do this?")) {
    return false;
  }
  this.form.submit();
}

Tri-state Check box in HTML?

Edit — Thanks to Janus Troelsen's comment, I found a better solution:

HTML5 defines a property for checkboxes called indeterminate

See w3c reference guide. To make checkbox appear visually indeterminate set it to true:

element.indeterminate = true;

Here is Janus Troelsen's fiddle. Note, however, that:

  • The indeterminate state cannot be set in the HTML markup, it can only be done via Javascript (see this JSfiddle test and this detailed article in CSS tricks)

  • This state doesn't change the value of the checkbox, it is only a visual cue that masks the input's real state.

  • Browser test: Worked for me in Chrome 22, Firefox 15, Opera 12 and back to IE7. Regarding mobile browsers, Android 2.0 browser and Safari mobile on iOS 3.1 don't have support for it.

Previous answer

Another alternative would be to play with the checkbox transparency for the "some selected" state (as Gmail does used to do in previous versions). It will require some javascript and a CSS class. Here I put a particular example that handles a list with checkable items and a checkbox that allows to select all/none of them. This checkbox shows a "some selected" state when some of the list items are selected.

Given a checkbox with an ID #select_all and several checkboxes with a class .select_one,

The CSS class that fades the "select all" checkbox would be the following:

.some_selected {
    opacity: 0.5;
    filter: alpha(opacity=50);
}

And the JS code that handles the tri-state of the select all checkbox is the following:

$('#select_all').change (function ()
{
    //Check/uncheck all the list's checkboxes
    $('.select_one').attr('checked', $(this).is(':checked'));
    //Remove the faded state
    $(this).removeClass('some_selected');
});

$('.select_one').change (function ()
{
  if ($('.select_one:checked').length == 0)
      $('#select_all').removeClass('some_selected').attr('checked', false);
  else if ($('.select_one:not(:checked)').length == 0)
      $('#select_all').removeClass('some_selected').attr('checked', true);
  else
      $('#select_all').addClass('some_selected').attr('checked', true);
});

You can try it here: http://jsfiddle.net/98BMK/

Hope that helps!

JavaScript, Node.js: is Array.forEach asynchronous?

There is a package on npm for easy asynchronous for each loops.

var forEachAsync = require('futures').forEachAsync;

// waits for one request to finish before beginning the next 
forEachAsync(['dogs', 'cats', 'octocats'], function (next, element, index, array) {
  getPics(element, next);
  // then after all of the elements have been handled 
  // the final callback fires to let you know it's all done 
  }).then(function () {
    console.log('All requests have finished');
});

Also another variation forAllAsync

Reading a UTF8 CSV file with Python

Python 2.X

There is a unicode-csv library which should solve your problems, with added benefit of not naving to write any new csv-related code.

Here is a example from their readme:

>>> import unicodecsv
>>> from cStringIO import StringIO
>>> f = StringIO()
>>> w = unicodecsv.writer(f, encoding='utf-8')
>>> w.writerow((u'é', u'ñ'))
>>> f.seek(0)
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
>>> print row[0], row[1]
é ñ

Python 3.X

In python 3 this is supported out of the box by the build-in csv module. See this example:

import csv
with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Android - R cannot be resolved to a variable

I've fixed the problem in my case very easy:
go to Build- Path->Configure Build Path->Order and Export and ensure that <project name>/gen folder is above <project name>/src
After fixing the order the error disappears.

Execute action when back bar button of UINavigationController is pressed

You can subclass UINavigationController and override popViewController(animated: Bool). Beside being able to execute some code there you can also prevent the user from going back altogether, for instance to prompt to save or discard his current work.

Sample implementation where you can set a popHandler that gets set/cleared by pushed controllers.

class NavigationController: UINavigationController
{
    var popHandler: (() -> Bool)?

    override func popViewController(animated: Bool) -> UIViewController?
    {
        guard self.popHandler?() != false else
        {
            return nil
        }
        self.popHandler = nil
        return super.popViewController(animated: animated)
    }
}

And sample usage from a pushed controller that tracks unsaved work.

let hasUnsavedWork: Bool = // ...
(self.navigationController as! NavigationController).popHandler = hasUnsavedWork ?
    {
        // Prompt saving work here with an alert

        return false // Prevent pop until as user choses to save or discard

    } : nil // No unsaved work, we clear popHandler to let it pop normally

As a nice touch, this will also get called by interactivePopGestureRecognizer when the user tries to go back using a swipe gesture.

How does one use glide to download an image into a bitmap?

UPDATE FOR NEW VERSION

Glide.with(context.applicationContext)
    .load(url)
    .listener(object : RequestListener<Drawable> {
        override fun onLoadFailed(
            e: GlideException?,
            model: Any?,
            target: Target<Drawable>?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadFailed(e)
            return false
        }

        override fun onResourceReady(
            resource: Drawable?,
            model: Any?,
            target: com.bumptech.glide.request.target.Target<Drawable>?,
            dataSource: DataSource?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadSuccess(resource)
            return false
        }

    })
    .into(this)

OLD ANSWER

@outlyer's answer is correct, but there're some changes in new Glide version

My version: 4.7.1

Code:

 Glide.with(context.applicationContext)
                .asBitmap()
                .load(iconUrl)
                .into(object : SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    override fun onResourceReady(resource: Bitmap, transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?) {
                        callback.onReady(createMarkerIcon(resource, iconId))
                    }
                })

Note: this code run in UI Thread, thus you can use AsyncTask, Executor or somethings else for concurrency (like @outlyer's code) If you want to get original size, put Target.SIZE_ORIGINA as my code. Don't use -1, -1

How to set the UITableView Section title programmatically (iPhone/iPad)?

I don't know about past versions of UITableView protocols, but as of iOS 9, func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? is part of the UITableViewDataSource protocol.

   class ViewController: UIViewController {

      @IBOutlet weak var tableView: UITableView!

      override func viewDidLoad() {
         super.viewDidLoad()
         tableView.dataSource = self
      }
   }

   extension ViewController: UITableViewDataSource {
      func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
         return "Section name"
      }
   }

You don't need to declare the delegate to fill your table with data.

Get counts of all tables in a schema

If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:

select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;

Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.

Facebook share link without JavaScript

Please visit the website and you will get Facebook, google+ and Twitter share links http://www.sharelinkgenerator.com/

How to display activity indicator in middle of the iphone screen?

For Swift 3 you can use the following:

 func setupSpinner(){
    spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
    spinner.color = UIColor(Colors.Accent)
    self.spinner.center = CGPoint(x:UIScreen.main.bounds.size.width / 2, y:UIScreen.main.bounds.size.height / 2)
    self.view.addSubview(spinner)
    spinner.hidesWhenStopped = true
}

How do I make entire div a link?

the html:

 <a class="xyz">your content</a>

the css:

.xyz{
  display: block;
}

This will make the anchor be a block level element like a div.

Best Practices for Custom Helpers in Laravel 5

In laravel 5.3 and above, the laravel team moved all procedural files (routes.php) out of the app/ directory, and the entire app/ folder is psr-4 autoloaded. The accepted answer will work in this case but it doesn't feel right to me.

So what I did was I created a helpers/ directory at the root of my project and put the helper files inside of that, and in my composer.json file I did this:

...
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "helpers/ui_helpers.php"
    ]
},
...

This way my app/ directory is still a psr-4 autoloaded one, and the helpers are a little better organized.

Hope this helps someone.

Wildcards in jQuery selectors

To get the id from the wildcard match:

_x000D_
_x000D_
$('[id^=pick_]').click(_x000D_
  function(event) {_x000D_
_x000D_
    // Do something with the id # here: _x000D_
    alert('Picked: '+ event.target.id.slice(5));_x000D_
_x000D_
  }_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="pick_1">moo1</div>_x000D_
<div id="pick_2">moo2</div>_x000D_
<div id="pick_3">moo3</div>
_x000D_
_x000D_
_x000D_

How to disable and then enable onclick event on <div> with javascript

First of all this is JavaScript and not C#

Then you cannot disable a div because it normally has no functionality. To disable a click event, you simply have to remove the event from the dom object. (bind and unbind)...

How do I open phone settings when a button is clicked?

SWIFT 4

This could take your app's specific settings, if that's what you're looking for.

UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)

Created Button Click Event c#

Create the Button and add it to Form.Controls list to display it on your form:

Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

Create the button click method here:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

Getting a Request.Headers value

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

R - argument is of length zero in if statement

"argument is of length zero" is a very specific problem that comes from one of my least-liked elements of R. Let me demonstrate the problem:

> FALSE == "turnip"
[1] FALSE
> TRUE == "turnip"
[1] FALSE
> NA == "turnip"
[1] NA
> NULL == "turnip"
logical(0)

As you can see, comparisons to a NULL not only don't produce a boolean value, they don't produce a value at all - and control flows tend to expect that a check will produce some kind of output. When they produce a zero-length output... "argument is of length zero".

(I have a very long rant about why this infuriates me so much. It can wait.)

So, my question; what's the output of sum(is.null(data[[k]]))? If it's not 0, you have NULL values embedded in your dataset and will need to either remove the relevant rows, or change the check to

if(!is.null(data[[k]][[k2]]) & temp > data[[k]][[k2]]){
    #do stuff
}

Hopefully that helps; it's hard to tell without the entire dataset. If it doesn't help, and the problem is not a NULL value getting in somewhere, I'm afraid I have no idea.

How to find a min/max with Ruby

In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

def max(*values)
 values.max
end

Output:

max(7, 1234, 9, -78, 156)
=> 1234

This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

If you want to define this method on the Math module, this should do the trick:

module Math
 def self.max(*values)
  values.max
 end
end

Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

Is there a JavaScript strcmp()?

localeCompare() is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:

str1 < str2 ? -1 : +(str1 > str2)

This is an order of magnitude faster than localeCompare() on my machine.

The + ensures that the answer is always numeric rather than boolean.

Store JSON object in data attribute in HTML jQuery

instead of embedding it in the text just use $('#myElement').data('key',jsonObject);

it won't actually be stored in the html, but if you're using jquery.data, all that is abstracted anyway.

To get the JSON back don't parse it, just call:

var getBackMyJSON = $('#myElement').data('key');

If you are getting [Object Object] instead of direct JSON, just access your JSON by the data key:

var getBackMyJSON = $('#myElement').data('key').key;

Java 8 Lambda function that throws exception?

By default, Java 8 Function does not allow to throw exception and as suggested in multiple answers there are many ways to achieve it, one way is:

@FunctionalInterface
public interface FunctionWithException<T, R, E extends Exception> {
    R apply(T t) throws E;
}

Define as:

private FunctionWithException<String, Integer, IOException> myMethod = (str) -> {
    if ("abc".equals(str)) {
        throw new IOException();
    }
  return 1;
};

And add throws or try/catch the same exception in caller method.

Invoke native date picker from web-app on iOS/Android

iOS5 has support for this (Reference). If you want to invoke the native date picker you might have a an option with PhoneGap (have not tested this myself).

Server Client send/receive simple text

bool SendReceiveTCP(string ipAddress, string sendMsg, ref string recMsg)
    {
        try
        {
            DateTime startTime=new DateTime();
            TcpClient clt = new TcpClient();
            clt.Connect(ipAddress, 8001);
            NetworkStream nts = clt.GetStream();
            nts.Write(Encoding.ASCII.GetBytes(sendMsg),0, sendMsg.Length);
            startTime = DateTime.Now;
            while (true)
            {
                if (nts.DataAvailable)
                {
                    byte[] tmpBuff = new byte[1024];
                    System.Threading.Thread.Sleep(100);
                    int readOut=nts.Read(tmpBuff, 0, 1024);
                    if (readOut > 0)
                    {
                        recMsg = Encoding.ASCII.GetString(tmpBuff, 0, readOut);
                        nts.Close();
                        clt.Close();
                        return true;
                    }
                    else
                    {
                        nts.Close();
                        clt.Close();
                        return false;
                    }
                }
                TimeSpan tps = DateTime.Now - startTime;
                if (tps.TotalMilliseconds > 2000)
                {
                    nts.Close();
                    clt.Close();
                    return false;
                }
                System.Threading.Thread.Sleep(50);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

How can I use "e" (Euler's number) and power operation in python 2.7

Just saying: numpy has this too. So no need to import math if you already did import numpy as np:

>>> np.exp(1)
2.718281828459045

Struct with template variables in C++

The syntax is wrong. The typedef should be removed.

How to Convert Int to Unsigned Byte and Back

Except char, every other numerical data type in Java are signed.

As said in a previous answer, you can get the unsigned value by performing an and operation with 0xFF. In this answer, I'm going to explain how it happens.

int i = 234;
byte b = (byte) i;
System.out.println(b);  // -22

int i2 = b & 0xFF;      
// This is like casting b to int and perform and operation with 0xFF

System.out.println(i2); // 234

If your machine is 32-bit, then the int data type needs 32-bits to store values. byte needs only 8-bits.

The int variable i is represented in the memory as follows (as a 32-bit integer).

0{24}11101010

Then the byte variable b is represented as:

11101010

As bytes are unsigned, this value represent -22. (Search for 2's complement to learn more on how to represent negative integers in memory)

Then if you cast is to int it will still be -22 because casting preserves the sign of a number.

1{24}11101010

The the casted 32-bit value of b perform and operation with 0xFF.

 1{24}11101010 & 0{24}11111111
=0{24}11101010

Then you get 234 as the answer.

How to Implement Custom Table View Section Headers and Footers with Storyboard

To follow up on Damon's suggestion, here is how I made the header selectable just like a normal row with a disclosure indicator.

I added a Button subclassed from UIButton (subclass name "ButtonWithArgument") to the header's prototype cell and deleted the title text (the bold "Title" text is another UILabel in the prototype cell)

Button In Interface Builder

then set the Button to the entire header view, and added a disclosure indicator with Avario's trick

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *CellIdentifier = @"PersonGroupHeader";
    UITableViewCell *headerView = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(headerView == nil)
    {
        [NSException raise:@"headerView == nil, PersonGroupTableViewController" format:[NSString stringWithFormat:@"Storyboard does not have prototype cell with identifier %@",CellIdentifier]];
    }

    //  https://stackoverflow.com/a/24044628/3075839
    while(headerView.contentView.gestureRecognizers.count)
    {
        [headerView.contentView removeGestureRecognizer:[headerView.contentView.gestureRecognizers objectAtIndex:0]];
    }


    ButtonWithArgument *button = (ButtonWithArgument *)[headerView viewWithTag:4];
    button.frame = headerView.bounds; // set tap area to entire header view
    button.argument = [[NSNumber alloc] initWithInteger:section]; // from ButtonWithArguments subclass
    [button addTarget:self action:@selector(headerViewTap:) forControlEvents:UIControlEventTouchUpInside];

    // https://stackoverflow.com/a/20821178/3075839
    UITableViewCell *disclosure = [[UITableViewCell alloc] init];
    disclosure.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    disclosure.userInteractionEnabled = NO;
    disclosure.frame = CGRectMake(button.bounds.origin.x + button.bounds.size.width - 20 - 5, // disclosure 20 px wide, right margin 5 px
          (button.bounds.size.height - 20) / 2,
          20,
          20);
    [button addSubview:disclosure];

    // configure header title text

    return headerView.contentView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35.0f;
}

-(void) headerViewTap:(UIGestureRecognizer *)gestureRecognizer;
{
    NSLog(@"header tap");
    NSInteger section = ((NSNumber *)sender.argument).integerValue;
    // do something here
}

ButtonWithArgument.h

#import <UIKit/UIKit.h>

@interface ButtonWithArgument : UIButton
@property (nonatomic, strong) NSObject *argument;
@end

ButtonWithArgument.m

#import "ButtonWithArgument.h"
@implementation ButtonWithArgument
@end

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

Node update a specific package

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

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

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

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

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

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

JQuery - how to select dropdown item based on value

$('#mySelect').val('fg');...........

assembly to compare two numbers

Compare two numbers. If it equals Yes "Y", it prints No "N" on the screen if it is not equal. I am using emu8086. You can use the SUB or CMP command.

MOV AX,5h
MOV BX,5h
SUB AX,BX 
JZ EQUALS
JNZ NOTEQUALS

EQUALS:
MOV CL,'Y'
JMP PRINT

NOTEQUALS:
MOV CL,'N'

PRINT:
MOV AH,2
MOV DL,CL
INT 21H

RET

enter image description here

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

Check image width and height before upload with Javascript

The file is just a file, you need to create an image like so:

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        var objectUrl = _URL.createObjectURL(file);
        img.onload = function () {
            alert(this.width + " " + this.height);
            _URL.revokeObjectURL(objectUrl);
        };
        img.src = objectUrl;
    }
});

Demo: http://jsfiddle.net/4N6D9/1/

I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.

P.S. The URL.createObjectURL() method has been removed from the MediaStream interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL() to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.

For more information, please refer here.

TCP vs UDP on video stream

For video streaming bandwidth is likely the constraint on the system. Using multicast you can greatly reduce the amount of upstream bandwidth used. With UDP you can easily multicast your packets to all connected terminals. You could also use a reliable multicast protocol, one is called Pragmatic General Multicast (PGM), I don't know anything about it and I guess it isn't widespread in its use.

How to delete duplicate rows in SQL Server?

You need to group by the duplicate records according to the field(s), then hold one of the records and delete the rest. For example:

DELETE prg.Person WHERE Id IN (
SELECT dublicateRow.Id FROM
(
select MIN(Id) MinId, NationalCode
 from  prg.Person group by NationalCode  having count(NationalCode ) > 1
 ) GroupSelect
 JOIN  prg.Person dublicateRow ON dublicateRow.NationalCode = GroupSelect.NationalCode 
 WHERE dublicateRow.Id <> GroupSelect.MinId)

no operator "<<" matches these operands

If you want to use std::string reliably, you must #include <string>.

MYSQL Truncated incorrect DOUBLE value

I did experience this error when I tried doing an WHERE EXIST where the subquery matched 2 columns that accidentially was different types. The two tables was also different storage engines.

One column was a CHAR (90) and the other was a BIGINT (20).

One table was InnoDB and the other was MEMORY.

Part of query:

[...] AND EXISTS (select objectid from temp_objectids where temp_objectids.objectid = items_raw.objectid );

Changing the column type on the one column from BIGINT to CHAR solved the issue.

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Postgresql Select rows where column = array

For dynamic SQL use:

'IN(' ||array_to_string(some_array, ',')||')'

Example

DO LANGUAGE PLPGSQL $$

DECLARE
    some_array bigint[];
    sql_statement text;

BEGIN

    SELECT array[1, 2] INTO some_array;
    RAISE NOTICE '%', some_array;

    sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
    RAISE NOTICE '%', sql_statement;

END;

$$;

Result: NOTICE: {1,2} NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)

What is the Sign Off feature in Git for?

There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).

Headers or trailers (?1) like “sign-off” (?2) is, in current practice in projects like Git and Linux, effectively structured metadata for the commit. These are all appended to the end of the commit message, after the “free form” (unstructured) part of the body of the message. These are token–value (or key–value) pairs typically delimited by a colon and a space (:?).

Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:

 mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
 This is an ancient bug that was actually attempted to be fixed once
 (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
 get_user_pages() race for write access") but that was then undone due to
 problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").

 In the meantime, the s390 situation has long been fixed, and we can now
 fix it by checking the pte_dirty() bit properly (and do it better).  The
 s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
 software dirty bits") which made it into v3.9.  Earlier kernels will
 have to look at the page state itself.

 Also, the VM has become more scalable, and what used a purely
 theoretical race back then has become easier to trigger.

 To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
 we already did a COW" rather than play racy games with FOLL_WRITE that
 is very fundamental, and then use the pte dirty flag to validate that
 the FOLL_COW flag is still valid.

 Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
 Acked-by: Hugh Dickins <[email protected]>
 Reviewed-by: Michal Hocko <[email protected]>
 Cc: Andy Lutomirski <[email protected]>
 Cc: Kees Cook <[email protected]>
 Cc: Oleg Nesterov <[email protected]>
 Cc: Willy Tarreau <[email protected]>
 Cc: Nick Piggin <[email protected]>
 Cc: Greg Thelen <[email protected]>
 Cc: [email protected]
 Signed-off-by: Linus Torvalds <[email protected]>

In addition to the “sign-off” trailer in the above, there is:

  • “Cc” (was notified about the patch)
  • “Acked-by” (acknowledged by the owner of the code, “looks good to me”)
  • “Reviewed-by” (reviewed)
  • “Reported-and-tested-by” (reported and tested the issue (I assume))

Other projects, like for example Gerrit, have their own headers and associated meaning for them.

See: https://git.wiki.kernel.org/index.php/CommitMessageConventions

Moral of the story

It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.

[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.

How to check if an environment variable exists and get its value?

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

You can check if a variable is defined:

if [ -z "$a" ]
then
    echo "not defined"
else 
    echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

XAMPP Apache Webserver localhost not working on MAC OS

I had to disable OSX's built-in Apache server (XAMPP support thread):

sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist

This allowed XAMPP to start on 80, while POW runs on 20559.

What had failed: I reconfigured /etc/apache2/httpd.conf to listen on an alternate port and rebooted OSX. No luck.

Remove characters before character "."

You can use the IndexOf method and the Substring method like so:

string output = input.Substring(input.IndexOf('.') + 1);

The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.

How to use variables in SQL statement in Python?

Meanwhile there is another way of how to do it with f-strings:

cursor.execute(f"INSERT INTO table VALUES {var1}, {var2}, {var3},")

Django Multiple Choice Field / Checkbox Select Multiple

The models.CharField is a CharField representation of one of the choices. What you want is a set of choices. This doesn't seem to be implemented in django (yet).

You could use a many to many field for it, but that has the disadvantage that the choices have to be put in a database. If you want to use hard coded choices, this is probably not what you want.

There is a django snippet at http://djangosnippets.org/snippets/1200/ that does seem to solve your problem, by implementing a ModelField MultipleChoiceField.

How can I use a DLL file from Python?

If the DLL is of type COM library, then you can use pythonnet.

pip install pythonnet

Then in your python code, try the following

import clr
clr.AddReference('path_to_your_dll')

then instantiate an object as per the class in the DLL, and access the methods within it.

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

How to unnest a nested list

itertools provides the chain function for that:

From http://docs.python.org/library/itertools.html#recipes:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

Naming Conventions: What to name a boolean variable?

How about:

 hasSiblings
 or isFollowedBySiblings (or isFolloedByItems, or isFollowedByOtherItems etc.)
 or moreItems

Although I think that even though you shouldn't make a habit of braking 'the rules' sometimes the best way to accomplish something may be to make an exception of the rule (Code Complete guidelines), and in your case, name the variable isNotLast

FIFO class in Java

You're looking for any class that implements the Queue interface, excluding PriorityQueue and PriorityBlockingQueue, which do not use a FIFO algorithm.

Probably a LinkedList using add (adds one to the end) and removeFirst (removes one from the front and returns it) is the easiest one to use.

For example, here's a program that uses a LinkedList to queue and retrieve the digits of PI:

import java.util.LinkedList;

class Test {
    public static void main(String args[]) {
        char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
        LinkedList<Integer> fifo = new LinkedList<Integer>();

        for (int i = 0; i < arr.length; i++)
            fifo.add (new Integer (arr[i]));

        System.out.print (fifo.removeFirst() + ".");
        while (! fifo.isEmpty())
            System.out.print (fifo.removeFirst());
        System.out.println();
    }
} 

Alternatively, if you know you only want to treat it as a queue (without the extra features of a linked list), you can just use the Queue interface itself:

import java.util.LinkedList;
import java.util.Queue;

class Test {
    public static void main(String args[]) {
        char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
        Queue<Integer> fifo = new LinkedList<Integer>();

        for (int i = 0; i < arr.length; i++)
            fifo.add (new Integer (arr[i]));

        System.out.print (fifo.remove() + ".");
        while (! fifo.isEmpty())
            System.out.print (fifo.remove());
        System.out.println();
    }
}

This has the advantage of allowing you to replace the underlying concrete class with any class that provides the Queue interface, without having to change the code too much.

The basic changes are to change the type of fifo to a Queue and to use remove() instead of removeFirst(), the latter being unavailable for the Queue interface.

Calling isEmpty() is still okay since that belongs to the Collection interface of which Queue is a derivative.

Changing an element's ID with jQuery

A PREFERRED OPTION over .attr is to use .prop like so:

$(this).prev('li').prop('id', 'newId');

.attr retrieves the element's attribute whereas .prop retrieves the property that the attribute references (i.e. what you're actually intending to modify)

How can I get a Dialog style activity window to fill the screen?

You may add this values to your style android:windowMinWidthMajor and android:windowMinWidthMinor

<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
    ...
    <item name="android:windowMinWidthMajor">97%</item>
    <item name="android:windowMinWidthMinor">97%</item>
</style>

Reading large text files with streams in C#

All excellent answers! however, for someone looking for an answer, these appear to be somewhat incomplete.

As a standard String can only of Size X, 2Gb to 4Gb depending on your configuration, these answers do not really fulfil the OP's question. One method is to work with a List of Strings:

List<string> Words = new List<string>();

using (StreamReader sr = new StreamReader(@"C:\Temp\file.txt"))
{

string line = string.Empty;

while ((line = sr.ReadLine()) != null)
{
    Words.Add(line);
}
}

Some may want to Tokenise and split the line when processing. The String List now can contain very large volumes of Text.

Get JSON object from URL

my solution only works for the next cases: if you are mistaking a multidimensaional array into a single one

$json = file_get_contents('url_json'); //get the json
$objhigher=json_decode($json); //converts to an object
$objlower = $objhigher[0]; // if the json response its multidimensional this lowers it
echo "<pre>"; //box for code
print_r($objlower); //prints the object with all key and values
echo $objlower->access_token; //prints the variable

i know that the answer was has already been answered but for those who came here looking for something i hope this can help you

How to sort a list/tuple of lists/tuples by the element at a given index?

itemgetter() is somewhat faster than lambda tup: tup[1], but the increase is relatively modest (around 10 to 25 percent).

(IPython session)

>>> from operator import itemgetter
>>> from numpy.random import randint
>>> values = randint(0, 9, 30000).reshape((10000,3))
>>> tpls = [tuple(values[i,:]) for i in range(len(values))]

>>> tpls[:5]    # display sample from list
[(1, 0, 0), 
 (8, 5, 5), 
 (5, 4, 0), 
 (5, 7, 7), 
 (4, 2, 1)]

>>> sorted(tpls[:5], key=itemgetter(1))    # example sort
[(1, 0, 0), 
 (4, 2, 1), 
 (5, 4, 0), 
 (8, 5, 5), 
 (5, 7, 7)]

>>> %timeit sorted(tpls, key=itemgetter(1))
100 loops, best of 3: 4.89 ms per loop

>>> %timeit sorted(tpls, key=lambda tup: tup[1])
100 loops, best of 3: 6.39 ms per loop

>>> %timeit sorted(tpls, key=(itemgetter(1,0)))
100 loops, best of 3: 16.1 ms per loop

>>> %timeit sorted(tpls, key=lambda tup: (tup[1], tup[0]))
100 loops, best of 3: 17.1 ms per loop

Set a border around a StackPanel.

What about this one :

<DockPanel Margin="8">
    <Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
        <StackPanel Orientation="Horizontal">
            <TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
            <TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
            <Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />            
        </StackPanel>
    </Border>
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>

Histogram Matplotlib

I know this does not answer your question, but I always end up on this page, when I search for the matplotlib solution to histograms, because the simple histogram_demo was removed from the matplotlib example gallery page.

Here is a solution, which doesn't require numpy to be imported. I only import numpy to generate the data x to be plotted. It relies on the function hist instead of the function bar as in the answer by @unutbu.

import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

enter image description here

Also check out the matplotlib gallery and the matplotlib examples.

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

Why use pointers?

Here's a slightly different, but insightful take on why many features of C make sense: http://steve.yegge.googlepages.com/tour-de-babel#C

Basically, the standard CPU architecture is a Von Neumann architecture, and it's tremendously useful to be able to refer to the location of a data item in memory, and do arithmetic with it, on such a machine. If you know any variant of assembly language, you will quickly see how crucial this is at the low level.

C++ makes pointers a bit confusing, since it sometimes manages them for you and hides their effect in the form of "references." If you use straight C, the need for pointers is much more obvious: there's no other way to do call-by-reference, it's the best way to store a string, it's the best way to iterate through an array, etc.

"Fatal error: Cannot redeclare <function>"

I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.

Declare your function as a lambda expression (I haven't seen this solution mentioned):

$generate_salt = function()
{
    ...
};

And use thusly:

$salt = $generate_salt();

Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

Adding the following block of code in web.config solves my problem

 <system.net>
    <defaultProxy enabled="false" >
    </defaultProxy>
  </system.net>

What exactly does Perl's "bless" do?

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.

Pass Additional ViewData to a Strongly-Typed Partial View

Create another class which contains your strongly typed class.

Add your new stuff to the class and return it in the view.

Then in the view, ensure you inherit your new class and change the bits of code that will now be in error. namely the references to your fields.

Hope this helps. If not then let me know and I'll post specific code.

Create a global variable in TypeScript

I'm using this:

interface Window {
    globalthing: any;
}

declare var globalthing: any;

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Swift 3 Bonus: Why didn't anyone mention the short form?

CGRect(origin: .zero, size: size)

.zero instead of CGPoint.zero

When the type is defined, you can safely omit it.

Matplotlib make tick labels font size smaller

To specify both font size and rotation at the same time, try this:

plt.xticks(fontsize=14, rotation=90)

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

Fit website background image to screen size

You can do it like what I did with my website:

background-repeat: no-repeat;

background-size: cover;

Writing to a TextBox from another thread?

Most simple, without caring about delegates

if(textBox1.InvokeRequired == true)
    textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});

else
    textBox1.Text = "Invoke was NOT needed"; 

How do I split a string, breaking at a particular character?

With JavaScript’s String.prototype.split function:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

How to create the pom.xml for a Java project with Eclipse

To create POM.XML file in Eclipse:

  1. Install M2E plugin (http://www.eclipse.org/m2e/)

  2. Right click on project -> Configure -> Convert to Maven Project

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

It's a separate statement.

It's also not possible to insert into a table and select from it and build an index in the same statement either.

The BOL entry contains the information you need:

CLUSTERED | NONCLUSTERED
Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.

In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.

You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.

A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.

That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).

End-line characters from lines read from text file, using Python

Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that:

if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1)) 
  line input #1 a$
  print a$
wend
close

Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:

def line_input (file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line_input(f):
    # do something with line

I am induced to think that something has gone the wrong way somewhere...

How to write a confusion matrix in Python?

In a general sense, you're going to need to change your probability array. Instead of having one number for each instance and classifying based on whether or not it is greater than 0.5, you're going to need a list of scores (one for each class), then take the largest of the scores as the class that was chosen (a.k.a. argmax).

You could use a dictionary to hold the probabilities for each classification:

prob_arr = [{classification_id: probability}, ...]

Choosing a classification would be something like:

for instance_scores in prob_arr :
    predicted_classes = [cls for (cls, score) in instance_scores.iteritems() if score = max(instance_scores.values())]

This handles the case where two classes have the same scores. You can get one score, by choosing the first one in that list, but how you handle that depends on what you're classifying.

Once you have your list of predicted classes and a list of expected classes you can use code like Torsten Marek's to create the confusion array and calculate the accuracy.

Zookeeper connection error

Check the zookeeper logs (/var/log/zookeeper). It looks like a connection is established, which should mean there is a record of it.

I had the same situation and it was because a process opened connections and failed to close them. This eventually exceeded the per-host connection limit and my logs were overflowing with

2016-08-03 15:21:13,201 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@188] - Too many connections from /172.31.38.64 - max is 50

Assuming zookeeper is on the usual port, you could do a check for that with:

lsof -i -P | grep 2181

Rename multiple files in cmd

I found the following in a small comment in Supperuser.com:

@JacksOnF1re - New information/technique added to my answer. You can actually delete your Copy of prefix using an obscure forward slash technique: ren "Copy of .txt" "////////"

Of How does the Windows RENAME command interpret wildcards? See in this thread, the answer of dbenham.

My problem was slightly different, I wanted to add a Prefix to the file and remove from the beginning what I don't need. In my case I had several hundred of enumerated files such as:

SKMBT_C36019101512510_001.jpg
SKMBT_C36019101512510_002.jpg
SKMBT_C36019101512510_003.jpg
SKMBT_C36019101512510_004.jpg
:
:

Now I wanted to respectively rename them all to (Album 07 picture #):

A07_P001.jpg
A07_P002.jpg
A07_P003.jpg
A07_P004.jpg
:
:

I did it with a single command line and it worked like charm:

ren "SKMBT_C36019101512510_*.*" "/////////////////A06_P*.*"

Note:

  1. Quoting (") the "<Name Scheme>" is not an option, it does not work otherwise, in our example: "SKMBT_C36019101512510_*.*" and "/////////////////A06_P*.*" were quoted.
  2. I had to exactly count the number of characters I want to remove and leave space for my new characters: The A06_P actually replaced 2510_ and the SKMBT_C3601910151 was removed, by using exactly the number of slashes ///////////////// (17 characters).
  3. I recommend copying your files (making a backup), before applying the above.

Using reCAPTCHA on localhost

localhost works now. However, remember that after adding localhost to list of domain names, it takes up to 30 minutes to take effect (according to the help tip shown against the domain names list).

Check for false

Like this:

if(borrar())
{
   // Do something
}

If borrar() returns true then do something (if it is not false).

Angular 2.0 router not working on reloading the browser

If you want to be able to enter urls in browser without configuring your AppServer to handle all requests to index.html, you must use HashLocationStrategy.

The easiest way to configure is using:

RouterModule.forRoot(routes, { useHash: true })

Instead of:

RouterModule.forRoot(routes)

With HashLocationStrategy your urls gonna be like:

http://server:port/#/path

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

How do I clear a search box with an 'x' in bootstrap 3?

Do not bind to element id, just use the 'previous' input element to clear.

CSS:

.clear-input > span {
    position: absolute;
    right: 24px;
    top: 10px;
    height: 14px;
    margin: auto;
    font-size: 14px;
    cursor: pointer;
    color: #AAA;
}

Javascript:

function $(document).ready(function() {
    $(".clear-input>span").click(function(){
        // Clear the input field before this clear button
        // and give it focus.

        $(this).prev().val('').focus();
    });
});

HTML Markup, use as much as you like:

<div class="clear-input">
    Pizza: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>
</div>

<div class="clear-input">
    Pasta: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>
</div>

Multiple radio button groups in one form

Set equal name attributes to create a group;

_x000D_
_x000D_
<form>_x000D_
  <fieldset id="group1">_x000D_
    <input type="radio" value="value1" name="group1">_x000D_
    <input type="radio" value="value2" name="group1">_x000D_
  </fieldset>_x000D_
_x000D_
  <fieldset id="group2">_x000D_
    <input type="radio" value="value1" name="group2">_x000D_
    <input type="radio" value="value2" name="group2">_x000D_
    <input type="radio" value="value3" name="group2">_x000D_
  </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

List only stopped Docker containers

docker container list -f "status=exited"

or

docker container ls -f "status=exited"

or

 docker ps -f "status=exited"

How can I remove item from querystring in asp.net using c#?

You're probably going to want use a Regular Expression to find the parameter you want to remove from the querystring, then remove it and redirect the browser to the same file with your new querystring.

SQL - How do I get only the numbers after the decimal?

The usual hack (which varies a bit in syntax) is

x - floor(x)

That's the fractional part. To make into an integer, scale it.

(x - floor(x)) * 1000

How to Display Multiple Google Maps per page with API V3

You haven't defined a div with id="map_canvas", you only have id="map_canvas2" and id="route2". The div ids need to match the argument in the GMap() constructor.

How to list records with date from the last 10 days?

Just generalising the query if you want to work with any given date instead of current date:

SELECT Table.date
  FROM Table 
  WHERE Table.date > '2020-01-01'::date - interval '10 day'

Formatting floats without trailing zeros

Use %g with big enough width, for example '%.99g'. It will print in fixed-point notation for any reasonably big number.

EDIT: it doesn't work

>>> '%.99g' % 0.0000001
'9.99999999999999954748111825886258685613938723690807819366455078125e-08'

PHP Array to CSV

In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:

function array2csv($array, &$title, &$data) {
    foreach($array as $key => $value) {      
        if(is_array($value)) {
            $title .= $key . ",";
            $data .= "" . ",";
            array2csv($value, $title, $data);
        } else {
            $title .= $key . ",";
            $data .= '"' . $value . '",';
        }
    }
}

Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:

agentid     fname           lname      empid    totals  sales   leads   dish    dishnet top200_plus top120  latino  base_packages
G-adriana   ADRIANA EUGENIA PALOMO PAIZ 886                0    19              0         0         0         0      0

You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:

$title .= $key . ",";
$data .= "" . ",";

after the is_array() to compact the code further and remove the extra column.

Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:

$title .= PHP_EOL;
$data .= PHP_EOL;

Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.

Exporting the values in List to excel

Exporting values List to Excel

  1. Install in nuget next reference
  2. Install-Package Syncfusion.XlsIO.Net.Core -Version 17.2.0.35
  3. Install-Package ClosedXML -Version 0.94.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClosedXML;
using ClosedXML.Excel;
using Syncfusion.XlsIO;

namespace ExporteExcel
{
    class Program
    {
        public class Auto
        {
            public string Marca { get; set; }

            public string Modelo { get; set; }
            public int Ano { get; set; }

            public string Color { get; set; }
            public int Peronsas { get; set; }
            public int Cilindros { get; set; }
        }
        static void Main(string[] args)
        {
            //Lista Estatica
            List<Auto> Auto = new List<Program.Auto>()
            {
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2019, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2018, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2017, Color= "Azul", Cilindros=6, Peronsas= 4 }
            };
            //Inizializar Librerias
            var workbook = new XLWorkbook();
            workbook.AddWorksheet("sheetName");
            var ws = workbook.Worksheet("sheetName");
            //Recorrer el objecto
            int row = 1;
            foreach (var c in Auto)
            {
                //Escribrie en Excel en cada celda
                ws.Cell("A" + row.ToString()).Value = c.Marca;
                ws.Cell("B" + row.ToString()).Value = c.Modelo;
                ws.Cell("C" + row.ToString()).Value = c.Ano;
                ws.Cell("D" + row.ToString()).Value = c.Color;
                ws.Cell("E" + row.ToString()).Value = c.Cilindros;
                ws.Cell("F" + row.ToString()).Value = c.Peronsas;
                row++;

            }
            //Guardar Excel 
            //Ruta = Nombre_Proyecto\bin\Debug
            workbook.SaveAs("Coches.xlsx");
        }
    }
}

Why is SQL Server 2008 Management Studio Intellisense not working?

No need to reinstall.

Click on the setup file. Then go to maintenance and click on Repair. This should correct the intellisense problem.

CSS list-style-image size

.your_class li {
    list-style-image: url('../images/image.svg');
}

.your_class li::marker {
    font-size: 1.5rem; /* You can use px, but I think rem is more respecful */
}

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

These steps really help me:

Step 1: Create a directory in android/app/src/main/assets

Linux command: mkdir android/app/src/main/assets

Step 2: Rename index.android.js (in root directory) to index.js (Maybe there is an index.js file in which case you do not need to rename it) then run the following command:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Step 3: Build your APK: react-native run-android

Please use index.js in latest version.

Enjoy :)

Android ImageButton with a selected state?

Try this:

 <item
   android:state_focused="true"
   android:state_enabled="true"
   android:drawable="@drawable/map_toolbar_details_selected" />

Also for colors i had success with

<selector
        xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:state_selected="true"

            android:color="@color/primary_color" />
        <item
            android:color="@color/secondary_color" />
</selector>

unable to start mongodb local server

Sat Jun 25 09:38:51 [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017

is self-speaking.

Another instance of mongod is already running and allocating the MongoDB default port which is 27017.

Either kill the other process or use a different port.

Bootstrap 4 - Inline List?

Inline

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>


<ul class="list-inline">
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
_x000D_
_x000D_
_x000D_

and learn more about https://getbootstrap.com/docs/4.0/content/typography/#inline

Can't get Python to import from a different folder

I believe you need to create a file called __init__.py in the Models directory so that python treats it as a module.

Then you can do:

from Models.user import User

You can include code in the __init__.py (for instance initialization code that a few different classes need) or leave it blank. But it must be there.

Creating a SearchView that looks like the material design guidelines

The following will create a SearchView identical to the one in Gmail and add it to the given Toolbar. You'll just have to implement your own "ViewUtil.convertDpToPixel" method.

private SearchView createMaterialSearchView(Toolbar toolbar, String hintText) {

    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);

    SearchView searchView = new SearchView(this);
    searchView.setIconifiedByDefault(false);
    searchView.setMaxWidth(Integer.MAX_VALUE);
    searchView.setMinimumHeight(Integer.MAX_VALUE);
    searchView.setQueryHint(hintText);

    int rightMarginFrame = 0;
    View frame = searchView.findViewById(getResources().getIdentifier("android:id/search_edit_frame", null, null));
    if (frame != null) {
        LinearLayout.LayoutParams frameParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rightMarginFrame = ((LinearLayout.LayoutParams) frame.getLayoutParams()).rightMargin;
        frameParams.setMargins(0, 0, 0, 0);
        frame.setLayoutParams(frameParams);
    }

    View plate = searchView.findViewById(getResources().getIdentifier("android:id/search_plate", null, null));
    if (plate != null) {
        plate.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        plate.setPadding(0, 0, rightMarginFrame, 0);
        plate.setBackgroundColor(Color.TRANSPARENT);
    }

    int autoCompleteId = getResources().getIdentifier("android:id/search_src_text", null, null);
    if (searchView.findViewById(autoCompleteId) != null) {
        EditText autoComplete = (EditText) searchView.findViewById(autoCompleteId);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int) ViewUtil.convertDpToPixel(36));
        params.weight = 1;
        params.gravity = Gravity.CENTER_VERTICAL;
        params.leftMargin = rightMarginFrame;
        autoComplete.setLayoutParams(params);
        autoComplete.setTextSize(16f);
    }

    int searchMagId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
    if (searchView.findViewById(searchMagId) != null) {
        ImageView v = (ImageView) searchView.findViewById(searchMagId);
        v.setImageDrawable(null);
        v.setPadding(0, 0, 0, 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);
        v.setLayoutParams(params);
    }

    toolbar.setTitle(null);
    toolbar.setContentInsetsAbsolute(0, 0);
    toolbar.addView(searchView);

    return searchView;
}

Iterating Through a Dictionary in Swift

Dictionaries in Swift (and other languages) are not ordered. When you iterate through the dictionary, there's no guarentee that the order will match the initialization order. In this example, Swift processes the "Square" key before the others. You can see this by adding a print statement to the loop. 25 is the 5th element of Square so largest would be set 5 times for the 5 elements in Square and then would stay at 25.

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    println("kind: \(kind)")
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest

This prints:

kind: Square
kind: Prime
kind: Fibonacci

HTML img onclick Javascript

here you go.

<img src="https://i.imgur.com/7KpCS0Y.jpg" onclick="window.open(this.src)">

Select elements by attribute in CSS

Is it possible to select elements in CSS by their HTML5 data attributes? This can easily be answered just by trying it, and the answer is, of course, yes. But this invariably leads us to the next question, 'Should we select elements in CSS by their HTML5 data attributes?' There are conflicting opinions on this.

In the 'no' camp is (or at least was, back in 2014) CSS legend Harry Roberts. In the article, Naming UI components in OOCSS, he wrote:

It’s important to note that although we can style HTML via its data-* attributes, we probably shouldn’t. data-* attributes are meant for holding data in markup, not for selecting on. This, from the HTML Living Standard (emphasis mine):

"Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements."

The W3C spec was frustratingly vague on this point, but based purely on what it did and didn't say, I think Harry's conclusion was perfectly reasonable.

Since then, plenty of articles have suggested that it's perfectly appropriate to use custom data attributes as styling hooks, including MDN's guide, Using data attributes. There's even a CSS methodology called CUBE CSS which has adopted the data attribute hook as the preferred way of adding styles to component 'exceptions' (known as modifiers in BEM).

Thankfully, the WHATWG HTML Living Standard has since added a few more words and even some examples (emphasis mine):

Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements.

In this example, custom data attributes are used to store the result of a feature detection for PaymentRequest, which could be used in CSS to style a checkout page differently.

Authors should carefully design such extensions so that when the attributes are ignored and any associated CSS dropped, the page is still usable.


TL;DR: Yes, it's okay to use data-* attributes in CSS selectors, provided the page is still usable without them.

Wait till a Function with animations is finished until running another Function

You can use the javascript Promise and async/await to implement a synchronized call of the functions.

Suppose you want to execute n number of functions in a synchronized manner that are stored in an array, here is my solution for that.

_x000D_
_x000D_
async function executeActionQueue(funArray) {_x000D_
  var length = funArray.length;_x000D_
  for(var i = 0; i < length; i++) {_x000D_
    await executeFun(funArray[i]);_x000D_
  }_x000D_
};_x000D_
_x000D_
function executeFun(fun) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    _x000D_
    // Execute required function here_x000D_
    _x000D_
    fun()_x000D_
      .then((data) => {_x000D_
        // do required with data _x000D_
        resolve(true);_x000D_
      })_x000D_
      .catch((error) => {_x000D_
      // handle error_x000D_
        resolve(true);_x000D_
      });_x000D_
  })_x000D_
};_x000D_
_x000D_
executeActionQueue(funArray);
_x000D_
_x000D_
_x000D_

How to handle screen orientation change when progress dialog and background thread active?

This is my proposed solution:

  • Move the AsyncTask or Thread to a retained Fragment, as explained here. I believe it is a good practice to move all network calls to fragments. If you are already using fragments, one of them could be made responsible for the calls. Otherwise, you can create a fragment just for doing the request, as the linked article proposes.
  • The fragment will use a listener interface to signal the task completion/failure. You don't have to worry for orientation changes there. The fragment will always have the correct link to the current activity and progress dialog can be safely resumed.
  • Make your progress dialog a member of your class. In fact you should do that for all dialogs. In the onPause method you should dismiss them, otherwise you will leak a window on the configuration change. The busy state should be kept by the fragment. When the fragment is attached to the activity, you can bring up the progress dialog again, if the call is still running. A void showProgressDialog() method can be added to the fragment-activity listener interface for this purpose.

UIDevice uniqueIdentifier deprecated - What to do now?

I had got some issue too, and solution is simple:

    // Get Bundle Info for Remote Registration (handy if you have more than one app)
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];


    // Get the users Device Model, Display Name, Unique ID, Token & Version Number
    UIDevice *dev = [UIDevice currentDevice];
    NSString *deviceUuid=[dev.identifierForVendor  UUIDString];

    NSString *deviceName = dev.name;

How to correctly catch change/focusOut event on text input in React.js?

Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.

Python DNS module import error

I installed DNSpython 2.0.0 from the github source, but running 'pip list' showed the old version of dnspython 1.2.0

It only worked after I ran 'pip uninstall dnspython' which removed the old version leaving just 2.0.0 and then 'import dns' ran smoothly

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

How to use a Bootstrap 3 glyphicon in an html select

I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.

<div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        Select icon <span class="caret"></span>
    </button>
    <ul class="dropdown-menu list-inline" role="menu">
        <li><span class="glyphicon glyphicon-cutlery"></span></li>
        <li><span class="glyphicon glyphicon-fire"></span></li>
        <li><span class="glyphicon glyphicon-glass"></span></li>
        <li><span class="glyphicon glyphicon-heart"></span></li>          
    </ul>
</div>

I'm using Angular.js so this is the actual code I used:

<div class="btn-group">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                Avatar <span class="caret"></span>
            </button>
            <ul class="dropdown-menu list-inline" role="menu">
                <li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
                    <span ng-class="getAvatar(avatar)"></span>
                </li>
            </ul>
        </div>

And in my controller:

$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];

$scope.getAvatar=function(avatar){
     return 'glyphicon glyphicon-'+avatar;
};

how to select first N rows from a table in T-SQL?

You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.

SELECT * 
FROM (SELECT row_number() over (order by UserID) AS line_no, * 
      FROM dbo.User) as users
WHERE users.line_no < 10
OR users.line_no BETWEEN 34 and 67

You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.

Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.

Numpy where function multiple conditions

This should work:

dists[((dists >= r) & (dists <= r+dr))]

The most elegant way~~

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

That's a tricky one... Your storage letter must be capical. For example "C:\..."

jquery: get value of custom attribute

You can also do this by passing function with onclick event

<a onclick="getColor(this);" color="red">

<script type="text/javascript">

function getColor(el)
{
     color = $(el).attr('color');
     alert(color);
}

</script> 

TypeError: 'NoneType' object is not iterable in Python

It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can't be iterable as a list, as you are trying to do.

How to get first object out from List<Object> using Linq

[0] or .First() will give you the same performance whatever happens.
But your Dictionary could contains IEnumerable<Component> instead of List<Component>, and then you cant use the [] operator. That is where the difference is huge.

So for your example, it doesn't really matters, but for this code, you have no choice to use First():

var dic = new Dictionary<String, IEnumerable<Component>>();
foreach (var components in dic.Values)
{
    // you can't use [0] because components is an IEnumerable<Component>
    var firstComponent = components.First(); // be aware that it will throw an exception if components is empty.
    var depCountry = firstComponent.ComponentValue("Dep");
}

When is del useful in Python?

del is often seen in __init__.py files. Any global variable that is defined in an __init__.py file is automatically "exported" (it will be included in a from module import *). One way to avoid this is to define __all__, but this can get messy and not everyone uses it.

For example, if you had code in __init__.py like

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

Then your module would export the sys name. You should instead write

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

del sys

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape