Programs & Examples On #Opcode cache

apc vs eaccelerator vs xcache

APC segfaults all day and all night, got no experience with eAccelerator but XCache is very reliable with loads of options and constant development.

What is the memory consumption of an object in Java?

Mindprod points out that this is not a straightforward question to answer:

A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.
For example, the JVM or native compiler might decide to store a boolean[] in 64-bit long chunks like a BitSet. It does not have to tell you, so long as the program gives the same answers.

  • It might allocate some temporary Objects on the stack.
  • It may optimize some variables or method calls totally out of existence replacing them with constants.
  • It might version methods or loops, i.e. compile two versions of a method, each optimized for a certain situation, then decide up front which one to call.

Then of course the hardware and OS have multilayer caches, on chip-cache, SRAM cache, DRAM cache, ordinary RAM working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption.

Measurement methods

You can use Instrumentation.getObjectSize() to obtain an estimate of the storage consumed by an object.

To visualize the actual object layout, footprint, and references, you can use the JOL (Java Object Layout) tool.

Object headers and Object references

In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. (From Dmitry Spikhalskiy's answer, Jayen's answer, and JavaWorld.)

Typically, references are 4 bytes on 32bit platforms or on 64bit platforms up to -Xmx32G; and 8 bytes above 32Gb (-Xmx32G). (See compressed object references.)

As a result, a 64-bit JVM would typically require 30-50% more heap space. (Should I use a 32- or a 64-bit JVM?, 2012, JDK 1.7)

Boxed types, arrays, and strings

Boxed wrappers have overhead compared to primitive types (from JavaWorld):

  • Integer: The 16-byte result is a little worse than I expected because an int value can fit into just 4 extra bytes. Using an Integer costs me a 300 percent memory overhead compared to when I can store the value as a primitive type

  • Long: 16 bytes also: Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like a Long is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast, Integer had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary.

Other containers are costly too:

  • Multidimensional arrays: it offers another surprise.
    Developers commonly employ constructs like int[dim1][dim2] in numerical and scientific computing.

    In an int[dim1][dim2] array instance, every nested int[dim2] array is an Object in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ.

    For example, a int[128][2] instance takes 3,600 bytes. Compared to the 1,040 bytes an int[256] instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case of byte[256][1], the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead.

  • String: a String's memory growth tracks its internal char array's growth. However, the String class adds another 24 bytes of overhead.

    For a nonempty String of size 10 characters or less, the added overhead cost relative to useful payload (2 bytes for each char plus 4 bytes for the length), ranges from 100 to 400 percent.

Alignment

Consider this example object:

class X {                      // 8 bytes for reference to the class definition
   int a;                      // 4 bytes
   byte b;                     // 1 byte
   Integer c = new Integer();  // 4 bytes for a reference
}

A naïve sum would suggest that an instance of X would use 17 bytes. However, due to alignment (also called padding), the JVM allocates the memory in multiples of 8 bytes, so instead of 17 bytes it would allocate 24 bytes.

Express-js can't GET my static files, why?

Webpack makes things awkward

As a supplement to all the other already existing solutions:

First things first: If you base the paths of your files and directories on the cwd (current working directory), things should work as usual, as the cwd is the folder where you were when you started node (or npm start, yarn run etc).

However...

If you are using webpack, __dirname behavior will be very different, depending on your node.__dirname settings, and your webpack version:

  1. In Webpack v4, the default behavior for __dirname is just /, as documented here.
    • In this case, you usually want to add this to your config which makes it act like the default in v5, that is __filename and __dirname now behave as-is but for the output file:
      module.exports = {
         // ...
         node: {
           // generate actual output file information
           // see: https://webpack.js.org/configuration/node/#node__filename
           __dirname: false,
           __filename: false,
         }
      };
      
    • This has also been discussed here.
  2. In Webpack v5, per the documentation here, the default is already for __filename and __dirname to behave as-is but for the output file, thereby achieving the same result as the config change for v4.

Example

For example, let's say:

  • you want to add the static public folder
  • it is located next to your output (usually dist) folder, and you have no sub-folders in dist, it's probably going to look like this
const ServerRoot = path.resolve(__dirname /** dist */, '..');
// ...
app.use(express.static(path.join(ServerRoot, 'public'))

(important: again, this is independent of where your source file is, only looks at where your output files are!)

More advanced Webpack scenarios

Things get more complicated if you have multiple entry points in different output directories, as the __dirname for the same file might be different for output file (that is each file in entry), depending on the location of the output file that this source file was merged into, and what's worse, the same source file might be merged into multiple different output files.

You probably want to avoid this kind of scenario scenario, or, if you cannot avoid it, use Webpack to manage and infuse the correct paths for you, possibly via the DefinePlugin or the EnvironmentPlugin.

How to run JUnit tests with Gradle?

How do I add a junit 4 dependency correctly?

Assuming you're resolving against a standard Maven (or equivalent) repo:

dependencies {
    ...
    testCompile "junit:junit:4.11"  // Or whatever version
}

Run those tests in the folders of tests/model?

You define your test source set the same way:

sourceSets {
    ...

    test {
        java {
            srcDirs = ["test/model"]  // Note @Peter's comment below
        }
    }
}

Then invoke the tests as:

./gradlew test

EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.

Is it possible to simulate key press events programmatically?

I wanted to simulate a 'Tab' press... Expanding on Trevor's answer, we can see that a special key like 'tab' does get pressed but we don't see the actual result which a 'tab' press would have...

tried with dispatching these events for 'activeElement' as well as the global document object both - code for both added below;

snippet below:

_x000D_
_x000D_
var element = document.getElementById("firstInput");

document.addEventListener("keydown", function(event) {

  console.log('we got key:', event.key, '  keyCode:', event.keyCode, '  charCode:', event.charCode);

  /* enter is pressed */
  if (event.keyCode == 13) {
    console.log('enter pressed:', event);

    setTimeout(function() {
      /*  event.keyCode = 13;  event.target.value += 'b';  */

      theKey = 'Tab';
      var e = new window.KeyboardEvent('focus', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('keydown', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('beforeinput', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('keypress', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('input', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('change', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('keyup', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.activeElement.dispatchEvent(e);
    }, 4);

    setTimeout(function() {
      theKey = 'Tab';
      var e = new window.KeyboardEvent('focus', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('keydown', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('beforeinput', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('keypress', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('input', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('change', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('keyup', {
        bubbles: true,
        key: theKey,
        keyCode: 9,
        charCode: 0,
      });
      document.dispatchEvent(e);
    }, 100);



  } else if (event.keyCode != 0) {
    console.log('we got a non-enter press...: :', event.key, '  keyCode:', event.keyCode, '  charCode:', event.charCode);
  }

});
_x000D_
<h2>convert each enter to a tab in JavaScript... check console for output</h2>
<h3>we dispatchEvents on the activeElement... and the global element as well</h3>

<input type='text' id='firstInput' />
<input type='text' id='secondInput' />

<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">
    Click me to display Date and Time.</button>
<p id="demo"></p>
_x000D_
_x000D_
_x000D_

How to color the Git console?

Well, if you are not satisfied with the default setting, you can use ANSI escape code to help you set the color, and if you want to modify some text, you can write bash to help you. see as below:

Eaxmplae

# .gitconfig

[alias]
    st-color = "!f() { \
        echo -n -e '\\033[38;2;255;0;01m\\033[4m' ;\
        git status -s | grep ' D' | \
        sed -e 's/^ ./DELETE:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[48;2;128;128;128m' ;\
        echo -n -e '\\033[38;2;0;255;01m' ;\
        git status -s | grep ' [AM]' | \
        sed -e 's/^ ./NEW OR MODIFY:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[38;2;255;0;255m' ;\
        echo Rename ;\
        git status -s | grep 'R ' | \
        sed -e 's/^..//' ; \
        echo -n -e '\\033[m' ;\
    }; f"

demo

enter image description here

Explanation

  1. you can write the long script on .gitconfig use the syntax as below:

    [alias]
        your-cmd = !f() { \
            \
        }; f"
    
  2. echo -n -e (see more echo)

    • -n = Do not output a trailing newline.
    • -e Enable interpretation of the following backslash-escaped
  3. \\033[38;2;255;0;0m\\033[4m (see more SGR parameters)

    • \\033[38;2;255;0;0m : 38 mean fore color. 255;0;0 = Red | r;g;b
    • \\033[4m : underline
  4. grep : The grep command is used to search text.

  5. sed -e 's/be_replace_string/new_string/' replace string to new string.

Converting a pointer into an integer

The best thing to do is to avoid converting from pointer type to non-pointer types. However, this is clearly not possible in your case.

As everyone said, the uintptr_t is what you should use.

This link has good info about converting to 64-bit code.

There is also a good discussion of this on comp.std.c

In JPA 2, using a CriteriaQuery, how to count results

You can also use Projections:

ProjectionList projection = Projections.projectionList();
projection.add(Projections.rowCount());
criteria.setProjection(projection);

Long totalRows = (Long) criteria.list().get(0);

Dynamic WHERE clause in LINQ

This is the solution I came up with if anyone is interested.

https://kellyschronicles.wordpress.com/2017/12/16/dynamic-predicate-for-a-linq-query/

First we identify the single element type we need to use ( Of TRow As DataRow) and then identify the “source” we are using and tie the identifier to that source ((source As TypedTableBase(Of TRow)). Then we must specify the predicate, or the WHERE clause that is going to be passed (predicate As Func(Of TRow, Boolean)) which will either be returned as true or false. Then we identify how we want the returned information ordered (OrderByField As String). Our function will then return a EnumerableRowCollection(Of TRow), our collection of datarows that have met the conditions of our predicate(EnumerableRowCollection(Of TRow)). This is a basic example. Of course you must make sure your order field doesn’t contain nulls, or have handled that situation properly and make sure your column names (if you are using a strongly typed datasource never mind this, it will rename the columns for you) are standard.

Selecting a row of pandas series/dataframe by integer index

echoing @HYRY, see the new docs in 0.11

http://pandas.pydata.org/pandas-docs/stable/indexing.html

Here we have new operators, .iloc to explicity support only integer indexing, and .loc to explicity support only label indexing

e.g. imagine this scenario

In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))

In [2]: df
Out[2]: 
          A         B
0  1.068932 -0.794307
2 -0.470056  1.192211
4 -0.284561  0.756029
6  1.037563 -0.267820
8 -0.538478 -0.800654

In [5]: df.iloc[[2]]
Out[5]: 
          A         B
4 -0.284561  0.756029

In [6]: df.loc[[2]]
Out[6]: 
          A         B
2 -0.470056  1.192211

[] slices the rows (by label location) only

Best Practice: Access form elements by HTML id or name attribute?

I much prefer a 5th method. That is
[5] Use the special JavaScript identifier this to pass the form or field object to the function from the event handler.

Specifically, for forms:

<form id="form1" name="form1" onsubmit="return validateForm(this)">

and

// The form validation function takes the form object as the input parameter
function validateForm(thisForm) {
  if (thisform.fullname.value !=...

Using this technique, the function never has to know
- the order in which forms are defined in the page,
- the form ID, nor
- the form name

Similarly, for fields:

<input type="text" name="maxWeight">
...
<input type="text" name="item1Weight" onchange="return checkWeight(this)">
<input type="text" name="item2Weight" onchange="return checkWeight(this)">

and

function checkWeight(theField) {
  if (theField.value > theField.form.maxWeight.value) {
    alert ("The weight value " + theField.value + " is larger than the limit");
    return false;
  }
return true;
}

In this case, the function never has to know the name or id of a particular weight field, though it does need to know the name of the weight limit field.

how do you pass images (bitmaps) between android activities using bundles?

Bitmap is Parcelable so you can add using [putExtra(String,Parcelable)][2] method, But not sure it is a best practice, If it is large size data it is better to store in a single place and use from both activities.

[2]: http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Parcelable)

What is external linkage and internal linkage?

In terms of 'C' (Because static keyword has different meaning between 'C' & 'C++')

Lets talk about different scope in 'C'

SCOPE: It is basically how long can I see something and how far.

  1. Local variable : Scope is only inside a function. It resides in the STACK area of RAM. Which means that every time a function gets called all the variables that are the part of that function, including function arguments are freshly created and are destroyed once the control goes out of the function. (Because the stack is flushed every time function returns)

  2. Static variable: Scope of this is for a file. It is accessible every where in the file
    in which it is declared. It resides in the DATA segment of RAM. Since this can only be accessed inside a file and hence INTERNAL linkage. Any
    other files cannot see this variable. In fact STATIC keyword is the only way in which we can introduce some level of data or function
    hiding in 'C'

  3. Global variable: Scope of this is for an entire application. It is accessible form every where of the application. Global variables also resides in DATA segment Since it can be accessed every where in the application and hence EXTERNAL Linkage

By default all functions are global. In case, if you need to hide some functions in a file from outside, you can prefix the static keyword to the function. :-)

MySQL Job failed to start

Reinstallation will works because it will reset all the value to default. It is better to find what the real culprits (my.cnf editing mistake does happens, e.g. bad/outdated parameter suggestion during mysql tuning.)

Here is the mysql diagnosis if you suspect some value is wrong inside my.cnf : Run the mysqld to show you the results.

sudo -u mysql  mysqld 

Afterwards, fix all the my.cnf key error that pop out from the screen until mysqld startup successfully.

Then restart it using

sudo service mysql restart

Is there a destructor for Java?

I fully agree to other answers, saying not to rely on the execution of finalize.

In addition to try-catch-finally blocks, you may use Runtime#addShutdownHook (introduced in Java 1.3) to perform final cleanups in your program.

That isn't the same as destructors are, but one may implement a shutdown hook having listener objects registered on which cleanup methods (close persistent database connections, remove file locks, and so on) can be invoked - things that would normally be done in destructors. Again - this is not a replacement for destructors but in some cases, you can approach the wanted functionality with this.

The advantage of this is having deconstruction behavior loosely coupled from the rest of your program.

Is there an operator to calculate percentage in Python?

You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:

def percentage(part, whole):
  return 100 * float(part)/float(whole)

Or with a % at the end:

 def percentage(part, whole):
  Percentage = 100 * float(part)/float(whole)
  return str(Percentage) + “%”

Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:

def percentage(percent, whole):
  return (percent * whole) / 100.0

How to stop and restart memcached server?

To shutdown memcache daemon:

sudo service memcached stop

To start memcached daemon:

sudo service memcached start

Restart memcached server:

sudo service memcached restart

You can see if Memcache is currently runing:

sudo ps -e | grep memcached

And you can check the TCP or UDP ports if something (e.g. Memcache) is listening to it:

netstat -ap | grep TheChosenPort#
netstat -ap | grep 11211

For some Linuxes you need to change your commands like:

sudo /etc/init.d/memcached start
sudo /etc/init.d/memcached restart
sudo /etc/init.d/memcached stop

test attribute in JSTL <c:if> tag

Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.

If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

How to plot data from multiple two column text files with legends in Matplotlib?

I feel the simplest way would be

 from matplotlib import pyplot;
 from pylab import genfromtxt;  
 mat0 = genfromtxt("data0.txt");
 mat1 = genfromtxt("data1.txt");
 pyplot.plot(mat0[:,0], mat0[:,1], label = "data0");
 pyplot.plot(mat1[:,0], mat1[:,1], label = "data1");
 pyplot.legend();
 pyplot.show();
  1. label is the string that is displayed on the legend
  2. you can plot as many series of data points as possible before show() to plot all of them on the same graph This is the simple way to plot simple graphs. For other options in genfromtxt go to this url.

Set default syntax to different filetype in Sublime Text 2

Go to a Packages/User, create (or edit) a .sublime-settings file named after the Syntax where you want to add the extensions, Ini.sublime-settings in your case, then write there something like this:

{
    "extensions":["cfg"]
}

And then restart Sublime Text

ScrollIntoView() causing the whole page to move

Using Brilliant's idea, here's a solution that only (vertically) scrolls if the element is NOT currently visible. The idea is to get the bounding box of the viewport and the element to be displayed in browser-window coordinate space. Check if it's visible and if not, scroll by the required distance so the element is shown at the top or bottom of the viewport.

    function ensure_visible(element_id)
    {
        // adjust these two to match your HTML hierarchy
        var element_to_show  = document.getElementById(element_id);
        var scrolling_parent = element_to_show.parentElement;

        var top = parseInt(scrolling_parent.getBoundingClientRect().top);
        var bot = parseInt(scrolling_parent.getBoundingClientRect().bottom);

        var now_top = parseInt(element_to_show.getBoundingClientRect().top);
        var now_bot = parseInt(element_to_show.getBoundingClientRect().bottom);

        // console.log("Element: "+now_top+";"+(now_bot)+" Viewport:"+top+";"+(bot) );

        var scroll_by = 0;
        if(now_top < top)
            scroll_by = -(top - now_top);
        else if(now_bot > bot)
            scroll_by = now_bot - bot;
        if(scroll_by != 0)
        {
            scrolling_parent.scrollTop += scroll_by; // tr.offsetTop;
        }
    }

Sum of two input value by jquery

_x000D_
_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
var a =parseInt($("#a").val());_x000D_
var b =parseInt($("#b").val());_x000D_
$("#submit").on("click",function(){_x000D_
var sum = a + b;_x000D_
alert(sum);_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

equivalent of rm and mv in windows .cmd

move in windows is equivalent of mv command in Linux

del in windows is equivalent of rm command in Linux

Get real path from URI, Android KitKat new storage access framework

Here is an updated version of Paul Burke's answer. In versions below Android 4.4 (KitKat) we don't have the DocumentsContract class.

In order to work on versions below KitKat create this class:

public class DocumentsContract {
    private static final String DOCUMENT_URIS =
        "com.android.providers.media.documents " +
        "com.android.externalstorage.documents " +
        "com.android.providers.downloads.documents " +
        "com.android.providers.media.documents";

    private static final String PATH_DOCUMENT = "document";
    private static final String TAG = DocumentsContract.class.getSimpleName();

    public static String getDocumentId(Uri documentUri) {
        final List<String> paths = documentUri.getPathSegments();
        if (paths.size() < 2) {
            throw new IllegalArgumentException("Not a document: " + documentUri);
        }

        if (!PATH_DOCUMENT.equals(paths.get(0))) {
            throw new IllegalArgumentException("Not a document: " + documentUri);
        }
        return paths.get(1);
    }

    public static boolean isDocumentUri(Uri uri) {
        final List<String> paths = uri.getPathSegments();
        Logger.v(TAG, "paths[" + paths + "]");
        if (paths.size() < 2) {
            return false;
        }
        if (!PATH_DOCUMENT.equals(paths.get(0))) {
            return false;
        }
        return DOCUMENT_URIS.contains(uri.getAuthority());
    }
}

How can I get a precise time, for example in milliseconds in Objective-C?

For those we need the Swift version of the answer of @Jeff Thompson:

// Get a current time for where you want to start measuring from
var date = NSDate()

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
var timePassed_ms: Double = date.timeIntervalSinceNow * -1000.0

I hope this help you.

What is the difference between ng-if and ng-show/ng-hide

ngIf

The ngIf directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

<!-- when $scope.myValue is truthy (element is restored) -->
<div ng-if="1"></div>

<!-- when $scope.myValue is falsy (element is removed) -->
<div ng-if="0"></div>

When an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf inherits from its parent scope using prototypal inheritance.

If ngModel is used within ngIf to bind to a JavaScript primitive defined in the parent scope, any modifications made to the variable within the child scope will not affect the value in the parent scope, e.g.

<input type="text" ng-model="data">
<div ng-if="true">
    <input type="text" ng-model="data">
</div>        

To get around this situation and update the model in the parent scope from inside the child scope, use an object:

<input type="text" ng-model="data.input">
<div ng-if="true">
    <input type="text" ng-model="data.input">
</div>

Or, $parent variable to reference the parent scope object:

<input type="text" ng-model="data">
<div ng-if="true">
    <input type="text" ng-model="$parent.data">
</div>

ngShow

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag).

<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="1"></div>

<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="0" class="ng-hide"></div>

When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute on the element causing it to become hidden. When true, the ng-hide CSS class is removed from the element causing the element not to appear hidden.

How do I format axis number format to thousands with a comma in matplotlib?

Use , as format specifier:

>>> format(10000.21, ',')
'10,000.21'

Alternatively you can also use str.format instead of format:

>>> '{:,}'.format(10000.21)
'10,000.21'

With matplotlib.ticker.FuncFormatter:

...
ax.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
ax2.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig1.show()

enter image description here

VB.NET Connection string (Web.Config, App.Config)

Connection in APPConfig

<connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public string ConnectionString
{
    get
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    }
}

What, exactly, is needed for "margin: 0 auto;" to work?

Off the top of my head, if the element is not a block element - make it so.

and then give it a width.

Download history stock prices automatically from yahoo finance in python

You can check out the yahoo_fin package. It was initially created after Yahoo Finance changed their API (documentation is here: http://theautomatic.net/yahoo_fin-documentation).

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")

aapl_data.head()

nflx_data.head()

aapl.to_csv("aapl_data.csv")

nflx_data.to_csv("nflx_data.csv")

Should I use window.navigate or document.location in JavaScript?

support for document.location is also good though its a deprecated method. I've been using this method for a while with no problems. you can refer here for more details:

https://developer.mozilla.org/en-US/docs/Web/API/document.location

Escaping quotation marks in PHP

Use a backslash as such

"From time to \"time\"";

Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this

'From time to "time"';

The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such

$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"

As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:

$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;

How to add a JAR in NetBeans

You want to add libraries to your project and in doing so you have two options as you yourself identified:

Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.

This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).

Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.

As for the other alernatives you have either global libraries using Library Manageror jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager.

Difference between scaling horizontally and vertically for databases

There is an additional architecture that wasn't mentioned - SQL-based database services that enable horizontal scaling without the complexity of manual sharding. These services do the sharding in the background, so they enable you to run a traditional SQL database and scale out like you would with NoSQL engines like MongoDB or CouchDB. Two services I am familiar with are EnterpriseDB for PostgreSQL and Xeround for MySQL. I saw an in-depth post by Xeround which explains why scale-out on SQL databases is difficult and how they do it differently - treat this with a grain of salt as it is a vendor post. Also check out Wikipedia's Cloud Database entry, there is a nice explanation of SQL vs. NoSQL and service vs. self-hosted, a list of vendors and scaling options for each combination. ;)

How to set up datasource with Spring for HikariCP?

I found it in http://www.baeldung.com/hikaricp and it works.

Your pom.xml

<dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.6.3</version>
        </dependency>

Your data.xml

<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="jdbcUrl" value="${jdbc.databaseurl}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
      p:dataSource-ref="dataSource"
/>

Your jdbc.properties

jdbc.driverClassName=org.postgresql.Driver
jdbc.dialect=org.hibernate.dialect.PostgreSQL94Dialect
jdbc.databaseurl=jdbc:postgresql://localhost:5432/dev_db
jdbc.username=dev
jdbc.password=dev

How do I setup the InternetExplorerDriver so it works

Unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

File file = new File("C:/Selenium/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();

Basically, you have to set this property before you initialize driver

Reference:

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

I added the control to the Triggers tag in the update panel:

    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="exportLinkButton" />
    </Triggers>
</asp:UpdatePanel>

This way the exportLinkButton will trigger the UpdatePanel to update.
More info here.

iterating through Enumeration of hastable keys throws NoSuchElementException error

Each time you do e.nextElement() you skip one. So you skip two elements in each iteration of your loop.

Can't use Swift classes inside Objective-C

I just discovered that adding a directory of swift files to a project won't work. You need to create a group first for the directory, then add the swift files...

How to use auto-layout to move other views when a view is hidden?

In case this helps someone, I built a helper class for using visual format constraints. I'm using it in my current app.

AutolayoutHelper

It might be a bit tailored to my needs, but you might find it useful or you might want to modify it and create your own helper.

I have to thank Tim for his answer above, this answer about UIScrollView and also this tutorial.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

    public string ToBase26(int number)
    {
        if (number < 0) return String.Empty;

        int remainder = number % 26;
        int value = number / 26;

        return value == 0 ?
            String.Format("{0}", Convert.ToChar(65 + remainder)) :
            String.Format("{0}{1}", ToBase26(value - 1), Convert.ToChar(65 + remainder));
    }

how to create and call scalar function in sql server 2008

Or you can simply use PRINT command instead of SELECT command. Try this,

PRINT dbo.fn_HomePageSlider(9, 3025)

Download/Stream file from URL - asp.net

The accepted solution from Dallas was working for us if we use Load Balancer on the Citrix Netscaler (without WAF policy).

The download of the file doesn't work through the LB of the Netscaler when it is associated with WAF as the current scenario (Content-length not being correct) is a RFC violation and AppFW resets the connection, which doesn't happen when WAF policy is not associated.

So what was missing was:

Response.End();

See also: Trying to stream a PDF file with asp.net is producing a "damaged file"

Is the Javascript date object always one day off?

I believe that it has to do with time-zone adjustment. The date you've created is in GMT and the default time is midnight, but your timezone is EDT, so it subtracts 4 hours. Try this to verify:

var doo = new Date("2011-09-25 EDT");

long long in C/C++

Try:

num3 = 100000000000LL;

And BTW, in C++ this is a compiler extension, the standard does not define long long, thats part of C99.

Div Scrollbar - Any way to style it?

This one does well its scrolling job. It's very easy to understand, just really few lines of code, well written and totally readable.

Converting an int to std::string

#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

Using reCAPTCHA on localhost

Recaptcha will not work on localhost/

Use `127.0.0.1/` instead of `localhost/`

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

I had this error message with boot2docker on windows with the docker-oracle-xe-11g image (https://registry.hub.docker.com/u/wnameless/oracle-xe-11g/).

The reason was that the virtual box disk was full (check with boot2docker.exe ssh df). Deleting old images and restarting the container solved the problem.

Adding space/padding to a UILabel

In Swift 3

best and simple way

class UILabelPadded: UILabel {
     override func drawText(in rect: CGRect) {
     let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
     super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

}

How to find the index of an element in an array in Java?

I believe the only sanest way to do this is to manually iterate through the array.

for (int i = 0; i < list.length; i++) {
  if (list[i] == 'e') {
    System.out.println(i);
    break;
  }
}

"No resource identifier found for attribute 'showAsAction' in package 'android'"

Add compat library compilation to the build.gradle file:

compile 'com.android.support:appcompat-v7:19.+'

Given URL is not allowed by the Application configuration

The problem is that whatever url you are currently hosting your app is not setup in your Application configuration. Go to your app settings and ensure the urls are matching.

Updated

Steps:

  1. Go to 'Basic' settings for your app
  2. Select 'Add Platform'
  3. Select 'Website'
  4. Put your website URL under 'Site URL'

enter image description here

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

Group by with union mysql select query

select sum(qty), name
from (
    select count(m.owner_id) as qty, o.name
    from transport t,owner o,motorbike m
    where t.type='motobike' and o.owner_id=m.owner_id
        and t.type_id=m.motorbike_id
    group by m.owner_id

    union all

    select count(c.owner_id) as qty, o.name,
    from transport t,owner o,car c
    where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
    group by c.owner_id
) t
group by name

asp.net validation to make sure textbox has integer values

http://msdn.microsoft.com/en-us/library/ad548tzy%28VS.71%29.aspx

When using Server validator controls you have to be careful about fact that any one can disable javascript in their browser. So you should use Page.IsValid Property always at server side.

Android: keeping a background service alive (preventing process death)

As Dave already pointed out, you could run your Service with foreground priority. But this practice should only be used when it's absolutely necessary, i.e. when it would cause a bad user experience if the Service got killed by Android. This is what the "foreground" really means: Your app is somehow in the foreground and the user would notice it immediately if it's killed (e.g. because it played a song or a video).

In most cases, requesting foreground priority for your Service is contraproductive!

Why is that? When Android decides to kill a Service, it does so because it's short of resources (usually RAM). Based on the different priority classes, Android decides which running processes, and this included services, to terminate in order to free resources. This is a healthy process that you want to happen so that the user has a smooth experience. If you request foreground priority, without a good reason, just to keep your service from being killed, it will most likely cause a bad user experience. Or can you guarantee that your service stays within a minimal resource consumption and has no memory leaks?1

Android provides sticky services to mark services that should be restarted after some grace period if they got killed. This restart usually happens within a few seconds.

Image you want to write an XMPP client for Android. Should you request foreground priority for the Service which contains your XMPP connection? Definitely no, there is absolutely no reason to do so. But you want to use START_STICKY as return flag for your service's onStartCommand method. So that your service is stopped when there is resource pressure and restarted once the situation is back to normal.

1: I am pretty sure that many Android apps have memory leaks. It something the casual (desktop) programmer doesn't care that much about.

Margin on child element moves parent element

the parent element has not to be empty at least put &nbsp; before the child element.

How to capitalize first letter of each word, like a 2-word city?

function convertCase(str) {
  var lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}

Auto insert date and time in form input field?

The fastest way to get date formatting thats any good is to use datejs.

The lib is really easy to use and does give you very pretty formatting.


as far as your code snippet, dont use document.write if you can help it. try

 document.getElementById("date").value = new Date().toUTCString(); 

What is the best way to prevent session hijacking?

Have you considered reading a book on PHP security? Highly recommended.

I have had much success with the following method for non SSL certified sites.

  1. Dis-allow multiple sessions under the same account, making sure you aren't checking this solely by IP address. Rather check by token generated upon login which is stored with the users session in the database, as well as IP address, HTTP_USER_AGENT and so forth

  2. Using Relation based hyperlinks Generates a link ( eg. http://example.com/secure.php?token=2349df98sdf98a9asdf8fas98df8 ) The link is appended with a x-BYTE ( preferred size ) random salted MD5 string, upon page redirection the randomly generated token corresponds to a requested page.

    • Upon reload, several checks are done.
    • Originating IP Address
    • HTTP_USER_AGENT
    • Session Token
    • you get the point.
  3. Short Life-span session authentication cookie. as posted above, a cookie containing a secure string, which is one of the direct references to the sessions validity is a good idea. Make it expire every x Minutes, reissuing that token, and re-syncing the session with the new Data. If any mis-matches in the data, either log the user out, or having them re-authenticate their session.

I am in no means an expert on the subject, I'v had a bit of experience in this particular topic, hope some of this helps anyone out there.

What is Ad Hoc Query?

Ad-hoc Query -

  • this type of query is designed for a "particular purpose,“ which is in contrast to a predefined query, which has the same output value on every execution.
  • An ad hoc query command executed in each time, but the result is different, depending on the value of the variable.
  • It cannot be predetermined and usually comes under dynamic programming SQL query.
  • An ad hoc query is short lived and is created at runtime.

What is the MySQL JDBC driver connection string?

Check if the Driver Connector jar matches the SQL version.

I was also getting the same error as I was using the

mySQl-connector-java-5.1.30.jar

with MySql 8

How do I select a MySQL database through CLI?

Alternatively, you can give the "full location" to the database in your queries a la:

SELECT photo_id FROM [my database name].photogallery;

If using one more often than others, use USE. Even if you do, you can still use the database.table syntax.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

I prefer to create an event:

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

Here is how you create it:

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

You could have this in a global javascript file somewhere.

How to test the type of a thrown exception in Jest

Try:

expect(t).rejects.toThrow()

How to check if object has any properties in JavaScript?

How about this?

var obj = {},
var isEmpty = !obj;
var hasContent = !!obj

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

Calculate execution time of a SQL query?

You can use

SET STATISTICS TIME { ON | OFF }

Displays the number of milliseconds required to parse, compile, and execute each statement

When SET STATISTICS TIME is ON, the time statistics for a statement are displayed. When OFF, the time statistics are not displayed

USE AdventureWorks2012;  
GO         
SET STATISTICS TIME ON;  
GO  
SELECT ProductID, StartDate, EndDate, StandardCost   
FROM Production.ProductCostHistory  
WHERE StandardCost < 500.00;  
GO  
SET STATISTICS TIME OFF;  
GO  

Git copy changes from one branch to another

This is 2 step process

  • git checkout BranchB ( destination branch is BranchB, so we need the head on this branch)
  • git merge BranchA (it will merge BranchB with BranchA. Here you have merged code in branch B)

If you want to push your branch code to remote repo then do

  • git push origin master (it will push your BranchB code to remote repo)

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

High Quality Image Scaling Library

You could try the magic kernel. It produces less pixelation artifacts than bicubic resample when upscaling and it also gives very good results when downscaling. The source code is available in c# from the web site.

How to line-break from css, without using <br />?

At the CSS use the code

p {
    white-space: pre-line;
}

With this code css every enter inside the P tag will be a break-line at the html.

Android WebView, how to handle redirects in app instead of opening a browser

Please use the below kotlin code

webview.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {   
                view.loadUrl(url)
                return false 
            }
        })

For more info click here

How can I add comments in MySQL?

Three types of commenting are supported

  1. Hash base single line commenting using #

    Select * from users ; # this will list users
    
    1. Double Dash commenting using --

    Select * from users ; -- this will list users

Note : Its important to have single white space just after --

3) Multi line commenting using /* */

Select * from users ; /* this will list users */

Controlling a USB power supply (on/off) with Linux

The reason why folks post questions such as this is due to the dreaded- indeed "EVIL"- USB Auto-Suspend "feature".

Auto suspend winds-down the power to an "idle" USB device and unless the device's driver supports this feature correctly, the device can become uncontactable. So powering a USB port on/off is a symptom of the problem, not the problem in itself.

I'll show you how to GLOBALLY disable auto-suspend, negating the need to manually toggle the USB ports on & off:

Short Answer:

You do NOT need to edit "autosuspend_delay_ms" individually: USB autosuspend can be disabled globally and PERSISTENTLY using the following commands:

sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/&usbcore.autosuspend=-1 /' /etc/default/grub

update-grub

systemctl reboot

An Ubuntu 18.04 screen-grab follows at the end of the "Long Answer" illustrating how my results were achieved.

Long Answer:

It's true that the USB Power Management Kernel Documentation states autosuspend is to be deprecated and in in its' place "autosuspend_delay_ms" used to disable USB autosuspend:

"In 2.6.38 the "autosuspend" file will be deprecated
and replaced by the "autosuspend_delay_ms" file."

HOWEVER my testing reveals that setting usbcore.autosuspend=-1 in /etc/default/grub as below can be used as a GLOBAL toggle for USB autosuspend functionality- you do NOT need to edit individual "autosuspend_delay_ms" files.

The same document linked above states a value of "0" is ENABLED and a negative value is DISABLED:

power/autosuspend_delay_ms

    <snip> 0 means to autosuspend
    as soon as the device becomes idle, and negative
    values mean never to autosuspend.  You can write a
    number to the file to change the autosuspend
    idle-delay time.

In the annotated Ubuntu 18.04 screen-grab below illustrating how my results were achieved (and reproducible), please remark the default is "0" (enabled) in autosuspend_delay_ms.

Then note that after ONLY setting usbcore.autosuspend=-1 in Grub, these values are now negative (disabled) after reboot. This will save me the bother of editing individual values and can now script disabling USB autosuspend.

screengrab: autosuspend values Before and after globally editing

Hope this makes disabling USB autosuspend a little easier and more scriptable-

How to extract elements from a list using indices in Python?

I think you're looking for this:

elements = [10, 11, 12, 13, 14, 15]
indices = (1,1,2,1,5)

result_list = [elements[i] for i in indices]    

Proper usage of Java -D command-line parameters

You're giving parameters to your program instead to Java. Use

java -Dtest="true" -jar myApplication.jar 

instead.

Consider using

"true".equalsIgnoreCase(System.getProperty("test"))

to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like

System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")

is right (providing default true). A shorter possibility is

!"false".equalsIgnoreCase(System.getProperty("test"))

but not using double negation doesn't make it less hard to misunderstand.

Execute another jar in a Java program

.jar isn't executable. Instantiate classes or make call to any static method.

EDIT: Add Main-Class entry while creating a JAR.

>p.mf (content of p.mf)

Main-Class: pk.Test

>Test.java

package pk;
public class Test{
  public static void main(String []args){
    System.out.println("Hello from Test");
  }
}

Use Process class and it's methods,

public class Exec
{
   public static void main(String []args) throws Exception
    {
        Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
        ps.waitFor();
        java.io.InputStream is=ps.getInputStream();
        byte b[]=new byte[is.available()];
        is.read(b,0,b.length);
        System.out.println(new String(b));
    }
}

add column to mysql table if it does not exist

Note that INFORMATION_SCHEMA isn't supported in MySQL prior to 5.0. Nor are stored procedures supported prior to 5.0, so if you need to support MySQL 4.1, this solution isn't good.

One solution used by frameworks that use database migrations is to record in your database a revision number for the schema. Just a table with a single column and single row, with an integer indicating which revision is current in effect. When you update the schema, increment the number.

Another solution would be to just try the ALTER TABLE ADD COLUMN command. It should throw an error if the column already exists.

ERROR 1060 (42S21): Duplicate column name 'newcolumnname'

Catch the error and disregard it in your upgrade script.

Convert LocalDateTime to LocalDateTime in UTC

tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTime wrong.

The reason is that LocalDateTime does not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.

As a matter of fact, LocalDateTime.now() should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTime instance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.

LocalDateTime can simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.

E.g.:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"

You can view the dump from the console on the mentioned path.

How should I pass multiple parameters to an ASP.Net Web API GET?

I know this is really old, but I wanted the same thing recently and here's what I found...

    public HttpResponseMessage Get([FromUri] string var, [FromUri] string test) {
        var retStr = new HttpResponseMessage(HttpStatusCode.OK);
        if (var.ToLower() == "getnew" && test.ToLower() == "test") {
            retStr.Content = new StringContent("Found Test", System.Text.Encoding.UTF8, "text/plain");
        } else {
            retStr.Content = new StringContent("Couldn't Find that test", System.Text.Encoding.UTF8, "text/plain");
        }

        return retStr;
    }

So now in your address/URI/...

http(s)://myURL/api/myController/?var=getnew&test=test

Result: "Found Test"


http(s)://myURL/api/myController/?var=getnew&test=anything

Result: "Couldn't Find that test"

What size should apple-touch-icon.png be for iPad and iPhone?

TL;DR: use one PNG icon at 180 x 180 px @ 150 ppi and then link to it like this:

<link rel="apple-touch-icon" href="path/to/apple-touch-icon.png">

Details on the Approach

As of 2020-04, the canonical response from Apple is reflected in their documentation on iOS.

Officially, the spec says:

  • iPhone 180px × 180px (60pt × 60pt @3x)
  • iPhone 120px × 120px (60pt × 60pt @2x)
  • iPad Pro 167px × 167px (83.5pt × 83.5pt @2x)
  • iPad, iPad mini 152px × 152px (76pt × 76pt @2x)

In reality, these sizing differences are tiny, so the performance savings will really only matter on very high traffic sites.

For lower traffic sites, I typically use one PNG icon at 180 x 180 px @ 150 ppi and get very good results on all devices, even the plus sized ones.

How to print out all the elements of a List in Java?

I have faced similar problems. My code:

List<Integer> leaveDatesList = new ArrayList<>();

.....inserted value in list.......

Way 1: printing a list in a for loop

for(int i=0;i<leaveDatesList.size();i++){
    System.out.println(leaveDatesList.get(i));
}

Way 2: printing the list in a forEach, for loop

for(Integer leave : leaveDatesList){
    System.out.println(leave);
}

Way 3: printing the list in java 8

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

Get difference between two lists

The difference between two lists (say list1 and list2) can be found using the following simple function.

def diff(list1, list2):
    c = set(list1).union(set(list2))  # or c = set(list1) | set(list2)
    d = set(list1).intersection(set(list2))  # or d = set(list1) & set(list2)
    return list(c - d)

or

def diff(list1, list2):
    return list(set(list1).symmetric_difference(set(list2)))  # or return list(set(list1) ^ set(list2))

By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2). Both will give the result ['Four', 'Three']. You don't have to worry about the order of the list or which list is to be given first.

Python doc reference

htaccess redirect to https://www

Michals answer worked for me, albeit with one small modification:

Problem:

when you have a single site security certificate, a browser that tries to access your page without https:// www. (or whichever domain your certificate covers) will display an ugly red warning screen before it even gets to receive the redirect to the safe and correct https page.

Solution

First use the redirect to the www (or whichever domain is covered by your certificate) and only then do the https redirect. This will ensure that your users are not confronted with any error because your browser sees a certificate that doesn't cover the current url.

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Deploy a project using Git push

Using the post-update file below:

  1. Copy over your .git directory to your web server
  2. On your local copy, modify your .git/config file and add your web server as a remote:

    [remote "production"]
        url = username@webserver:/path/to/htdocs/.git
    
  3. On the server, replace .git/hooks/post-update with file below

  4. Add execute access to the file (again, on the server):

    chmod +x .git/hooks/post-update
    
  5. Now, just locally push to your web server and it should automatically update the working copy:

    git push production
    
#!/bin/sh
#
# This hook does two things:
#
#  1. update the "info" files that allow the list of references to be
#     queries over dumb transports such as http
#
#  2. if this repository looks like it is a non-bare repository, and
#     the checked-out branch is pushed to, then update the working copy.
#     This makes "push" function somewhat similarly to darcs and bzr.
#
# To enable this hook, make this file executable by "chmod +x post-update". 
git-update-server-info 
is_bare=$(git-config --get --bool core.bare) 
if [ -z "$is_bare" ]
then
      # for compatibility's sake, guess
      git_dir_full=$(cd $GIT_DIR; pwd)
      case $git_dir_full in */.git) is_bare=false;; *) is_bare=true;; esac
fi 
update_wc() {
      ref=$1
      echo "Push to checked out branch $ref" >&2
      if [ ! -f $GIT_DIR/logs/HEAD ]
      then
             echo "E:push to non-bare repository requires a HEAD reflog" >&2
             exit 1
      fi
      if (cd $GIT_WORK_TREE; git-diff-files -q --exit-code >/dev/null)
      then
             wc_dirty=0
      else
             echo "W:unstaged changes found in working copy" >&2
             wc_dirty=1
             desc="working copy"
      fi
      if git diff-index --cached HEAD@{1} >/dev/null
      then
             index_dirty=0
      else
             echo "W:uncommitted, staged changes found" >&2
             index_dirty=1
             if [ -n "$desc" ]
             then
                   desc="$desc and index"
             else
                   desc="index"
             fi
      fi
      if [ "$wc_dirty" -ne 0 -o "$index_dirty" -ne 0 ]
      then
             new=$(git rev-parse HEAD)
             echo "W:stashing dirty $desc - see git-stash(1)" >&2
             ( trap 'echo trapped $$; git symbolic-ref HEAD "'"$ref"'"' 2 3 13 15 ERR EXIT
             git-update-ref --no-deref HEAD HEAD@{1}
             cd $GIT_WORK_TREE
             git stash save "dirty $desc before update to $new";
             git-symbolic-ref HEAD "$ref"
             )
      fi 
      # eye candy - show the WC updates :)
      echo "Updating working copy" >&2
      (cd $GIT_WORK_TREE
      git-diff-index -R --name-status HEAD >&2
      git-reset --hard HEAD)
} 
if [ "$is_bare" = "false" ]
then
      active_branch=`git-symbolic-ref HEAD`
      export GIT_DIR=$(cd $GIT_DIR; pwd)
      GIT_WORK_TREE=${GIT_WORK_TREE-..}
      for ref
      do
             if [ "$ref" = "$active_branch" ]
             then
                   update_wc $ref
             fi
      done
fi

How to change string into QString?

If by string you mean std::string you can do it with this method:

QString QString::fromStdString(const std::string & str)

std::string str = "Hello world";
QString qstr = QString::fromStdString(str);

If by string you mean Ascii encoded const char * then you can use this method:

QString QString::fromAscii(const char * str, int size = -1)

const char* str = "Hello world";
QString qstr = QString::fromAscii(str);

If you have const char * encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:

QString QString::fromLocal8Bit(const char * str, int size = -1)

const char* str = "zazólc gesla jazn";      // latin2 source file and system encoding
QString qstr = QString::fromLocal8Bit(str);

If you have const char * that's UTF8 encoded then you'll need to use this method:

QString QString::fromUtf8(const char * str, int size = -1)

const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
QString qstr = QString::fromUtf8(str);

There's also method for const ushort * containing UTF16 encoded string:

QString QString::fromUtf16(const ushort * unicode, int size = -1)

const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
QString qstr = QString::fromUtf16(str);

How can I INSERT data into two tables simultaneously in SQL Server?

I was also struggling with this problem, and find that the best way is to use a CURSOR.

I have tried Denis solution with OUTPUT, but as he mentiond, it's impossible to output external columns in an insert statement, and the MERGE can't work when insert multiple rows by select.

So, i've used a CURSOR, for each row in the outer table, i've done a INSERT, then use the @@IDENTITY for another INSERT.

DECLARE @OuterID int

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT  ID FROM   [external_Table]

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @OuterID

WHILE @@FETCH_STATUS = 0
BEGIN 
INSERT INTO [Table]   (data)
    SELECT data
    FROM     [external_Table] where ID = @OuterID 

    INSERT INTO [second_table] (FK,OuterID)
    VALUES(@OuterID,@@identity)

    FETCH NEXT FROM MY_CURSOR INTO @OuterID
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

C++ Remove new line from multiline string

 std::string some_str = SOME_VAL;
 if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
  some_str.resize( some_str.length()-1 );

or (removes several newlines at the end)

some_str.resize( some_str.find_last_not_of(L"\n")+1 );

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

How do I install g++ on MacOS X?

Type g++(or make) on terminal.

This will prompt for you to install the developer tools, if they are missing.

Also the size will be very less when compared to xcode

How can I show three columns per row?

Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:

_x000D_
_x000D_
.flex-row-container {_x000D_
    background: #aaa;_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
    flex: 1 1 30%; /*grow | shrink | basis */_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
  background-color: #fff4e6;_x000D_
  border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
  <div class="flex-row-item">1</div>_x000D_
  <div class="flex-row-item">2</div>_x000D_
  <div class="flex-row-item">3</div>_x000D_
  <div class="flex-row-item">4</div>_x000D_
  <div class="flex-row-item">5</div>_x000D_
  <div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone else.

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to wait till the response comes from the $http request, in angularjs?

You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

An example implementation would be like:

myApp.factory('myService', function($http) {

    var getData = function() {

        // Angular $http() and then() both return promises themselves 
        return $http({method:"GET", url:"/my/url"}).then(function(result){

            // What we return here is the data that will be accessible 
            // to us after the promise resolves
            return result.data;
        });
    };


    return { getData: getData };
});


function myFunction($scope, myService) {
    var myDataPromise = myService.getData();
    myDataPromise.then(function(result) {  

       // this is only run after getData() resolves
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });
}

Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

function myFunction($scope, myService) { 
    var myDataPromise = myService.getData(); 
    myDataPromise.then(function(result) { 
         $scope.data = result; 
         console.log("data.name"+$scope.data.name); 
    }); 
    console.log("This will get printed before data.name inside then. And I don't want that."); 
 }

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)

SQL: How to to SUM two values from different tables

For your current structure, you could also try the following:

select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country

I think I prefer a union between the two tables, and a group by on the country name as mentioned above.

But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)

How to apply color in Markdown?

Seems that kramdown supports colors in some form.

Kramdown allows inline html:

This is <span style="color: red">written in red</span>.

Also it has another syntax for including css classes inline:

This is *red*{: style="color: red"}.

This page further explains how GitLab utilizes more compact way to apply css classes in Kramdown:

Applying blue class to text:

This is a paragraph that for some reason we want blue.
{: .blue}

Applying blue class to headings:

#### A blue heading
{: .blue}

Applying two classes:

A blue and bold paragraph.
{: .blue .bold}

Applying ids:

#### A blue heading
{: .blue #blue-h}

This produces:

<h4 class="blue" id="blue-h">A blue heading</h4>

There is a lot of other stuff explained at above link. You may need to check.

Also, as other answer said, Kramdown is also the default markdown renderer behind Jekyll. So if you are authoring anything on github pages, above functionality might be available out of the box.

Finding all cycles in a directed graph

In the case of undirected graph, a paper recently published (Optimal listing of cycles and st-paths in undirected graphs) offers an asymptotically optimal solution. You can read it here http://arxiv.org/abs/1205.2766 or here http://dl.acm.org/citation.cfm?id=2627951 I know it doesn't answer your question, but since the title of your question doesn't mention direction, it might still be useful for Google search

A simple explanation of Naive Bayes Classification

Naive Bayes: Naive Bayes comes under supervising machine learning which used to make classifications of data sets. It is used to predict things based on its prior knowledge and independence assumptions.

They call it naive because it’s assumptions (it assumes that all of the features in the dataset are equally important and independent) are really optimistic and rarely true in most real-world applications.

It is classification algorithm which makes the decision for the unknown data set. It is based on Bayes Theorem which describe the probability of an event based on its prior knowledge.

Below diagram shows how naive Bayes works

enter image description here

Formula to predict NB:

enter image description here

How to use Naive Bayes Algorithm ?

Let's take an example of how N.B woks

Step 1: First we find out Likelihood of table which shows the probability of yes or no in below diagram. Step 2: Find the posterior probability of each class.

enter image description here

Problem: Find out the possibility of whether the player plays in Rainy condition?

P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)

P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36

Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.

For more reference refer these blog.

Refer GitHub Repository Naive-Bayes-Examples

.toLowerCase not working, replacement function?

It's not an error. Javascript will gladly convert a number to a string when a string is expected (for example parseInt(42)), but in this case there is nothing that expect the number to be a string.

Here's a makeLowerCase function. :)

function makeLowerCase(value) {
  return value.toString().toLowerCase();
}

Unable to run Java code with Intellij IDEA

If you use Maven, you must to declare your source and test folder in project directory.

For these, click F4 on Intellij Idea and Open Project Structure. Select your project name on the left panel and Mark As your "Source" and "Test" directory.

Python: Checking if a 'Dictionary' is empty doesn't seem to work

A dictionary can be automatically cast to boolean which evaluates to False for empty dictionary and True for non-empty dictionary.

if myDictionary: non_empty_clause()
else: empty_clause()

If this looks too idiomatic, you can also test len(myDictionary) for zero, or set(myDictionary.keys()) for an empty set, or simply test for equality with {}.

The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.

  1. The return False statement is indented one level too deep. It should be outside the for loop and at the same level as the for statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives.
  2. If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
  3. Let us say you correct the indentation of the return False statement and bring it outside the for loop. Then what you get is the boolean OR of all the keys, or False if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.

myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}

how to use concatenate a fixed string and a variable in Python

With python 3.6+:

msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"

Is "else if" faster than "switch() case"?

Technically, they produce the exact same result so they should be optimizable in pretty much the same way. However, there are more chances that the compiler will optimize the switch case with a jump table than the ifs.

I'm talking about the general case here. For 5 entries, the average number of tests performed for the ifs should be less than 2.5, assuming you order the conditions by frequency. Hardly a bottleneck to write home about unless in a very tight loop.

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

Absolute path routing

There are 2 methods for navigation, .navigate() and .navigateByUrl()

You can use the method .navigateByUrl() for absolute path routing:

import {Router} from '@angular/router';

constructor(private router: Router) {}

navigateToLogin() {
   this.router.navigateByUrl('/login');
}

You put the absolute path to the URL of the component you want to navigate to.

Note: Always specify the complete absolute path when calling router's navigateByUrl method. Absolute paths must start with a leading /

// Absolute route - Goes up to root level    
this.router.navigate(['/root/child/child']);

// Absolute route - Goes up to root level with route params   
this.router.navigate(['/root/child', crisis.id]);

Relative path routing

If you want to use relative path routing, use the .navigate() method.

NOTE: It's a little unintuitive how the routing works, particularly parent, sibling, and child routes:

// Parent route - Goes up one level 
// (notice the how it seems like you're going up 2 levels)
this.router.navigate(['../../parent'], { relativeTo: this.route });

// Sibling route - Stays at the current level and moves laterally, 
// (looks like up to parent then down to sibling)
this.router.navigate(['../sibling'], { relativeTo: this.route });

// Child route - Moves down one level
this.router.navigate(['./child'], { relativeTo: this.route });

// Moves laterally, and also add route parameters
// if you are at the root and crisis.id = 15, will result in '/sibling/15'
this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });

// Moves laterally, and also add multiple route parameters
// will result in '/sibling;id=15;foo=foo'. 
// Note: this does not produce query string URL notation with ? and & ... instead it
// produces a matrix URL notation, an alternative way to pass parameters in a URL.
this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route });

Or if you just need to navigate within the current route path, but to a different route parameter:

// If crisis.id has a value of '15'
// This will take you from `/hero` to `/hero/15`
this.router.navigate([crisis.id], { relativeTo: this.route });

Link parameters array

A link parameters array holds the following ingredients for router navigation:

  • The path of the route to the destination component. ['/hero']
  • Required and optional route parameters that go into the route URL. ['/hero', hero.id] or ['/hero', { id: hero.id, foo: baa }]

Directory-like syntax

The router supports directory-like syntax in a link parameters list to help guide route name lookup:

./ or no leading slash is relative to the current level.

../ to go up one level in the route path.

You can combine relative navigation syntax with an ancestor path. If you must navigate to a sibling route, you could use the ../<sibling> convention to go up one level, then over and down the sibling route path.

Important notes about relative nagivation

To navigate a relative path with the Router.navigate method, you must supply the ActivatedRoute to give the router knowledge of where you are in the current route tree.

After the link parameters array, add an object with a relativeTo property set to the ActivatedRoute. The router then calculates the target URL based on the active route's location.

From official Angular Router Documentation

How to create Haar Cascade (.xml file) to use in OpenCV?

If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.

http://note.sonots.com/SciSoftware/haartraining.html

And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.

http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/

JPanel Padding in Java

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

How to cherry-pick multiple commits

Git 1.7.2 introduced the ability to cherry pick a range of commits. From the release notes:

git cherry-pick learned to pick a range of commits (e.g. cherry-pick A..B and cherry-pick --stdin), so did git revert; these do not support the nicer sequencing control rebase [-i] has, though.

To cherry-pick all the commits from commit A to commit B (where A is older than B), run:

git cherry-pick A^..B

If you want to ignore A itself, run:

git cherry-pick A..B

(Credit goes to damian, J. B. Rainsberger and sschaef in the comments)

Svn switch from trunk to branch

You don't need to --relocate since the branch is within the same repository URL. Just do:

svn switch https://www.example.com/svn/branches/v1p2p3

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

PHP cURL, extract an XML response

Example:

<songs>
<song dateplayed="2011-07-24 19:40:26">
    <title>I left my heart on Europa</title>
    <artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
    <title>Oh Ganymede</title>
    <artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
    <title>Kallichore</title>
    <artist>Jewitt K. Sheppard</artist>
</song>

then:

<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>

Output on your browser: Ship of Nomads

credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

CSS Background image not loading

The path to the image should be relative, that means if css file is in css folder than you should start path with ../ such as

_x000D_
_x000D_
body{_x000D_
   background-image: url(../images/logo.jpg);_x000D_
}
_x000D_
_x000D_
_x000D_

this is because you have to get back to home dir by ../ path and then /images/logo.jpg path to the image file. If you are including css file in html itself

_x000D_
_x000D_
body{_x000D_
   background-image: url(images/logo.jpg);_x000D_
}
_x000D_
_x000D_
_x000D_ this code will work just fine.

Git/GitHub can't push to master

There is a simple solution to this for someone new to this:

Edit the configuration file in your local .git directory (config). Change git: to https: below.

[remote "origin"]
    url = https://github.com/your_username/your_repo

Pass multiple optional parameters to a C# function

1.You can make overload functions.

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

Main(string[] args){}

Using bootstrap with bower

I ended up going with a shell script that you should only really have to run once when you first checkout a project

#!/usr/bin/env bash

mkdir -p webroot/js
mkdir -p webroot/css
mkdir -p webroot/css-min
mkdir -p webroot/img
mkdir -p webroot/font

npm i
bower i

# boostrap
pushd components/bootstrap
npm i
make bootstrap
popd
cp components/bootstrap/bootstrap/css/*.min.css webroot/css-min/
cp components/bootstrap/bootstrap/js/bootstrap.js src/js/deps/
cp components/bootstrap/bootstrap/img/* webroot/img/

# fontawesome
cp components/font-awesome/css/*.min.css webroot/css-min/
cp components/font-awesome/font/* webroot/font/

Composer: The requested PHP extension ext-intl * is missing from your system

In linux (Debian Jessie for example):

apt-get install php7.0-intl

will make the job to you due will create a simbolic link to it.

sklearn plot confusion matrix with labels

from sklearn import model_selection
test_size = 0.33
seed = 7
X_train, X_test, y_train, y_test = model_selection.train_test_split(feature_vectors, y, test_size=test_size, random_state=seed)

from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

model = LogisticRegression()
model.fit(X_train, y_train)
result = model.score(X_test, y_test)
print("Accuracy: %.3f%%" % (result*100.0))
y_pred = model.predict(X_test)
print("F1 Score: ", f1_score(y_test, y_pred, average="macro"))
print("Precision Score: ", precision_score(y_test, y_pred, average="macro"))
print("Recall Score: ", recall_score(y_test, y_pred, average="macro")) 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix

def cm_analysis(y_true, y_pred, labels, ymap=None, figsize=(10,10)):
    """
    Generate matrix plot of confusion matrix with pretty annotations.
    The plot image is saved to disk.
    args: 
      y_true:    true label of the data, with shape (nsamples,)
      y_pred:    prediction of the data, with shape (nsamples,)
      filename:  filename of figure file to save
      labels:    string array, name the order of class labels in the confusion matrix.
                 use `clf.classes_` if using scikit-learn models.
                 with shape (nclass,).
      ymap:      dict: any -> string, length == nclass.
                 if not None, map the labels & ys to more understandable strings.
                 Caution: original y_true, y_pred and labels must align.
      figsize:   the size of the figure plotted.
    """
    if ymap is not None:
        y_pred = [ymap[yi] for yi in y_pred]
        y_true = [ymap[yi] for yi in y_true]
        labels = [ymap[yi] for yi in labels]
    cm = confusion_matrix(y_true, y_pred, labels=labels)
    cm_sum = np.sum(cm, axis=1, keepdims=True)
    cm_perc = cm / cm_sum.astype(float) * 100
    annot = np.empty_like(cm).astype(str)
    nrows, ncols = cm.shape
    for i in range(nrows):
        for j in range(ncols):
            c = cm[i, j]
            p = cm_perc[i, j]
            if i == j:
                s = cm_sum[i]
                annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s)
            elif c == 0:
                annot[i, j] = ''
            else:
                annot[i, j] = '%.1f%%\n%d' % (p, c)
    cm = pd.DataFrame(cm, index=labels, columns=labels)
    cm.index.name = 'Actual'
    cm.columns.name = 'Predicted'
    fig, ax = plt.subplots(figsize=figsize)
    sns.heatmap(cm, annot=annot, fmt='', ax=ax)
    #plt.savefig(filename)
    plt.show()

cm_analysis(y_test, y_pred, model.classes_, ymap=None, figsize=(10,10))

enter image description here

using https://gist.github.com/hitvoice/36cf44689065ca9b927431546381a3f7

Note that if you use rocket_r it will reverse the colors and somehow it looks more natural and better such as below: enter image description here

Show a popup/message box from a Windows batch file

msg * /time:0 /w Hello everybody!

This message waits forever until OK is clicked (it lasts only one minute by default) and works fine in Windows 8.1

Git keeps asking me for my ssh key passphrase

If you've tried ssh-add and you're still prompted to enter your passphrase then try using ssh-add -K. This adds your passphrase to your keychain.

Update: if you're using macOS Sierra then you likely need to do another step as the above might no longer work. Add the following to your ~/.ssh/config:

Host *
  UseKeychain yes

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

offsetting an html anchor to adjust for fixed header

As @moeffju suggests, this can be achieved with CSS. The issue I ran into (which I'm surprised I haven't seen discussed) is the trick of overlapping previous elements with padding or a transparent border prevents hover and click actions at the bottom of those sections because the following one comes higher in the z-order.

The best fix I found was to place section content in a div that is at z-index: 1:

// Apply to elements that serve as anchors
.offset-anchor {
  border-top: 75px solid transparent;
  margin: -75px 0 0;
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding;
  background-clip: padding-box;
}

// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
  position: relative;
  z-index: 1;
}

How can I use a local image as the base image with a dockerfile?

You can have - characters in your images. Assume you have a local image (not a local registry) named centos-base-image with tag 7.3.1611.

docker version 
      Client:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

      Server:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

docker images
 REPOSITORY            TAG
 centos-base-image     7.3.1611

Dockerfile

FROM centos-base-image:7.3.1611
RUN yum -y install epel-release libaio bc flex

Result

Sending build context to Docker daemon 315.9 MB
Step 1 : FROM centos-base-image:7.3.1611
  ---> c4d84e86782e
Step 2 : RUN yum -y install epel-release libaio bc flex
  ---> Running in 36d8abd0dad9
...

In the example above FROM is fetching your local image, you can provide additional instructions to fetch an image from your custom registry (e.g. FROM localhost:5000/my-image:with.tag). See https://docs.docker.com/engine/reference/commandline/pull/#pull-from-a-different-registry and https://docs.docker.com/registry/#tldr

Finally, if your image is not being resolved when providing a name, try adding a tag to the image when you create it

This GitHub thread describes a similar issue of not finding local images by name.

By omitting a specific tag, docker will look for an image tagged "latest", so either create an image with the :latest tag, or change your FROM

How to create war files

You can use Ant to set up, compile, WAR, and deploy your solution.

<target name="default" depends="setup,compile,buildwar,deploy"></target>

You can then execute one click in Eclipse to run that Ant target. Here are examples of each of the steps:

Preconditions

We'll assume that you have your code organized like:

  • ${basedir}/src: Java files, properties, XML config files
  • ${basedir}/web: Your JSP files
  • ${basedir}/web/lib: Any JARs required at runtime
  • ${basedir}/web/META-INF: Your manifest
  • ${basedir}/web/WEB-INF: Your web.xml files

Set up

Define a setup task that creates the distribution directory and copies any artifacts that need to be WARred directly:

<target name="setup">
    <mkdir dir="dist" />
    <echo>Copying web into dist</echo>
    <copydir dest="dist/web" src="web" />
    <copydir dest="dist/web/WEB-INF/lib" src="${basedir}/../web/WEB-INF/lib" />
</target>

Compile

Build your Java files into classes and copy over any non-Java artifacts that reside under src but need to be available at runtime (e.g. properties, XML files, etc.):

<target name="compile">
    <delete dir="${dist.dir}/web/WEB-INF/classes" />
    <mkdir dir="${dist.dir}/web/WEB-INF/classes" />
    <javac destdir="${dist.dir}/web/WEB-INF/classes" srcdir="src">
        <classpath>
            <fileset dir="${basedir}/../web/WEB-INF/lib">
                  <include name="*" />
            </fileset>
        </classpath>
    </javac>
    <copy todir="${dist.dir}/web/WEB-INF/classes">
        <fileset dir="src">
            <include name="**/*.properties" />
            <include name="**/*.xml" />
        </fileset>
    </copy>
</target>

Build WAR

Create the WAR itself:

<target name="buildwar">
    <war basedir="${basedir}/dist/web" destfile="My.war"
     webxml="${basedir}/dist/web/WEB-INF/web.xml">
        <exclude name="WEB-INF/**" />
        <webinf dir="${basedir}/dist/web/WEB-INF/">
            <include name="**/*.jar" />
        </webinf>
    </war>
</target>

Deploy

Finally, you can set up a task to deploy the WAR directly into your Tomcat deploy location:

<target name="deploy">
    <copy file="My.war" todir="${tomcat.deploydir}" />
</target>

Click and go!

Once all this is set up, simply launching the default target from Eclipse will compile, WAR, and deploy your solution.

The advantage of this approach is that it will work outside Eclipse as well as within Eclipse and can be used to easily share your deployment strategy (e.g. via source control) with other developers who are also working on your project.

how to create a Java Date object of midnight today and midnight tomorrow?

The simplest way with JodaTime

DateMidnight date = DateMidnight.now();

Different CURRENT_TIMESTAMP and SYSDATE in oracle

SYSDATE returns the system date, of the system on which the database resides

CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of datatype TIMESTAMP WITH TIME ZONE

execute this comman

    ALTER SESSION SET TIME_ZONE = '+3:0';

and it will provide you the same result.

How can I find the current OS in Python?

Something along the lines:

import os
if os.name == "posix":
    print(os.system("uname -a"))
# insert other possible OSes here
# ...
else:
    print("unknown OS")

Pandas - Plotting a stacked Bar Chart

If you want to change the size of plot the use arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))

Volatile vs. Interlocked vs. lock

I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is similar. Interlocked is not necessary faster in multi-cpu environment. Here is the test result for Increment on a 2 years old 16 CPU server. Bare in mind that the test also involves the safe read after increase, which is typical in real world.

D:\>InterlockVsMonitor.exe 16
Using 16 threads:
          InterlockAtomic.RunIncrement         (ns):   8355 Average,   8302 Minimal,   8409 Maxmial
    MonitorVolatileAtomic.RunIncrement         (ns):   7077 Average,   6843 Minimal,   7243 Maxmial

D:\>InterlockVsMonitor.exe 4
Using 4 threads:
          InterlockAtomic.RunIncrement         (ns):   4319 Average,   4319 Minimal,   4321 Maxmial
    MonitorVolatileAtomic.RunIncrement         (ns):    933 Average,    802 Minimal,   1018 Maxmial

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

How to quietly remove a directory with content in PowerShell

in short, We can use rm -r -fo {folderName} to remove the folder recursively (remove all the files and folders inside) and force

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Change bootstrap datepicker date format on select

As of 2016 I used datetimepicker like this:

$(function () {
    $('#date_box').datetimepicker({
        format: 'YYYY-MM-DD hh:mm'
    });
});

vim - How to delete a large block of text without counting the lines?

Go to the starting line and type ma (mark "a"). Then go to the last line and enter d'a (delete to mark "a").

That will delete all lines from the current to the marked one (inclusive). It's also compatible with vi as well as vim, on the off chance that your environment is not blessed with the latter.

How do I get monitor resolution in Python?

To get bits per pixel:

import ctypes
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32

screensize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
print "screensize =%s"%(str(screensize))
dc = user32.GetDC(None);

screensize = (gdi32.GetDeviceCaps(dc,8), gdi32.GetDeviceCaps(dc,10), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
screensize = (gdi32.GetDeviceCaps(dc,118), gdi32.GetDeviceCaps(dc,117), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))

parameters in gdi32:

#/// Vertical height of entire desktop in pixels
#DESKTOPVERTRES = 117,
#/// Horizontal width of entire desktop in pixels
#DESKTOPHORZRES = 118,
#/// Horizontal width in pixels
#HORZRES = 8,
#/// Vertical height in pixels
#VERTRES = 10,
#/// Number of bits per pixel
#BITSPIXEL = 12,

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

ASP.NET MVC - Getting QueryString values

Actually you can capture Query strings in MVC in two ways.....

public ActionResult CrazyMVC(string knownQuerystring)
{

  // This is the known query string captured by the Controller Action Method parameter above
  string myKnownQuerystring = knownQuerystring;

  // This is what I call the mysterious "unknown" query string
  // It is not known because the Controller isn't capturing it
  string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];

  return Content(myKnownQuerystring + " - " + myUnknownQuerystring);

}

This would capture both query strings...for example:

/CrazyMVC?knownQuerystring=123&unknownQuerystring=456

Output: 123 - 456

Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?

Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.

Where is my m2 folder on Mac OS X Mavericks

It's in your home folder but it's hidden by default.

Typing the below commands in the terminal made it visible for me (only the .m2 folder that is, not all the other hidden folders).

> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2         

Source

Example of a strong and weak entity types

A weak entity is the entity which can't be fully identified by its own attributes and takes the foreign key as an attribute (generally it takes the primary key of the entity it is related to) in conjunction.

Examples

The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel.
Another example is the
bank account of a particular bank has no existence if the bank doesn't exist anymore.

How to check for the type of a template parameter?

You can specialize your templates based on what's passed into their parameters like this:

template <> void foo<animal> {

}

Note that this creates an entirely new function based on the type that's passed as T. This is usually preferable as it reduces clutter and is essentially the reason we have templates in the first place.

Interface or an Abstract Class: which one to use?

Use an interface when you want to force developers working in your system (yourself included) to implement a set number of methods on the classes they'll be building.

Use an abstract class when you want to force developers working in your system (yourself included) to implement a set numbers of methods and you want to provide some base methods that will help them develop their child classes.

Another thing to keep in mind is client classes can only extend one abstract class, whereas they can implement multiple interfaces. So, if you're defining your behavior contracts in abstract classes, that means each child class may only conform to a single contract. Sometimes this a good thing, when you want to force your user-programmers along a particular path. Other times it would be bad. Imagine if PHP's Countable and Iterator interfaces were abstract classes instead of interfaces.

One approach that's common when you're uncertain which way to go (as mentioned by cletus below) is to create an interface, and then have your abstract class implement that interface.

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

Remove directory from remote repository after adding them to .gitignore

This method applies the standard .gitignore behavior, and does not require manually specifying the files that need to be ignored.

Can't use --exclude-from=.gitignore anymore :/ - Here's the updated method:

General advice: start with a clean repo - everything committed, nothing pending in working directory or index, and make a backup!

#commit up-to-date .gitignore (if not already existing)
#this command must be run on each branch
git add .gitignore
git commit -m "Create .gitignore"

#apply standard git ignore behavior only to current index, not working directory (--cached)
#if this command returns nothing, ensure /.git/info/exclude AND/OR .gitignore exist
#this command must be run on each branch
git ls-files -z --ignored --exclude-standard | xargs -0 git rm --cached

#optionally add anything to the index that was previously ignored but now shouldn't be:
git add *

#commit again
#optionally use the --amend flag to merge this commit with the previous one instead of creating 2 commits.

git commit -m "re-applied modified .gitignore"

#other devs who pull after this commit is pushed will see the  newly-.gitignored files DELETED

If you also need to purge the newly-ignored files from the branch's commit history or if you don't want the newly-ignored files to be deleted from future pulls, see this answer.

How do I automatically set the $DISPLAY variable for my current session?

You'll need to tell your vnc client to export the correct $DISPLAY once you have logged in. How you do that will probably depend on your vnc client.

Unity 2d jumping script

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

Example:

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

Hide div element when screen size is smaller than a specific size

You can do this with CSS:

@media only screen and (max-width: 1026px) {
    #fadeshow1 {
        display: none;
    }
}

We're using max-width, because we want to make an exception to the CSS, when a screen is smaller than the 1026px. min-width would make the CSS rule count for all screens of 1026px width and larger.

Something to keep in mind is that @media queries are not supported on IE8 and lower.

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,

  • Xpath engines are different in each browser, hence make them inconsistent
  • IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
  • Xpath tend to become complex and hence make hard to read in my opinion

However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).

You can read blog from Simon here . He also recommends CSS over Xpath.

If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.

edit 1

Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better

Stop all active ajax requests in jQuery

I have updated the code to make it works for me

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(idx, jqXHR) {
        jqXHR.abort();
    });
    $(this).each(function(idx, jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    });
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});

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

I just encountered this problem myself. I'm developing an app internally, so my host is 'localhost'. It wasn't obvious how to set 'localhost' up in the app configuration. If you want to develop locally, set up your app by following these steps:

  1. Go to the place where you manage your Facebook app. Specifically, you want to be in "Basic" under the "Settings" menu.
  2. Add 'localhost' to "App Domain".
  3. Under "Select how your app integrates with Facebook", select "Website", and enter "http://localhost/".

Save and wait a couple of minutes for the information to propagate, although it worked right away for me.

How to get a password from a shell script without echoing

This link is help in defining, * How to read password from use without echo-ing it back to terminal * How to replace each character with * -character.

https://www.tutorialkart.com/bash-shell-scripting/bash-read-username-and-password/

Django: Redirect to previous page after login

To support full urls with param/values you'd need:

?next={{ request.get_full_path|urlencode }}

instead of just:

?next={{ request.path }}

Whitespace Matching Regex - Java

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);

boolean flag = true;
while(flag)
{
 //Update your original search text with the result of the replace
 modLine = matcher.replaceAll(" ");
 //reset matcher to look at this "new" text
 matcher = whitespace.matcher(modLine);
 //search again ... and if no match , set flag to false to exit, else run again
 if(!matcher.find())
 {
 flag = false;
 }
}

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

You should use this example with AUTHID CURRENT_USER :

CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
   AUTHID CURRENT_USER
IS
   SEQ_NAME       VARCHAR2 (100);
   FINAL_QUERY    VARCHAR2 (100);
   COUNT_NUMBER   NUMBER := 0;
   cur_id         NUMBER;
BEGIN
   SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;

   SELECT COUNT (*)
     INTO COUNT_NUMBER
     FROM USER_SEQUENCES
    WHERE SEQUENCE_NAME = SEQ_NAME;

   DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);

   IF COUNT_NUMBER = 0
   THEN
      --DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
      -- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
      -- ELSE
      SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
        INTO FINAL_QUERY
        FROM DUAL;

      DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
      cur_id := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
      DBMS_SQL.CLOSE_CURSOR (cur_id);
   -- EXECUTE IMMEDIATE FINAL_QUERY;

   END IF;

   COMMIT;
END;
/

django order_by query set, ascending and descending

Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.

We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters

Kubernetes service external ip pending

If you are using minikube then run commands below from terminal,

$ minikube ip
$ 172.17.0.2 // then 
$ curl http://172.17.0.2:31245
or simply
$ curl http://$(minikube ip):31245

Gets last digit of a number

Although the best way to do this is to use % if you insist on using strings this will work

public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}

but I just wrote this for completeness. Do not use this code. it is just awful.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

This answer uses the jQuery UI Datepicker, which is a separate include. There are other ways to do this without including jQuery UI.

First, you simply need to add the datepicker class to the textbox, in addition to form-control:

<div class="form-group input-group-sm">
    @Html.LabelFor(model => model.DropOffDate)
    @Html.TextBoxFor(model => model.DropOffDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
    @Html.ValidationMessageFor(model => model.DropOffDate)
</div>

Then, to be sure the javascript is triggered after the textbox is rendered, you have to put the datepicker call in the jQuery ready function:

<script type="text/javascript">
    $(function () { // will trigger when the document is ready
       $('.datepicker').datepicker(); //Initialise any date pickers
    });
</script>

How to add custom validation to an AngularJS form?

@synergetic I think @blesh suppose to put function validate as below

function validate(value) {
    var valid = blacklist.indexOf(value) === -1;
    ngModel.$setValidity('blacklist', valid);
    return valid ? value : undefined;
}

ngModel.$formatters.unshift(validate);
ngModel.$parsers.unshift(validate);

Using Tkinter in python to edit the title bar

Having just done this myself you can do it this way:

from tkinter import Tk, Button, Frame, Entry, END

class ABC(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        ABC.make_widgets(self)

    def make_widgets(self):
        self.parent.title("Simple Prog")

You will see the title change, and you won't get two windows. I've left my parent as master as in the Tkinter reference stuff in the python library documentation.

Terminating a script in PowerShell

I coincidentally found out that Break <UnknownLabel> (e.g. simply Break Script, where the label Script doesn't exists) appears to break out of the entire script (even from within a function) and keeps the host alive.
This way you could create a function that breaks the script from anywhere (e.g. a recursive loop) without knowing the current scope (and creating labels):

Function Quit($Text) {
    Write-Host "Quiting because: " $Text
    Break Script
} 

How to initialize static variables

best way is to create an accessor like this:

/**
* @var object $db : map to database connection.
*/
public static $db= null; 

/**
* db Function for initializing variable.   
* @return object
*/
public static function db(){
 if( !isset(static::$db) ){
  static::$db= new \Helpers\MySQL( array(
    "hostname"=> "localhost",
    "username"=> "root",
    "password"=> "password",
    "database"=> "db_name"
    )
  );
 }
 return static::$db;
}

then you can do static::db(); or self::db(); from anywhere.

Convert a JSON String to a HashMap

Imagine u have a list of email like below. not constrained to any programming language,

emailsList = ["[email protected]","[email protected]","[email protected]"]

Now following is JAVA code - for converting json to map

JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList);
Map<String, Object> s = jsonObj.getMap();

Converting an object to a string

If you're just outputting to the console, you can use console.log('string:', obj). Notice the comma.

Splitting comma separated string in a PL/SQL stored proc

As for the connect by use case, this approach should work for you:

select regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
from dual
connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;

Reimport a module in python while interactive

In python 3, reload is no longer a built in function.

If you are using python 3.4+ you should use reload from the importlib library instead:

import importlib
importlib.reload(some_module)

If you are using python 3.2 or 3.3 you should:

import imp  
imp.reload(module)  

instead. See http://docs.python.org/3.0/library/imp.html#imp.reload

If you are using ipython, definitely consider using the autoreload extension:

%load_ext autoreload
%autoreload 2

Most efficient method to groupby on an array of objects

MDN has this example in their Array.reduce() documentation.

// Grouping objects by a property
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Grouping_objects_by_a_property#Grouping_objects_by_a_property

var people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}

var groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// { 
//   20: [
//     { name: 'Max', age: 20 }, 
//     { name: 'Jane', age: 20 }
//   ], 
//   21: [{ name: 'Alice', age: 21 }] 
// }

How do I force detach Screen from another SSH session?

As Jose answered, screen -d -r should do the trick. This is a combination of two commands, as taken from the man page.

screen -d detaches the already-running screen session, and screen -r reattaches the existing session. By running screen -d -r, you force screen to detach it and then resume the session.

If you use the capital -D -RR, I quote the man page because it's too good to pass up.

Attach here and now. Whatever that means, just do it.

Note: It is always a good idea to check the status of your sessions by means of "screen -list".

Setting Different Bar color in matplotlib Python

Simple, just use .set_color

>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()

enter image description here

For your new question, not much harder either, just need to find the bar from your axis, an example:

>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>, 
 <matplotlib.axis.YAxis object at 0x78460d0>,  
 <matplotlib.patches.Rectangle object at 0x733cc50>, 
 <matplotlib.patches.Rectangle object at 0x733cdd0>, 
 <matplotlib.patches.Rectangle object at 0x777f290>, 
 <matplotlib.patches.Rectangle object at 0x777f710>, 
 <matplotlib.text.Text object at 0x7836450>, 
 <matplotlib.patches.Rectangle object at 0x7836390>, 
 <matplotlib.spines.Spine object at 0x6529950>, 
 <matplotlib.spines.Spine object at 0x69aef50>,
 <matplotlib.spines.Spine object at 0x69ae310>, 
 <matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r') 
 #You can also try to locate the first patches.Rectangle object 
 #instead of direct calling the index.

If you have a complex plot and want to identify the bars first, add those:

>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>, 
 <matplotlib.patches.Rectangle object at 0x3103810>, 
 <matplotlib.patches.Rectangle object at 0x3129850>, 
 <matplotlib.patches.Rectangle object at 0x3129cd0>, 
 <matplotlib.patches.Rectangle object at 0x3112ad0>]

Send mail via CMD console

Scenario: Your domain: mydomain.com Domain you wish to send to: theirdomain.com

1. Determine the mail server you're sending to. Open a CMD prompt Type

NSLOOKUP 
 set q=mx 
 theirdomain.com

Response:

Non-authoritative answer: 
theirdomain.com MX preference = 50, mail exchanger = mail.theirdomain.com 
Nslookup_big

EDIT Be sure to type exit to terminate NSLOOKUP.

2. Connect to their mail server

SMTP communicates over port 25. We will now try to use TELNET to connect to their mail server "mail.theirdomain.com"

Open a CMD prompt

TELNET MAIL.THEIRDOMAIN.COM 25

You should see something like this as a response:

220 mx.google.com ESMTP 6si6253627yxg.6

Be aware that different servers will come up with different greetings but you should get SOMETHING. If nothing comes up at this point there are 2 possible problems. Port 25 is being blocked at your firewall, or their server is not responding. Try a different domain, if that works then it's not you.

3. Send an Email

Now, use simple SMTP commands to send a test email. This is very important, you CANNOT use the backspace key, it will work onscreen but not be interpreted correctly. You have to type these commands perfectly.

ehlo mydomain.com 
mail from:<[email protected]> 
rcpt to:<[email protected]> 
data 
This is a test, please do not respond
. 
quit

So, what does that all mean? EHLO - introduce yourself to the mail server HELO can also be used but EHLO tells the server to use the extended command set (not that we're using that).

MAIL FROM - who's sending the email. Make sure to place this is the greater than/less than brackets as many email servers will require this (Postini).

RCPT TO - who you're sending it to. Again you need to use the brackets. See Step #4 on how to test relaying mail!

DATA - tells the SMTP server that what follows is the body of your email. Make sure to hit "Enter" at the end.

. - the period alone on the line tells the SMTP server you're all done with the data portion and it's clear to send the email.

quit - exits the TELNET session.

4. Test SMTP relay Testing SMTP relay is very easy, and simply requires a small change to the above commands. See below:

ehlo mydomain.com 
mail from:<[email protected]> 
rcpt to:<[email protected]> 
data 
This is a test, please do not respond 
. 
quit

See the difference? On the RCPT TO line, we're sending to a domain that is not controlled by the SMTP server we're sending to. You will get an immediate error is SMTP relay is turned off. If you're able to continue and send an email, then relay is allowed by that server.

Is there a download function in jsFiddle?

There is npm-package jsfiddle-downloader.

Objective-C : BOOL vs bool

Another difference between bool and BOOL is that they do not convert exactly to the same kind of objects, when you do key-value observing, or when you use methods like -[NSObject valueForKey:].

As everybody has said here, BOOL is char. As such, it is converted to an NSNumber holding a char. This object is indistinguishable from an NSNumber created from a regular char like 'A' or '\0'. You have totally lost the information that you originally had a BOOL.

However, bool is converted to an CFBoolean, which behaves the same as NSNumber, but which retains the boolean origin of the object.

I do not think that this is an argument in a BOOL vs. bool debate, but this may bite you one day.

Generally speaking, you should go with BOOL, since this is the type used everywhere in the Cocoa/iOS APIs (designed before C99 and its native bool type).

Get value from hashmap based on key to JSTL

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

Need to perform Wildcard (*,?, etc) search on a string using Regex

You can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.

using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

if (Operators.LikeString("This is just a test", "*just*", CompareMethod.Text))
{
  Console.WriteLine("This matched!");
}

If you use CompareMethod.Text it will compare case-insensitive. For case-sensitive comparison, you can use CompareMethod.Binary.

More info here: http://www.henrikbrinch.dk/Blog/2012/02/14/Wildcard-matching-in-C

MSDN: http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators.likestring%28v=vs.100%29.ASPX

Byte Array to Hex String

Or, if you are a fan of functional programming:

>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>

window.location.reload with clear cache

i had this problem and i solved it using javascript

 location.reload(true);

you may also use

window.history.forward(1);

to stop the browser back button after user logs out of the application.

HTML5 video - show/hide controls programmatically

<video id="myvideo">
  <source src="path/to/movie.mp4" />
</video>

<p onclick="toggleControls();">Toggle</p>

<script>
var video = document.getElementById("myvideo");

function toggleControls() {
  if (video.hasAttribute("controls")) {
     video.removeAttribute("controls")   
  } else {
     video.setAttribute("controls","controls")   
  }
}
</script>

See it working on jsFiddle: http://jsfiddle.net/dgLds/

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Execute SQL script from command line

You can do like this

sqlcmd -S <server Name> -U sa -P sapassword -i inputquery_file_name -o outputfile_name

From your command prompt run sqlcmd /? to get all the options you can use with sqlcmd utility

Sum function in VBA

Place the function value into the cell

Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).

The function that works best for me is Excel.WorksheetFunction.Sum()

Example:

Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.

Place the function directly into the cell

The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:

    Dim Report As Worksheet 'Set up your new worksheet variable.
    Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

    Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.

How I could add dir to $PATH in Makefile?

To set the PATH variable, within the Makefile only, use something like:

PATH := $(PATH):/my/dir

test:
@echo my new PATH = $(PATH)

How to write log to file

If you run binary on linux machine you could use shell script.

overwrite into a file

./binaryapp > binaryapp.log

append into a file

./binaryapp >> binaryapp.log

overwrite stderr into a file

./binaryapp &> binaryapp.error.log

append stderr into a file

./binaryapp &>> binalyapp.error.log

it can be more dynamic using shell script file.

How to delete specific characters from a string in Ruby?

Do as below using String#tr :

 "((String1))".tr('()', '')
 # => "String1"

How to select rows in a DataFrame between two values, in Python Pandas?

Consider also series between:

df = df[df['closing_price'].between(99, 101)]

Adding a column after another column within SQL

Assuming MySQL (EDIT: posted before the SQL variant was supplied):

ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn

The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.

How to hide image broken Icon using only CSS/HTML?

A basic and very simple way of doing this without any code required would be to just provide an empty alt statement. The browser will then return the image as blank. It would look just like if the image isn't there.

Example:

<img class="img_gal" alt="" src="awesome.jpg">

Try it out to see! ;)

Seeing if data is normally distributed in R

when you perform a test, you ever have the probabilty to reject the null hypothesis when it is true.

See the nextt R code:

p=function(n){
  x=rnorm(n,0,1)
  s=shapiro.test(x)
  s$p.value
}

rep1=replicate(1000,p(5))
rep2=replicate(1000,p(100))
plot(density(rep1))
lines(density(rep2),col="blue")
abline(v=0.05,lty=3)

The graph shows that whether you have a sample size small or big a 5% of the times you have a chance to reject the null hypothesis when it s true (a Type-I error)

How to get the cell value by column name not by index in GridView in asp.net

It is possible to use the data field name, if not the title so easily, which solved the problem for me. For ASP.NET & VB:

e.g. For a string:

Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()

e.g. For an integer:

Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

C++11 reverse range-based for-loop

If you can use range v3 , you can use the reverse range adapter ranges::view::reverse which allows you to view the container in reverse.

A minimal working example:

#include <iostream>
#include <vector>
#include <range/v3/view.hpp>

int main()
{
    std::vector<int> intVec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (auto const& e : ranges::view::reverse(intVec)) {
        std::cout << e << " ";   
    }
    std::cout << std::endl;

    for (auto const& e : intVec) {
        std::cout << e << " ";   
    }
    std::cout << std::endl;
}

See DEMO 1.

Note: As per Eric Niebler, this feature will be available in C++20. This can be used with the <experimental/ranges/range> header. Then the for statement will look like this:

for (auto const& e : view::reverse(intVec)) {
       std::cout << e << " ";   
}

See DEMO 2

How to select rows with NaN in particular column?

Try the following:

df[df['Col2'].isnull()]

What is the lifetime of a static variable in a C++ function?

FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.

C:\> sample.exe 1 2
Created in foo
Created in if
Destroyed in foo
Destroyed in if

... which is another reason not to rely on the destruction order!

Android emulator doesn't take keyboard input - SDK tools rev 20

Update

As of SDK rev 21 the Android Virtual Device Manager has an improved UI which resolves this issue. I have highlighted some of the more important configuration settings below:

enter image description here

If you notice that the soft (screen-based) main keys Back, Home, etc. are missing from your emulator you can set hw.mainKeys=no to enable them.

enter image description here

Original answer

Even though the developer documentation says keyboard support is enabled by default it doesn't seem to be that way in SDK rev 20. I explicitly enabled keyboard support in my emulator's config.ini file and that worked!

Add: hw.keyboard=yes

To: ~/.android/avd/<emulator-device-name>.avd/config.ini

Similarly, add hw.dPad=yes if you wish to use the arrow-keys to navigate the application list.

Reference: http://developer.android.com/tools/devices/managing-avds-cmdline.html#hardwareopts

On Mac OS and Linux you can edit all of your emulator configurations with one Terminal command:

for f in ~/.android/avd/*.avd/config.ini; do echo 'hw.keyboard=yes' >> "$f"; done


On a related note, if your tablet emulator is missing the BACK/HOME buttons, try selecting WXGA800 as the Built-in skin in the AVD editor: enter image description here

Or by manually setting the skin in config.ini:

skin.name=WXGA800
skin.path=platforms/android-16/skins/WXGA800

(example is for API 16)

How to globally replace a forward slash in a JavaScript string?

This has worked for me in turning "//" into just "/".

str.replace(/\/\//g, '/');

git replacing LF with CRLF

If you already have checked out the code, the files are already indexed. After changing your git settings, say by running:

git config --global core.autocrlf input 

you should refresh the indexes with

git rm --cached -r . 

and re-write git index with

git reset --hard

https://help.github.com/articles/dealing-with-line-endings/#refreshing-a-repository-after-changing-line-endings

Note: this is will remove your local changes, consider stashing them before you do this.

write() versus writelines() and concatenated strings

Exercise 16 from Zed Shaw's book? You can use escape characters as follows:

paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()