Programs & Examples On #Pdfpages

A Python method, in matplotlib, for generating a pdf with multiple pages or a Latex package for inserting external pdf documents.

How to commit and rollback transaction in sql server?

Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ...... 

How do I convert a Django QuerySet into list of dicts?

Use the .values() method:

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

Note: the result is a QuerySet which mostly behaves like a list, but isn't actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.

How to beautify JSON in Python?

From the command-line:

echo '{"one":1,"two":2}' | python -mjson.tool

which outputs:

{
    "one": 1, 
    "two": 2
}

Programmtically, the Python manual describes pretty-printing JSON:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
    "4": 5,
    "6": 7
}

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

How to get coordinates of an svg element?

You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.

An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.

how to console.log result of this ajax call?

If you want to check your URL. I suppose you are using Chrome. You can go to chrome console and URL will be displayed under "XHR finished loading:"

How to put a link on a button with bootstrap?

You can just simply add the following code;

<a class="btn btn-primary" href="http://localhost:8080/Home" role="button">Home Page</a>

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

unsigned int vs. size_t

Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide size_t. The C standards committee introduced size_t to eliminate a portability problem

Explained in detail at embedded.com (with a very good example)

Mean per group in a data.frame

I describe two ways to do this, one based on data.table and the other based on reshape2 package . The data.table way already has an answer, but I have tried to make it cleaner and more detailed.

The data is like this:

 d <- structure(list(Name = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("Aira", "Ben", "Cat"), class = "factor"), 
    Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(12L, 
    18L, 19L, 53L, 22L, 19L, 22L, 67L, 45L), Rate2 = c(23L, 73L, 
    45L, 19L, 87L, 45L, 87L, 43L, 32L)), .Names = c("Name", "Month", 
"Rate1", "Rate2"), class = "data.frame", row.names = c(NA, -9L
))
head(d)
  Name Month Rate1 Rate2
1 Aira     1    12    23
2 Aira     2    18    73
3 Aira     3    19    45
4  Ben     1    53    19
5  Ben     2    22    87
6  Ben     3    19    45


library("reshape2")
mym <- melt(d, id = c("Name"))
res <- dcast(mym, Name ~ variable, mean)
res
#Name Month    Rate1    Rate2
#1 Aira     2 16.33333 47.00000
#2  Ben     2 31.33333 50.33333
#3  Cat     2 44.66667 54.00000

Using data.table:

# At first, I convert the data.frame to data.table and then I group it 
setDT(d)
d[, .(Rate1 = mean(Rate1), Rate2 = mean(Rate2)), by = .(Name)]
#   Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

There is another way of doing it by avoiding to write many argument for j in data.table using a .SD

d[, lapply(.SD, mean), by = .(Name)]
#   Name Month    Rate1    Rate2
#1: Aira     2 16.33333 47.00000
#2:  Ben     2 31.33333 50.33333
#3:  Cat     2 44.66667 54.00000

if we only want to have Rate1 and Rate2 then we can use the .SDcols as follows:

d[, lapply(.SD, mean), by = .(Name), .SDcols = 3:4]
#  Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

Failed to run sdkmanager --list with Java 9

As we read in the previous comments this error is occurring because the current SDK version is incompatible with the newest Java versions: 9 and 10.

So, to solve it, you can downgrade your java version to Java 8, or as a workaround, you can export the following option on your terminal:

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

If this does not work try to exports the java.xml.bind instead.

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

This will solve this error for the sdkmanager

And to make it saved permanently you can export the JAVA_OPTS in your profile file on Linux (.zshrc, .bashrc and etc.) or add it as an environment variable permanently on Windows.


ps. This doesn't work for Java 11/11+, which doesn't have Java EE modules. For this option is a good idea, downgrade your Java version or wait for a Flutter update.

Ref: JDK 11: End of the road for Java EE modules

Git checkout: updating paths is incompatible with switching branches

Not sure if this is helpful or exactly relevant to your question, but if you are trying to fetch and checkout only a single branch from the remote repository, then the following git commands will do the trick:

url= << URL TO REPOSITORY >>
branch= << BRANCH NAME >>

git init
git remote add origin $url
git fetch origin $branch:origin/$branch
git checkout -b $branch --track origin/$branch

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

Windows 10 Professional

PHP 7.3.1

I ran these commands to fix the problem on my desktop

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php

Starting the week on Monday with isoWeekday()

This way you can set the initial day of the week.

moment.locale('en', {
    week: {
        dow: 6
    }
});
moment.locale('en');

Make sure to use it with moment().weekday(1); instead of moment.isoWeekday(1)

justify-content property isn't working

This answer might be stupid, but I spent quite some time to figure it out.

What happened to me was I didn't set display: flex to the container. And of course, justify-content won't work without a container with that property.

How to change the Content of a <textarea> with JavaScript

Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:

document.forms['yourform']['yourtextarea'].value = 'yourvalue';

where in the HTML your textarea is nested somewhere in a form like this:

<form name="yourform">
    <textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>

And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.

Which comment style should I use in batch files?

good question... I've been looking for this functionality for long too...

after several tests and tricks it seem the better solution is the more obvious one...

--> best way I found to do it, preventing parser integrity fail, is reusing REM:

echo this will show until the next REM &REM this will not show

you can also use multiline with the "NULL LABEL" trick... (dont forget the ^ at the end of the line for continuity)

::(^
this is a multiline^
comment... inside a null label!^
dont forget the ^caret at the end-of-line^
to assure continuity of text^ 
)

Write a formula in an Excel Cell using VBA

The correct character (comma or colon) depends on the purpose.

Comma (,) will sum only the two cells in question.

Colon (:) will sum all the cells within the range with corners defined by those two cells.

Disabling of EditText in Android

In my case I needed my EditText to scroll text if no. of lines exceed maxLines when its disabled. This implementation worked perfectly for me.

private void setIsChatEditTextEditable(boolean value)
{
    if(value)
    {
        mEdittext.setCursorVisible(true);
        mEdittext.setSelection(chat_edittext.length());
       // use new EditText(getApplicationContext()).getKeyListener()) if required below
        mEdittext.setKeyListener(new AppCompatEditText(getApplicationContext()).getKeyListener());  
    }
    else
    {
        mEdittext.setCursorVisible(false);
        mEdittext.setKeyListener(null);
    }
}

How to Call a Function inside a Render in React/Jsx

To call the function you have to add ()

{this.renderIcon()}   

What is setBounds and how do I use it?

The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components. Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.

For the NullLayoutManager (in case you used new JPanel(null)) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.

So with public void Component.setBounds(int x, int y, int width, int height) you specify where your component is placed and how many pixel it is wide and high.

Here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      JPanel panel = new JPanel(null);

      JLabel helloLabel = new JLabel("Hello world!");
      helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
      panel.add(helloLabel);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}

How to set a timeout on a http.request() in Node?

There is simpler method.

Instead of using setTimeout or working with socket directly,
We can use 'timeout' in the 'options' in client uses

Below is code of both server and client, in 3 parts.

Module and options part:

'use strict';

// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js

const assert = require('assert');
const http = require('http');

const options = {
    host: '127.0.0.1', // server uses this
    port: 3000, // server uses this

    method: 'GET', // client uses this
    path: '/', // client uses this
    timeout: 2000 // client uses this, timesout in 2 seconds if server does not respond in time
};

Server part:

function startServer() {
    console.log('startServer');

    const server = http.createServer();
    server
            .listen(options.port, options.host, function () {
                console.log('Server listening on http://' + options.host + ':' + options.port);
                console.log('');

                // server is listening now
                // so, let's start the client

                startClient();
            });
}

Client part:

function startClient() {
    console.log('startClient');

    const req = http.request(options);

    req.on('close', function () {
        console.log("got closed!");
    });

    req.on('timeout', function () {
        console.log("timeout! " + (options.timeout / 1000) + " seconds expired");

        // Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
        req.destroy();
    });

    req.on('error', function (e) {
        // Source: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js#L248
        if (req.connection.destroyed) {
            console.log("got error, req.destroy() was called!");
            return;
        }

        console.log("got error! ", e);
    });

    // Finish sending the request
    req.end();
}


startServer();

If you put all the above 3 parts in one file, "a.js", and then run:

node a.js

then, output will be:

startServer
Server listening on http://127.0.0.1:3000

startClient
timeout! 2 seconds expired
got closed!
got error, req.destroy() was called!

Hope that helps.

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

Resource interpreted as Document but transferred with MIME type application/zip

I've faced this today, and my issue was that my Content-Disposition tag was wrongly set. It looks like for both pdf & application/x-zip-compressed, you're supposed to set it to inline instead of attachment.

So to set your header, Java code would look like this:

...
String fileName = "myFileName.zip";
String contentDisposition = "attachment";
if ("application/pdf".equals(contentType)
    || "application/x-zip-compressed".equals(contentType)) {
    contentDisposition = "inline";
}
response.addHeader("Content-Disposition", contentDisposition + "; filename=\"" + fileName + "\"");
...

How to install lxml on Ubuntu

For Ubuntu 14.04

sudo apt-get install python-lxml

worked for me.

Multiple actions were found that match the request in Web Api

Have you tried like:

[HttpGet("Summary")]
public HttpResponseMessage Summary(MyVm vm)
{
    return null;
}

[HttpGet("FullDetails")]
public HttpResponseMessage FullDetails()
{
    return null;
}

Using atan2 to find angle between two vectors

 atan2(vector1.y - vector2.y, vector1.x - vector2.x)

is the angle between the difference vector (connecting vector2 and vector1) and the x-axis, which is problably not what you meant.

The (directed) angle from vector1 to vector2 can be computed as

angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x);

and you may want to normalize it to the range [0, 2 p):

if (angle < 0) { angle += 2 * M_PI; }

or to the range (-p, p]:

if (angle > M_PI)        { angle -= 2 * M_PI; }
else if (angle <= -M_PI) { angle += 2 * M_PI; }

How to compare dates in Java?

You can use Date.getTime() which:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

This means you can compare them just like numbers:

if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
    /*
     * date is between date1 and date2 (both inclusive)
     */
}

/*
 * when date1 = 2015-01-01 and date2 = 2015-01-10 then
 * returns true for:
 * 2015-01-01
 * 2015-01-01 00:00:01
 * 2015-01-02
 * 2015-01-10
 * returns false for:
 * 2014-12-31 23:59:59
 * 2015-01-10 00:00:01
 * 
 * if one or both dates are exclusive then change <= to <
 */

How to extract URL parameters from a URL with Ruby or Rails?

For a pure Ruby solution combine URI.parse with CGI.parse (this can be used even if Rails/Rack etc. are not required):

CGI.parse(URI.parse(url).query) 
# =>  {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }

CSS scrollbar style cross browser

As of IE6 I believe you cannot customize the scroll bar using those properties. The Chris Coyier article linked to above goes into nice detail about the options for webkit proprietary css for customizing the scroll bar.

If you really want a cross browser solution that you can fully customize you're going to have to use some JS. Here is a link to a nice plugin for it called FaceScroll: http://www.dynamicdrive.com/dynamicindex11/facescroll/index.htm

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

There's a great blog post on this here:

http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/

Along with a demo here:

http://www.kylejlarson.com/files/iosdemo/

In summary, you can use the following on a div containing your main content:

.scrollable {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
}

The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?

In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.

It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:

document.addEventListener('touchmove', function(event) {
   if(event.target.parentNode.className.indexOf('noBounce') != -1 
|| event.target.className.indexOf('noBounce') != -1 ) {
    event.preventDefault(); }
}, false);

Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.

Other alternatives, also mentioned in the blog post, are Scrollability and iScroll

Bootstrap 4 responsive tables won't take up 100% width

Create responsive tables by wrapping any .table with .table-responsive{-sm|-md|-lg|-xl}, making the table scroll horizontally at each max-width breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.

just wrap table with .table-responsive{-sm|-md|-lg|-xl}

for example

<div class="table-responsive-md">
    <table class="table">
    </table>
</div>

bootstrap 4 tables

How to implement infinity in Java?

Only Double and Float type support POSITIVE_INFINITY constant.

How to uninstall Anaconda completely from macOS

The official instructions seem to be here: https://docs.anaconda.com/anaconda/install/uninstall/

but if you like me that didn't work for some reason and for some reason your conda was installed somewhere else with telling you do this:

rm -rf ~/opt

I have no idea why it was saved there but that's what did it for me.


This was useful to me in fixing my conda installation (if that is the reason you are uninstalling it in the first place like me): https://stackoverflow.com/a/60902863/1601580 that ended up fixing it for me. Not sure why conda was acting weird in the first place or installing things wrongly in the first place though...

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

For Docker users: In my case it was caused by excessive docker image size. You can remove unused data using prune command:

docker system prune --all --force --volumes

Warning: as per manual (docker system prune --help):

This will remove:

  • all stopped containers
  • all networks not used by at least one container
  • all dangling images
  • all dangling build cache

Opening database file from within SQLite command-line shell

I think the simplest way to just open a single database and start querying is:

sqlite> .open "test.db"
sqlite> SELECT * FROM table_name ... ;

Notice: This works only for versions 3.8.2+

Add tooltip to font awesome icon

The issue of adding tooltips to any HTML-Output (not only FontAwesome) is an entire book on its own. ;-)

The default way would be to use the title-attribute:

  <div id="welcomeText" title="So nice to see you!">
    <p>Welcome Harriet</p>
  </div>

or

<i class="fa fa-cog" title="Do you like my fa-coq icon?"></i>

But since most people (including me) do not like the standard-tooltips, there are MANY tools out there which will "beautify" them and offer all sort of enhancements. My personal favourites are jBox and qtip2.

Node.js ES6 classes with require

Using Classes in Node -

Here we are requiring the ReadWrite module and calling a makeObject(), which returns the object of the ReadWrite class. Which we are using to call the methods. index.js

const ReadWrite = require('./ReadWrite').makeObject();
const express = require('express');
const app = express();

class Start {
  constructor() {
    const server = app.listen(8081),
     host = server.address().address,
     port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port);
    console.log('Running');

  }

  async route(req, res, next) {
    const result = await ReadWrite.readWrite();
    res.send(result);
  }
}

const obj1 = new Start();
app.get('/', obj1.route);
module.exports = Start;

ReadWrite.js

Here we making a makeObject method, which makes sure that a object is returned, only if a object is not available.

class ReadWrite {
    constructor() {
        console.log('Read Write'); 
        this.x;   
    }
    static makeObject() {        
        if (!this.x) {
            this.x = new ReadWrite();
        }
        return this.x;
    }
    read(){
    return "read"
    }

    write(){
        return "write"
    }


    async readWrite() {
        try {
            const obj = ReadWrite.makeObject();
            const result = await Promise.all([ obj.read(), obj.write()])
            console.log(result);
            check();
            return result
        }
        catch(err) {
            console.log(err);

        }
    }
}
module.exports = ReadWrite;

For more explanation go to https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74

Return multiple values from a SQL Server function

Change it to a table-valued function

Please refer to the following link, for example.

diff current working copy of a file with another branch's committed copy

The following works for me:

git diff master:foo foo

In the past, it may have been:

git diff foo master:foo

XML Parsing - Read a Simple XML File and Retrieve Values

I usually use XmlDocument for this. The interface is pretty straight forward:

var doc = new XmlDocument();
doc.LoadXml(xmlString);

You can access nodes similar to a dictionary:

var tasks = doc["Tasks"];

and loop over all children of a node.

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Hope this Helps:

public String getSystemTimeInBelowFormat() {
    String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
    return timestamp;
}

Git push error pre-receive hook declined

Seems the problem is with some services, like sidekiq. Running sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production outputs all the problems with config.

Error to run Android Studio

I ran into this issue when I was referencing

 [drive]:\Program Files\Java\jdk1.8.0_65 

in my JAVA_HOME environment var instead of the Android Studio recommended

[drive]:\Program Files\Java\jdk1.7.0_79. 

I am using the x64 version of the JDK on Windows 10 Pro.

From the Android Studio installation instructions.

Before you set up Android Studio, be sure you have installed JDK 6 or higher (the JRE alone is not sufficient)—JDK 7 is required when developing for Android 5.0 and higher. To check if you have JDK installed (and which version), open a terminal and type javac -version. If the JDK is not available or the version is lower than version 6, download the Java SE Development Kit 7

http://developer.android.com/sdk/installing/index.html?pkg=studio

TypeError: not all arguments converted during string formatting python

You're mixing different format functions.

The old-style % formatting uses % codes for formatting:

'It will cost $%d dollars.' % 95

The new-style {} formatting uses {} codes and the .format method

'It will cost ${0} dollars.'.format(95)

Note that with old-style formatting, you have to specify multiple arguments using a tuple:

'%d days and %d nights' % (40, 40)

In your case, since you're using {} format specifiers, use .format:

"'{0}' is longer than '{1}'".format(name1, name2)

Failed Apache2 start, no error log

I ran into this exact issue today. I had copied the entire /etc/httpd from RHEL 6 and put it onto a CentOS 6 system, and ensured all RPMs were installed.

Anytime apache would be started, it would silently fail. It took an strace to find the culprit: I was using CustomLog to call a program that was not installed on the target system. Once I installed the expected program, Apache HTTP Server started right up.

Why do I get a "permission denied" error while installing a gem?

After setting the gems directory to the user directory that runs the gem install, using export GEM_HOME=/home/<user>/gems, the issue has been solved.

How do I get sed to read from standard input?

  1. Open the file using vi myfile.csv
  2. Press Escape
  3. Type :%s/replaceme/withthis/
  4. Type :wq and press Enter

Now you will have the new pattern in your file.

Prevent jQuery UI dialog from setting focus to first textbox

Just figured this out while playing around.

I found with these solutions to remove focus, caused the ESC key to stop working (ie close the dialog) when first going into the Dialog.

If the dialog opens and you immediately press ESC, it won't close the dialog (if you have that enabled), because the focus is on some hidden field or something, and it is not getting keypress events.

The way I fixed it was to add this to the open event to remove the focus from the first field instead:

$('#myDialog').dialog({
    open: function(event,ui) {
        $(this).parent().focus();
    }
});

This sets focus to the dialog box, which is not visible, and then the ESC key works.

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

The query either returned no rows or is erroneus, thus FALSE is returned. Change it to

if (!$dbc || mysqli_num_rows($dbc) == 0)

mysqli_num_rows:

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

websocket closing connection automatically

I believe this is a Jetty issue. I have not seen any browsers close WebSocket connections due to inactivity nor have I encountered other WebSocket servers that timeout WebSocket connections.

Jetty is (was) primarily focused on building HTTP based application servlets. In that context, HTTP connections need to be cleaned up pretty aggressively and HTTP was not designed for long-lived connections so having a short default timeout is reasonable.

I've not seen the precise problem you described (closing even with activity) but I do see WebSocket connections closed after 30 second of inactivity. It's possible that in older versions of Jetty or in the current version for some other reason, the timer is not reset by WebSocket activity. I get around this by using the setMaxIdleTime method on my BlockingChannelConnector object to set the timeout value to Integer MAX_VALUE.

WooCommerce - get category for product page

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

Unity 2d jumping script

Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.

Example:

rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);

How do I convert a file path to a URL in ASP.NET

For get the left part of the URL:

?HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)
"http://localhost:1714"

For get the application (web) name:

?HttpRuntime.AppDomainAppVirtualPath
"/"

With this, you are available to add your relative path after that obtaining the complete URL.

How to convert Json array to list of objects in c#

This is possible too:

using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);

Simulate a specific CURL in PostMan

As mentioned in multiple answers above you can import the cURL in POSTMAN directly. But if URL is authorized (or is not working for some reason) ill suggest you can manually add all the data points as JSON in your postman body. take the API URL from the cURL.

for the Authorization part- just add an Authorization key and base 64 encoded string as value.

example:

curl -u rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a \ https://api.razorpay.com/v1/orders -X POST \ --data "amount=50000" \ --data "currency=INR" \ --data "receipt=Receipt #20" \ --data "payment_capture=1" https://api.razorpay.com/v1/orders

{ "amount": "5000", "currency": "INR", "receipt": "Receipt #20", "payment_capture": "1" }

Headers: Authorization:Basic cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J where "cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J" is the encoded form of "rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a"`

small tip: for encoding, you can easily go to your chrome console (right-click => inspect) and type : btoa("string you want to encode") ( or use postman basic authorization)

jquery - return value using ajax result on success

I saw the answers here and although helpful, they weren't exactly what I wanted since I had to alter a lot of my code.

What worked out for me, was doing something like this:

function isSession(selector) {
    //line added for the var that will have the result
    var result = false;
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        //line added to get ajax response in sync
        async: false,
        success: function(data) {
            //line added to save ajax response in var result
            result = data;
        },
        error: function() {
            alert('Error occured');
        }
    });
    //line added to return ajax response
    return result;
}

Hope helps someone

anakin

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

What is `related_name` used for in Django?

The essentials of your question are as follows.

Since you have Map and User models and you have defined ManyToManyField in Map model, if you want to get access to members of the Map then you have the option of map_instance.members.all() since you have defined members field. However, say you want to access all maps a user is a part of then what option do you have.

By default, Django provided you with user_instance.modelname_set.all() and this will translate to the user.map_set.all() in this case.

maps is much better than map_set.

related_name provides you an ability to let Django know how you are going to access Map from User model or in general how you can access reverse models which is the whole point in creating ManyToMany fields and using ORM in that sense.

How to access Session variables and set them in javascript?

You could also set the variable in a property and call it from js:

On the Server side :

Protected ReadOnly Property wasFieldEditedStatus() As Boolean
    Get
        Return If((wasFieldEdited), "true", "false")
    End Get
End Property

And then in the javascript:

alert("The wasFieldEdited Value: <%= wasFieldEditedStatus %>" );

Can't find/install libXtst.so.6?

Had that issue on Ubuntu 14.04, In my case I had also libXtst.so missing:

Could not open library 'libXtst.so': libXtst.so: cannot open shared object 
file: No such file or directory

Make sure your symbolic link is pointing to proper file, cd /usr/lib/x86_64-linux-gnu and list libXtst with:

 ll |grep libXtst                                                                                                                                                           
 lrwxrwxrwx   1 root root        16 Oct  7  2016 libXtst.so.6 -> libXtst.so.6.1.0
 -rw-r--r--   1 root root     22880 Aug 16  2013 libXtst.so.6.1.0

Then just create proper symbolic link using:

sudo ln -s libXtst.so.6 libXtst.so

List again:

ll | grep libXtst
lrwxrwxrwx   1 root root        12 Sep 20 10:23 libXtst -> libXtst.so.6
lrwxrwxrwx   1 root root        12 Sep 20 10:23 libXtst.so -> libXtst.so.6
lrwxrwxrwx   1 root root        16 Oct  7  2016 libXtst.so.6 -> libXtst.so.6.1.0
-rw-r--r--   1 root root     22880 Aug 16  2013 libXtst.so.6.1.0

all set!

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

One more point I want to add. In spring-servlet.xml we include component scan for Controller package. In following example we include filter annotation for controller package.

<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

In applicationcontext.xml we add filter for remaining package excluding controller.

<context:component-scan base-package="org.test">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

SQL: capitalize first letter only

select replace(wm_concat(new),',','-') exp_res from (select distinct initcap(substr(name,decode(level,1,1,instr(name,'-',1,level-1)+1),decode(level,(length(name)-length(replace(name,'-','')))+1,9999,instr(name,'-',1,level)-1-decode(level,1,0,instr(name,'-',1,level-1))))) new from table;
connect by level<= (select (length(name)-length(replace(name,'-','')))+1 from table));

How to set delay in vbscript

As stated in this answer:

Application.Wait (Now + TimeValue("0:00:01"))

will wait for 1 second

Which browser has the best support for HTML 5 currently?

Seems that new browsers support most of the tags: <header>, <section> etc. For older browsers (IE, Fx2, Camino etc) then you can use this to allow styling of these tags:

document.createElement('header');

Would make these older browsers allow CSS styling of a header tag, instead of just ignoring it.

This means that you can now use the new tags without any loss of functionality, which is a good start!

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

there may be more than 1 IBAction for a button in your view controller try finding out those and removing all previous item for that button in your controller and create new button .It will solve your problem.

How can I get the UUID of my Android phone in an application?

As of API 26, getDeviceId() is deprecated. If you need to get the IMEI of the device, use the following:

 String deviceId = "";
    if (Build.VERSION.SDK_INT >= 26) {
        deviceId = getSystemService(TelephonyManager.class).getImei();
    }else{
        deviceId = getSystemService(TelephonyManager.class).getDeviceId();
    }

Performing a query on a result from another query?

I don't know if you even need to wrap it. Won't this work?

SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms    ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' 
  AND date_add('2009-06-25', INTERVAL 4 DAY)
  AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);

If your goal is to return both result sets then you'll need to store it some place temporarily.

What does "to stub" mean in programming?

Stub is a piece of code which converts the parameters during RPC (Remote procedure call).The parameters of RPC have to be converted because both client and server use different address space. Stub performs this conversion so that server perceive the RPC as a local function call.

Hiding the R code in Rmarkdown/knit and just showing the results

Sure, just do

```{r someVar, echo=FALSE}
someVariable
```

to show some (previously computed) variable someVariable. Or run code that prints etc pp.

So for plotting, I have eg

### Impact of choice of ....
```{r somePlot, echo=FALSE}
plotResults(Res, Grid, "some text", "some more text")
```

where the plotting function plotResults is from a local package.

Optional args in MATLAB functions

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})
   end

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

'Source code does not match the bytecode' when debugging on a device

You should use an Android emulator with the same api level as the compileSdkVersion. In your case you should use Android emulator with api level 21.

Check object empty

If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

How to resize Twitter Bootstrap modal dynamically based on the content

I simply override the css:

.modal-dialog {
    max-width: 1000px;
}

Connection timeout for SQL server

If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .

It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.

In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?

Also as it creates an Object and its always good to assign value in object rather than manipulating string.

Here is the code sample:

var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);

sscsb.ConnectTimeout = 30;

var conn = new SqlConnection(sscsb.ConnectionString);

How can I scale an entire web page with CSS?

As Johannes says -- not enough rep to comment directly on his answer -- you can indeed do this as long as all elements' "dimensions are specified as a multiple of the font's size. Meaning, everything where you used %, em or ex units". Although I think % are based on containing element, not font-size.

And you wouldn't normally use these relative units for images, given they are composed of pixels, but there's a trick which makes this a lot more practical.

If you define body{font-size: 62.5%}; then 1em will be equivalent to 10px. As far as I know this works across all main browsers.

Then you can specify your (e.g.) 100px square images with width: 10em; height: 10em; and assuming Firefox's scaling is set to default, the images will be their natural size.

Make body{font-size: 125%}; and everything - including images - wil be double original size.

Can't append <script> element

The Good News is:

It's 100% working.

Just add something inside the script tag such as alert('voila!');. The right question you might want to ask perhaps, "Why didn't I see it in the DOM?".

Karl Swedberg has made a nice explanation to visitor's comment in jQuery API site. I don't want to repeat all his words, you can read directly there here (I found it hard to navigate through the comments there).

All of jQuery's insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an "evalScript routine" rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM.

I believe that one of the reasons jQuery does this is to avoid "Permission Denied" errors that can occur in Internet Explorer when inserting scripts under certain circumstances. It also avoids repeatedly inserting/evaluating the same script (which could potentially cause problems) if it is within a containing element that you are inserting and then moving around the DOM.

The next thing is, I'll summarize what's the bad news by using .append() function to add a script.


And The Bad News is..

You can't debug your code.

I'm not joking, even if you add debugger; keyword between the line you want to set as breakpoint, you'll be end up getting only the call stack of the object without seeing the breakpoint on the source code, (not to mention that this keyword only works in webkit browser, all other major browsers seems to omit this keyword).

If you fully understand what your code does, than this will be a minor drawback. But if you don't, you will end up adding a debugger; keyword all over the place just to find out what's wrong with your (or my) code. Anyway, there's an alternative, don't forget that javascript can natively manipulate HTML DOM.


Workaround.

Use javascript (not jQuery) to manipulate HTML DOM

If you don't want to lose debugging capability, than you can use javascript native HTML DOM manipulation. Consider this example:

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "path/to/your/javascript.js";    // use this for linked script
script.text  = "alert('voila!');"               // use this for inline script
document.body.appendChild(script);

There it is, just like the old days isn't it. And don't forget to clean things up whether in the DOM or in the memory for all object that's referenced and not needed anymore to prevent memory leaks. You can consider this code to clean things up:

document.body.removechild(document.body.lastChild);
delete UnusedReferencedObjects; // replace UnusedReferencedObject with any object you created in the script you load.

The drawback from this workaround is that you may accidentally add a duplicate script, and that's bad. From here you can slightly mimic .append() function by adding an object verification before adding, and removing the script from the DOM right after it was added. Consider this example:

function AddScript(url, object){
    if (object != null){
        // add script
        var script   = document.createElement("script");
        script.type  = "text/javascript";
        script.src   = "path/to/your/javascript.js";
        document.body.appendChild(script);

        // remove from the dom
        document.body.removeChild(document.body.lastChild);
        return true;
    } else {
        return false;
    };
};

function DeleteObject(UnusedReferencedObjects) {
    delete UnusedReferencedObjects;
}

This way, you can add script with debugging capability while safe from script duplicity. This is just a prototype, you can expand for whatever you want it to be. I have been using this approach and quite satisfied with this. Sure enough I will never use jQuery .append() to add a script.

checking for typeof error in JS

Thanks @Trott for your code, I just used the same code and added with a real time working example for the benefit of others.

_x000D_
_x000D_
<html>_x000D_
<body >_x000D_
_x000D_
<p>The **instanceof** operator returns true if the specified object is an instance of the specified object.</p>_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
 var myError = new Error("TypeError: Cannot set property 'innerHTML' of null"); // error type when element is not defined_x000D_
 myError instanceof Error // true_x000D_
 _x000D_
 _x000D_
 _x000D_
 _x000D_
 function test(){_x000D_
 _x000D_
 var v1 = document.getElementById("myid").innerHTML ="zunu"; // to change with this_x000D_
 _x000D_
 try {_x000D_
    var v1 = document.getElementById("myidd").innerHTML ="zunu"; // exception caught_x000D_
    } _x000D_
    _x000D_
 catch (e) {_x000D_
    if (e instanceof Error) {_x000D_
   console.error(e.name + ': ' + e.message) // error will be displayed at browser console_x000D_
    }_x000D_
  }_x000D_
  finally{_x000D_
  var v1 = document.getElementById("myid").innerHTML ="Text Changed to Zunu"; // finally innerHTML changed to this._x000D_
 }_x000D_
 _x000D_
 }_x000D_
 _x000D_
</script>_x000D_
<p id="myid">This text will change</p>_x000D_
<input type="button" onclick="test();">_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Converting String to Double in Android

What about using the Double(String) constructor? So,

protein = new Double(p);

Don't know why it would be different, but might be worth a shot.

WPF Datagrid Get Selected Cell Value

Ok after doing reverse engineering and a little pixie dust of reflection, one can do this operation on SelectedCells (at any point) to get all (regardless of selected on one row or many rows) the data from one to many selected cells:

MessageBox.Show(

string.Join(", ", myGrid.SelectedCells
                        .Select(cl => cl.Item.GetType()
                                             .GetProperty(cl.Column.SortMemberPath)
                                             .GetValue(cl.Item, null)))

               );

I tried this on text (string) fields only though a DateTime field should return a value the initiate ToString(). Also note that SortMemberPath is not the same as Header so that should always provide the proper property to reflect off of.

<DataGrid ItemsSource="{Binding MyData}"                      
          AutoGenerateColumns="True"
          Name="myGrid"
          IsReadOnly="True"
          SelectionUnit="Cell"
          SelectionMode="Extended">

How to start nginx via different port(other than 80)

You have to go to the /etc/nginx/sites-enabled/ and if this is the default configuration, then there should be a file by name: default.

Edit that file by defining your desired port; in the snippet below, we are serving the Nginx instance on port 81.

server {
    listen 81;
}

To start the server, run the command line below;

sudo service nginx start

You may now access your application on port 81 (for localhost, http://localhost:81).

Combine multiple results in a subquery into a single comma-separated value

1. Create the UDF:

CREATE FUNCTION CombineValues
(
    @FK_ID INT -- The foreign key from TableA which is used 
               -- to fetch corresponding records
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @SomeColumnList VARCHAR(8000);

SELECT @SomeColumnList =
    COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) 
FROM TableB C
WHERE C.FK_ID = @FK_ID;

RETURN 
(
    SELECT @SomeColumnList
)
END

2. Use in subquery:

SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA

3. If you are using stored procedure you can do like this:

CREATE PROCEDURE GetCombinedValues
 @FK_ID int
As
BEGIN
DECLARE @SomeColumnList VARCHAR(800)
SELECT @SomeColumnList =
    COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) 
FROM TableB
WHERE FK_ID = @FK_ID 

Select *, @SomeColumnList as SelectedIds
    FROM 
        TableA
    WHERE 
        FK_ID = @FK_ID 
END

How to remove default chrome style for select Input?

In your CSS add this:

input {-webkit-appearance: none; box-shadow: none !important; }
:-webkit-autofill { color: #fff !important; }

Only for Chrome! :)

How would one write object-oriented code in C?

Yes, but I have never seen anyone attempt to implement any sort of polymorphism with C.

Can you autoplay HTML5 videos on the iPad?

iOS 10 update

The ban on autoplay has been lifted as of iOS 10 - but with some restrictions (e.g. A can be autoplayed if there is no audio track).

To see a full list of these restrictions, see the official docs: https://webkit.org/blog/6784/new-video-policies-for-ios/

iOS 9 and before

As of iOS 6.1, it is no longer possible to auto-play videos on the iPad.

My assumption as to why they've disabled the auto-play feature?

Well, as many device owners have data usage/bandwidth limits on their devices, I think Apple felt that the user themselves should decide when they initiate bandwidth usage.


After a bit of research I found the following extract in the Apple documentation in regard to auto-play on iOS devices to confirm my assumption:

"Apple has made the decision to disable the automatic playing of video on iOS devices, through both script and attribute implementations.

In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.

Here is a separate warning featured on the Safari HTML5 Reference page about why embedded media cannot be played in Safari on iOS:

Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.


What this means (in terms of code) is that Javascript's play() and load() methods are inactive until the user initiates playback, unless the play() or load() method is triggered by user action (e.g. a click event).

Basically, a user-initiated play button works, but an onLoad="play()" event does not.

For example, this would play the movie:

<input type="button" value="Play" onclick="document.myMovie.play()">

Whereas the following would do nothing on iOS:

<body onload="document.myMovie.play()">

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

Make a nav bar stick

Give headercss position fixed.

.headercss {
    width: 100%;
    height: 320px;
    background-color: #000000;
    position: fixed;
    top:0
}

Then give the content container a 320px padding-top, so it doesn't get behind the header.

Maven2: Missing artifact but jars are in place

Wow, this had me tearing my hair out, banging my head against walls, tables and other things. I had the same or a similar issue as the OP where it was either missing / not downloading the jar files or downloading them, but not including them in the Maven dependencies with the same error message. My limited knowledge of java packaging and maven probably didn't help.

For me the problem seems to have been caused by the Dependency Type "bundle" (but I don't know how or why). I was using the Add Dependency dialog in Eclipse Mars on the pom.xml, which allows you to search and browse the central repository. I was searching and adding a dependency to jackson-core libraries, picking the latest version, available as a bundle. This kept failing.

So finally, I changed the dependency properties form bundle to jar (again using the dependency properties window), which finally downloaded and referenced the dependencies properly after saving the changes.

Difference between Date(dateString) and new Date(dateString)

I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:

var temp = new Date(  Date("2010-08-17 12:09:36")   );
alert(temp);

the internal call to Date() returns a string that new Date() can parse.

What is the difference between bottom-up and top-down?

A key feature of dynamic programming is the presence of overlapping subproblems. That is, the problem that you are trying to solve can be broken into subproblems, and many of those subproblems share subsubproblems. It is like "Divide and conquer", but you end up doing the same thing many, many times. An example that I have used since 2003 when teaching or explaining these matters: you can compute Fibonacci numbers recursively.

def fib(n):
  if n < 2:
    return n
  return fib(n-1) + fib(n-2)

Use your favorite language and try running it for fib(50). It will take a very, very long time. Roughly as much time as fib(50) itself! However, a lot of unnecessary work is being done. fib(50) will call fib(49) and fib(48), but then both of those will end up calling fib(47), even though the value is the same. In fact, fib(47) will be computed three times: by a direct call from fib(49), by a direct call from fib(48), and also by a direct call from another fib(48), the one that was spawned by the computation of fib(49)... So you see, we have overlapping subproblems.

Great news: there is no need to compute the same value many times. Once you compute it once, cache the result, and the next time use the cached value! This is the essence of dynamic programming. You can call it "top-down", "memoization", or whatever else you want. This approach is very intuitive and very easy to implement. Just write a recursive solution first, test it on small tests, add memoization (caching of already computed values), and --- bingo! --- you are done.

Usually you can also write an equivalent iterative program that works from the bottom up, without recursion. In this case this would be the more natural approach: loop from 1 to 50 computing all the Fibonacci numbers as you go.

fib[0] = 0
fib[1] = 1
for i in range(48):
  fib[i+2] = fib[i] + fib[i+1]

In any interesting scenario the bottom-up solution is usually more difficult to understand. However, once you do understand it, usually you'd get a much clearer big picture of how the algorithm works. In practice, when solving nontrivial problems, I recommend first writing the top-down approach and testing it on small examples. Then write the bottom-up solution and compare the two to make sure you are getting the same thing. Ideally, compare the two solutions automatically. Write a small routine that would generate lots of tests, ideally -- all small tests up to certain size --- and validate that both solutions give the same result. After that use the bottom-up solution in production, but keep the top-bottom code, commented out. This will make it easier for other developers to understand what it is that you are doing: bottom-up code can be quite incomprehensible, even you wrote it and even if you know exactly what you are doing.

In many applications the bottom-up approach is slightly faster because of the overhead of recursive calls. Stack overflow can also be an issue in certain problems, and note that this can very much depend on the input data. In some cases you may not be able to write a test causing a stack overflow if you don't understand dynamic programming well enough, but some day this may still happen.

Now, there are problems where the top-down approach is the only feasible solution because the problem space is so big that it is not possible to solve all subproblems. However, the "caching" still works in reasonable time because your input only needs a fraction of the subproblems to be solved --- but it is too tricky to explicitly define, which subproblems you need to solve, and hence to write a bottom-up solution. On the other hand, there are situations when you know you will need to solve all subproblems. In this case go on and use bottom-up.

I would personally use top-bottom for Paragraph optimization a.k.a the Word wrap optimization problem (look up the Knuth-Plass line-breaking algorithms; at least TeX uses it, and some software by Adobe Systems uses a similar approach). I would use bottom-up for the Fast Fourier Transform.

XMLHttpRequest status 0 (responseText is empty)

Here's another case in which status === 0, specific to uploading:

If you attach a 'load' event handler to XHR.upload, as suggested by MDN (scroll down to the upload part of 'Monitoring progress'), the XHR object will have status=0 and all the other properties will be empty strings. If you attach the 'load' handler directly to the XHR object, as you would when downloading content, you should be fine (given you're not running off localhost).

However, if you want to get good data in your 'progress' event handlers, you need to attach a handler to XHR.upload, not directly to the XHR object itself.

I've only tested this so far on Chrome OSX, so I'm not sure how much of the problem here is MDN's documentation and how much is Chrome's implementation...

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

Create a day-of-week column in a Pandas dataframe using Python

In version 0.18.1 is added dt.weekday_name:

print df
    my_dates  myvals
0 2015-01-01       1
1 2015-01-02       2
2 2015-01-03       3

print df.dtypes
my_dates    datetime64[ns]
myvals               int64
dtype: object

df['day_of_week'] = df['my_dates'].dt.weekday_name
print df
    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Another solution with assign:

print df.assign(day_of_week = df['my_dates'].dt.weekday_name)
    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Creating an instance using the class name and calling constructor

You can use reflections

return Class.forName(className).getConstructor(String.class).newInstance(arg);

Binding multiple events to a listener (without JQuery)?

Some compact syntax that achieves the desired result, POJS:

   "mousemove touchmove".split(" ").forEach(function(e){
      window.addEventListener(e,mouseMoveHandler,false);
    });

How to disable <br> tags inside <div> by css?

You could alter your CSS to render them less obtrusively, e.g.

div p,
div br {
    display: inline;
}

http://jsfiddle.net/zG9Ax/

or - as my commenter points out:

div br {
    display: none;
}

but then to achieve the example of what you want, you'll need to trim the p down, so:

div br {
    display: none;
}
div p {
    padding: 0;
    margin: 0;
}

http://jsfiddle.net/zG9Ax/1

PIG how to count a number of rows in alias

COUNT is part of pig see the manual

LOGS= LOAD 'log';
LOGS_GROUP= GROUP LOGS ALL;
LOG_COUNT = FOREACH LOGS_GROUP GENERATE COUNT(LOGS);

Java 8 forEach with index

It works with params if you capture an array with one element, that holds the current index.

int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));

The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.

If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:

int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

How to change font size in Eclipse for Java text editors?

I tend to use menu Windows ? Preferences ? General ? Appearances ? Colors and Fonts ? Java Text Editors ? Change ? Apply.

Auto-center map with multiple markers in Google Maps API v3

I use the method above to set the map boundaries, then, instead of resetting the zoom level, I just calculate the average LAT and average LON and set the center point to that location. I add up all the lat values into latTotal and all the lon values into lontotal and then divide by the number of markers. I then set the map center point to those average values.

latCenter = latTotal / markercount; lonCenter = lontotal / markercount;

onNewIntent() lifecycle and registered listeners

Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.

OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.

You can invoke onNewIntent always by putting it into onCreate method like

@Override
public void onCreate(Bundle savedState){
    super.onCreate(savedState);
    onNewIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //code
}

Multiple line code example in Javadoc comment

I just read the Javadoc 1.5 reference here, and only the code with <and > must be enclosed inside {@code ...}. Here a simple example:

 /** 
 * Bla bla bla, for example:
 *
 * <pre>
 * void X() {
 *    List{@code <String>} a = ...;
 *    ...
 * }
 * </pre>
 *
 * @param ...
 * @return ...
 */
 .... your code then goes here ...

IE8 css selector

In the light of the evolving thread, see below for a more complete answer:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading

How many characters can a Java String have?

Java9 uses byte[] to store String.value, so you can only get about 1GB Strings in Java9. Java8 on the other hand can have 2GB Strings.

By character I mean "char"s, some character is not representable in BMP(like some of the emojis), so it will take more(currently 2) chars.

Groovy built-in REST/HTTP client?

HTTPBuilder is it. Very easy to use.

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder('https://google.com')
def html = http.get(path : '/search', query : [q:'waffles'])

It is especially useful if you need error handling and generally more functionality than just fetching content with GET.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

This was happening for me when I had Skype running on my local machine. As soon as I closed that the exception went away.

Idea courtesy of this page

Program to find largest and smallest among 5 numbers without using array

Heres what I did, without using an array. This was a method to return the highest number of 5 scores.

double findHighest(double score1, double score2, double score3, double score4, double score5)
 {
   double highest = score1;
   if (score2 > score1 && score2 > score3 && score2 > score4 && score2 > score5)
      highest = score2;
   if(score3 > score1 && score3 > score2 && score3 > score4 && score3 > score5)
      highest = score3;
   if(score4 > score1 && score4 > score2 && score4 > score3 && score4 > score5)
      highest = score4;
   if (score5 > score1 && score5 > score2 && score5 > score3 && score5 > score4)
      highest = score5;
   return highest;
 }

An array is going to be far more efficient, but I had to do it for homework without using an array.

How do I change the UUID of a virtual disk?

Another alternative to your original solution would be to use the escape character \ before the space:

VBoxManage internalcommands sethduuid /home/user/VirtualBox\ VMs/drupal/drupal.vhd

Cannot find the '@angular/common/http' module

For anyone using Ionic 3 and Angular 5, I had the same error pop up and I didn't find any solutions here. But I did find some steps that worked for me.

Steps to reproduce:

  • npm install -g cordova ionic
  • ionic start myApp tabs
  • cd myApp
  • cd node_modules/angular/common (no http module exists).

ionic:(run ionic info from a terminal/cmd prompt), check versions and make sure they're up to date. You can also check the angular versions and packages in the package.json folder in your project.

I checked my dependencies and packages and installed cordova. Restarted atom and the error went away. Hope this helps!

jQuery rotate/transform

It's because you have a recursive function inside of rotate. It's calling itself again:

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Take that out and it won't keep on running recursively.

I would also suggest just using this function instead:

function rotate($el, degrees) {
    $el.css({
  '-webkit-transform' : 'rotate('+degrees+'deg)',
     '-moz-transform' : 'rotate('+degrees+'deg)',  
      '-ms-transform' : 'rotate('+degrees+'deg)',  
       '-o-transform' : 'rotate('+degrees+'deg)',  
          'transform' : 'rotate('+degrees+'deg)',  
               'zoom' : 1

    });
}

It's much cleaner and will work for the most amount of browsers.

Java Replace Character At Specific Position Of String?

If you need to re-use a string, then use StringBuffer:

String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
    sb.setCharAt(1, 'k');
}

EDIT:

Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.

Passing an array of parameters to a stored procedure

declare @ids nvarchar(1000)

set @ids = '100,2,3,4,5' --Parameter passed

set @ids = ',' + @ids + ','

select   *
from     TableName 
where    charindex(',' + CAST(Id as nvarchar(50)) + ',', @ids) > 0

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

Is it possible to style html5 audio tag?

Yes: you can hide the built-in browser UI (by removing the controls attribute from audio) and instead build your own interface and control the playback using Javascript (source):

<audio id="player" src="vincent.mp3"></audio>
<div> 
  <button onclick="document.getElementById('player').play()">Play</button> 
  <button onclick="document.getElementById('player').pause()">Pause</button> 
  <button onclick="document.getElementById('player').volume += 0.1">Vol +</button> 
  <button onclick="document.getElementById('player').volume -= 0.1">Vol -</button> 
</div>

You can then style the elements however you wish using CSS.

MDN HTMLAudioElement API reference

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Regex - how to match everything except a particular pattern

pattern - re

str.split(/re/g) 

will return everything except the pattern.

Test here

How to disable scrolling temporarily?

This is the simplest solution I got so far. And believe me I tried all the others and this is the easiest one. It works great on Windows devices, which pushes the page from the right to have room for the system scrollbar and IOS devices which don't require space for their scrollbars in the browsers. So by using this you wont need to add padding on the right so the page doesn't flicker when you hide the overflow of the body or html with css.

The solution is pretty simple if you think about it. The idea is to give the window.scrollTop() the same exact position at the moment that a popup is opened. Also change that position when the window resizes ( as the scroll position changes once that happens ).

So here we go...

First lets create the variable that will let you know that the popup is open and call it stopWindowScroll. If we don't do this then you'll get an error of an undefined variable on your page and set it to 0 - as not active.

$(document).ready(function(){
    stopWindowScroll = 0;
});

Now lets make the open popup function witch can be any function in your code that triggers whatever popup you are using as a plugin or custom. In this case it will be a simple custom popup with a simple document on click function.

$(document).on('click','.open-popup', function(){
    // Saving the scroll position once opening the popup.
    stopWindowScrollPosition = $(window).scrollTop();
    // Setting the stopWindowScroll to 1 to know the popup is open.
    stopWindowScroll = 1;
    // Displaying your popup.
    $('.your-popup').fadeIn(300);
});

So the next thing we do is create the close popup function, which I repeat again can be any function you already have created or are using in a plugin. The important thing is that we need those 2 functions to set the stopWindowScroll variable to 1 or 0 to know when it's open or closed.

$(document).on('click','.open-popup', function(){
    // Setting the stopWindowScroll to 0 to know the popup is closed.
    stopWindowScroll = 0;
    // Hiding your popup
    $('.your-popup').fadeOut(300);
});

Then lets create the window.scroll function so we can prevent the scrolling once the stopWindowScroll mentioned above is set to 1 - as active.

$(window).scroll(function(){
    if(stopWindowScroll == 1) {
         // Giving the window scrollTop() function the position on which
         // the popup was opened, this way it will stay in its place.
         $(window).scrollTop(stopWindowScrollPosition);
    }
});

Thats it. No CSS required for this to work except your own styles for the page. This worked like a charm for me and I hope it helps you and others.

Here is a working example on JSFiddle:

JS Fiddle Example

Let me know if this helped. Regards.

Set cellpadding and cellspacing in CSS?

td {
    padding: npx; /* For cellpadding */
    margin: npx; /* For cellspacing */
    border-collapse: collapse; /* For showing borders in a better shape. */
}

If margin didn't work, try to set display of tr to block and then margin will work.

What is "Connect Timeout" in sql server connection string?

Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout%28v=vs.110%29.aspx

Android "Only the original thread that created a view hierarchy can touch its views."

I solved this by putting runOnUiThread( new Runnable(){ .. inside run():

thread = new Thread(){
        @Override
        public void run() {
            try {
                synchronized (this) {
                    wait(5000);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dbloadingInfo.setVisibility(View.VISIBLE);
                            bar.setVisibility(View.INVISIBLE);
                            loadingText.setVisibility(View.INVISIBLE);
                        }
                    });

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent mainActivity = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(mainActivity);
        };
    };  
    thread.start();

How to list all installed packages and their versions in Python?

yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )

with pip installed packages, you can do a

pip freeze

and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do

mkvirtualenv my_new_project

and then (inside that virtualenv), do

pip install all_your_stuff

This way, you can workon my_new_project and then pip freeze to see which packages are installed for that virtualenv/project.

for example:

?  ~  mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details

(yo_dude)?  ~  pip install django
Downloading/unpacking django
  Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
  Running setup.py egg_info for package django

Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...

(yo_dude)?  ~  pip freeze
Django==1.4.1
wsgiref==0.1.2

(yo_dude)?  ~  

or if you have a python package with a requirements.pip file,

mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze

will do the trick

Where does Java's String constant pool live, the heap or the stack?

As other answers explain Memory in Java is divided into two portions

1. Stack: One stack is created per thread and it stores stack frames which again stores local variables and if a variable is a reference type then that variable refers to a memory location in heap for the actual object.

2. Heap: All kinds of objects will be created in heap only.

Heap memory is again divided into 3 portions

1. Young Generation: Stores objects which have a short life, Young Generation itself can be divided into two categories Eden Space and Survivor Space.

2. Old Generation: Store objects which have survived many garbage collection cycles and still being referenced.

3. Permanent Generation: Stores metadata about the program e.g. runtime constant pool.

String constant pool belongs to the permanent generation area of Heap memory.

We can see the runtime constant pool for our code in the bytecode by using javap -verbose class_name which will show us method references (#Methodref), Class objects ( #Class ), string literals ( #String )

runtime-constant-pool

You can read more about it on my article How Does JVM Handle Method Overloading and Overriding Internally.

To show error message without alert box in Java Script

you can try it like this

 <html>
          <head>
          <script type="text/javascript">
          function validate() 
          {
            var fnameval=document.getElementById("fname").value;
            var fnamelen=Number(fnameval.length);
               if(fnamelen==0)
               {
                  document.getElementById("fname_msg").innerHTML="this is invalid name ";
                }
            }
          </script>
          </head>
          <body>
          <form name="myform">
          First_Name
          <input type=text id=fname name=fname onblur="validate()"> </input>
           <span id=fname_msg></span>
          <br> <br>
          Last_Name
          <input type=text id=lname name=lname onblur="validate()"> </input>

          <br>
          <input type=button value=check> 

          </form>
          </body>
        </html>

How do I add a border to an image in HTML?

Two ways:

<img src="..." border="1" />

or

<img style='border:1px solid #000000' src="..." />

Stash only one file out of multiple files that have changed with Git?

This can be done easily in 3 steps using SourceTree.

  1. Temporarily commit everything you don't want stashed.
  2. Git add everything else, then stash it.
  3. Pop your temporary commit by running git reset, targetting the commit before your temporary one.

This can all be done in a matter of seconds in SourceTree, where you can just click on the files (or even individual lines) you want to add. Once added, just commit them to a temporary commit. Next, click the checkbox to add all changes, then click stash to stash everything. With the stashed changes out of the way, glance over at your commit list and note the hash for the commit before your temporary commit, then run 'git reset hash_b4_temp_commit', which is basically like "popping" the commit by resetting your branch to the commit right before it. Now, you're left with just the stuff you didn't want stashed.

What is the easiest way to parse an INI File in C++?

I ended up using inipp which is not mentioned in this thread.

https://github.com/mcmtroffaes/inipp

Was a MIT licensed header only implementation which was simple enough to add to a project and 4 lines to use.

Xpath: select div that contains class AND whose specific child element contains text

You can use ancestor. I find that this is easier to read because the element you are actually selecting is at the end of the path.

//span[contains(text(),'someText')]/ancestor::div[contains(@class, 'measure-tab')]

Java parsing XML document gives "Content not allowed in prolog." error

Make sure there's no hidden whitespace at the start of your XML file. Also maybe include encoding="UTF-8" (or 16? No clue) in the node.

How to install pip for Python 3 on Mac OS X?

Also, it's worth to mention that Max OSX/macOS users can just use Homebrew to install pip3.

$> brew update
$> brew install python3
$> pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

Convert IEnumerable to DataTable

Look at this one: Convert List/IEnumerable to DataTable/DataView

In my code I changed it into a extension method:

public static DataTable ToDataTable<T>(this List<T> items)
{
    var tb = new DataTable(typeof(T).Name);

    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach(var prop in props)
    {
        tb.Columns.Add(prop.Name, prop.PropertyType);
    }

     foreach (var item in items)
    {
       var values = new object[props.Length];
        for (var i=0; i<props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }

    return tb;
}

PHP Function Comments

You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().

http://www.php.net/manual/en/reflectionclass.getdoccomment.php

install apt-get on linux Red Hat server

I think you're running into problems because RedHat uses RPM for managing packages. Debian based systems use DEBs, which are managed with tools like apt.

How can I stop redis-server?

Another way could be :

brew services stop redis

Switch in Laravel 5 - Blade

You can just add these code in AppServiceProvider class boot method.

Blade::extend(function($value, $compiler){
        $value = preg_replace('/(\s*)@switch\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
        $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
        $value = preg_replace('/(\s*)@case\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
        $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
        $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
        return $value;
    });

then you can use as:

@switch( $item )
    @case( condition_1 )
        // do something
    @breakswitch
    @case( condition_2 )
        // do something else
    @breakswitch
    @default
        // do default behaviour
    @breakswitch
@endswitch

Enjoy It~

How to set top position using jquery

You can use CSS to do the trick:

$("#yourElement").css({ top: '100px' });

How do I properly clean up Excel interop objects?

So far it seems all answers involve some of these:

  1. Kill the process
  2. Use GC.Collect()
  3. Keep track of every COM object and release it properly.

Which makes me appreciate how difficult this issue is :)

I have been working on a library to simplify access to Excel, and I am trying to make sure that people using it won't leave a mess (fingers crossed).

Instead of writing directly on the interfaces Interop provides, I am making extension methods to make live easier. Like ApplicationHelpers.CreateExcel() or workbook.CreateWorksheet("mySheetNameThatWillBeValidated"). Naturally, anything that is created may lead to an issue later on cleaning up, so I am actually favoring killing the process as last resort. Yet, cleaning up properly (third option), is probably the least destructive and most controlled.

So, in that context I was wondering whether it wouldn't be best to make something like this:

public abstract class ReleaseContainer<T>
{
    private readonly Action<T> actionOnT;

    protected ReleaseContainer(T releasible, Action<T> actionOnT)
    {
        this.actionOnT = actionOnT;
        this.Releasible = releasible;
    }

    ~ReleaseContainer()
    {
        Release();
    }

    public T Releasible { get; private set; }

    private void Release()
    {
        actionOnT(Releasible);
        Releasible = default(T);
    }
}

I used 'Releasible' to avoid confusion with Disposable. Extending this to IDisposable should be easy though.

An implementation like this:

public class ApplicationContainer : ReleaseContainer<Application>
{
    public ApplicationContainer()
        : base(new Application(), ActionOnExcel)
    {
    }

    private static void ActionOnExcel(Application application)
    {
        application.Show(); // extension method. want to make sure the app is visible.
        application.Quit();
        Marshal.FinalReleaseComObject(application);
    }
}

And one could do something similar for all sorts of COM objects.

In the factory method:

    public static Application CreateExcelApplication(bool hidden = false)
    {
        var excel = new ApplicationContainer().Releasible;
        excel.Visible = !hidden;

        return excel;
    }

I would expect that every container will be destructed properly by the GC, and therefore automatically make the call to Quit and Marshal.FinalReleaseComObject.

Comments? Or is this an answer to the question of the third kind?

Problems with Android Fragment back stack

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

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

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

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

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

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

Install specific version using laravel installer

From Laravel 6, Now It's working with the following command:

composer create-project --prefer-dist laravel/laravel:^7.0 blog

Creating an array from a text file in Bash

Use mapfile or read -a

Always check your code using shellcheck. It will often give you the correct answer. In this case SC2207 covers reading a file that either has space separated or newline separated values into an array.

Don't do this

array=( $(mycommand) )

Files with values separated by newlines

mapfile -t array < <(mycommand)

Files with values separated by spaces

IFS=" " read -r -a array <<< "$(mycommand)"

The shellcheck page will give you the rationale why this is considered best practice.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

By using the value attribute:

var today = new Date();
document.getElementById('DATE').value += today;

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Can I use a :before or :after pseudo-element on an input field?

Pseudo elements like :after, :before are only for container elements. Elements starting and closing in a single place like <input/>, <img> etc are not container elements and hence pseudo elements are not supported. Once you apply a pseudo element to container element like <div> and if you inspect the code(see the image) you can understand what I mean. Actually the pseudo element is created inside the container element. This is not possible in case of <input> or <img>

enter image description here

How to apply !important using .css()?

It may or may not be appropriate for your situation but you can use CSS selectors for a lot of these type of situations.

If, for example you wanted of the 3rd and 6th instances of .cssText to have a different width you could write:

.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}

Or:

.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}

Number input type that takes only integers?

The easy way using JavaScript:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

Why is there no Char.Empty like String.Empty?

If you want to eliminate the empty char in string, the following will work. Just convert to any datatype representation you want.

private void button1_Click(object sender, EventArgs e)
{

    Int32 i;

    String name;

    Int32[] array_number = new int[100];

    name = "1 3  5  17   8    9    6";

    name = name.Replace(' ', 'x');

    char[] chr = name.ToCharArray();


    for (i = 0; i < name.Length; i++)
    {
        if ((chr[i] != 'x'))
        {
            array_number[i] = Convert.ToInt32(chr[i].ToString());
            MessageBox.Show(array_number[i].ToString());
        }
    }
}

Is it safe to store a JWT in localStorage with ReactJS?

Basically it's OK to store your JWT in your localStorage.

And I think this is a good way. If we are talking about XSS, XSS using CDN, it's also a potential risk of getting your client's login/pass as well. Storing data in local storage will prevent CSRF attacks at least.

You need to be aware of both and choose what you want. Both attacks it's not all you are need to be aware of, just remember: YOUR ENTIRE APP IS ONLY AS SECURE AS THE LEAST SECURE POINT OF YOUR APP.

Once again storing is OK, be vulnerable to XSS, CSRF,... isn't

@viewChild not working - cannot read property nativeElement of undefined

@ViewChild('keywords-input') keywordsInput; doesn't match id="keywords-input"

id="keywords-input"

should be instead a template variable:

#keywordsInput

Note that camel case should be used, since - is not allowed in template reference names.

@ViewChild() supports names of template variables as string:

@ViewChild('keywordsInput') keywordsInput;

or component or directive types:

@ViewChild(MyKeywordsInputComponent) keywordsInput;

See also https://stackoverflow.com/a/35209681/217408

Hint:
keywordsInput is not set before ngAfterViewInit() is called

Passing data between controllers in Angular JS?

1

using $localStorage

app.controller('ProductController', function($scope, $localStorage) {
    $scope.setSelectedProduct = function(selectedObj){
        $localStorage.selectedObj= selectedObj;
    };
});

app.controller('CartController', function($scope,$localStorage) { 
    $scope.selectedProducts = $localStorage.selectedObj;
    $localStorage.$reset();//to remove
});

2

On click you can call method that invokes broadcast:

$rootScope.$broadcast('SOME_TAG', 'your value');

and the second controller will listen on this tag like:
$scope.$on('SOME_TAG', function(response) {
      // ....
})

3

using $rootScope:

4

window.sessionStorage.setItem("Mydata",data);
$scope.data = $window.sessionStorage.getItem("Mydata");

5

One way using angular service:

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

app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});

app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});

app.factory('ser1', function(){
return {o: ''};
});

Is it possible to append to innerHTML without destroying descendants' event listeners?

I'm a lazy programmer. I don't use DOM because it seems like extra typing. To me, the less code the better. Here's how I would add "bar" without replacing "foo":

function start(){
var innermyspan = document.getElementById("myspan").innerHTML;
document.getElementById("myspan").innerHTML=innermyspan+"bar";
}

event.preventDefault() vs. return false

Generally, your first option (preventDefault()) is the one to take, but you have to know what context you're in and what your goals are.

Fuel Your Coding has a great article on return false; vs event.preventDefault() vs event.stopPropagation() vs event.stopImmediatePropagation().

Is PowerShell ready to replace my Cygwin shell on Windows?

Tools are just tools.
They help or they don't.
You need help or you don't.

If you know Unix and those tools do what you need them to do on Windows - then you are a happy guy and there is no need to learn PowerShell (unless you want to explore).

My original intent was to include a set of Unix tools in Windows and be done with it (a number of us on the team have deep Unix backgrounds and a healthy dose of respect for that community.)

What I found was that this didn't really help much. The reason for that is that AWK/grep/sed don't work against COM, WMI, ADSI, the Registry, the certificate store, etc., etc.

In other words, UNIX is an entire ecosystem self-tuned around text files. As such, text processing tools are effectively management tools. Windows is a completely different ecosystem self-tuned around APIs and Objects. That's why we invented PowerShell.

What I think you'll find is that there will be lots of occasions when text-processing won't get you what you want on Windows. At that point, you'll want to pick up PowerShell. NOTE - it is not an all or nothing deal. Within PowerShell, you can call out to your Unix tools (and use their text process or PowerShell's text processing). Also you can call PowerShell from your Unix tools and get text.

Again - there is no religion here - our focus is on giving you the tools you need to succeed. That is why we are so passionate about feedback. Let us know where we are falling down on the job or where you don't have a tool you need and we'll put it on the list and get to it.

In all honesty, we are digging ourselves out of a 30-year-hole, so it is going to take a while. That said, if you pick up the beta of Windows Server 2008 /R2 and/or the betas of our server products, I think you'll be shocked at how quickly that hole is getting filled.

With regard to usage - we've had > 3.5 million downloads to date. That does not include the people using it in Windows Server 2008, because it is included as an optional component and does not need a download.

V2 will ship in all versions of Windows. It will be on-by-default for all editions except Server core where it is an optional component. Shortly after Windows 7/Windows Server 2008 R2 ships, we'll make V2 available on all platforms, Windows XP and above. In other words - your investment in learning will be applicable to a very large number of machines/environments.

One last comment. If/when you start to learn PowerShell, I think you'll be pretty happy. Much of the design is heavily influenced by our Unix backgrounds, so while we are quite different, you'll pick it up very quickly (after you get over cussing that it isn't Unix :-) ).

We know that people have a very limited budget for learning - that is why we are super hard-core about consistency. You are going to learn something, and then you'll use it over and over and over again.

Experiment! Enjoy! Engage!

Two models in one view in ASP MVC 3

I hope you find it helpfull !!

i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag's value or data

_x000D_
_x000D_
List<tblproject> Plist = new List<tblproject>();_x000D_
            Plist = ps.getmanagerproject(c, id);_x000D_
_x000D_
            ViewBag.projectList = Plist.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.ProjectId.ToString(),_x000D_
                Text = x.Title_x000D_
            });
_x000D_
_x000D_
_x000D_

and in view tbltask and projectlist are my two diff models

@{

IEnumerable<SelectListItem> plist = ViewBag.projectList;

} @model List

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

MySQL (and subsequently SQLite) also support the REPLACE INTO syntax:

REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');

This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.

SQL Server - Convert date field to UTC

Here is a tested procedure that upgraded my database from local to utc time. The only input required to upgrade a database is to enter the number of minutes local time is offset from utc time into @Offset and if the timezone is subject to daylight savings adjustments by setting @ApplyDaylightSavings.

For example, US Central Time would enter @Offset=-360 and @ApplyDaylightSavings=1 for 6 hours and yes apply daylight savings adjustment.

Supporting Database Function


CREATE FUNCTION [dbo].[GetUtcDateTime](@LocalDateTime DATETIME, @Offset smallint, @ApplyDaylightSavings bit) 
RETURNS DATETIME AS BEGIN 

    --====================================================
    --Calculate the Offset Datetime
    --====================================================
    DECLARE @UtcDateTime AS DATETIME
    SET @UtcDateTime = DATEADD(MINUTE, @Offset * -1, @LocalDateTime)

    IF @ApplyDaylightSavings = 0 RETURN @UtcDateTime;

    --====================================================
    --Calculate the DST Offset for the UDT Datetime
    --====================================================
    DECLARE @Year as SMALLINT
    DECLARE @DSTStartDate AS DATETIME
    DECLARE @DSTEndDate AS DATETIME

    --Get Year
    SET @Year = YEAR(@LocalDateTime)

    --Get First Possible DST StartDay
    IF (@Year > 2006) SET @DSTStartDate = CAST(@Year AS CHAR(4)) + '-03-08 02:00:00'
    ELSE              SET @DSTStartDate = CAST(@Year AS CHAR(4)) + '-04-01 02:00:00'
    --Get DST StartDate 
    WHILE (DATENAME(dw, @DSTStartDate) <> 'sunday') SET @DSTStartDate = DATEADD(day, 1,@DSTStartDate)


    --Get First Possible DST EndDate
    IF (@Year > 2006) SET @DSTEndDate = CAST(@Year AS CHAR(4)) + '-11-01 02:00:00'
    ELSE              SET @DSTEndDate = CAST(@Year AS CHAR(4)) + '-10-25 02:00:00'

    --Get DST EndDate 
    WHILE (DATENAME(dw, @DSTEndDate) <> 'sunday') SET @DSTEndDate = DATEADD(day,1,@DSTEndDate)

    --Finally add the DST Offset if needed 
    RETURN CASE WHEN @LocalDateTime BETWEEN @DSTStartDate AND @DSTEndDate THEN 
        DATEADD(MINUTE, -60, @UtcDateTime) 
    ELSE 
        @UtcDateTime
    END

END
GO

Upgrade Script


  1. Make a backup before running this script!
  2. Set @Offset & @ApplyDaylightSavings
  3. Only run once!

begin try
    begin transaction;

    declare @sql nvarchar(max), @Offset smallint, @ApplyDaylightSavings bit;

    set @Offset = -360;             --US Central Time, -300 for US Eastern Time, -480 for US West Coast
    set @ApplyDaylightSavings = 1;  --1 for most US time zones except Arizona which doesn't observer daylight savings, 0 for most time zones outside the US

    declare rs cursor for
    select 'update [' + a.TABLE_SCHEMA + '].[' + a.TABLE_NAME + '] set [' + a.COLUMN_NAME + '] = dbo.GetUtcDateTime([' + a.COLUMN_NAME + '], ' + cast(@Offset as nvarchar) + ', ' + cast(@ApplyDaylightSavings as nvarchar) + ') ;'
    from INFORMATION_SCHEMA.COLUMNS a
        inner join INFORMATION_SCHEMA.TABLES b on a.TABLE_SCHEMA = b.TABLE_SCHEMA and a.TABLE_NAME = b.TABLE_NAME
    where a.DATA_TYPE = 'datetime' and b.TABLE_TYPE = 'BASE TABLE' ;

    open rs;
    fetch next from rs into @sql;
    while @@FETCH_STATUS = 0 begin
        exec sp_executesql @sql;
        print @sql;
        fetch next from rs into @sql;
    end
    close rs;
    deallocate rs;

    commit transaction;
end try
begin catch
    close rs;
    deallocate rs;

    declare @ErrorMessage nvarchar(max), @ErrorSeverity int, @ErrorState int;
    select @ErrorMessage = ERROR_MESSAGE() + ' Line ' + cast(ERROR_LINE() as nvarchar(5)), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE();
    rollback transaction;
    raiserror (@ErrorMessage, @ErrorSeverity, @ErrorState);
end catch

Safe width in pixels for printing web pages?

One solution to the problem that I found was to just set the width in inches. So far I've only tested/confirmed this working in Chrome. It worked well for what I was using it for (to print out an 8.5 x 11 sheet)

@media print {
    .printEl { 
        width: 8.5in;
        height: 11in;
    }
}

Why dict.get(key) instead of dict[key]?

What is the dict.get() method?

As already mentioned the get method contains an additional parameter which indicates the missing value. From the documentation

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

An example can be

>>> d = {1:2,2:3}
>>> d[1]
2
>>> d.get(1)
2
>>> d.get(3)
>>> repr(d.get(3))
'None'
>>> d.get(3,1)
1

Are there speed improvements anywhere?

As mentioned here,

It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words.

Earlier get was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only)

def getway(d):
    for i in range(100):
        s = d.get(i)

def lookup(d):
    for i in range(100):
        s = d[i]

Now timing these two functions using timeit

>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
20.2124660015
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))
16.16223979

As we can see the lookup is faster than the get as there is no function lookup. This can be seen through dis

>>> def lookup(d,val):
...     return d[val]
... 
>>> def getway(d,val):
...     return d.get(val)
... 
>>> dis.dis(getway)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_ATTR                0 (get)
              6 LOAD_FAST                1 (val)
              9 CALL_FUNCTION            1
             12 RETURN_VALUE        
>>> dis.dis(lookup)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_FAST                1 (val)
              6 BINARY_SUBSCR       
              7 RETURN_VALUE  

Where will it be useful?

It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. This reduces

 if key in dic:
      val = dic[key]
 else:
      val = def_val

To a single line, val = dic.get(key,def_val)

Where will it be NOT useful?

Whenever you want to return a KeyError stating that the particular key is not available. Returning a default value also carries the risk that a particular default value may be a key too!

Is it possible to have get like feature in dict['key']?

Yes! We need to implement the __missing__ in a dict subclass.

A sample program can be

class MyDict(dict):
    def __missing__(self, key):
        return None

A small demonstration can be

>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

If you need a body in your response, you can call

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

This will return a 500 with the response object...

Check whether there is an Internet connection available on Flutter app

Here Is My Solution It Checks Internet Connectivity as well as Data Connection I hope You Like it.

First of all add dependencies in your pubsec.yaml
dependencies:        
    data_connection_checker:
And Here Is The main.dart Of My Solution
import 'dart:async';

import 'package:data_connection_checker/data_connection_checker.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Data Connection Checker",
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  StreamSubscription<DataConnectionStatus> listener;

  var Internetstatus = "Unknown";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    _updateConnectionStatus();
      CheckInternet();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    listener.cancel();
    super.dispose();
  }

  CheckInternet() async {
    // Simple check to see if we have internet
    print("The statement 'this machine is connected to the Internet' is: ");
    print(await DataConnectionChecker().hasConnection);
    // returns a bool

    // We can also get an enum instead of a bool
    print("Current status: ${await DataConnectionChecker().connectionStatus}");
    // prints either DataConnectionStatus.connected
    // or DataConnectionStatus.disconnected

    // This returns the last results from the last call
    // to either hasConnection or connectionStatus
    print("Last results: ${DataConnectionChecker().lastTryResults}");

    // actively listen for status updates
    listener = DataConnectionChecker().onStatusChange.listen((status) {
      switch (status) {
        case DataConnectionStatus.connected:
          Internetstatus="Connectd TO THe Internet";
          print('Data connection is available.');
          setState(() {

          });
          break;
        case DataConnectionStatus.disconnected:
          Internetstatus="No Data Connection";
          print('You are disconnected from the internet.');
          setState(() {

          });
          break;
      }
    });

    // close listener after 30 seconds, so the program doesn't run forever
//    await Future.delayed(Duration(seconds: 30));
//    await listener.cancel();
    return await await DataConnectionChecker().connectionStatus;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Data Connection Checker"),
      ),
      body: Container(
        child: Center(
          child: Text("$Internetstatus"),
        ),
      ),
    );
  }
}

Eclipse gives “Java was started but returned exit code 13”

I could resolve this issue by changing JDK1.8 64bit version to JDK 1.8 32bit(x86) version

Enabling HTTPS on express.js

This is how its working for me. The redirection used will redirect all the normal http as well.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('certificates/private.key'),
  cert: fs.readFileSync('certificates/certificate.crt'),
  ca: fs.readFileSync('certificates/ca_bundle.crt')
};

// API file for interacting with MongoDB
const api = require('./server/routes/api');

// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
  if (req.headers['x-forwarded-proto'] == 'http') {
      return resp.redirect(301, 'https://' + req.headers.host + '/');
  } else {
      return next();
  }
});


http.createServer(app).listen(80)
https.createServer(options, app).listen(443);

How to restore to a different database in sql server?

Here is how to restore a backup as an additional db with a unique db name.

For SQL 2005 this works very quickly. I am sure newer versions will work the same.

First, you don't have to take your original db offline. But for safety sake, I like to. In my example, I am going to mount a clone of my "billing" database and it will be named "billingclone".

1) Make a good backup of the billing database

2) For safety, I took the original offline as follows:

3) Open a new Query window

**IMPORTANT! Keep this query window open until you are all done! You need to restore the db from this window!

Now enter the following code:

-- 1) free up all USER databases
USE master;
GO
-- 2) kick all other users out:
ALTER DATABASE billing SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
-- 3) prevent sessions from re-establishing connection:
ALTER DATABASE billing SET OFFLINE;

3) Next, in Management Studio, rt click Databases in Object Explorer, choose "Restore Database"

4) enter new name in "To Database" field. I.E. billingclone

5) In Source for Restore, click "From Device" and click the ... navigate button

6) Click Add and navigate to your backup

7) Put a checkmark next to Restore (Select the backup sets to restore)

8) next select the OPTIONS page in upper LH corner

9) Now edit the database file names in RESTORE AS. Do this for both the db and the log. I.E. billingclone.mdf and billingclone_log.ldf

10) now hit OK and wait for the task to complete.

11) Hit refresh in your Object Explorer and you will see your new db

12) Now you can put your billing db back online. Use the same query window you used to take billing offline. Use this command:

-- 1) free up all USER databases
USE master; GO
-- 2) restore access to all users:
ALTER DATABASE billing SET MULTI_USER WITH ROLLBACK IMMEDIATE;GO
-- 3) put the db back online:
ALTER DATABASE billing SET ONLINE;

done!

How to display a loading screen while site content loads

First, set up a loading image in a div. Next, get the div element. Then, set a function that edits the css to make the visibility to "hidden". Now, in the <body>, put the onload to the function name.

SQL 'LIKE' query using '%' where the search criteria contains '%'

You need to escape it: on many databases this is done by preceding it with backslash, \%.

So abc becomes abc\%.

Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.

How can I find out if an .EXE has Command-Line Options?

Really this is an extension to Marcin's answer.

But you could also try passing "rubbish" arguments to see if you get any errors back. Getting any response from the executable directly in the shell will mean that it is likely looking at the arguments you're passing, with an error response being close to a guarantee that it is.

Failing that you might have to directly ask the publishers/creators/owners... sniffing the binaries yourself just seems like far too much work for an end-user.

Parsing domain from a URL

parse_url didn't work for me. It only returned the path. Switching to basics using php5.3+:

$url  = str_replace('http://', '', strtolower( $s->website));
if (strpos($url, '/'))  $url = strstr($url, '/', true);

Changing route doesn't scroll to top in the new page

I found this solution. If you go to a new view the function gets executed.

var app = angular.module('hoofdModule', ['ngRoute']);

    app.controller('indexController', function ($scope, $window) {
        $scope.$on('$viewContentLoaded', function () {
            $window.scrollTo(0, 0);
        });
    });

Remove a folder from git tracking

This works for me:

git rm -r --cached --ignore-unmatch folder_name

--ignore-unmatch is important here, without that option git will exit with error on the first file not in the index.

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

Bootstrap modal - close modal when "call to action" button is clicked

You need to bind the modal hide call to the onclick event.

Assuming you are using jQuery you can do that with:

$('#closemodal').click(function() {
    $('#modalwindow').modal('hide');
});

Also make sure the click event is bound after the document has finished loading:

$(function() {
   // Place the above code inside this block
});
enter code here

Twitter Bootstrap 3 Sticky Footer

The push div should go right after the wrap, NOT within.. just like this

<div id="wrap">
  *content goes here*
</div>

<div id="push">
</div>

<div id="footer">
  <div class="container credit">
  </div>
  <div class="container">
    <p class="muted credit">© Your Page 2013</p>
  </div>
</div>

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

i work on a multi platform project, so i can't use _s function and i don't want pollute my code with visual studio specific code.
my solution is disable the warning 4996 on the visual studio project. go to Project -> Properties -> Configuration properties -> C/C++ -> Advanced -> Disable specific warning add the value 4996.
if you use also the mfc and/or atl library (not my case) define before include mfc _AFX_SECURE_NO_DEPRECATE and before include atl _ATL_SECURE_NO_DEPRECATE.
i use this solution across visual studio 2003 and 2005.

p.s. if you use only visual studio the secure template overloads could be a good solution.

Automatic vertical scroll bar in WPF TextBlock?

<ScrollViewer Height="239" VerticalScrollBarVisibility="Auto">
    <TextBox AcceptsReturn="True" TextWrapping="Wrap" LineHeight="10" />
</ScrollViewer>

This is way to use the scrolling TextBox in XAML and use it as a text area.

Do I need <class> elements in persistence.xml?

Do I need Class elements in persistence.xml?

No, you don't necessarily. Here is how you do it in Eclipse (Kepler tested):

Right click on the project, click Properties, select JPA, in the Persistence class management tick Discover annotated classes automatically.

enter image description here

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Right Click on Project, Properties ---> Java Compiler ( on same page change compiler Compliance Level to 1.6 (or) 1.7 (or) 1.8 ( match with your JAVA_HOME)

Send form data using ajax

I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
Following part of the function might be of interest:

  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }

It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.

Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:

function ajax_create_request_string(data, recursion) {
  var data_string = '';
  //Zpracovani formulare
  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        if(elem[i].className.indexOf("autoempty")!=-1) {
          data_string += elem[i].name+"=";
        }
        else
          data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }
  //Loop through array
  if(data instanceof Array) {
    for(var i=0; i<data.length; i++) {
      if(data_string!="")
        data_string+="&";
      data_string+=recursion+"["+i+"]="+data[i];
    }
    return data_string;
  }
  //Loop through object (like foreach)
  for(var i in data) {
    if(data_string!="")
      data_string+="&";
    if(typeof data[i]=="object") {
      if(recursion==null)
        data_string+= ajax_create_request_string(data[i], i);
      else
        data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
    }
    else if(recursion==null)
      data_string+=i+"="+data[i];
    else 
      data_string+=recursion+"["+i+"]="+data[i];
  }
  return data_string;
}

Forward declaring an enum in C++

I'd do it this way:

[in the public header]

typedef unsigned long E;

void Foo(E e);

[in the internal header]

enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,
  FORCE_32BIT = 0xFFFFFFFF };

By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.

Failed to connect to camera service

I came up with the same problem and I'm sharing how I fixed it. It may help some people.

First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :

  1. Declare a permission in the app manifest. Make sure to insert the permission above the application tag.

**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**

<application ...>
    ...
</application>

  1. Then, request that the user approve each permission at runtime

      if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {
    // here, Permission is not granted
    ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
    }
    

For more information, have a look at the API documentation here

How do I change the data type for a column in MySQL?

If you want to alter the column details add a comment, use this

ALTER TABLE [table_name] MODIFY [column_name] [new data type] DEFAULT [VALUE] COMMENT '[column comment]' 

How to make Java work with SQL Server?

Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).

I used 1.5 for the other server, so I waisted a lot of time on this.

Tricky issue.

How to get GET (query string) variables in Express.js on Node.js?

app.get('/user/:id', function(req, res) {
    res.send('user' + req.params.id);    
});

You can use this or you can try body-parser for parsing special element from the request parameters.

Count unique values using pandas groupby

I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:

df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)

How to remove word wrap from textarea?

The following CSS based solution works for me:

<html>
 <head>
  <style type='text/css'>
   textarea {
    white-space: nowrap;
    overflow:    scroll;
    overflow-y:  hidden;
    overflow-x:  scroll;
    overflow:    -moz-scrollbars-horizontal;
   }
  </style>
 </head>
 <body>
  <form>
   <textarea>This is a long line of text for testing purposes...</textarea>
  </form>
 </body>
</html>

How to concatenate strings in django templates?

And multiple concatenation:

from django import template
register = template.Library()


@register.simple_tag
def concat_all(*args):
    """concatenate all args"""
    return ''.join(map(str, args))

And in Template:

{% concat_all 'x' 'y' another_var as string_result %}
concatenated string: {{ string_result }}

How to use (install) dblink in PostgreSQL?

# or even faster copy paste answer if you have sudo on the host 
sudo su - postgres  -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"

Entity Framework - Code First - Can't Store List<String>

JSON.NET to the rescue.

You serialize it to JSON to persist in the Database and Deserialize it to reconstitute the .NET collection. This seems to perform better than I expected it to with Entity Framework 6 & SQLite. I know you asked for List<string> but here's an example of an even more complex collection that works just fine.

I tagged the persisted property with [Obsolete] so it would be very obvious to me that "this is not the property you are looking for" in the normal course of coding. The "real" property is tagged with [NotMapped] so Entity framework ignores it.

(unrelated tangent): You could do the same with more complex types but you need to ask yourself did you just make querying that object's properties too hard for yourself? (yes, in my case).

using Newtonsoft.Json;
....
[NotMapped]
public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>();

/// <summary> <see cref="MetaData"/> for database persistence. </summary>
[Obsolete("Only for Persistence by EntityFramework")]
public string MetaDataJsonForDb
{
    get
    {
        return MetaData == null || !MetaData.Any()
                   ? null
                   : JsonConvert.SerializeObject(MetaData);
    }

    set
    {
        if (string.IsNullOrWhiteSpace(value))
           MetaData.Clear();
        else
           MetaData = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
    }
}

ReactJS: "Uncaught SyntaxError: Unexpected token <"

I have the same issue with you and I have change something in my server

you might try this

const root = require("path").join(__dirname, "./build");
app.use(express.static(root));
app.get("*", (req, res) => {
  res.sendFile("index.html", { root });
});

How can I express that two values are not equal to eachother?

Just put a '!' in front of the boolean expression

Changing file permission in Python

No need to remember flags. Remember that you can always do:

subprocess.call(["chmod", "a-w", "file/path])

Not portable but easy to write and remember:

  • u - user
  • g - group
  • o - other
  • a - all
  • + or - (add or remove permission)
  • r - read
  • w - write
  • x - execute

Refer man chmod for additional options and more detailed explanation.

fill an array in C#

public static void Fill<T>(this IList<T> col, T value, int fromIndex, int toIndex)
{
    if (fromIndex > toIndex)
        throw new ArgumentOutOfRangeException("fromIndex");

    for (var i = fromIndex; i <= toIndex; i++)
        col[i] = value;
}

Something that works for all IList<T>s.