Programs & Examples On #Visual web developer

Visual Web Developer Express is a freeware web development tool, with the role of former ASP.NET Web Matrix, that allows developers to evaluate the web development and editing capabilities of the other Visual Studio 2005/2008/2010 editions at no charge.

How do I start/stop IIS Express Server?

Closing IIS Express

By default Visual Studio places the IISExpress icon in your system tray at the lower right hand side of your screen, by the clock. You can right click it and choose exit. If you don't see the icon, try clicking the small arrow to view the full list of icons in the system tray.

IIS Express icon

then right click and choose Exit:

enter image description here


Changing the Port

Another option is to change the port by modifying the project properties. You'll need to do this for each web project in your solution.

  1. Visual Studio > Solution Explorer
  2. Right click the web project and choose Properties
  3. Go to the Web tab
  4. In the 'Servers' section, change the port in the Project URL box
  5. Repeat for each web project in the solution

Changing the IIS Express port


If All Else Fails

If that doesn't work, you can try to bring up Task Manager and close the IIS Express System Tray (32 bit) process and IIS Express Worker Process (32 bit).

Terminating the IIS Express Worker Thread process

If it still doesn't work, as ni5ni6 pointed out, there is a 'Web Deployment Agent Service' running on the port 80. Use this article to track down which process uses it, and turn it off:

https://sites.google.com/site/anashkb/port-80-in-use

Connecting to SQL Server with Visual Studio Express Editions

Workaround:

  1. Open your solution in Visual Web Developer Express. It will not load some of the projects in the solution but it is ok.
  2. Make a new connection in Database Explorer to the required database from SQL Server.
  3. Add a new class library project.
  4. Add a LINQ to SQL Classes item and link it to your database.
  5. Close the solution.
  6. Open the solution in Visual C# Express.

Now you have a LINQ to SQL classes library that is linked to your SQL Server database in Visual C# Express.

Update

The solution is for Visual Studio Express 2010.

Creating a custom JButton in Java

You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:

try {
    SynthLookAndFeel synth = new SynthLookAndFeel();
    Class aClass = MainFrame.class;
    InputStream stream = aClass.getResourceAsStream("\\default.xml");

    if (stream == null) {
        System.err.println("Missing configuration file");
        System.exit(-1);                
    }

    synth.load(stream, aClass);

    UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
    System.err.println("Bad configuration file");
    pe.printStackTrace();
    System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
    System.err.println("Old JRE in use. Get a new one");
    System.exit(-3);
}

From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.

The xml file might look like this:

<synth>
    <style id="button">
        <font name="DIALOG" size="12" style="BOLD"/>
        <state value="MOUSE_OVER">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
        <state value="ENABLED">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
    </style>
    <bind style="button" type="name" key="dirt"/>
</synth>

The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").

And a couple of useful links:

http://javadesktop.org/articles/synth/

http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html

Should I call Close() or Dispose() for stream objects?

On many classes which support both Close() and Dispose() methods, the two calls would be equivalent. On some classes, however, it is possible to re-open an object which has been closed. Some such classes may keep some resources alive after a Close, in order to permit reopening; others may not keep any resources alive on Close(), but might set a flag on Dispose() to explicitly forbid re-opening.

The contract for IDisposable.Dispose explicitly requires that calling it on an object which will never be used again will be at worst harmless, so I would recommend calling either IDisposable.Dispose or a method called Dispose() on every IDisposable object, whether or not one also calls Close().

Difference between string object and string literal

According to String class documentation they are equivalent.

Documentation for String(String original) also says that: Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

Look for other responses, because it seems that Java documentation is misleading :(

SQL grouping by all the columns

You can use Group by All but be careful as Group by All will be removed from future versions of SQL server.

CSS /JS to prevent dragging of ghost image?

You can assign an alternate ghost image if you really need to use drag events and can't set draggable=false. So just assign a blank png like so:

    $('#img').bind({
        dragstart: function(e) {
            var dragIcon = document.createElement('img');
            dragIcon.src = 'blank.png';
            dragIcon.width = 100;
            e.dataTransfer.setDragImage(dragIcon, -10, -10);
        }
    });

Change the spacing of tick marks on the axis of a plot?

With base graphics, the easiest way is to stop the plotting functions from drawing axes and then draw them yourself.

plot(1:10, 1:10, axes = FALSE)
axis(side = 1, at = c(1,5,10))
axis(side = 2, at = c(1,3,7,10))
box()

What's the common practice for enums in Python?

class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3

How to vertically center <div> inside the parent element with CSS?

You can vertically align a div in another div. See this example on JSFiddle or consider the example below.

HTML

<div class="outerDiv">
    <div class="innerDiv"> My Vertical Div </div>
</div>

CSS

.outerDiv {
    display: inline-flex;  // <-- This is responsible for vertical alignment
    height: 400px;
    background-color: red;
    color: white;
}

.innerDiv {
    margin: auto 5px;   // <-- This is responsible for vertical alignment
    background-color: green;   
}

The .innerDiv's margin must be in this format: margin: auto *px;

[Where, * is your desired value.]

display: inline-flex is supported in the latest (updated/current version) browsers with HTML5 support.

It may not work in Internet Explorer :P :)

Always try to define a height for any vertically aligned div (i.e. innerDiv) to counter compatibility issues.

How to set the environmental variable LD_LIBRARY_PATH in linux

Alternatively you can execute program with specified library dir:

/lib/ld-linux.so.2 --library-path PATH EXECUTABLE

Read more here.

What is the best way to generate a unique and short file name in Java

Well, you could use the 3-argument version: File.createTempFile(String prefix, String suffix, File directory) which will let you put it where you'd like. Unless you tell it to, Java won't treat it differently than any other file. The only drawback is that the filename is guaranteed to be at least 8 characters long (minimum of 3 characters for the prefix, plus 5 or more characters generated by the function).

If that's too long for you, I suppose you could always just start with the filename "a", and loop through "b", "c", etc until you find one that doesn't already exist.

How to read large text file on windows?

While Large Text File Viewer works great for just looking at a large file (and is free!), if the file is either a delimited or fixed-width file, then you should check out File Query. Not only can it open a file of any size (I have personally opened a 280GB file, but it can go larger), but it lets you query the file as though it was in a database as well, finding out any sort of information you could want from it.

It is not free though, so it is more for people that work with large files a lot, but if you have a one-off problem, you can just use the 30-day trial for free.

Java error: Implicit super constructor is undefined for default constructor

Another way is call super() with the required argument as a first statement in derived class constructor.

public class Sup {
    public Sup(String s) { ...}
}

public class Sub extends Sup {
    public Sub() { super("hello"); .. }
}

jquery .on() method with load event

As the other have mentioned, the load event does not bubble. Instead you can manually trigger a load-like event with a custom event:

$('#item').on('namespace/onload', handleOnload).trigger('namespace/onload')

If your element is already listening to a change event:

$('#item').on('change', handleChange).trigger('change')

I find this works well. Though, I stick to custom events to be more explicit and avoid side effects.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

I ran into this error after my client PC crashed, the jest --watch command I was running on the server persisted, and I tried to run jest --watch again.

The addition to /etc/sysctl.conf described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node and kill it.

How to read a single char from the console in Java (as the user types it)?

What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.

Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:

If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.

One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.

How to check if a value exists in an array in Ruby

If you're trying to do this in a MiniTest unit test, you can use assert_includes. Example:

pets = ['Cat', 'Dog', 'Bird']
assert_includes(pets, 'Dog')      # -> passes
assert_includes(pets, 'Zebra')    # -> fails 

How does the @property decorator work in Python?

A property can be declared in two ways.

  • Creating the getter, setter methods for an attribute and then passing these as argument to property function
  • Using the @property decorator.

You can have a look at few examples I have written about properties in python.

Ping a site in Python?

read a file name, the file contain the one url per line, like this:

http://www.poolsaboveground.com/apache/hadoop/core/
http://mirrors.sonic.net/apache/hadoop/core/

use command:

python url.py urls.txt

get the result:

Round Trip Time: 253 ms - mirrors.sonic.net
Round Trip Time: 245 ms - www.globalish.com
Round Trip Time: 327 ms - www.poolsaboveground.com

source code(url.py):

import re
import sys
import urlparse
from subprocess import Popen, PIPE
from threading import Thread


class Pinger(object):
    def __init__(self, hosts):
        for host in hosts:
            hostname = urlparse.urlparse(host).hostname
            if hostname:
                pa = PingAgent(hostname)
                pa.start()
            else:
                continue

class PingAgent(Thread):
    def __init__(self, host):
        Thread.__init__(self)        
        self.host = host

    def run(self):
        p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
        m = re.search('Average = (.*)ms', p.stdout.read())
        if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
        else: print 'Error: Invalid Response -', self.host


if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        content = f.readlines() 
    Pinger(content)

How to set up ES cluster?

its super easy.

You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.

The only thing you really need to do is edit the config file to include the name of the cluster.

If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)

Read here to get you started: https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html

When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)

How to remove lines in a Matplotlib plot

This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around.

WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.

Okay, here we go. Each matplotlib object (Figure, Axes, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating.

We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id()).

>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]

>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)

>>> #The object in ax is the same as the object in fig.axes[0], which is 
>>> #   a list of axes objects attached to fig 
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8)  #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects

This also extends to lines in an axes object:

>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))

>>> #Lines and ax.lines contain the same line2D instances 
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]

>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)

>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)

If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line:

A figure containing a set of axes and a single line

Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:

>>> id(lines), id(ax.lines)
(212754584, 211335288)

As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:

>>> #THIS DOES NOTHING:
>>> lines.pop(0)

>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)

So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:

>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and two lines

>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and only the second line

All of the above works for fig.axes just as well as it works for ax.lines

Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn't get garbage collected:

>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]

>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn't have the same ID as ax.lines but contained the same elements? Well, that's the problem.

>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.

>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>

So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.

What is the difference between Integer and int in Java?

int is a primitive type that represent an integer. whereas Integer is an Object that wraps int. The Integer object gives you more functionality, such as converting to hex, string, etc.

You can also use OOP concepts with Integer. For example, you can use Integer for generics (i.e. Collection<Integer>).

INSERT INTO from two different server database

The answer given by Simon works fine for me but you have to do it in the right sequence: First you have to be in the server that you want to insert data into which is [DATABASE.WINDOWS.NET].[basecampdev] in your case.

You can try to see if you can select some data out of the Invoice table to make sure you have access.

Select top 10 * from [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]

Secondly, execute the query given by Simon in order to link to a different server. This time use the other server:

EXEC sp_addlinkedserver [BC1-PC]; -- this will create a link tempdb that you can access from where you are
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR 
    [BC1-PC].testdabse.dbo.invoice; -- Make a copy of the table and data that you can use
GO

Now just do your insert statement.

INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
       ([InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks])
SELECT [InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks] FROM MyInvoice

Hope this helps!

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

I usualy use a multi-culture function to parse user input, mostly because if someone is used to the numpad and is using a culture that use a comma as the decimal separator, that person will use the point of the numpad instead of a comma.

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

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

    return result;
}

Beware though, @nikie comments are true. To my defense, I use this function in a controlled environment where I know that the culture can either be en-US, en-CA or fr-CA. I use this function because in French, we use the comma as a decimal separator, but anybody who ever worked in finance will always use the decimal separator on the numpad, but this is a point, not a comma. So even in the fr-CA culture, I need to parse number that will have a point as the decimal separator.

Format numbers in JavaScript similar to C#

Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.

Method 0 (RegExp)

Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
        return a.join('.');
    }
}

Method 1

if (typeof Number.prototype.format1 === 'undefined') {
    Number.prototype.format1 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // skip the '-' sign
            head = Number(this < 0);

        // skip the digits that's before the first thousands separator 
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
        return a.join('.');
    };
}

Method 2 (Split to Array)

if (typeof Number.prototype.format2 === 'undefined') {
    Number.prototype.format2 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '$&,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

Method 3 (Loop)

if (typeof Number.prototype.format3 === 'undefined') {
    Number.prototype.format3 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

Example

console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

Separator

If we want custom thousands separator or decimal separator, use replace():

123456.78.format(2).replace(',', ' ').replace('.', ' ');

Test suite

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))
    // decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))
    // decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))
    // thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
    // thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

Benchmark

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

How to connect HTML Divs with Lines?

It's kind of a pain to position, but you could use 1px wide divs as lines and position and rotate them appropriately.

http://jsfiddle.net/sbaBG/1

<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>

<div class="line" id="line1"></div>
<div class="line" id="line2"></div>
.box {
    border: 1px solid black;
    background-color: #ccc;
    width: 100px;
    height: 100px;
    position: absolute;
}
.line {
    width: 1px;
    height: 100px;
    background-color: black;
    position: absolute;
}
#box1 {
    top: 0;
    left: 0;
}
#box2 {
    top: 200px;
    left: 0;
}
#box3 {
    top: 250px;
    left: 200px;
}
#line1 {
    top: 100px;
    left: 50px;
}
#line2 {
    top: 220px;
    left: 150px;
    height: 115px;

    transform: rotate(120deg);
    -webkit-transform: rotate(120deg);
    -ms-transform: rotate(120deg);
}

Font Awesome icon inside text input element

Easy way ,but you need bootstrap

 <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text"><i class="fa fa-envelope"></i></span> <!-- icon envelope "class="fa fa-envelope""-->
    </div>
    <input type="email" id="senha_nova" placeholder="Email">
  </div><!-- input-group -->

enter image description here

Execute a terminal command from a Cocoa app

Or since Objective C is just C with some OO layer on top you can use the posix conterparts:

int execl(const char *path, const char *arg0, ..., const char *argn, (char *)0);
int execle(const char *path, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execlp(const char *file, const char *arg0, ..., const char *argn, (char *)0);
int execlpe(const char *file, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execv(const char *path, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]); 

They are included from unistd.h header file.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

Your problem is that you have declare twice the exec-maven-plugin :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-  
      integration\src\main\java\example\Main< /mainClass>
    </configuration>
</plugin>

...

< plugin>
    < groupId>org.codehaus.mojo</groupId>
    < artifactId>exec-maven-plugin</artifactId>
    < version>1.2</version>
< /plugin>

How To: Best way to draw table in console app (C#)

I have a project on GitHub that you can use

https://github.com/BrunoVT1992/ConsoleTable

You can use it like this:

var table = new Table();

table.SetHeaders("Name", "Date", "Number");

for (int i = 0; i <= 10; i++)
{
    if (i % 2 == 0)
        table.AddRow($"name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), i.ToString());
    else
        table.AddRow($"long name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), (i * 5000).ToString());
}

Console.WriteLine(table.ToString());

It will give this result:

enter image description here

PHP multiline string with PHP

To do that, you must remove all ' charachters in your string or use an escape character. Like:

<?php
    echo '<?php
              echo \'hello world\';
          ?>';
?>

Excel - extracting data based on another list

I couldn't get the first method to work, and I know this is an old topic, but this is what I ended up doing for a solution:

=IF(ISNA(MATCH(A1,B:B,0)),"Not Matched", A1)

Basically, MATCH A1 to Column B exactly (the 0 stands for match exactly to a value in Column B). ISNA tests for #N/A response which match will return if the no match is found. Finally, if ISNA is true, write "Not Matched" to the selected cell, otherwise write the contents of the matched cell.

How can I suppress the newline after a print statement?

print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:

print "Foo %10s bar" % baz,

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

How to send a PUT/DELETE request in jQuery?

$.ajax will work.

$.ajax({
   url: 'script.php',
   type: 'PUT',
   success: function(response) {
     //...
   }
});

SQL: Group by minimum value in one field while selecting distinct rows

How about something like:

SELECT mt.*     
FROM MyTable mt INNER JOIN
    (
        SELECT id, MIN(record_date) AS MinDate
        FROM MyTable
        GROUP BY id
    ) t ON mt.id = t.id AND mt.record_date = t.MinDate

This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.

Returning value that was passed into a method

You can use a lambda with an input parameter, like so:

.Returns((string myval) => { return myval; });

Or slightly more readable:

.Returns<string>(x => x);

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

ImportError: No module named requests

If you are using Ubuntu, there is need to install requests

run this command:

pip install requests

if you face permission denied error, use sudo before command:

sudo pip install requests

jQuery - how to write 'if not equal to' (opposite of ==)

!=

For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

Questions every good PHP Developer should be able to answer

  • When calling the "name" element of $array, which is correct?:

    • $array[name]
    • $array['name']

    Both will often work, but only the quoted form is correct. define('name', 0); and watch the bugs fly. I've seen this way too much.

  • How can you force form elements be submitted as an array?

    Append empty brackets to the name attribute: multiple <input type="checkbox" name="checkboxes[]" /> elements will be converted to an array on the server (e.g. $_POST['checkboxes'][0..n]). I don't think it's 100% PHP-specific, but it sure beats looping through $_POST for every possible 'checkboxes'.$i element.

  • mysql_, mysqli_, or PDO?

    Only one truly wrong answer here: the mysql_ library doesn't do prepared statements and can no longer excuse it's capacity for evil. Naming a function, one expected to be called multiple times per executed query, "mysql_real_escape_string()", is just salt in the wound.

MySQL Delete all rows from table and reset ID to zero

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a database with approximately 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

How to take complete backup of mysql database using mysqldump command line utility

On MySQL 5.7 its work for me, I'm using CentOS7.

For taking Dump.

Command :

mysqldump -u user_name -p database_name -R -E > file_name.sql

Exemple :

mysqldump -u root -p mr_sbc_clean -R -E > mr_sbc_clean_dump.sql

For deploying Dump.

Command :

mysql -u user_name -p database_name < file_name.sql

Exemple :

mysql -u root -p mr_sbc_clean_new < mr_sbc_clean_dump.sql

RegEx for valid international mobile phone number

Even though it is about international numbers I would want the code to be like :

/^(\+|\d)[0-9]{7,16}$/;

As you can have international numbers starting with '00' as well.

Why I prefer 15 digits : http://en.wikipedia.org/wiki/E.164

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

Java unsupported major minor version 52.0

You have to compile with Java 1.7. But if you have *.jsp files, you should also completely remove Java 1.8 from the system. If you use Mac, here is how you can do it.

How to include a PHP variable inside a MySQL statement

The rules of adding a PHP variable inside of any MySQL statement are plain and simple:

  1. Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) MUST be added through a prepared statement. No exceptions.
  2. Any other query part, such as an SQL keyword, a table or a field name, or an operator - must be filtered through a white list.

So as your example only involves data literals, then all variables must be added through placeholders (also called parameters). To do so:

  • In your SQL statement, replace all variables with placeholders
  • prepare the resulting query
  • bind variables to placeholders
  • execute the query

And here is how to do it with all popular PHP database drivers:

Adding data literals using mysql ext

Such a driver doesn't exist.

Adding data literals using mysqli

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $type, $reporter);
$stmt->execute();

The code is a bit complicated but the detailed explanation of all these operators can be found in my article, How to run an INSERT query using Mysqli, as well as a solution that eases the process dramatically.

For a SELECT query you will need to add just a call to get_result() method to get a familiar mysqli_result from which you can fetch the data the usual way:

$reporter = "John O'Hara";
$stmt = $mysqli->prepare("SELECT * FROM users WHERE name=?");
$stmt->bind_param("s", $reporter);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc(); // or while (...)

Adding data literals using PDO

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $pdo->prepare($query);
$stmt->execute([$type, $reporter]);

In PDO, we can have the bind and execute parts combined, which is very convenient. PDO also supports named placeholders which some find extremely convenient.

Adding keywords or identifiers

Sometimes we have to add a variable that represents another part of a query, such as a keyword or an identifier (a database, table or a field name). It's a rare case but it's better to be prepared.

In this case, your variable must be checked against a list of values explicitly written in your script. This is explained in my other article, Adding a field name in the ORDER BY clause based on the user's choice:

Unfortunately, PDO has no placeholder for identifiers (table and field names), therefore a developer must filter them out manually. Such a filter is often called a "white list" (where we only list allowed values) as opposed to a "black-list" where we list disallowed values.

So we have to explicitly list all possible variants in the PHP code and then choose from them.

Here is an example:

$orderby = $_GET['orderby'] ?: "name"; // set the default value
$allowed = ["name","price","qty"]; // the white list of allowed field names
$key = array_search($orderby, $allowed, true); // see if we have such a name
if ($key === false) { 
    throw new InvalidArgumentException("Invalid field name"); 
}

Exactly the same approach should be used for the direction,

$direction = $_GET['direction'] ?: "ASC";
$allowed = ["ASC","DESC"];
$key = array_search($direction, $allowed, true);
if ($key === false) { 
    throw new InvalidArgumentException("Invalid ORDER BY direction"); 
}

After such a code, both $direction and $orderby variables can be safely put in the SQL query, as they are either equal to one of the allowed variants or there will be an error thrown.

The last thing to mention about identifiers, they must be also formatted according to the particular database syntax. For MySQL it should be backtick characters around the identifier. So the final query string for our order by example would be

$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction";

Line Break in HTML Select Option?

Instead, maybe try replacing the select with markup, e.g.

_x000D_
_x000D_
// Wrap any selects that should be replaced_x000D_
$('select.replace').wrap('<div class="select-replacement-wrapper"></div>');_x000D_
_x000D_
// Replace placeholder text with select's initial value_x000D_
$('.select-replacement-wrapper').each(function() {_x000D_
 $(this).prepend('<a>' + $('select option:selected', this).text() + '</a>');_x000D_
});_x000D_
_x000D_
// Update placeholder text with updated select value_x000D_
$('select.replace').change(function(event) {_x000D_
  $(this).siblings('a').text( $('option:selected', this).text() );_x000D_
});
_x000D_
/* Position relative, so that we can overlay the hidden select */_x000D_
.select-replacement-wrapper {_x000D_
  position: relative;_x000D_
  border: 3px solid red; /* to show area */_x000D_
  width: 33%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
/* Only shows if JS is enabled */_x000D_
.select-replacement-wrapper a {_x000D_
  /* display: none; */_x000D_
  /* Notice that we've centered this text - _x000D_
   you can do whatever you want, mulitple lines wrap, etc, _x000D_
   since this is not a select element' */_x000D_
  text-align: center;_x000D_
  display: block;_x000D_
  border: 1px solid blue;_x000D_
}_x000D_
_x000D_
select.replace {_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  top: 0;_x000D_
  border: 1px solid green;_x000D_
  opacity: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<select id="dropdown" class="replace">_x000D_
  <option value="First">First</option>_x000D_
  <option value="Second" selected>Second, and this is a long line, just to show wrapping</option>_x000D_
  <option value="Third">Third</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Spring Boot - Handle to Hibernate SessionFactory

Another way similar to the yglodt's

In application.properties:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

And in your configuration class:

@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
    return hemf.getSessionFactory();
}

Then you can autowire the SessionFactory in your services as usual:

@Autowired
private SessionFactory sessionFactory;

Firebase TIMESTAMP to date and Time

I know the firebase give the timestamp in {seconds: '', and nanoseconds: ''} for converting into date u have to only do:

  • take a firebase time in one var ex:- const date

and then date.toDate() => It returns the date.

Task vs Thread differences

The Thread class is used for creating and manipulating a thread in Windows.

A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

In the days of old (i.e. before TPL) it used to be that using the Thread class was one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool), however this was cumbersome and had several disadvantages, not least of which was the performance overhead of creating a whole new thread to perform a task in the background.

Nowadays using tasks and the TPL is a far better solution 90% of the time as it provides abstractions which allows far more efficient use of system resources. I imagine there are a few scenarios where you want explicit control over the thread on which you are running your code, however generally speaking if you want to run something asynchronously your first port of call should be the TPL.

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

How to convert latitude or longitude to meters?

One nautical mile (1852 meters) is defined as one arcminute of longitude at the equator. However, you need to define a map projection (see also UTM) in which you are working for the conversion to really make sense.

JSON to string variable dump

i personally use the jquery dump plugin alot to dump objects, its a bit similar to php's print_r() function Basic usage:

var obj = {
            hubba: "Some string...",
            bubba: 12.5,
            dubba: ["One", "Two", "Three"]
        }
$("#dump").append($.dump(obj));
/* will return:
Object { 
     hubba: "Some string..."
     bubba: 12.5
     dubba: Array ( 
          0 => "One"
          1 => "Two"
          2 => "Three"
     )
}
*/

Its very human readable, i also recommend this site http://json.parser.online.fr/ for creating/parsing/reading json, because it has nice colors

In bash, how to store a return value in a variable?

Use the special bash variable "$?" like so:

function_output=$(my_function)
function_return_value=$?

Java 8 NullPointerException in Collectors.toMap

Yep, a late answer from me, but I think it may help to understand what's happening under the hood in case anyone wants to code some other Collector-logic.

I tried to solve the problem by coding a more native and straight forward approach. I think it's as direct as possible:

public class LambdaUtilities {

  /**
   * In contrast to {@link Collectors#toMap(Function, Function)} the result map
   * may have null values.
   */
  public static <T, K, U, M extends Map<K, U>> Collector<T, M, M> toMapWithNullValues(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
    return toMapWithNullValues(keyMapper, valueMapper, HashMap::new);
  }

  /**
   * In contrast to {@link Collectors#toMap(Function, Function, BinaryOperator, Supplier)}
   * the result map may have null values.
   */
  public static <T, K, U, M extends Map<K, U>> Collector<T, M, M> toMapWithNullValues(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, Supplier<Map<K, U>> supplier) {
    return new Collector<T, M, M>() {

      @Override
      public Supplier<M> supplier() {
        return () -> {
          @SuppressWarnings("unchecked")
          M map = (M) supplier.get();
          return map;
        };
      }

      @Override
      public BiConsumer<M, T> accumulator() {
        return (map, element) -> {
          K key = keyMapper.apply(element);
          if (map.containsKey(key)) {
            throw new IllegalStateException("Duplicate key " + key);
          }
          map.put(key, valueMapper.apply(element));
        };
      }

      @Override
      public BinaryOperator<M> combiner() {
        return (left, right) -> {
          int total = left.size() + right.size();
          left.putAll(right);
          if (left.size() < total) {
            throw new IllegalStateException("Duplicate key(s)");
          }
          return left;
        };
      }

      @Override
      public Function<M, M> finisher() {
        return Function.identity();
      }

      @Override
      public Set<Collector.Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
      }

    };
  }

}

And the tests using JUnit and assertj:

  @Test
  public void testToMapWithNullValues() throws Exception {
    Map<Integer, Integer> result = Stream.of(1, 2, 3)
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null));

    assertThat(result)
        .isExactlyInstanceOf(HashMap.class)
        .hasSize(3)
        .containsEntry(1, 1)
        .containsEntry(2, null)
        .containsEntry(3, 3);
  }

  @Test
  public void testToMapWithNullValuesWithSupplier() throws Exception {
    Map<Integer, Integer> result = Stream.of(1, 2, 3)
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null, LinkedHashMap::new));

    assertThat(result)
        .isExactlyInstanceOf(LinkedHashMap.class)
        .hasSize(3)
        .containsEntry(1, 1)
        .containsEntry(2, null)
        .containsEntry(3, 3);
  }

  @Test
  public void testToMapWithNullValuesDuplicate() throws Exception {
    assertThatThrownBy(() -> Stream.of(1, 2, 3, 1)
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null)))
            .isExactlyInstanceOf(IllegalStateException.class)
            .hasMessage("Duplicate key 1");
  }

  @Test
  public void testToMapWithNullValuesParallel() throws Exception {
    Map<Integer, Integer> result = Stream.of(1, 2, 3)
        .parallel() // this causes .combiner() to be called
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null));

    assertThat(result)
        .isExactlyInstanceOf(HashMap.class)
        .hasSize(3)
        .containsEntry(1, 1)
        .containsEntry(2, null)
        .containsEntry(3, 3);
  }

  @Test
  public void testToMapWithNullValuesParallelWithDuplicates() throws Exception {
    assertThatThrownBy(() -> Stream.of(1, 2, 3, 1, 2, 3)
        .parallel() // this causes .combiner() to be called
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null)))
            .isExactlyInstanceOf(IllegalStateException.class)
            .hasCauseExactlyInstanceOf(IllegalStateException.class)
            .hasStackTraceContaining("Duplicate key");
  }

And how do you use it? Well, just use it instead of toMap() like the tests show. This makes the calling code look as clean as possible.

EDIT:
implemented Holger's idea below, added a test method

How to decrypt a password from SQL server?

You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.

Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?

AWS : The config profile (MyName) could not be found

I ran into this problem when I moved to a new machine, carrying with me my AWS_DEFAULT_PROFILE environment variable, but not my ~/.aws directory. I couldn't get any awscli commands to work until I unset that variable or properly configured the named profile. But even the aws configure command was broken, making things a bit tricky. Assuming you have a Unix-like shell handy:

  • To determine what AWS-specific variables you might have in your session: env | grep AWS_
    • if you don't see AWS_DEFAULT_PROFILE listed here, this answer is not applicable to you.
  • To temporarily remove the default profile: unset AWS_DEFAULT_PROFILE
  • To configure that default profile: aws --profile foo configure
  • To reset the default profile variable: exec $SHELL
  • To test your new setup: aws iam get-user

Getting the object's property name

When you do the for/in loop you put up first, i is the property name. So you have the property name, i, and access the value by doing myObject[i].

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

Python JSON serialize a Decimal object

How about subclassing json.JSONEncoder?

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            # wanted a simple yield str(o) in the next line,
            # but that would mean a yield on the line with super(...),
            # which wouldn't work (see my comment below), so...
            return (str(o) for o in [o])
        return super(DecimalEncoder, self).default(o)

Then use it like so:

json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)

Read lines from a text file but skip the first two lines

That whole Open <file path> For Input As <some number> thing is so 1990s. It's also slow and very error-prone.

In your VBA editor, Select References from the Tools menu and look for "Microsoft Scripting Runtime" (scrrun.dll) which should be available on pretty much any XP or Vista machine. It it's there, select it. Now you have access to a (to me at least) rather more robust solution:

With New Scripting.FileSystemObject
    With .OpenTextFile(sFilename, ForReading)

        If Not .AtEndOfStream Then .SkipLine
        If Not .AtEndOfStream Then .SkipLine

        Do Until .AtEndOfStream
            DoSomethingImportantTo .ReadLine
        Loop

    End With
End With

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

How to set header and options in axios?

You can initialize a default header axios.defaults.headers

 axios.defaults.headers = {
        'Content-Type': 'application/json',
        Authorization: 'myspecialpassword'
    }

   axios.post('https://myapi.com', { data: "hello world" })
        .then(response => {
            console.log('Response', response.data)
        })
        .catch(e => {
            console.log('Error: ', e.response.data)
        })

Increasing the maximum number of TCP/IP connections in Linux

There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.

More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:

  • Check if your TCP window setting is large enough. Linux defaults are good for everything except really fast inet link (hundreds of mbps) or fast satellite links. What is your bandwidth*delay product?
  • Check for packet loss using ping with large packets (ping -s 1472 ...)
  • Check for rate limiting. On Linux, this is configured with tc
  • Confirm that the bandwidth you think exists actually exists using e.g., iperf
  • Confirm that your protocol is sane. Remember latency.
  • If this is a gigabit+ LAN, can you use jumbo packets? Are you?

Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat or lsof). If that number is substantial, you might:

  • Have a lot of bandwidth, e.g., 100mbps+. In this case, you may actually need to up the ulimit -n. Still, ~1000 connections (default on my system) is quite a few.
  • Have network problems which are slowing down your connections (e.g., packet loss)
  • Have something else slowing you down, e.g., IO bandwidth, especially if you're seeking. Have you checked iostat -x?

Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.

I hope this provides some help. You're really asking a networking question.

How to force a UIViewController to Portrait orientation in iOS 6

IOS 5

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

IOS 6

-(BOOL)shouldAutorotate{
    return YES;
}

-(NSInteger)supportedInterfaceOrientations{

    //    UIInterfaceOrientationMaskLandscape;
    //    24
    //
    //    UIInterfaceOrientationMaskLandscapeLeft;
    //    16
    //
    //    UIInterfaceOrientationMaskLandscapeRight;
    //    8
    //
    //    UIInterfaceOrientationMaskPortrait;
    //    2

    //    return UIInterfaceOrientationMaskPortrait; 
    //    or
          return 2;
}

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

Ideally, I would use a construct like this instead:

for (std::vector<your_type>::const_iterator i = things.begin(); i != things.end(); ++i)
{
  // if you ever need the distance, you may call std::distance
  // it won't cause any overhead because the compiler will likely optimize the call
  size_t distance = std::distance(things.begin(), i);
}

This a has the neat advantage that your code suddenly becomes container agnostic.

And regarding your problem, if some library you use requires you to use int where an unsigned int would better fit, their API is messy. Anyway, if you are sure that those int are always positive, you may just do:

int int_distance = static_cast<int>(distance);

Which will specify clearly your intent to the compiler: it won't bug you with warnings anymore.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Maybe Series would provide all the functions you need:

pd.Series({'A':a,'B':b})

DataFrame can be thought of as a collection of Series hence you can :

  • Concatenate multiple Series into one data frame (as described here )

  • Add a Series variable into existing data frame ( example here )

Output single character in C

Be careful of difference between 'c' and "c"

'c' is a char suitable for formatting with %c

"c" is a char* pointing to a memory block with a length of 2 (with the null terminator).

Only detect click event on pseudo-element

Short Answer:

I did it. I wrote a function for dynamic usage for all the little people out there...

Working example which displays on the page

Working example logging to the console

Long Answer:

...Still did it.

It took me awhile to do it, since a psuedo element is not really on the page. While some of the answers above work in SOME scenarios, they ALL fail to be both dynamic and work in a scenario in which an element is both unexpected in size and position(such as absolute positioned elements overlaying a portion of the parent element). Mine does not.

Usage:

//some element selector and a click event...plain js works here too
$("div").click(function() {
    //returns an object {before: true/false, after: true/false}
    psuedoClick(this);

    //returns true/false
    psuedoClick(this).before;

    //returns true/false
    psuedoClick(this).after;

});

How it works:

It grabs the height, width, top, and left positions(based on the position away from the edge of the window) of the parent element and grabs the height, width, top, and left positions(based on the edge of the parent container) and compares those values to determine where the psuedo element is on the screen.

It then compares where the mouse is. As long as the mouse is in the newly created variable range then it returns true.

Note:

It is wise to make the parent element RELATIVE positioned. If you have an absolute positioned psuedo element, this function will only work if it is positioned based on the parent's dimensions(so the parent has to be relative...maybe sticky or fixed would work too....I dont know).

Code:

function psuedoClick(parentElem) {

    var beforeClicked,
      afterClicked;

  var parentLeft = parseInt(parentElem.getBoundingClientRect().left, 10),
      parentTop = parseInt(parentElem.getBoundingClientRect().top, 10);

  var parentWidth = parseInt(window.getComputedStyle(parentElem).width, 10),
      parentHeight = parseInt(window.getComputedStyle(parentElem).height, 10);

  var before = window.getComputedStyle(parentElem, ':before');

  var beforeStart = parentLeft + (parseInt(before.getPropertyValue("left"), 10)),
      beforeEnd = beforeStart + parseInt(before.width, 10);

  var beforeYStart = parentTop + (parseInt(before.getPropertyValue("top"), 10)),
      beforeYEnd = beforeYStart + parseInt(before.height, 10);

  var after = window.getComputedStyle(parentElem, ':after');

  var afterStart = parentLeft + (parseInt(after.getPropertyValue("left"), 10)),
      afterEnd = afterStart + parseInt(after.width, 10);

  var afterYStart = parentTop + (parseInt(after.getPropertyValue("top"), 10)),
      afterYEnd = afterYStart + parseInt(after.height, 10);

  var mouseX = event.clientX,
      mouseY = event.clientY;

  beforeClicked = (mouseX >= beforeStart && mouseX <= beforeEnd && mouseY >= beforeYStart && mouseY <= beforeYEnd ? true : false);

  afterClicked = (mouseX >= afterStart && mouseX <= afterEnd && mouseY >= afterYStart && mouseY <= afterYEnd ? true : false);

  return {
    "before" : beforeClicked,
    "after"  : afterClicked

  };      

}

Support:

I dont know....it looks like ie is dumb and likes to return auto as a computed value sometimes. IT SEEMS TO WORK WELL IN ALL BROWSERS IF DIMENSIONS ARE SET IN CSS. So...set your height and width on your psuedo elements and only move them with top and left. I recommend using it on things that you are okay with it not working on. Like an animation or something. Chrome works...as usual.

When is a C++ destructor called?

To give a detailed answer to question 3: yes, there are (rare) occasions when you might call the destructor explicitly, in particular as the counterpart to a placement new, as dasblinkenlight observes.

To give a concrete example of this:

#include <iostream>
#include <new>

struct Foo
{
    Foo(int i_) : i(i_) {}
    int i;
};

int main()
{
    // Allocate a chunk of memory large enough to hold 5 Foo objects.
    int n = 5;
    char *chunk = static_cast<char*>(::operator new(sizeof(Foo) * n));

    // Use placement new to construct Foo instances at the right places in the chunk.
    for(int i=0; i<n; ++i)
    {
        new (chunk + i*sizeof(Foo)) Foo(i);
    }

    // Output the contents of each Foo instance and use an explicit destructor call to destroy it.
    for(int i=0; i<n; ++i)
    {
        Foo *foo = reinterpret_cast<Foo*>(chunk + i*sizeof(Foo));
        std::cout << foo->i << '\n';
        foo->~Foo();
    }

    // Deallocate the original chunk of memory.
    ::operator delete(chunk);

    return 0;
}

The purpose of this kind of thing is to decouple memory allocation from object construction.

Phone Number Validation MVC

[DataType(DataType.PhoneNumber)] does not come with any validation logic out of the box.

According to the docs:

When you apply the DataTypeAttribute attribute to a data field you must do the following:

  • Issue validation errors as appropriate.

The [Phone] Attribute inherits from [DataType] and was introduced in .NET Framework 4.5+ and is in .NET Core which does provide it's own flavor of validation logic. So you can use like this:

[Phone()]
public string PhoneNumber { get; set; }

However, the out-of-the-box validation for Phone numbers is pretty permissive, so you might find yourself wanting to inherit from DataType and implement your own IsValid method or, as others have suggested here, use a regular expression & RegexValidator to constrain input.

Note: Use caution with Regex against unconstrained input per the best practices as .NET has made the pivot away from regular expressions in their own internal validation logic for phone numbers

Launch custom android application from android browser

You need to add a pseudo-hostname to the CALLBACK_URL 'app://' doesn't make sense as a URL and cannot be parsed.

Open links in new window using AngularJS

this is the code of your button

<a href="AddNewUserAdmin" 
   class="btn btn-info " 
   ng-click="showaddnewuserpage()">
  <span class="glyphicon glyphicon-plus-sign"></span> Add User</a>

in the controller just add this function.

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

app.controller('useraddcontroller', function ($scope, $http, $window) {

$scope.showaddnewuserpage = function () {

    $window.location.href = ('/AddNewUserAdmin');
}

});

label or @html.Label ASP.net MVC 4

The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.

With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.

Use of def, val, and var in scala

With

def person = new Person("Kumar", 12) 

you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.

When writing

person.age = 45

you assign a new value to the age property in class Person, which is valid since age is declared as var. The compiler will complain if you try to reassign person with a new Person object like

person = new Person("Steve", 13)  // Error

How to get arguments with flags in Bash

I like Robert McMahan's answer the best here as it seems the easiest to make into sharable include files for any of your scripts to use. But it seems to have a flaw with the line if [[ -n ${variables[$argument_label]} ]] throwing the message, "variables: bad array subscript". I don't have the rep to comment, and I doubt this is the proper 'fix,' but wrapping that if in if [[ -n $argument_label ]] ; then cleans it up.

Here's the code I ended up with, if you know a better way please add a comment to Robert's answer.

Include File "flags-declares.sh"

# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();

# declaring an index integer
declare -i index=1;

Include File "flags-arguments.sh"

# $@ here represents all arguments passed in
for i in "$@"
do
  arguments[$index]=$i;
  prev_index="$(expr $index - 1)";

  # this if block does something akin to "where $i contains ="
  # "%=*" here strips out everything from the = to the end of the argument leaving only the label
  if [[ $i == *"="* ]]
    then argument_label=${i%=*}
    else argument_label=${arguments[$prev_index]}
  fi

  if [[ -n $argument_label ]] ; then
    # this if block only evaluates to true if the argument label exists in the variables array
    if [[ -n ${variables[$argument_label]} ]] ; then
      # dynamically creating variables names using declare
      # "#$argument_label=" here strips out the label leaving only the value
      if [[ $i == *"="* ]]
        then declare ${variables[$argument_label]}=${i#$argument_label=} 
        else declare ${variables[$argument_label]}=${arguments[$index]}
      fi
    fi
  fi

  index=index+1;
done;

Your "script.sh"

. bin/includes/flags-declares.sh

# any variables you want to use here
# on the left left side is argument label or key (entered at the command line along with it's value) 
# on the right side is the variable name the value of these arguments should be mapped to.
# (the examples above show how these are being passed into this script)
variables["-gu"]="git_user";
variables["--git-user"]="git_user";
variables["-gb"]="git_branch";
variables["--git-branch"]="git_branch";
variables["-dbr"]="db_fqdn";
variables["--db-redirect"]="db_fqdn";
variables["-e"]="environment";
variables["--environment"]="environment";

. bin/includes/flags-arguments.sh

# then you could simply use the variables like so:
echo "$git_user";
echo "$git_branch";
echo "$db_fqdn";
echo "$environment";

SQL SERVER, SELECT statement with auto generate row id

IDENTITY(int, 1, 1) should do it if you are doing a select into. In SQL 2000, I use to just put the results in a temp table and query that afterwords.

Fragments onResume from back stack

I have used enum FragmentTags to define all my fragment classes.

TAG_FOR_FRAGMENT_A(A.class),
TAG_FOR_FRAGMENT_B(B.class),
TAG_FOR_FRAGMENT_C(C.class)

pass FragmentTags.TAG_FOR_FRAGMENT_A.name() as fragment tag.

and now on

@Override
public void onBackPressed(){
   FragmentManager fragmentManager = getFragmentManager();
   Fragment current
   = fragmentManager.findFragmentById(R.id.fragment_container);
    FragmentTags fragmentTag = FragmentTags.valueOf(current.getTag());

  switch(fragmentTag){
    case TAG_FOR_FRAGMENT_A:
        finish();
        break;
   case TAG_FOR_FRAGMENT_B:
        fragmentManager.popBackStack();
        break;
   case default: 
   break;
}

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

What is the difference between & and && in Java?

It depends on the type of the arguments...

For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should occur.

How to set menu to Toolbar in Android

In my case, I'm using an AppBarLayout with a CollapsingToolbarLayout and the menu was always being scrolled out of the screen, I solved my problem by switching android:actionLayout in menu's XML to the toolbar's id. I hope it can help people in the same situation!

activity_main.xml

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainScreenActivity"
    android:screenOrientation="portrait">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        app:elevation="0dp"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingBar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="exitUntilCollapsed|scroll"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="48dp"
            >
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:elevation="0dp"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                app:layout_collapseMode="pin"/>
        </android.support.design.widget.CollapsingToolbarLayout>


    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

main_menu.xml

<?xml version="1.0" encoding="utf-8"?> <menu
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/logoutMenu"
        android:orderInCategory="100"
        android:title="@string/log_out"
        app:showAsAction="never"
        android:actionLayout="@id/toolbar"/>
    <item
        android:id="@+id/sortMenu"
        android:orderInCategory="100"
        android:title="@string/sort"
        app:showAsAction="never"/> </menu>

How can I get file extensions with JavaScript?

function getFileExtension(filename)
{
  var ext = /^.+\.([^.]+)$/.exec(filename);
  return ext == null ? "" : ext[1];
}

Tested with

"a.b"     (=> "b") 
"a"       (=> "") 
".hidden" (=> "") 
""        (=> "") 
null      (=> "")  

Also

"a.b.c.d" (=> "d")
".a.b"    (=> "b")
"a..b"    (=> "b")

Disable browser's back button

If you rely on client-side technology, it can be circumvented. Javascript may be disabled, for example. Or user might execute a JS script to work around your restrictions.

My guess is you can only do this by server-side tracking of the user session, and redirecting (as in Server.Transfer, not Response.Redirect) the user/browser to the required page.

Setting a JPA timestamp column to be generated by the database?

This also works for me:-

@Temporal(TemporalType.TIMESTAMP)   
@Column(name = "CREATE_DATE_TIME", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
public Date getCreateDateTime() {
    return createDateTime;
}

public void setCreateDateTime(Date createDateTime) {
    this.createDateTime = createDateTime;
}

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

It worked when I downgrade the support appcompat gradle dependency, like follwing :

implementation 'com.android.support:appcompat-v7:27.0.2'

previously it was

implementation 'com.android.support:appcompat-v7:27.1.0'

OR

Also this can be fixed by just adding support design dependency of version 27.1.0 or above to your app level build.gradle as following :

implementation 'com.android.support:design:27.1.0'

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

How to turn off word wrapping in HTML?

Added webkit specific values missing from above

white-space: -moz-pre-wrap; /* Firefox */
white-space: -o-pre-wrap; /* Opera */
white-space: pre-wrap; /* Chrome */
word-wrap: break-word; /* IE */

Arduino error: does not name a type?

The only thing you have to do is adding this line to your sketch

#include <SPI.h>

before #include <Adafruit_MAX31855.h>.

How to specify jackson to only use fields - preferably globally

How about this: I used it with a mixin

non-compliant object

@Entity
@Getter
@NoArgsConstructor
public class Telemetry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long pk;
    private String id;
    private String organizationId;
    private String baseType;
    private String name;
    private Double lat;
    private Double lon;
    private Instant updateTimestamp;
}

Mixin:

@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)
public static class TelemetryMixin {}

Usage:

    ObjectMapper om = objectMapper.addMixIn(Telemetry.class, TelemetryMixin.class);
    Telemetry[] telemetries = om.readValue(someJson, Telemetry[].class);

There is nothing that says you couldn't foreach any number of classes and apply the same mixin.

If you're not familiar with mixins, they are conceptually simply: The structure of the mixin is super imposed on the target class (according to jackson, not as far as the JVM is concerned).

Best way in asp.net to force https for an entire site?

I spent sometime looking for best practice that make sense and found the following which worked perfected for me. I hope this will save you sometime.

Using Config file (for example an asp.net website) https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/

or on your own server https://www.sslshopper.com/iis7-redirect-http-to-https.html

[SHORT ANSWER] Simply The code below goes inside

<system.webServer> 
 <rewrite>
     <rules>
       <rule name="HTTP/S to HTTPS Redirect" enabled="true" 
           stopProcessing="true">
       <match url="(.*)" />
        <conditions logicalGrouping="MatchAny">
        <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
       </conditions>
       <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" 
        redirectType="Permanent" />
        </rule>
       </rules>
 </rewrite>

Randomize numbers with jQuery?

Javascript has a random() available. Take a look at Math.random().

How can I run a directive after the dom has finished rendering?

Here is how I do it:

app.directive('example', function() {

    return function(scope, element, attrs) {
        angular.element(document).ready(function() {
                //MANIPULATE THE DOM
        });
    };

});

jQuery AJAX form data serialize using PHP

try it , but first be sure what is you response console.log(response) on ajax success from server

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(response){
        if(response === 1){
            //load chech.php file  
        }  else {
            //show error
        }
        }
    });
});
});

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

I had the same problem. It turned out that I didn't specify a default page and I didn't have any page that is named after the default page convention (default.html, defult.aspx etc). As a result, ASP.NET doesn't allow the user to browse the directory (not a problem in Visual Studio built-in web server that allows you to view the directory) and shows the error message. To fix it, I added one default page in Web.Config and it worked.

<system.webServer>
    <defaultDocument>
        <files>
            <add value="myDefault.aspx"/>
        </files>
    </defaultDocument>
</system.webServer>

Combining C++ and C - how does #ifdef __cplusplus work?

It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.

Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.

While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.

People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.

What is the difference between class and instance methods?

Note: This is only in pseudo code format

Class method

Almost does all it needs to do is during compile time. It doesn't need any user input, nor the computation of it is based on an instance. Everything about it is based on the class/blueprint——which is unique ie you don't have multiple blueprints for one class. Can you have different variations during compile time? No, therefore the class is unique and so no matter how many times you call a class method the pointer pointing to it would be the same.

PlanetOfLiving: return @"Earth" // No matter how many times you run this method...nothing changes.

Instance Method

On the contrary instance method happens during runtime, since it is only then that you have created an instance of something which could vary upon every instantiation.

initWithName: @"John" lastName: @"Doe"Age:12 @"cool"
initWithName: @"Donald" lastName: @"Drumpf"Age:5 attitude:@"He started"
initWithName: @"President" lastName: @"Obama"Age:54 attitude: @"Awesome"
//As you can see the value can change for each instance.

If you are coming from other languages Static methods are same as class methods.
If you are coming from Swift, type methods are same as class methods.

How to convert NSData to byte array in iPhone?

Already answered, but to generalize to help other readers:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }

how to access master page control from content page

You cannot use var in a field, only on local variables.

But even this won't work:

Site master = Master as Site;

Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:

Site master = null;

protected void Page_Init(object sender, EventArgs e)
{            
    master = this.Master as Site;
}

Listen for key press in .NET console app

Here is an approach for you to do something on a different thread and start listening to the key pressed in a different thread. And the Console will stop its processing when your actual process ends or the user terminates the process by pressing Esc key.

class SplitAnalyser
{
    public static bool stopProcessor = false;
    public static bool Terminate = false;

    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Split Analyser starts");
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Press Esc to quit.....");
        Thread MainThread = new Thread(new ThreadStart(startProcess));
        Thread ConsoleKeyListener = new Thread(new ThreadStart(ListerKeyBoardEvent));
        MainThread.Name = "Processor";
        ConsoleKeyListener.Name = "KeyListener";
        MainThread.Start();
        ConsoleKeyListener.Start();

        while (true) 
        {
            if (Terminate)
            {
                Console.WriteLine("Terminating Process...");
                MainThread.Abort();
                ConsoleKeyListener.Abort();
                Thread.Sleep(2000);
                Thread.CurrentThread.Abort();
                return;
            }

            if (stopProcessor)
            {
                Console.WriteLine("Ending Process...");
                MainThread.Abort();
                ConsoleKeyListener.Abort();
                Thread.Sleep(2000);
                Thread.CurrentThread.Abort();
                return;
            }
        } 
    }

    public static void ListerKeyBoardEvent()
    {
        do
        {
            if (Console.ReadKey(true).Key == ConsoleKey.Escape)
            {
                Terminate = true;
            }
        } while (true); 
    }

    public static void startProcess()
    {
        int i = 0;
        while (true)
        {
            if (!stopProcessor && !Terminate)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Processing...." + i++);
                Thread.Sleep(3000);
            }
            if(i==10)
                stopProcessor = true;

        }
    }

}

How to locate the php.ini file (xampp)

In MacOS : /Applications/XAMPP/xamppfiles/etc/php.ini

Add a new element to an array without specifying the index in Bash

If your array is always sequential and starts at 0, then you can do this:

array[${#array[@]}]='foo'

# gets the length of the array
${#array_name[@]}

If you inadvertently use spaces between the equal sign:

array[${#array[@]}] = 'foo'

Then you will receive an error similar to:

array_name[3]: command not found

How to change the background color on a Java panel?

You could call:


getContentPane().setBackground(Color.black);

Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call


setBackground(Color.black);

on the JPanel to set the background color.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

What is the fastest way to create a checksum for large files in C#

The problem here is that SHA256Managed reads 4096 bytes at a time (inherit from FileStream and override Read(byte[], int, int) to see how much it reads from the filestream), which is too small a buffer for disk IO.

To speed things up (2 minutes for hashing 2 Gb file on my machine with SHA256, 1 minute for MD5) wrap FileStream in BufferedStream and set reasonably-sized buffer size (I tried with ~1 Mb buffer):

// Not sure if BufferedStream should be wrapped in using block
using(var stream = new BufferedStream(File.OpenRead(filePath), 1200000))
{
    // The rest remains the same
}

SUM of grouped COUNT in SQL Query

For Sql server you can try this one.

SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

How to make div occupy remaining height?

You can use

display: flex;

CSS property, as mentioned before by @Ayan, but I've created a working example: https://jsfiddle.net/d2kjxd51/

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

My StreamEx library which enhances standard stream API provides an EntryStream class which suits better for transforming maps:

Map<String, Integer> output = EntryStream.of(input).mapValues(Integer::valueOf).toMap();

Rotating x axis labels in R for barplot

You can simply pass your data frame into the following function:

rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
    plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
    text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6) 
}

Usage:

rotate_x(mtcars, 'mpg', row.names(mtcars), 45)

enter image description here

You can change the rotation angle of the labels as needed.

How do I execute a program using Maven?

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

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

This is then executable as:

mvn exec:exec -Ptraverse

How do I execute a PowerShell script automatically using Windows task scheduler?

Create the scheduled task and set the action to:

Program/Script: Powershell.exe

Arguments: -File "C:\Users\MyUser\Documents\ThisisMyFile.ps1"

Place a button right aligned

It is not always so simple and sometimes the alignment must be defined in the container and not in the Button element itself !

For your case, the solution would be

<div style="text-align:right; width:100%; padding:0;">
    <input type="button" value="Click Me"/>
</div>

I have taken care to specify width=100% to be sure that <div> take full width of his container.

I have also added padding:0 to avoid before and after space as with <p> element.

I can say that if <div> is defined in a FSF/Primefaces table's footer, the float:right don't work correctly because the Button height will become higher than the footer height !

In this Primefaces situation, the only acceptable solution is to use text-align:right in container.

With this solution, if you have 6 Buttons to align at right, you must only specify this alignment in container :-)

<div style="text-align:right; width:100%; padding:0;">
    <input type="button" value="Click Me 1"/>
    <input type="button" value="Click Me 2"/>
    <input type="button" value="Click Me 3"/>
    <input type="button" value="Click Me 4"/>
    <input type="button" value="Click Me 5"/>
    <input type="button" value="Click Me 6"/>
</div>

How do I change selected value of select2 dropdown with JqGrid?

if you have ajax data source please refer this for bugs free

https://select2.org/programmatic-control/add-select-clear-items

// Set up the Select2 control

$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control

var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});

Replacing NULL and empty string within Select statement

For an example data in your table such as combinations of

'', null and as well as actual value than if you want to only actual value and replace to '' and null value by # symbol than execute this query

SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name

and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull function but here only i am mentioning IIF function

SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name  
SELECT IIF(Column_Name  = '', '#', Column_Name) FROM Table_Name  
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name

How do I show running processes in Oracle DB?

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

SVG fill color transparency / alpha?

fill="#044B9466"

This is an RGBA color in hex notation inside the SVG, defined with hex values. This is valid, but not all programs can display it properly...

You can find the browser support for this syntax here: https://caniuse.com/#feat=css-rrggbbaa

As of August 2017: RGBA fill colors will display properly on Mozilla Firefox (54), Apple Safari (10.1) and Mac OS X Finder's "Quick View". However Google Chrome did not support this syntax until version 62 (was previously supported from version 54 with the Experimental Platform Features flag enabled).

Declare global variables in Visual Studio 2010 and VB.NET

A global variable could be accessible in all your forms in your project if you use the keyword public shared if it is in a class. It will also work if you use the keyword "public" if it is under a Module, but it is not the best practice for many reasons.

(... Yes, I somewhat repeating what "Cody Gray" and "RBarryYoung" said.)

One of the problems is when you have two threads that call the same global variable at the same time. You will have some surprises. You might have unexpected reactions if you don't know their limitations. Take a look at the post Global Variables in Visual Basic .NET and download the sample project!

Proxy setting for R

Inspired by all the responses related on the internet, finally I've found the solution to correctly configure the Proxy for R and Rstudio.

There are several steps to follow, perhaps some of the steps are useless, but the combination works!

  1. Add environment variables http_proxy and https_proxy with proxy details.

    variable name: http_proxy
    variable value: https://user_id:password@your_proxy:your_port/
    
    variable name: https_proxy
    variable value: https:// user_id:password@your_proxy:your_port
    
  2. If you start R from a desktop icon, you can add the --internet flag to the target line (right click -> Properties)

    e.g."C:\Program Files\R\R-2.8.1\bin\Rgui.exe" --internet2

  3. For RStudio just you have to do this:

    Firstly, open RStudio like always, select from the top menu:

    Tools-Global Options-Packages

    Uncheck the option: Use Internet Explorer library/proxy for HTTP

  4. Find the file (.Renviron) in your computer, most probably you would find it here: C:\Users\your user name\Documents.

    Note that: if it does not exist you can create it just by writing this command in R:

    file.edit('~/.Renviron')
    

    Then add these six lines to the initials of the file:

    options(internet.info = 0)
    
    http_proxy = https:// user_id:password@your_proxy:your_port
    
    http_proxy_user = user_id:password
    
    https_proxy = https:// user_id:password0@your_proxy:your_port
    
    https_proxy_user = user_id:password
    
    ftp_proxy = user_id:password@your_proxy:your_port
    
  5. Restart R. Type the following commands in R to assure that the configuration above works well:

    Sys.getenv("http_proxy")
    
    Sys.getenv("http_proxy_user")
    
    Sys.getenv("https_proxy")
    
    Sys.getenv("https_proxy_user")
    
    Sys.getenv("ftp_proxy")
    
  6. Now you can install the packages as you want by using the command like:

    install.packages("mlr",method="libcurl")
    

    It's important to add method="libcurl", otherwise it won't work.

Getting value from appsettings.json in .net core

I guess the simplest way is by DI. An example of reaching into Controller.

// StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
    ...
    // for get appsettings from anywhere
    services.AddSingleton(Configuration);
}

public class ContactUsController : Controller
{
    readonly IConfiguration _configuration;

    public ContactUsController(
        IConfiguration configuration)
    {
        _configuration = configuration;

        // sample:
        var apiKey = _configuration.GetValue<string>("SendGrid:CAAO");
        ...
    }
}

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

How do I pass options to the Selenium Chrome driver using Python?

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')

# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())

Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.

Function overloading in Javascript - Best practices

Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.

    function optionsObjectTest(x, y, opts) {
        opts = opts || {}; // default to an empty options object

        var stringValue = opts.stringValue || "string default value";
        var boolValue = !!opts.boolValue; // coerces value to boolean with a double negation pattern
        var numericValue = opts.numericValue === undefined ? 123 : opts.numericValue;

        return "{x:" + x + ", y:" + y + ", stringValue:'" + stringValue + "', boolValue:" + boolValue + ", numericValue:" + numericValue + "}";

}

here is an example on how to use options object

Xampp MySQL not starting - "Attempting to start MySQL service..."

After Stop xampp, go to configure and change the port 3306 to 3308 of mysql and save. Now start the sql......Enjoy

Is a LINQ statement faster than a 'foreach' loop?

Why should LINQ be faster? It also uses loops internally.

Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code.

Changing text color onclick

   <p id="text" onclick="func()">
    Click on text to change
</p>
<script>
function func()
{
    document.getElementById("text").style.color="red";
    document.getElementById("text").style.font="calibri";
}
</script>

How can I compare time in SQL Server?

One (possibly small) issue I have noted with the solutions so far is that they all seem to require a function call to process the comparison. This means that the query engine will need to do a full table scan to seek the rows you are after - and be unable to use an index. If the table is not going to get particularly large, this probably won't have any adverse affects (and you can happily ignore this answer).

If, on the other hand, the table could get quite large, the performance of the query could suffer.

I know you stated that you do not wish to compare the date part - but is there an actual date being stored in the datetime column, or are you using it to store only the time? If the latter, you can use a simple comparison operator, and this will reduce both CPU usage, and allow the query engine to use statistics and indexes (if present) to optimise the query.

If, however, the datetime column is being used to store both the date and time of the event, this obviously won't work. In this case if you can modify the app and the table structure, separate the date and time into two separate datetime columns, or create a indexed view that selects all the (relevant) columns of the source table, and a further column that contains the time element you wish to search for (use any of the previous answers to compute this) - and alter the app to query the view instead.

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

Connect over ssh using a .pem file

chmod 400 mykey.pem

ssh -i mykey.pem [email protected]

Will connect you over ssh using a .pem file to any server.

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

Finishing current activity from a fragment

You should use getActivity() method in order to finish the activity from the fragment.

getActivity().finish();

How do you set the Content-Type header for an HttpClient request?

.Net tries to force you to obey certain standards, namely that the Content-Type header can only be specified on requests that have content (e.g. POST, PUT, etc.). Therefore, as others have indicated, the preferred way to set the Content-Type header is through the HttpContent.Headers.ContentType property.

With that said, certain APIs (such as the LiquidFiles Api, as of 2016-12-19) requires setting the Content-Type header for a GET request. .Net will not allow setting this header on the request itself -- even using TryAddWithoutValidation. Furthermore, you cannot specify a Content for the request -- even if it is of zero-length. The only way I could seem to get around this was to resort to reflection. The code (in case some else needs it) is

var field = typeof(System.Net.Http.Headers.HttpRequestHeaders)
    .GetField("invalidHeaders", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static) 
  ?? typeof(System.Net.Http.Headers.HttpRequestHeaders) 
    .GetField("s_invalidHeaders", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (field != null)
{
  var invalidFields = (HashSet<string>)field.GetValue(null);
  invalidFields.Remove("Content-Type");
}
_client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/xml");

Edit:

As noted in the comments, this field has different names in different versions of the dll. In the source code on GitHub, the field is currently named s_invalidHeaders. The example has been modified to account for this per the suggestion of @David Thompson.

Getting absolute URLs using ASP.NET Core

In a new ASP.Net 5 MVC project in a controller action you can still do this.Context and this.Context.Request It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.

 public IActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        var schema = this.Context.Request.Scheme;

        return View();
    }

Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

How to change text color and console color in code::blocks?

You should define the function textcolor before. Because textcolor is not a standard function in C.

void textcolor(unsigned short color) {
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon,color);
}

How to check if a key exists in Json Object and get its value

Use below code to find key is exist or not in JsonObject. has("key") method is used to find keys in JsonObject.

containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
    //get Value of video
    String video = containerObject.optString("video");
}

If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject.

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

Nginx 403 error: directory index of [folder] is forbidden

In my case I didn't run this command

sudo apt-get install php7.4-fpm

How to stop the Timer in android?

I had a similar problem and it was caused by the placement of the Timer initialisation.

It was placed in a method that was invoked oftener.

Try this:

Timer waitTimer;

  void exampleMethod() {

   if (waitTimer == null ) {
    //initialize your Timer here
    ...
   }

The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.

Passing event and argument to v-on in Vue.js

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.

Windows batch: sleep

You can try

ping -n XXX 127.0.0.1 >nul

where XXX is the number of seconds to wait, plus one.

Current date without time

String test = DateTime.Now.ToShortDateString();

Collapse all methods in Visual Studio Code

Like this ? (Visual Studio Code version 0.10.11)

Fold All (Ctrl+K Ctrl+0)

Unfold All (Ctrl+K Ctrl+J)

Fold Level n (Ctrl+K Ctrl+N)

Arithmetic overflow error converting numeric to data type numeric

Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.

How to give color to each class in scatter plot in R?

Here is an example that I built based on this page.

library(e1071); library(ggplot2)

mysvm      <- svm(Species ~ ., iris)
Predicted  <- predict(mysvm, iris)

mydf = cbind(iris, Predicted)
qplot(Petal.Length, Petal.Width, colour = Species, shape = Predicted, 
   data = iris)

This gives you the output. You can easily spot the misclassified species from this figure.

enter image description here

SQL to add column and comment in table in single command

You can use below query to update or create comment on already created table.

SYNTAX:

COMMENT ON COLUMN TableName.ColumnName IS 'comment text';

Example:

COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

this is better approach and its successful :

Actions oAction = new Actions(driver);
oAction.moveToElement(Webelement);
oAction.contextClick(Webelement).build().perform();  /* this will perform right click */
WebElement elementOpen = driver.findElement(By.linkText("Open")); /*This will select menu after right click */

elementOpen.click();

DropDownList's SelectedIndexChanged event not firing

I know its bit older post, but still i would like to add up something to the answers above.

There might be some situation where in, the "value" of more than one items in the dropdown list is duplicated/same. So, make sure that you have no repeated values in the list items to trigger this "onselectedindexchanged" event

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I put this for future visitors:

if you are receiving the error on creating an Exception object, then the cause of it probably is a lack of definition for what() virtual function.

How to detect duplicate values in PHP array?

You could try turning that array into a associative array with the fruits as keys and the number of occurrences as values. Bit long-winded, but it looks like:

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
   'pear', 'kiwi', 'kiwi', 'kiwi');
$new_array = array();
foreach ($array as $key => $value) {
    if(isset($new_array[$value]))
        $new_array[$value] += 1;
    else
        $new_array[$value] = 1;
}
foreach ($new_array as $fruit => $n) {
    echo $fruit;
    if($n > 1)
        echo "($n)";
    echo "<br />";
}

Run PHP Task Asynchronously

Another way to fork processes is via curl. You can set up your internal tasks as a webservice. For example:

Then in your user accessed scripts make calls to the service:

$service->addTask('t1', $data); // post data to URL via curl

Your service can keep track of the queue of tasks with mysql or whatever you like the point is: it's all wrapped up within the service and your script is just consuming URLs. This frees you up to move the service to another machine/server if necessary (ie easily scalable).

Adding http authorization or a custom authorization scheme (like Amazon's web services) lets you open up your tasks to be consumed by other people/services (if you want) and you could take it further and add a monitoring service on top to keep track of queue and task status.

It does take a bit of set-up work but there are a lot of benefits.

SELECT max(x) is returning null; how can I make it return 0?

or:

SELECT coalesce(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1

From milliseconds to hour, minutes, seconds and milliseconds

milliseconds = x
total = 0
while (milliseconds >= 1000) {
  milliseconds = (milliseconds - 1000)
  total = total + 1
}
hr = 0
min = 0
while (total >= 60) {
  total = total - 60
  min = min + 1
  if (min >= 60) hr = hr + 1
  if (min == 60) min = 0
}
sec = total

This is on groovy, but I thing that this is not problem for you. Method work perfect.

How to sort an ArrayList?

Here is a short cheatsheet that covers typical cases:

// sort
list.sort(naturalOrder())

// sort (reversed)
list.sort(reverseOrder())

// sort by field
list.sort(comparing(Type::getField))

// sort by field (reversed)
list.sort(comparing(Type::getField).reversed())

// sort by int field
list.sort(comparingInt(Type::getIntField))

// sort by double field (reversed)
list.sort(comparingDouble(Type::getDoubleField).reversed())

// sort by nullable field (nulls last)
list.sort(comparing(Type::getNullableField, nullsLast(naturalOrder())))

// two-level sort
list.sort(comparing(Type::getField1).thenComparing(Type::getField2))

Call ASP.NET function from JavaScript?

If the __doPostBack function is not generated on the page you need to insert a control to force it like this:

<asp:Button ID="btnJavascript" runat="server" UseSubmitBehavior="false" />

How to change Vagrant 'default' machine name?

If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:

Change the basebox name, when using "vagrant status"

 config.vm.define "tendo" do |tendo|
  end

Where "tendo" will be the name that will appear instead of default

The type or namespace name could not be found

The compiled dll should have public Class.

How do I load an url in iframe with Jquery

here is Iframe in view:

<iframe class="img-responsive" id="ifmReport" width="1090" height="1200" >

    </iframe>

Load it in script:

 $('#ifmReport').attr('src', '/ReportViewer/ReportViewer.aspx');

C++ Singleton design pattern

Being a Singleton, you usually do not want it to be destructed.

It will get torn down and deallocated when the program terminates, which is the normal, desired behavior for a singleton. If you want to be able to explicitly clean it, it's fairly easy to add a static method to the class that allows you to restore it to a clean state, and have it reallocate next time it's used, but that's outside of the scope of a "classic" singleton.

Operand type clash: uniqueidentifier is incompatible with int

Sounds to me like at least one of those tables has defined UserID as a uniqueidentifier, not an int. Did you check the data in each table? What does SELECT TOP 1 UserID FROM each table yield? An int or a GUID?

EDIT

I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership table in your script, since it's not really one of "your" tables.

If you meant to design your tables around the aspnet_Membership database, then why are the rest of the columns int when that table clearly uses a uniqueidentifier for the UserID column?

How to find whether a number belongs to a particular range in Python?

print 'yes' if 0 < x < 0.5 else 'no'

range() is for generating arrays of consecutive integers

Laravel - check if Ajax request

To check an ajax request you can use if (Request::ajax())

Note: If you are using laravel 5, then in the controller replace

use Illuminate\Http\Request;

with

use Request; 

I hope it'll work.

How to initialize a two-dimensional array in Python?

Another way is to use a dictionary to hold a two-dimensional array.

twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0

This just can hold any 1D, 2D values and to initialize this to 0 or any other int value, use collections.

import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Another way of doing it. This approach can be useful for changing the text to 2 different colors, just by adding 2 spans.

Label1.Text = "String with original color" + "<b><span style=""color:red;"">" + "Your String Here" + "</span></b>";

How can I upload files asynchronously?

Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder. Fiddle here

var reader = new FileReader();

        reader.onload = function(readerEvt) {
            var binaryString = readerEvt.target.result;
            document.getElementById("base64textarea").value = btoa(binaryString);
        };

        reader.readAsBinaryString(file);

Then to retrieve:

window.open("data:application/octet-stream;base64," + base64);

JavaScript URL Decode function

Use this

unescape(str);

I'm not a great JS programmer, tried all, and this worked awesome!

Alternative to the HTML Bold tag

Use the <strong> tag because it's more semantic. <b> has been depreciated so it's best not to use it. Also bold text is given more Search Engine Optimisation (SEO) weight so it's always best to use a real <strong> rather than making a <p> or <span> bold using CSS.

How to concatenate strings in a Windows batch file?

Note that the variables @fname or @ext can be simply concatenated. This:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

Get url without querystring

Good answer also found here source of answer

Request.Url.GetLeftPart(UriPartial.Path)

Image resizing client-side with JavaScript before upload to the server

Perhaps with the canvas tag (though it's not portable). There's a blog about how to rotate an image with canvas here, I suppose if you can rotate it, you can resize it. Maybe it can be a starting point.

See this library also.

How do I debug Node.js applications?

Use this commands

DEBUG_LEVEL=all node file.js
DEBUG=* node file.js
node file.js --inspect

How do I concatenate strings?

When you concatenate strings, you need to allocate memory to store the result. The easiest to start with is String and &str:

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    owned_string.push_str(borrowed_string);
    println!("{}", owned_string);
}

Here, we have an owned string that we can mutate. This is efficient as it potentially allows us to reuse the memory allocation. There's a similar case for String and String, as &String can be dereferenced as &str.

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    owned_string.push_str(&another_owned_string);
    println!("{}", owned_string);
}

After this, another_owned_string is untouched (note no mut qualifier). There's another variant that consumes the String but doesn't require it to be mutable. This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let new_owned_string = owned_string + borrowed_string;
    println!("{}", new_owned_string);
}

Note that owned_string is no longer accessible after the call to +.

What if we wanted to produce a new string, leaving both untouched? The simplest way is to use format!:

fn main() {
    let borrowed_string: &str = "hello ";
    let another_borrowed_string: &str = "world";
    
    let together = format!("{}{}", borrowed_string, another_borrowed_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{borrowed_string}{another_borrowed_string}");

    println!("{}", together);
}

Note that both input variables are immutable, so we know that they aren't touched. If we wanted to do the same thing for any combination of String, we can use the fact that String also can be formatted:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    let together = format!("{}{}", owned_string, another_owned_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{owned_string}{another_owned_string}");
    println!("{}", together);
}

You don't have to use format! though. You can clone one string and append the other string to the new string:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let together = owned_string.clone() + borrowed_string;
    println!("{}", together);
}

Note - all of the type specification I did is redundant - the compiler can infer all the types in play here. I added them simply to be clear to people new to Rust, as I expect this question to be popular with that group!

When to use NSInteger vs. int

OS X is "LP64". This means that:

int is always 32-bits.

long long is always 64-bits.

NSInteger and long are always pointer-sized. That means they're 32-bits on 32-bit systems, and 64 bits on 64-bit systems.

The reason NSInteger exists is because many legacy APIs incorrectly used int instead of long to hold pointer-sized variables, which meant that the APIs had to change from int to long in their 64-bit versions. In other words, an API would have different function signatures depending on whether you're compiling for 32-bit or 64-bit architectures. NSInteger intends to mask this problem with these legacy APIs.

In your new code, use int if you need a 32-bit variable, long long if you need a 64-bit integer, and long or NSInteger if you need a pointer-sized variable.

Node/Express file upload

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

// https://www.npmjs.com/package/formidable
const formidable    = require('formidable');

// https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js
const path          = require('path');

router.post('/upload', (req, res) => {
    console.log(req.files);

    let oldpath = req.files.fileUploaded.path;

    // https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js       
    let newpath = path.resolve( `./${req.files.fileUploaded.name}` );

    // copy
    // https://stackoverflow.com/questions/43206198/what-does-the-exdev-cross-device-link-not-permitted-error-mean
    fs.copyFile( oldpath, newpath, (err) => {

        if (err) throw err;

        // delete
        fs.unlink( oldpath, (err) => {

            if (err) throw err;

            console.log('Success uploaded")
        } );                

    } );

});

How to set portrait and landscape media queries in css?

It can also be as simple as this.

@media (orientation: landscape) {

}

How to reload or re-render the entire page using AngularJS

If you want to refresh the controller while refreshing any services you are using, you can use this solution:

  • Inject $state

i.e.

app.controller('myCtrl',['$scope','MyService','$state', function($scope,MyService,$state) {

    //At the point where you want to refresh the controller including MyServices

    $state.reload();

    //OR:

    $state.go($state.current, {}, {reload: true});
}

This will refresh the controller and the HTML as well you can call it Refresh or Re-Render.

Add tooltip to font awesome icon

The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a> tag:

   <Tooltip title="Node.js" >
     <a>
        <FontAwesomeIcon icon={faNode} size="2x" />
     </a>
   </Tooltip>

Sum across multiple columns with dplyr

I would use regular expression matching to sum over variables with certain pattern names. For example:

df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
                    sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))

This way you can create more than one variable as a sum of certain group of variables of your data frame.

How do I get a list of installed CPAN modules?

The answer can be found in the Perl FAQ list.

You should skim the excellent documentation that comes with Perl

perldoc perltoc

DB query builder toArray() laravel 4

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);

How to convert an object to a byte array in C#

Take a look at Serialization, a technique to "convert" an entire object to a byte stream. You may send it to the network or write it into a file and then restore it back to an object later.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

For one full day i searched online and i found a solution on my own. The same scenario, the application works fine in developer machine but when deployed it is throwing the exception "crystaldecisions.crystalreports.engine.reportdocument threw an exception" Details: sys.io.filenotfoundexcep crystaldecisions.reportappserver.commlayer version 13.0.2000 is missing

My IDE: MS VS 2010 Ultimate, CR V13.0.10

Solution:

  1. i set x86 for my application, then i set x64 for my setup application

  2. Prerequisite: i Placed the supporting CR runtime file CRRuntime_32bit_13_0_10.msi, CRRuntime_64bit_13_0_10.msi in the following directory C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\Crystal Reports for .NET Framework 4.0

  3. Include merge module file to the setup project. Here is version is not serious thing because i use 13.0.10 soft, 13.0.16 merge module file File i included: CRRuntime_13_0_16.msm This file is found one among the set msm files.

While installing this Merge module will add the necessary dll in the following dir C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI 4.0\win32_x86\dotnet

dll file version will not cause any issues.

In your developer machine you confirm it same.

I need reputation points, if this answer is useful kindly mark it useful(+1)

C++, What does the colon after a constructor mean?

You are calling the constructor of its base class, demo.

How to test code dependent on environment variables using JUnit?

The library https://github.com/webcompere/system-stubs/tree/master/system-stubs-jupiter - a fork of system-lambda - provides a JUnit 5 plug-in:

@ExtendWith(SystemStubsExtension.class)
class SomeTest {
    @SystemStub
    private EnvironmentVariables environmentVariables =
       new EnvironmentVariables("name", "value");

    @Test
    void someTest() {
       // environment is set here

       // can set a new value into the environment too
       environmentVariables.set("other", "value");

       // tidy up happens at end of this test
    }

}

The https://junit-pioneer.org/ alternative requires environment variable values to be known at compile time. The above also supports the setting of environment variables in the @BeforeAll, which means it interoperates well with things like Testcontainers that might set up some resources needed by child tests.

How to import Swagger APIs into Postman?

I work on PHP and have used Swagger 2.0 to document the APIs. The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.

Sample document

{
    "swagger": "2.0",
    "info": {
    "title": "Company Admin Panel",
        "description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
        "contact": {
        "email": "[email protected]"
        },
        "version": "1.0.0"
    },
    "host": "localhost/cv_admin/api",
    "schemes": [
    "http"
],
    "paths": {
    "/getCustomerByEmail.php": {
        "post": {
            "summary": "List the details of customer by the email.",
                "consumes": [
                "string",
                "application/json",
                "application/x-www-form-urlencoded"
            ],
                "produces": [
                "application/json"
            ],
                "parameters": [
                    {
                        "name": "email",
                        "in": "body",
                        "description": "Customer email to ge the data",
                        "required": true,
                        "schema": {
                        "properties": {
                            "id": {
                                "properties": {
                                    "abc": {
                                        "properties": {
                                            "inner_abc": {
                                                "type": "number",
                                                    "default": 1,
                                                    "example": 123
                                                }
                                            },
                                            "type": "object"
                                        },
                                        "xyz": {
                                        "type": "string",
                                            "default": "xyz default value",
                                            "example": "xyz example value"
                                        }
                                    },
                                    "type": "object"
                                }
                            }
                        }
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "Email required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getCustomerById.php": {
        "get": {
            "summary": "List the details of customer by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Customer ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getShipmentById.php": {
        "get": {
            "summary": "List the details of shipment by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Shipment ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the shipment"
                    },
                    "404": {
                    "description": "Shipment does not exist"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        }
    },
    "definitions": {

    }
}

This can be imported into Postman as follow.

  1. Click on the 'Import' button in the top left corner of Postman UI.
  2. You will see multiple options to import the API doc. Click on the 'Paste Raw Text'.
  3. Paste the JSON format in the text area and click import.
  4. You will see all your APIs as 'Postman Collection' and can use it from the Postman.

Importing the JSON into Postman

Imported APIs

You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.

This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.

<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;

Iterate through a C++ Vector using a 'for' loop

Here is a simpler way to iterate and print values in vector.

for(int x: A) // for integer x in vector A
    cout<< x <<" "; 

TypeError: 'float' object is not subscriptable

It looks like you are trying to set elements 0 through 11 of PriceList to new values. The syntax would usually look like this:

prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in [0, 1, 2, 3, 4, 5, 6]: PriceList[i] = PizzaChange
for i in [7, 8, 9, 10, 11]: PriceList[i] = PizzaChange + 3

If they are always consecutive ranges, then it's even simpler to write:

prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in range(0, 7): PriceList[i] = PizzaChange
for i in range(7, 12): PriceList[i] = PizzaChange + 3

For reference, PriceList[0][1][2][3][4][5][6] refers to "Element 6 of element 5 of element 4 of element 3 of element 2 of element 1 of element 0 of PriceList. Put another way, it's the same as ((((((PriceList[0])[1])[2])[3])[4])[5])[6].

MySQL - SELECT all columns WHERE one column is DISTINCT

SELECT DISTINCT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month

OR

SELECT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.

Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.

This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.

See also here:

The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.


In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.


1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I am using the following construct, although you might want to avoid shell=True. This gives you the output and error message for any command, and the error code as well:

process = subprocess.Popen(cmd, shell=True,
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode

How to directly execute SQL query in C#?

Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):

// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "

DataTable dt            = new DataTable() ;
int       rows_returned ;

const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
  select tPatCulIntPatIDPk ,
         tPatSFirstname    ,
         tPatSName         ,
         tPatDBirthday
  from dbo.TPatientRaw
  where tPatSName = @patientSurname
  " ;

using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand    cmd        = connection.CreateCommand() )
using ( SqlDataAdapter sda       = new SqlDataAdapter( cmd ) )
{
  cmd.CommandText = sqlQuery ;
  cmd.CommandType = CommandType.Text ;
  connection.Open() ;
  rows_returned = sda.Fill(dt) ;
  connection.Close() ;
}

if ( dt.Rows.Count == 0 )
{
  // query returned no rows
}
else
{

  //write semicolon-delimited header
  string[] columnNames = dt.Columns
                           .Cast<DataColumn>()
                           .Select( c => c.ColumnName )
                           .ToArray()
                           ;
  string   header      = string.Join("," , columnNames) ;
  Console.WriteLine(header) ;

  // write each row
  foreach ( DataRow dr in dt.Rows )
  {

    // get each rows columns as a string (casting null into the nil (empty) string
    string[] values = new string[dt.Columns.Count];
    for ( int i = 0 ; i < dt.Columns.Count ; ++i )
    {
      values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
    }

    // construct the string to be dumped, quoting each value and doubling any embedded quotes.
    string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
    Console.WriteLine(values);

  }

}