Programs & Examples On #Nsimagerep

Preventing twitter bootstrap carousel from auto sliding on page load

if you're using bootstrap 3 set data-interval="false" on the HTML structure of carousel


<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" data-interval="false">

PDO mysql: How to know if insert was successful

Use id as primary key with auto increment

$insertid = $conn->lastInsertId();

incremental id is always bigger than zero even on first record so that means it will always return a true value for id coz bigger than zero means true in PHP

if ($insertid)
   echo "record inserted successfully";
   echo "record insertion failed";

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

HTML 5 video recording and storing a stream

The followin example shows how to capture and process video frames in HTML5:

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Capturing & Processing Video in HTML5</title>
        <h2>Camera Preview</h2>
        <video id="cameraPreview" width="240" height="180" autoplay></video>
            <button id="startButton" onclick="startCapture();">Start Capture</button>
            <button id="stopButton" onclick="stopCapture();">Stop Capture</button>

        <h2>Processing Preview</h2>
        <canvas id="processingPreview" width="240" height="180"></canvas>

        <h2>Recording Preview</h2>
        <video id="recordingPreview" width="240" height="180" autoplay controls></video>
            <a id="downloadButton">Download</a>


    const ROI_X = 250;
    const ROI_Y = 150;
    const ROI_WIDTH = 240;
    const ROI_HEIGHT = 180;
    const FPS = 25;
    let cameraStream = null;
    let processingStream = null;
    let mediaRecorder = null;
    let mediaChunks = null;
    let processingPreviewIntervalId = null;

    function processFrame() {
        let cameraPreview = document.getElementById("cameraPreview");
            .drawImage(cameraPreview, ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT, 0, 0, ROI_WIDTH, ROI_HEIGHT);
    function generateRecordingPreview() {
        let mediaBlob = new Blob(mediaChunks, { type: "video/webm" });
        let mediaBlobUrl = URL.createObjectURL(mediaBlob);
        let recordingPreview = document.getElementById("recordingPreview");
        recordingPreview.src = mediaBlobUrl;

        let downloadButton = document.getElementById("downloadButton");
        downloadButton.href = mediaBlobUrl; = "RecordedVideo.webm";
    function startCapture() {
        const constraints = { video: true, audio: false };
        .then((stream) => {
            cameraStream = stream;
            let processingPreview = document.getElementById("processingPreview");
            processingStream = processingPreview.captureStream(FPS);
            mediaRecorder = new MediaRecorder(processingStream);
            mediaChunks = []
            mediaRecorder.ondataavailable = function(event) {
                if(mediaRecorder.state == "inactive") {
            let cameraPreview = document.getElementById("cameraPreview");
            cameraPreview.srcObject = stream;
            processingPreviewIntervalId = setInterval(processFrame, 1000 / FPS);
        .catch((err) => {
            alert("No media device found!");
    function stopCapture() {
        if(cameraStream != null) {
            cameraStream.getTracks().forEach(function(track) {
        if(processingStream != null) {
            processingStream.getTracks().forEach(function(track) {
        if(mediaRecorder != null) {
            if(mediaRecorder.state == "recording") {
        if(processingPreviewIntervalId != null) {
            processingPreviewIntervalId = null;

The ternary (conditional) operator in C

The fact that the ternary operator is an expression, not a statement, allows it to be used in macro expansions for function-like macros that are used as part of an expression. Const may not have been part of original C, but the macro pre-processor goes way back.

One place where I've seen it used is in an array package that used macros for bound-checked array accesses. The syntax for a checked reference was something like aref(arrayname, type, index), where arrayname was actually a pointer to a struct that included the array bounds and an unsigned char array for the data, type was the actual type of the data, and index was the index. The expansion of this was quite hairy (and I'm not going to do it from memory), but it used some ternary operators to do the bound checking.

You can't do this as a function call in C because of the need for polymorphism of the returned object. So a macro was needed to do the type casting in the expression. In C++ you could do this as a templated overloaded function call (probably for operator[]), but C doesn't have such features.

Edit: Here's the example I was talking about, from the Berkeley CAD array package (glu 1.4 edition). The documentation of the array_fetch usage is:

array_fetch(type, array, position)
typeof type;
array_t *array;
int position;

Fetch an element from an array. A runtime error occurs on an attempt to reference outside the bounds of the array. There is no type-checking that the value at the given position is actually of the type used when dereferencing the array.

and here is the macro defintion of array_fetch (note the use of the ternary operator and the comma sequencing operator to execute all the subexpressions with the right values in the right order as part of a single expression):

#define array_fetch(type, a, i)         \
(array_global_index = (i),              \
  (array_global_index >= (a)->num) ? array_abort((a),1) : 0,\
  *((type *) ((a)->space + array_global_index * (a)->obj_size)))

The expansion for array_insert ( which grows the array if necessary, like a C++ vector) is even hairier, involving multiple nested ternary operators.

iOS: how to perform a HTTP POST request?

You can use NSURLConnection as follows:

  1. Set your NSURLRequest: Use requestWithURL:(NSURL *)theURL to initialise the request.

    If you need to specify a POST request and/or HTTP headers, use NSMutableURLRequest with

    • (void)setHTTPMethod:(NSString *)method
    • (void)setHTTPBody:(NSData *)data
    • (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
  2. Send your request in 2 ways using NSURLConnection:

    • Synchronously: (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

      This returns a NSData variable that you can process.

      IMPORTANT: Remember to kick off the synchronous request in a separate thread to avoid blocking the UI.

    • Asynchronously: (void)start

Don't forget to set your NSURLConnection's delegate to handle the connection as follows:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [ setLength:0];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
    [ appendData:d];

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
                                 message:[error localizedDescription]
                       cancelButtonTitle:NSLocalizedString(@"OK", @"") 
                       otherButtonTitles:nil] autorelease] show];

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseText = [[NSString alloc] encoding:NSUTF8StringEncoding];

    // Do anything you want with it 

    [responseText release];

// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSString *username = @"username";
    NSString *password = @"password";

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];

How to convert string to integer in PowerShell

Once you have selected the highest value, which is "12" in my example, you can then declare it as integer and increment your value:

$FileList = "1", "2", "11"
$foldername = [int]$FileList[2] + 1

Where does R store packages?

This is documented in the 'R Installation and Administration' manual that came with your installation.

On my Linux box:

R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"      
[3] "/usr/lib/R/library"           

meaning that the default path is the first of these. You can override that via an argument to both install.packages() (from inside R) or R CMD INSTALL (outside R).

You can also override by setting the R_LIBS_USER variable.

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

if you still need to use the double-colon then make sure your on PHP 5.3+

'git status' shows changed files, but 'git diff' doesn't

I had a similar problem: git diff would show differences, but git diff <filename> would not. It turned out that I set LESS to a string including -F (--quit-if-one-screen). Removing that flag solved the problem.

ruby LoadError: cannot load such file

The problem shall have solved if you specify your path.


"require 'st.rb'" --> "require './st.rb'"

See if your problem get solved or not.

How can I search an array in VB.NET?

This would do the trick, returning the values at indeces 0, 2 and 3.

Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

SPA best practices for authentication and session management

I would go for the second, the token system.

Did you know about ember-auth or ember-simple-auth? They both use the token based system, like ember-simple-auth states:

A lightweight and unobtrusive library for implementing token based authentication in Ember.js applications.

They have session management, and are easy to plug into existing projects too.

There is also an Ember App Kit example version of ember-simple-auth: Working example of ember-app-kit using ember-simple-auth for OAuth2 authentication.

Android button onClickListener

Use OnClicklistener or you can use android:onClick="myMethod" in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod function in class look like this.

public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);

And in that SecondActivity.class set new layout in contentview.

Can a Windows batch file determine its own file name?

Bear in mind that 0 is a special case of parameter numbers inside a batch file, where 0 means this file as given on the command line.

So if the file is myfile.bat, you could call it in several ways as follows, each of which would give you a different output from the %0 or %~0 usage:






All of the above are legal calls if you call it from the correct relative place to the directory in which it exists. %~0 strips the quotes from the last example, whereas %0 does not.

Because these all give different results, %0 and %~0 are very unlikely to be what you actually want to use.

Here's a batch file to illustrate:

@echo Full path and filename: %~f0
@echo Drive: %~d0
@echo Path: %~p0
@echo Drive and path: %~dp0
@echo Filename without extension: %~n0
@echo Filename with    extension: %~nx0
@echo Extension: %~x0
@echo Filename as given on command line: %0
@echo Filename as given on command line minus quotes: %~0
@REM Build from parts
@SET drv=%~d0
@SET pth=%~p0
@SET fpath=%~dp0
@SET fname=%~n0
@SET ext=%~x0
@echo Simply Constructed name: %fpath%%fname%%ext%
@echo Fully  Constructed name: %drv%%pth%%fname%%ext%

Launching Google Maps Directions via an intent on Android

try this

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(""+src_lat+","+src_ltg+"&daddr="+des_lat+","+des_ltg));
intent.setClassName("", "");

Simple way to sort strings in the (case sensitive) alphabetical order

The simple way to solve the problem is to use ComparisonChain from Guava

private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
        public int compare(String str1, String str2) {
            return ComparisonChain.start().
                                compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
Collections.sort(list, stringAlphabeticalComparator);

The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:


How to find the largest file in a directory and its subdirectories?

Quote from this link-

If you want to find and print the top 10 largest files names (not directories) in a particular directory and its sub directories

$ find . -printf '%s %p\n'|sort -nr|head

To restrict the search to the present directory use "-maxdepth 1" with find.

$ find . -maxdepth 1 -printf '%s %p\n'|sort -nr|head

And to print the top 10 largest "files and directories":

$ du -a . | sort -nr | head

** Use "head -n X" instead of the only "head" above to print the top X largest files (in all the above examples)

How can I pass a class member function as a callback?

This question and answer from the C++ FAQ Lite covers your question and the considerations involved in the answer quite nicely I think. Short snippet from the web page I linked:


Because a member function is meaningless without an object to invoke it on, you can’t do this directly (if The X Window System was rewritten in C++, it would probably pass references to objects around, not just pointers to functions; naturally the objects would embody the required function and probably a whole lot more).

Apache - MySQL Service detected with wrong path. / Ports already in use

hello i have had same problem an i did the steps with tommer and the problem solved thank you

note :

you don't have to go to that like just do this ;

1)-- Edit your “my.ini” file in c:\xampp\mysql\bin\ Change all default 3306 port entries to a new value 3308

2)--edit your “php.ini” in c:\xampp\php and replace 3306 by 3308

3)--Create the service entry - in Windows command line type

sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"

4)--Open Windows Services and set Startup Type: Automatic, Start the service

How to calculate modulus of large numbers?

To add to Jason's answer:

You can speed the process up (which might be helpful for very large exponents) using the binary expansion of the exponent. First calculate 5, 5^2, 5^4, 5^8 mod 221 - you do this by repeated squaring:

 5^1 = 5(mod 221)
 5^2 = 5^2 (mod 221) = 25(mod 221)
 5^4 = (5^2)^2 = 25^2(mod 221) = 625 (mod 221) = 183(mod221)
 5^8 = (5^4)^2 = 183^2(mod 221) = 33489 (mod 221) = 118(mod 221)
5^16 = (5^8)^2 = 118^2(mod 221) = 13924 (mod 221) = 1(mod 221)
5^32 = (5^16)^2 = 1^2(mod 221) = 1(mod 221)

Now we can write

55 = 1 + 2 + 4 + 16 + 32

so 5^55 = 5^1 * 5^2 * 5^4 * 5^16 * 5^32 
        = 5   * 25  * 625 * 1    * 1 (mod 221)
        = 125 * 625 (mod 221)
        = 125 * 183 (mod 183) - because 625 = 183 (mod 221)
        = 22875 ( mod 221)
        = 112 (mod 221)

You can see how for very large exponents this will be much faster (I believe it's log as opposed to linear in b, but not certain.)

How to change the docker image installation directory?

Much easier way to do so:

Stop docker service

sudo systemctl stop docker

Move existing docker directory to new location

sudo mv /var/lib/docker/ /path/to/new/docker/

Create symbolic link

sudo ln -s /path/to/new/docker/ /var/lib/docker

Start docker service

sudo systemctl start docker

How to make div occupy remaining height?

Use absolute positioning:

    width: 100%;_x000D_
    height: 50px;_x000D_
    background-color:red;/*Development Only*/_x000D_
    width: 100%;_x000D_
    position: absolute;_x000D_
    top: 50px;_x000D_
    bottom: 0;_x000D_
    background-color:blue;/*Development Only*/_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>

How do I wait for an asynchronously dispatched block to finish?

Trying to use a dispatch_semaphore. It should look something like this:

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

[object runSomeLongOperationAndDo:^{


if (![NSThread isMainThread]) {
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
} else {
    while (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW)) { 
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]]; 

This should behave correctly even if runSomeLongOperationAndDo: decides that the operation isn't actually long enough to merit threading and runs synchronously instead.

How to change the port of Tomcat from 8080 to 80?

If someone is looking for, how to change the tomcat port number in Eclipse IDE user following are the steps.

1.In the Servers view, double click on the server name: enter image description here

2.That will open a configuration page for Tomcat as follows: enter image description here

3.Notice the port numbers are shown in the table on the right. Click to edit, for example: enter image description here

4.That will change port number for HTTP from 8080 to 80. Press Ctrl + S to save the change and restart the server. We can spot the change of port number in the Console view: enter image description here

This all content were taken from below link, please refer that link for further information thanks.

Is it possible to write data to file using only JavaScript?

const data = {name: 'Ronn', age: 27};              //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob); = 'sample-profile';                     //filename to download;

Check Blob documentation here - Blob MDN to provide extra parameters for file type. By default it will make .txt file

Setting environment variables on OS X

Sometimes all of the previous answers simply don't work. If you want to have access to a system variable (like M2_HOME) in Eclipse or in IntelliJ IDEA the only thing that works for me in this case is:

First (step 1) edit /etc/launchd.conf to contain a line like this: "setenv VAR value" and then (step 2) reboot.

Simply modifying .bash_profile won't work because in OS X the applications are not started as in other Unix'es; they don't inherit the parent's shell variables. All the other modifications won't work for a reason that is unknown to me. Maybe someone else can clarify about this.

Get the ID of a drawable in ImageView

Digging StackOverflow for answers on the similar issue I found people usually suggesting 2 approaches:

  • Load a drawable into memory and compare ConstantState or bitmap itself to other one.
  • Set a tag with drawable id into a view and compare tags when you need that.

Personally, I like the second approach for performance reason but tagging bunch of views with appropriate tags is painful and time consuming. This could be very frustrating in a big project. In my case I need to write a lot of Espresso tests which require comparing TextView drawables, ImageView resources, View background and foreground. A lot of work.

So I eventually came up with a solution to delegate a 'dirty' work to the custom inflater. In every inflated view I search for a specific attributes and and set a tag to the view with a resource id if any is found. This approach is pretty much the same guys from Calligraphy used. I wrote a simple library for that: TagView

If you use it, you can retrieve any of predefined tags, containing drawable resource id that was set in xml layout file:


The library supports any attribute, actually. You can add them manually, just look into the Custom attributes section on Github. If you set a drawable in runtime you can use convenient library methods:

setImageViewResource(ImageView view, int id)

In this case tagging is done for you internally. If you use Kotlin you can write a handy extensions to call view itself. Something like this:

fun ImageView.setImageResourceWithTag(@DrawableRes int id) {
    TagViewUtils.setImageViewResource(this, id)

You can find additional info in Tagging in runtime

Most popular screen sizes/resolutions on Android phones


  • 240*320-ldpi
  • 240*400-ldpi
  • 240*432-ldpi

  • 320*480-mdpi
  • 480*800-mdpi
  • 480*854-mdpi
  • 1024*600-mdpi
  • 1280*800-mdpi

  • 480*800-hdpi
  • 480*854-hdpi
  • 280*280-hdpi
  • 320*320-hdpi

  • 720*1280-xhdpi
  • 1200*1290-xhdpi
  • 2560*1600-xhdpi
  • 768*1280-xhdpi

  • 1080*1920-xxhdpi
  • 800*1280-tvdpi

I use these reference to make my app

Quoting an answer from another stackOverflow post for more details

---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------                                                          
Galaxy Y                                 320 x  240     ldpi    0.75    120      427 x 320      4:3     1.3333                   427 x 320
?                                        400 x  240     ldpi    0.75    120      533 x 320      5:3     1.6667                   533 x 320
?                                        432 x  240     ldpi    0.75    120      576 x 320      9:5     1.8000                   576 x 320
Galaxy Ace                               480 x  320     mdpi    1       160      480 x 320      3:2     1.5000                   480 x 320
Nexus S                                  800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
"Galaxy SIII    Mini"                    800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
?                                        854 x  480     hdpi    1.5     240      569 x 320      427:240 1.7792                   569 x 320

Galaxy SIII                             1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Galaxy Nexus                            1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
HTC One X                       4.7"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 5                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778      YES          592 x 360
Galaxy S4                       5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note III                 5.7"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One Max                     5.9"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note II                  5.6"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 4                         4.4"    1200 x  768     xhdpi   2       320      600 x 384      25:16   1.5625      YES          552 x 384
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
?                                        800 x  480     mdpi    1       160      800 x 480      5:3     1.6667                   800 x 480
?                                        854 x  480     mdpi    1       160      854 x 480      427:240 1.7792                   854 x 480
Galaxy Mega                     6.3"    1280 x  720     hdpi    1.5     240      853 x 480      16:9    1.7778                   853 x 480
Kindle Fire HD                  7"      1280 x  800     hdpi    1.5     240      853 x 533      8:5     1.6000                   853 x 533
Galaxy Mega                     5.8"     960 x  540     tvdpi   1.33333 213.333  720 x 405      16:9    1.7778                   720 x 405
Sony Xperia Z Ultra             6.4"    1920 x 1080     xhdpi   2       320      960 x 540      16:9    1.7778                   960 x 540

Kindle Fire (1st & 2nd gen)     7"      1024 x  600     mdpi    1       160     1024 x 600      128:75  1.7067                  1024 x 600
Tesco Hudl                      7"      1400 x  900     hdpi    1.5     240      933 x 600      14:9    1.5556                   933 x 600
Nexus 7 (1st gen/2012)          7"      1280 x  800     tvdpi   1.33333 213.333  960 x 600      8:5     1.6000      YES          912 x 600
Nexus 7 (2nd gen/2013)          7"      1824 x 1200     xhdpi   2       320      912 x 600      38:25   1.5200      YES          864 x 600
Kindle Fire HDX                 7"      1920 x 1200     xhdpi   2       320      960 x 600      8:5     1.6000                   960 x 600
?                                        800 x  480     ldpi    0.75    120     1067 x 640      5:3     1.6667                  1067 x 640
?                                        854 x  480     ldpi    0.75    120     1139 x 640      427:240 1.7792                  1139 x 640

Kindle Fire HD                  8.9"    1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Kindle Fire HDX                 8.9"    2560 x 1600     xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 2                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 3                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer                10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer 2              10"     1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Nexus 10                        10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Note 10.1                10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------

Oracle SqlPlus - saving output in a file but don't show on screen

Try this:

spool M:\Documents\test;
select * from employees;
spool off;

How can I run a windows batch file but hide the command window?

Create a shortcut to your bat file by using the right-click and selecting Create shortcut. Right-click on the shortcut you created and click on properties. Click on the Run drop-down box and select Minimized.

How to trigger HTML button when you press Enter in textbox?


How to overlay image with color in CSS?

Use mutple backgorund on the element, and use a linear-gradient as your color overlay by declaring both start and end color-stops as the same value.

Note that layers in a multi-background declaration are read much like they are rendered, top-to-bottom, so put your overlay first, then your bg image:

#header {
    linear-gradient(to bottom, rgba(100, 100, 0, 0.5), rgba(100, 100, 0, 0.5)) cover,
    url(../img/bg.jpg) 0 0 no-repeat fixed;
  height: 100%;
  overflow: hidden;
  color: #FFFFFF

Java random numbers using a seed

If you're giving the same seed, that's normal. That's an important feature allowing tests.

Check this to understand pseudo random generation and seeds:

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
    return generator.nextDouble()*0.5;

Use Font Awesome Icon in Placeholder

Use placeholder="&#xF002;" in your input. You can find unicode in FontAwesome page . But you have to make sure add style="font-family: FontAwesome;" in your input.

Convert between UIImage and Base64 string

SWIFT 3.0, XCODE 8.0

Replace String with your URL. and testImage is an outlet of ImageView

// Put Your Image URL
let url:NSURL = NSURL(string : "http://.jpg")!
// It Will turn Into Data
let imageData : NSData = NSData.init(contentsOf: url as URL)!
// Data Will Encode into Base64
let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
// Now Base64 will Decode Here
let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)!
// turn  Decoded String into Data
let dataImage = UIImage(data: data as Data)
// pass the data image to image View.:)
testImage.image = dataImage

Hope It Helps Thanks.

How to edit hosts file via CMD?

echo >> %WINDIR%\System32\Drivers\Etc\Hosts

the >> appends the output of echo to the file.

Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.

First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.

Second, it requires you to add an entry for every host name on a domain; just adding will not block, for example.

How to use sudo inside a docker container?

Just got it. As regan pointed out, I had to add the user to the sudoers group. But the main reason was I'd forgotten to update the repositories cache, so apt-get couldn't find the sudo package. It's working now. Here's the completed code:

FROM ubuntu:12.04

RUN apt-get update && \
      apt-get -y install sudo

RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo

USER docker
CMD /bin/bash

How to access remote server with local phpMyAdmin client?

I would have added this as a comment, but my reputation is not yet high enough.

Under version, and I am guessing any other versions 4.5.x or newer. There is no need to modify the file at all. Instead go one more directory down conf.d.

Create a new file with the '.php' extension and add the lines. This is a better modularized approach and isolates each remote database server access information.

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

You can also get timeout errors based on silly typos. e.g This seemingly innocuous mistake:

describe('Something', () => {
  it('Should do something', () => {

  it('Should do nothing', something_that_does_not_exist => {

Produces the following error:

FAIL src/TestNothing.spec.js (5.427s)
  ? Something › Should do nothing

    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
      at node_modules/jest-jasmine2/build/queue_runner.js:68:21
      at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:678:19)

Whilst the code sample posted doesn't suffer from this it might be a cause of failures elsewhere. Also note that I'm not setting a timeout for anything anywhere - either here or in the config. The 5000ms is just the default setting.

How to fix 'sudo: no tty present and no askpass program specified' error?

Using pipeline:

echo your_pswd | sudo -S your_cmd

Using here-document:

sudo -S cmd <<eof
#remember to put the above two lines without "any" indentations.

Open a terminal to ask password (whichever works):

gnome-terminal -e "sudo cmd"
xterm -e "sudo cmd"

Column/Vertical selection with Keyboard in SublimeText 3

This should do it:

  1. Ctrl+A - select all.
  2. Ctrl+Shift+L - split selection into lines.
  3. Then move all cursors with left/right, select with Shift+left/right. Move all cursors to start of line with Home.

Range with step of type float

The problem with floating point is that you may not get the same number of items as you expected, due to inaccuracy. This can be a real problem if you are playing with polynomials where the exact number of items is quite important.

What you really want is an arithmetic progression; the following code will work quite happily for int, float and complex ... and strings, and lists ...

def arithmetic_progression(start, step, length):
    for i in xrange(length):
        yield start + i * step

Note that this code stands a better chance of your last value being within a bull's roar of the expected value than any alternative which maintains a running total.

>>> 10000 * 0.0001, sum(0.0001 for i in xrange(10000))
(1.0, 0.9999999999999062)
>>> 10000 * (1/3.), sum(1/3. for i in xrange(10000))
(3333.333333333333, 3333.3333333337314)

Correction: here's a competetive running-total gadget:

def kahan_range(start, stop, step):
    assert step > 0.0
    total = start
    compo = 0.0
    while total < stop:
        yield total
        y = step - compo
        temp = total + y
        compo = (temp - total) - y
        total = temp

>>> list(kahan_range(0, 1, 0.0001))[-1]
>>> list(kahan_range(0, 3333.3334, 1/3.))[-1]

Is Java a Compiled or an Interpreted programming language ?

Java does both compilation and interpretation,

In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then interprets / executes at runtime. Java source code is compiled into bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file extension .class.

When the program is to be run, the bytecode is converted the bytecode may be converted, using the just-in-time (JIT) compiler. The result is machine code which is then fed to the memory and is executed.

Javac is the Java Compiler which Compiles Java code into Bytecode. JVM is Java Virtual Machine which Runs/ Interprets/ translates Bytecode into Native Machine Code. In Java though it is considered as an interpreted language, It may use JIT (Just-in-Time) compilation when the bytecode is in the JVM. The JIT compiler reads the bytecodes in many sections (or in full, rarely) and compiles them dynamically into machine code so the program can run faster, and then cached and reused later without needing to be recompiled. So JIT compilation combines the speed of compiled code with the flexibility of interpretation.

An interpreted language is a type of programming language for which most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions. The interpreter executes the program directly, translating each statement into a sequence of one or more subroutines already compiled into machine code.

A compiled language is a programming language whose implementations are typically compilers (translators that generate machine code from source code), and not interpreters (step-by-step executors of source code, where no pre-runtime translation takes place)

In modern programming language implementations like in Java, it is increasingly popular for a platform to provide both options.

@angular/material/index.d.ts' is not a module


// old code that breaks
import { MatDialogModule,
  MatButtonModule} from '@angular/material';

? DO:

// new code that works
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';

? Because:

Components can no longer be imported through "@angular/material". Use the individual secondary entry-points, such as @angular/material/button.

Use virtualenv with Python with Visual Studio Code in Ubuntu

I put the absolute path of the virtual environment Python executable as well has the packages. I then restarted Visual Studio Code.

I am trying to get ${workspaceRoot} to avoid hardcoding absolute paths.

    "editor.rulers": [80,100],
    "python.pythonPath": "/home/jesvin/dev/ala/venv/bin/python",
    "python.autoComplete.extraPaths": [

Extract subset of key-value pairs from Python dictionary object?


subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n']])

Python 3 even supports the following:

subdict={a:bigdict[a] for a in ['l','m','n']}

Note that you can check for existence in dictionary as follows:

subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n'] if x in bigdict])

resp. for python 3

subdict={a:bigdict[a] for a in ['l','m','n'] if a in bigdict}

System.Drawing.Image to stream C#

public static Stream ToStream(this Image image)
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;

Extension methods must be defined in a non-generic static class

Add keyword static to class declaration:

// this is a non-generic static class
public static class LinqHelper

Fatal error: Call to undefined function curl_init()

curl is an extension that needs to be installed, it's got nothing to do with the PHP version.

How do I determine the dependencies of a .NET application?

Another handy Reflector add-in that I use is the Dependency Structure Matrix. It's really great to see what classes use what. Plus it's free.

How to download an entire directory and subdirectories using wget?

You may use this in shell:

wget -r --no-parent

The Parameters are:

-r     //recursive Download


--no-parent // Don´t download something from the parent directory

If you don't want to download the entire content, you may use:

-l1 just download the directory (tzivi in your case)

-l2 download the directory and all level 1 subfolders ('tzivi/something' but not 'tivizi/somthing/foo')  

And so on. If you insert no -l option, wget will use -l 5 automatically.

If you insert a -l 0 you´ll download the whole Internet, because wget will follow every link it finds.

Objective-C Static Class Level variables

Another possibility would be to have a little NSNumber subclass singleton.

Select All as default value for Multivalue parameter

Adding to the answer from E_8.
This does not work if you have empty strings.

You can get around this by modifying your select statement in SQL or modifying your query in the SSRS dataset.

 Select distinct phonenumber
from YourTable
where phonenumber <> ''
Order by Phonenumber

Java 8 - Best way to transform a list: map or foreach?

One of the main benefits of using streams is that it gives the ability to process data in a declarative way, that is, using a functional style of programming. It also gives multi-threading capability for free meaning there is no need to write any extra multi-threaded code to make your stream concurrent.

Assuming the reason you are exploring this style of programming is that you want to exploit these benefits then your first code sample is potentially not functional since the foreach method is classed as being terminal (meaning that it can produce side-effects).

The second way is preferred from functional programming point of view since the map function can accept stateless lambda functions. More explicitly, the lambda passed to the map function should be

  1. Non-interfering, meaning that the function should not alter the source of the stream if it is non-concurrent (e.g. ArrayList).
  2. Stateless to avoid unexpected results when doing parallel processing (caused by thread scheduling differences).

Another benefit with the second approach is if the stream is parallel and the collector is concurrent and unordered then these characteristics can provide useful hints to the reduction operation to do the collecting concurrently.

How to use the 'main' parameter in package.json?

If you have for instance in your package.json file:

"name": "zig-zag",
"main": "lib/entry.js",

lib/entry.js will be the main entry point to your package.

When calling


in node, lib/entry.js will be the actual file that is required.

Passing just a type as a parameter in C#

You can use an argument of type Type - iow, pass typeof(int). You can also use generics for a (probably more efficient) approach.

Populate a datagridview with sql query results

This is suppose to be the safest and error pron query :

    public void Load_Data()
            using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
                var bindingSource = new BindingSource();
                string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
                       SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                        DataTable table = new DataTable();
                        bindingSource.DataSource = table;
                        recent_slides_grd_view.ReadOnly = true;
                        recent_slides_grd_view.DataSource = bindingSource;
                    catch (SqlException ex)
                       MessageBox.Show(ex.Message.ToString(), "ERROR Loading");


How do I get bit-by-bit data from an integer value in C?

@prateek thank you for your help. I rewrote the function with comments for use in a program. Increase 8 for more bits (up to 32 for an integer).

std::vector <bool> bits_from_int (int integer)    // discern which bits of PLC codes are true
    std::vector <bool> bool_bits;

    // continously divide the integer by 2, if there is no remainder, the bit is 1, else it's 0
    for (int i = 0; i < 8; i++)
        bool_bits.push_back (integer%2);    // remainder of dividing by 2
        integer /= 2;    // integer equals itself divided by 2

    return bool_bits;

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Make docker use IPv4 for port binding


USE docker run -it -p 80:80 --name nginx --net=host -d nginx

that's issue we face with VM some time instead of bridge network try with host that will work for you

tcp     0    0  *             LISTEN      - 
tcp6    0    0 :::80                 :::*                  LISTEN      -  

Create boolean column in MySQL with false as default value?

You have to specify 0 (meaning false) or 1 (meaning true) as the default. Here is an example:

create table mytable (
     mybool boolean not null default 0

FYI: boolean is an alias for tinyint(1).

Here is the proof:

mysql> create table mytable (
    ->          mybool boolean not null default 0
    ->     );
Query OK, 0 rows affected (0.35 sec)

mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from mytable;
| mybool |
|      0 |
1 row in set (0.00 sec)

FYI: My test was done on the following version of MySQL:

mysql> select version();
| version()      |
| 5.0.18-max-log |
1 row in set (0.00 sec)

How do I get a list of all subdomains of a domain?

If you can't get this information from DNS (e.g. you aren't authorized) then one alternative is to use Wolfram Alpha.

  1. Enter the domain into the search box and run the search. (E.g.

Wolfram - Homepage

  1. In the 3rd section from the top (named "Web statistics for all of") click Subdomains

Wolfram - Subdomains button

  1. In the Subdomains section click More

Wolfram - More subdomains button

You will be able to see a list of sub-domains there. Although I suspect it does not show ALL sub-domains.

Create table using Javascript

Slightly shorter code using insertRow and insertCell:

function tableCreate(){_x000D_
    var body = document.body,_x000D_
        tbl  = document.createElement('table');_x000D_  = '100px';_x000D_ = '1px solid black';_x000D_
    for(var i = 0; i < 3; i++){_x000D_
        var tr = tbl.insertRow();_x000D_
        for(var j = 0; j < 2; j++){_x000D_
            if(i == 2 && j == 1){_x000D_
            } else {_x000D_
                var td = tr.insertCell();_x000D_
       = '1px solid black';_x000D_
                if(i == 1 && j == 1){_x000D_
                    td.setAttribute('rowSpan', '2');_x000D_

Also, this doesn't use some "bad practices", such as setting a border attribute instead of using CSS, and it accesses the body through document.body instead of document.getElementsByTagName('body')[0];

Change drive in git bash for windows

In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].

Insert a row to pandas dataframe

Below would be the best way to insert a row into pandas dataframe without sorting and reseting an index:

import pandas as pd

df = pd.DataFrame(columns=['a','b','c'])

def insert(df, row):
    insert_loc = df.index.max()

    if pd.isna(insert_loc):
        df.loc[0] = row
        df.loc[insert_loc + 1] = row


How to set HTTP headers (for cache-control)?

OWASP recommends the following,

Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.

<IfModule mod_headers.c>
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"

Hot to get all form elements values using jQuery?

jQuery has very helpful function called serialize.


//Just type:

//to get result:

onchange event on input type=range is not triggering in firefox while dragging

Yet another approach - just set a flag on an element signaling which type of event should be handled:

function setRangeValueChangeHandler(rangeElement, handler) {
    rangeElement.oninput = (event) => {
        // Save flag that we are using onInput in current browser = true;

    rangeElement.onchange = (event) => {
        // Call only if we are not using onInput in current browser
        if (! {

How to do sed like text replace with python?

If I want something like sed, then I usually just call sed itself using the sh library.

from sh import sed

sed(['-i', 's/^# deb/deb/', '/etc/apt/sources.list'])

Sure, there are downsides. Like maybe the locally installed version of sed isn't the same as the one you tested with. In my cases, this kind of thing can be easily handled at another layer (like by examining the target environment beforehand, or deploying in a docker image with a known version of sed).

Apache shutdown unexpectedly

On your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):

there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".

Start apache now.

If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):

there, look for the line "Listen 443" and change it to "Listen 7331".

Start apache, it should be working now.

How to switch back to 'master' with git?

You need to checkout the branch:

git checkout master

See the Git cheat sheets for more information.

Edit: Please note that git does not manage empty directories, so you'll have to manage them yourself. If your directory is empty, just remove it directly.

select2 onchange event only works once

My select2 element was not firing the onchange event as the drop down list offered only one value, making it impossible to change the value.

The value not having changed, no event was fired and the handler could not execute.

I then added another handler to clear the value, with the select2-open handler being executed before the onchange handler.

The source code now looks like:

el.on("select2-open", function(e) {
el.on('change', function() {

The first handler clears the value, allowing the second handler to fire up even if selecting the same value.

How to grep for contents after pattern?

Modern BASH has support for regular expressions:

while read -r line; do
  if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
    echo "${BASH_REMATCH[1]}"

Can I convert a boolean to Yes/No in a ASP.NET GridView

I had the same need as the original poster, except that my client's db schema is a nullable bit (ie, allows for True/False/NULL). Here's some code I wrote to both display Yes/No and handle potential nulls.


public string ConvertNullableBoolToYesNo(object pBool)
    if (pBool != null)
        return (bool)pBool ? "Yes" : "No";
        return "No";


<%# ConvertNullableBoolToYesNo(Eval("YOUR_FIELD"))%>

Javascript to export html table to Excel

If you add:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

in the head of the document it will start working as expected:

<script type="text/javascript">
var tableToExcel = (function() {
  var uri = 'data:application/;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns=""><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))

Updated Fiddle Here.

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

Javascript: How to pass a function with string parameters as a parameter to another function

Try this:


Then you just need to call these two functions passed to myfunction:

function myfunction(url, f1, f2) {
    // …

jquery .on() method with load event

I'm not sure what you're going for here--by the time jQuery(document).ready() has executed, it has already loaded, and thus document's load event will already have been called. Attaching the load event handler at this point will have no effect and it will never be called. If you're attempting to alert "started" once the document has loaded, just put it right in the (document).ready() call, like this:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {



If, as your code also appears to insinuate, you want to fire the alert when .abc has loaded, put it in an individual .load handler:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {

    $(".abc").on("load", function() {

Finally, I see little point in using jQuery in one place and $ in another. It's generally better to keep your code consistent, and either use jQuery everywhere or $ everywhere, as the two are generally interchangeable.

Counting array elements in Python

The method len() returns the number of elements in the list.




myArray = [1, 2, 3]



Using Tkinter in python to edit the title bar

Easy method:

root = Tk()
root.title('Hello World')

Bootstrap 3 only for mobile

I found a solution wich is to do:

<span class="visible-sm"> your code without col </span>
<span class="visible-xs"> your code with col </span>

It's not very optimized but it works. Did you find something better? It really miss a class like col-sm-0 to apply colons just to the xs size...

Checking if a variable exists in javascript

I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but

If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...

is not the only way. One can do just:


to check if there is a variable bar declared in the current context. (I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).

How to display an unordered list in two columns?

With Bootstrap... This answer ( got me pointed towards this solution:

<ul class="list-unstyled row">
   <li class="col-xs-6">Item 1</li>
   <li class="col-xs-6">Item 2</li>
   <li class="col-xs-6">Item 3</li>

How do I represent a time only value in .NET?

You can use timespan

TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString());     // Displays "02:14:18".

Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.

Show/Hide Table Rows using Javascript classes

It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.

Here's the fiddle: link.

What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>s with class="cat1" or class="cat2".

I also mark the links with a simple .toggler class. It's not good practice to have onclick attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.

    // you handle the event here

With this format, you are binding an event handler to the click event of links with class toggler. In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. (The reason for my using a data-* attribute is explained here. You can Google 'html5 data attributes' for more information.)

In the event handler, I do this:


With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggles the visibility of the specified element(s).

I hope this was explanatory enough.

Checking for an empty file in C++

Ok, so this piece of code should work for you. I changed the names to match your parameter.

inFile.seekg(0, ios::end);  
if (inFile.tellg() == 0) {    
  // something with empty file...  

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Another way to do this, is using directly a parameter on the libreoffice command:

libreoffice --convert-to pdf /path/to/file.{doc,docx}

---- ---- ---- ---- ---- ---- Explanation ---- ---- ---- ---- ---- ----

First you need to download and install LibreOffice. Can be downloaded from Here
Now open your terminal / command prompt then go to libreOffice root, for windows it may be OS/Program Files/LibreOffice/program here you'll find an executable soffice.exe

Here you can convert it directly by the above mentioned commands or you may also use :
soffice in place of libreoffice

How to use boolean datatype in C?

As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:

<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
    <div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
        <div class="uil-default-css">
            <img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
        <div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;">&nbsp;</div>
    <div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>

Finally, replace .loader-text element's content on the fly on every navigation event and turn on the #resultloading div, note that it is initially hidden.

var showLoader = function (text) {

jQuery(document).ready(function () {
    jQuery(window).on("beforeunload ", function () {
        showLoader('Loading, please wait...');

This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.

The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.

Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.

Gradle DSL method not found: 'runProguard'

By changing runProguard to minifyEnabled, part of the issue gets fixed.

But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").

By removing application Id in the build.gradle file, you should be good to go.

iframe refuses to display

For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:

Content-Security-Policy: frame-ancestors 'self'

Or, add this to your web server's CSP configuration.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:

Component    | Submit          | Refresh
------------ | --------------- | --------------
f:ajax       | execute="@this" | render="@none"
p:ajax       | process="@this" | update="@none"
p:commandXXX | process="@form" | update="@none"

What is the shortest function for reading a cookie by name in JavaScript?

How about this one?

function getCookie(k){var v=document.cookie.match('(^|;) ?'+k+'=([^;]*)(;|$)');return v?v[2]:null}

Counted 89 bytes without the function name.

How to allow only one radio button to be checked?

All radio buttons have to have the same name:

<input type='radio' name='foo'>

Only 1 radio button of each group of buttons with the same name can be checked.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

Python vs Cpython

Even I had the same problem understanding how are CPython, JPython, IronPython, PyPy are different from each other.

So, I am willing to clear three things before I begin to explain:

  1. Python: It is a language, it only states/describes how to convey/express yourself to the interpreter (the program which accepts your python code).
  2. Implementation: It is all about how the interpreter was written, specifically, in what language and what it ends up doing.
  3. Bytecode: It is the code that is processed by a program, usually referred to as a virtual machine, rather than by the "real" computer machine, the hardware processor.

CPython is the implementation, which was written in C language. It ends up producing bytecode (stack-machine based instruction set) which is Python specific and then executes it. The reason to convert Python code to a bytecode is because it's easier to implement an interpreter if it looks like machine instructions. But, it isn't necessary to produce some bytecode prior to execution of the Python code (but CPython does produce).

If you want to look at CPython's bytecode then you can. Here's how you can:

>>> def f(x, y):                # line 1
...    print("Hello")           # line 2
...    if x:                    # line 3
...       y += x                # line 4
...    print(x, y)              # line 5
...    return x+y               # line 6
...                             # line 7
>>> import dis                  # line 8
>>> dis.dis(f)                  # line 9
  2           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('Hello')
              4 CALL_FUNCTION            1
              6 POP_TOP

  3           8 LOAD_FAST                0 (x)
             10 POP_JUMP_IF_FALSE       20

  4          12 LOAD_FAST                1 (y)
             14 LOAD_FAST                0 (x)
             16 INPLACE_ADD
             18 STORE_FAST               1 (y)

  5     >>   20 LOAD_GLOBAL              0 (print)
             22 LOAD_FAST                0 (x)
             24 LOAD_FAST                1 (y)
             26 CALL_FUNCTION            2
             28 POP_TOP

  6          30 LOAD_FAST                0 (x)
             32 LOAD_FAST                1 (y)
             34 BINARY_ADD

Now, let's have a look at the above code. Lines 1 to 6 are a function definition. In line 8, we import the 'dis' module which can be used to view the intermediate Python bytecode (or you can say, disassembler for Python bytecode) that is generated by CPython (interpreter).

NOTE: I got the link to this code from #python IRC channel:

And then, there is Jython, which is written in Java and ends up producing Java byte code. The Java byte code runs on Java Runtime Environment, which is an implementation of Java Virtual Machine (JVM). If this is confusing then I suspect that you have no clue how Java works. In layman terms, Java (the language, not the compiler) code is taken by the Java compiler and outputs a file (which is Java byte code) that can be run only using a JRE. This is done so that, once the Java code is compiled then it can be ported to other machines in Java byte code format, which can be only run by JRE. If this is still confusing then you may want to have a look at this web page.

Here, you may ask if the CPython's bytecode is portable like Jython, I suspect not. The bytecode produced in CPython implementation was specific to that interpreter for making it easy for further execution of code (I also suspect that, such intermediate bytecode production, just for the ease the of processing is done in many other interpreters).

So, in Jython, when you compile your Python code, you end up with Java byte code, which can be run on a JVM.

Similarly, IronPython (written in C# language) compiles down your Python code to Common Language Runtime (CLR), which is a similar technology as compared to JVM, developed by Microsoft.

smooth scroll to top

theMaxx answer works in nuxt/vue, smooth scrolling is default behavior

<button @click=scrollToTop()>Jump to top of page

  methods: {
    scrollToTop() {
      window.scrollTo({ top: 0 });

Could not load file or assembly System.Net.Http, Version= with ASP.NET (MVC 4) Web API OData Prerelease

Visual Studio 2013 has a new feature to take care of this. When you build the app, you should see warnings about different versions of an assembly being referenced. Double click the warning to add assembly binding redirects to the web.config.

See for more details.

jeff.eynon notes below that you need to have the web.config checked out (if using TFS source control) to get VS to edit the file automatically. Thanks for the tip!

How to dynamic filter options of <select > with jQuery?

You can use select2 plugin for creating such a filter. With this lot's of coding work can be avoided. You can grab the plugin from

This plugin is much simple to apply and even advanced work can be easily done with it. :)

Setting a log file name to include current date in Log4j

I'm 99% sure that RollingFileAppender/DailyRollingFileAppender, while it gives you the date-rolling functionality you want, doesn't have any way to specify that the current log file should use the DatePattern as well.

You might just be able to simply subclass RollingFileAppender (or DailyRollingFileAppender, I forget which is which in log4net) and modify the naming logic.

How to run vbs as administrator from vbs?

`My vbs file path :

D:\QTP Practice\Driver\Testany.vbs'

objShell = CreateObject("Shell.Application")

objShell.ShellExecute "cmd.exe","/k echo test", "", "runas", 1

set x=createobject("")


x.sendkeys "CD\"&"{ENTER}"&"cd D:"&"{ENTER}"&"cd "&"QTP Practice\Driver"&"{ENTER}"&"Testany.vbs"&"{ENTER}"

--from google search and some tuning, working for me

Render basic HTML view?

If you are trying to serve an HTML file which ALREADY has all it's content inside it, then it does not need to be 'rendered', it just needs to be 'served'. Rendering is when you have the server update or inject content before the page is sent to the browser, and it requires additional dependencies like ejs, as the other answers show.

If you simply want to direct the browser to a file based on their request, you should use res.sendFile() like this:

const express = require('express');
const app = express();
var port = process.env.PORT || 3000; //Whichever port you want to run on
app.use(express.static('./folder_with_html')); //This ensures local references to cs and js files work

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/folder_with_html/index.html');

app.listen(port, () => console.log("lifted app; listening on port " + port));

This way you don't need additional dependencies besides express. If you just want to have the server send your already created html files, the above is a very lightweight way to do so.

Make just one slide different size in Powerpoint

true, this option is not available in any version of MS ppt.Now the solution is that You put your different sized slide in other file and put a hyperlink in first file.

Python: IndexError: list index out of range

As the error notes, the problem is in the line:

if guess[i] == winning_numbers[i]

The error is that your list indices are out of range--that is, you are trying to refer to some index that doesn't even exist. Without debugging your code fully, I would check the line where you are adding guesses based on input:

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")

The size of how many guesses you are giving your user is based on

# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

So if the number of tickets they want is less than 5, then your code here

for i in range(5):

if guess[i] == winning_numbers[i]:
    match = match+1

return match

will throw an error because there simply aren't that many elements in the guess list.

How to find the Number of CPU Cores via .NET/C#?

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);


int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
    coreCount += int.Parse(item["NumberOfCores"].ToString());
Console.WriteLine("Number Of Cores: {0}", coreCount);

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);


foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args)
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
                deviceCount = deviceNumber;
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    Console.WriteLine("Number of cores: {0}", deviceCount);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

private struct SP_DEVINFO_DATA
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;

private enum DIGCF
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,

querySelectorAll with multiple conditions

Is it possible to make a search by querySelectorAll using multiple unrelated conditions?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:

var list = document.querySelectorAll("form, p, legend");

...will return a list containing any element that is a form or p or legend.

CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:

var list = document.querySelectorAll("");

...will return a list of all div elements that also (and) have the class foo, ignoring other div elements.

You can, of course, combine them:

var list = document.querySelectorAll(",, div legend");

...which means "Include any div element that also has the foo class, any p element that also has the bar class, and any legend element that's also inside a div."

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

How to get an isoformat datetime string including the default timezone?

You need to make your datetime objects timezone aware. from the datetime docs:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

When you have an aware datetime object, you can use isoformat() and get the output you need.

To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

Using pytz, this would look like:

import datetime, pytz'US/Central')).isoformat()

You can also control the output format, if you use strftime with the '%z' format directive like'US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

Remove trailing zeros from decimal in SQL Server

How about this? Assuming data coming into your function as @thisData:

  DECLARE @thisText VARCHAR(255)
  SET @thisText = REPLACE(RTRIM(REPLACE(@thisData, '0', ' ')), ' ', '0')
  IF SUBSTRING(@thisText, LEN(@thisText), 1) = '.'
    RETURN STUFF(@thisText, LEN(@thisText), 1, '')
  RETURN @thisText

How to replace list item in best way

Following rokkuchan's answer, just a little upgrade:

List<string> listOfStrings = new List<string> {"abc", "123", "ghi"};

int index = listOfStrings.FindIndex(ind => ind.Equals("123"));
if (index > -1)
    listOfStrings[index] =  "def";

How can I get the line number which threw exception?

Simple way, use the Exception.ToString() function, it will return the line after the exception description.

You can also check the program debug database as it contains debug info/logs about the whole application.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar

How to get enum value by string or int

Could be much simpler if you use TryParse or Parse and ToObject methods.

public static class EnumHelper
    public static  T GetEnumValue<T>(string str) where T : struct, IConvertible
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
            throw new Exception("T must be an Enumeration type.");
        T val;
        return Enum.TryParse<T>(str, true, out val) ? val : default(T);

    public static T GetEnumValue<T>(int intValue) where T : struct, IConvertible
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
            throw new Exception("T must be an Enumeration type.");

        return (T)Enum.ToObject(enumType, intValue);

As noted by @chrfin in comments, you can make it an extension method very easily just by adding this before the parameter type which can be handy.

Can anyone explain python's relative imports?

If you are going to call directly and i.e. if you really want to import from a top level module you have to explicitly add it to the sys.path list.
Here is how it should work:

# Add this line to the beginning of file
import sys

# Now you can do imports from one directory top cause it is in the sys.path
import parent

# And even like this:
from parent import Parent

If you think the above can cause some kind of inconsistency you can use this instead:

sys.path.append(sys.path[0] + "/..")

sys.path[0] refers to the path that the entry point was ran from.

codeigniter model error: Undefined property

It solved throung second parameter in Model load:


first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
$result = $this->User->showusers();

How to manage exceptions thrown in filters in Spring?

If you want a generic way, you can define an error page in web.xml:


And add mapping in Spring MVC:

public class ErrorController {

    public @ResponseBody String handleException(HttpServletRequest req) {
        // you can get the exception thrown
        Throwable t = (Throwable)req.getAttribute("javax.servlet.error.exception");

        // customize response to what you want
        return "Internal server error.";

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

In android app Toolbar.setTitle method has no effect – application name is shown as title

To set the title for each Navbar fragment title

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    myView = inflater.inflate(R.layout.second_layout, container, false);

    return myView;

make a header full screen (width) css


<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="style.css"
<ul class="menu">
    <li><a href="#">My Dashboard</a>
            <li><a href="#" class="learn">Learn</a></li>
            <li><a href="#" class="teach">Teach</a></li>
            <li><a href="#" class="Mylibrary">My Library</a></li>
    <li><a href="#">Likes</a>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
    <li><a href="#">Views</a>
            <li><a href="#" class="documents">Documents</a></li>
            <li><a href="#" class="messages">Messages</a></li>
            <li><a href="#" class="signout">Videos</a></li>
        <li><a href="#">account</a>
            <li><a href="#" class="SI">Sign In</a></li>
            <li><a href="#" class="Reg">Register</a></li>
            <li><a href="#" class="Deactivate">Deactivate</a></li>
    <li><a href="#">Uploads</a>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
    <li><a href="#">Videos</a>
            <li><a href="#" class="Add">Add</a></li>
            <li><a href="#" class="delete">Delete</a></li>
    <li><a href="#">Documents</a>
            <li><a href="#" class="Add">Upload</a></li>
            <li><a href="#" class="delete">Download</a></li>


.menu ul,
.menu li,
.menu a {
    margin: 0;
    padding: 0;
    border: none;
    outline: none;
.menu {
    height: 40px;

    background: #4c4e5a;
    background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);

    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
.menu li {
    position: relative;
    list-style: none;
    float: left;
    display: block;
    height: 40px;
.menu li a {
    display: block;
    padding: 0 14px;
    margin: 6px 0;
    line-height: 28px;
    text-decoration: none;

    border-left: 1px solid #393942;
    border-right: 1px solid #4f5058;

    font-family: Helvetica, Arial, sans-serif;
    font-weight: bold;
    font-size: 13px;

    color: #f3f3f3;
    text-shadow: 1px 1px 1px rgba(0,0,0,.6);

    -webkit-transition: color .2s ease-in-out;
    -moz-transition: color .2s ease-in-out;
    -o-transition: color .2s ease-in-out;
    -ms-transition: color .2s ease-in-out;
    transition: color .2s ease-in-out;

.menu li:first-child a { border-left: none; }
.menu li:last-child a{ border-right: none; }

.menu li:hover > a { color: #8fde62; }
.menu ul {
    position: absolute;
    top: 40px;
    left: 0;

    opacity: 0;
    background: #1f2024;

    -webkit-border-radius: 0 0 5px 5px;
    -moz-border-radius: 0 0 5px 5px;
    border-radius: 0 0 5px 5px;

    -webkit-transition: opacity .25s ease .1s;
    -moz-transition: opacity .25s ease .1s;
    -o-transition: opacity .25s ease .1s;
    -ms-transition: opacity .25s ease .1s;
    transition: opacity .25s ease .1s;

.menu li:hover > ul { opacity: 1; }

.menu ul li {
    height: 0;
    overflow: hidden;
    padding: 0;

    -webkit-transition: height .25s ease .1s;
    -moz-transition: height .25s ease .1s;
    -o-transition: height .25s ease .1s;
    -ms-transition: height .25s ease .1s;
    transition: height .25s ease .1s;

.menu li:hover > ul li {
    height: 36px;
    overflow: visible;
    padding: 0;

.menu ul li a {
    width: 100px;
    padding: 4px 0 4px 40px;
    margin: 0;

    border: none;
    border-bottom: 1px solid #353539;

.menu ul li:last-child a { border: none; }

demo here

try also resizing the browser tab to see it in action

How do I center a Bootstrap div with a 'spanX' class?

Incidentally, if your span class is even-numbered (e.g. span8) you can add an offset class to center it – for span8 that would be offset2 (assuming the default 12-column grid), for span6 it would be offset3 and so on (basically, half the number of remaining columns if you subtract the span-number from the total number of columns in the grid).

UPDATE Bootstrap 3 renamed a lot of classes so all the span*classes should be col-md-* and the offset classes should be col-md-offset-*, assuming you're using the medium-sized responsive grid.

I created a quick demo here, hope it helps:

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
      AND A.ITEM_KEY = b.item_key
      AND = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

Delaying AngularJS route change until model loaded to prevent flicker

This snippet is dependency injection friendly (I even use it in combination of ngmin and uglify) and it's a more elegant domain driven based solution.

The example below registers a Phone resource and a constant phoneRoutes, which contains all your routing information for that (phone) domain. Something I didn't like in the provided answer was the location of the resolve logic -- the main module should not know anything or be bothered about the way the resource arguments are provided to the controller. This way the logic stays in the same domain.

Note: if you're using ngmin (and if you're not: you should) you only have to write the resolve functions with the DI array convention.

angular.module('myApp').factory('Phone',function ($resource) {
  return $resource('/api/phone/:id', {id: '@id'});
}).constant('phoneRoutes', {
    '/phone': {
      templateUrl: 'app/phone/index.tmpl.html',
      controller: 'PhoneIndexController'
    '/phone/create': {
      templateUrl: 'app/phone/edit.tmpl.html',
      controller: 'PhoneEditController',
      resolve: {
        phone: ['$route', 'Phone', function ($route, Phone) {
          return new Phone();
    '/phone/edit/:id': {
      templateUrl: 'app/phone/edit.tmpl.html',
      controller: 'PhoneEditController',
      resolve: {
        form: ['$route', 'Phone', function ($route, Phone) {
          return Phone.get({ id: $ }).$promise;

The next piece is injecting the routing data when the module is in the configure state and applying it to the $routeProvider.

angular.module('myApp').config(function ($routeProvider, 
                                         /* ... otherRoutes ... */) {

  $routeProvider.when('/', { templateUrl: 'app/main/index.tmpl.html' });

  // Loop through all paths provided by the injected route data.

  angular.forEach(phoneRoutes, function(routeData, path) {
    $routeProvider.when(path, routeData);

  $routeProvider.otherwise({ redirectTo: '/' });


Testing the route configuration with this setup is also pretty easy:

describe('phoneRoutes', function() {

  it('should match route configuration', function() {


    // Mock the Phone resource
    function PhoneMock() {}
    PhoneMock.get = function() { return {}; };

    module(function($provide) {
      $provide.value('Phone', FormMock);

    inject(function($route, $location, $rootScope, phoneRoutes) {
      angular.forEach(phoneRoutes, function (routeData, path) {



You can see it in full glory in my latest (upcoming) experiment. Although this method works fine for me, I really wonder why the $injector isn't delaying construction of anything when it detects injection of anything that is a promise object; it would make things soooOOOOOooOOOOO much easier.

Edit: used Angular v1.2(rc2)

How to pass an array into a function, and return the results with an array

You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)

function foo(&$arr) { # note the &
  $arr[3] = $arr[0]+$arr[1]+$arr[2];
$waffles = array(1,2,3);
echo $waffles[3]; # prints 6

That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt


for a,b in zip(x, y): 
    plt.text(a, b, str(b))

How to modify STYLE attribute of element with known ID using JQuery

$("span").mouseover(function () {

Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.

Is there an equivalent to background-size: cover and contain for image elements?

We can take ZOOM approach. We can assume that max 30% (or more upto 100%) can be the zooming effect if aspect image height OR width is less than the desired height OR width. We can hide the rest not needed area with overflow: hidden.

.image-container {
  width: 200px;
  height: 150px;
  overflow: hidden;
.stage-image-gallery a img {
  max-height: 130%;
  max-width: 130%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);

This will adjust images with different width OR height.

Connection Strings for Entity Framework

Silverlight applications do not have direct access to machine.config.

Moment.js get day name from date


var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');

mydate is the input date. The variable weekDayName get the name of the day. Here the output is



var mydate = "2017-08-30T00:00:00";_x000D_
console.log('Day in number[0,1,2,3,4,5,6]: '+moment(mydate).format('d'));_x000D_
<script src=""></script>

trying to animate a constraint in swift

You need to first change the constraint and then animate the update.
This should be in the superview.

self.nameInputConstraint.constant = 8

Swift 2

UIView.animateWithDuration(0.5) {

Swift 3, 4, 5

UIView.animate(withDuration: 0.5) {

android start activity from service

one cannot use the Context of the Service; was able to get the (package) Context alike:

Intent intent = new Intent(getApplicationContext(), SomeActivity.class);

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()


How do I solve this "Cannot read property 'appendChild' of null" error?

Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.

Most efficient way to concatenate strings in JavaScript?

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.

(Thanks @zAlbee for correction)

How to close a web page on a button click, a hyperlink or a link button click?

To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Thanks for the original answer here. With python 3 the following line of code:


was ok. Consider trying not writing too much text in the code if it's not imperative.

This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2)

basically install he_IL or whatever language locale on ubuntu check it is not installed

locale -a 

install it where XX is your language

sudo apt-get install language-pack-XX

For example:

sudo apt-get install language-pack-he

add the following text to /etc/apache2/envvrs

export LANG='he_IL.UTF-8'
export LC_ALL='he_IL.UTF-8'

Than you would hopefully not get python errors on from apache like:

print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)

Also in apache try to make utf the default encoding as explained here:
How to change the default encoding to UTF-8 for Apache?

Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation

Close a MessageBox after several seconds

If anyone wants AutoClosingMessageBox in c++ I have implemented the equivalent code here is the link to gists

static intptr_t MessageBoxHookProc(int nCode, intptr_t wParam, intptr_t lParam)
    if (nCode < 0)
        return CallNextHookEx(hHook, nCode, wParam, lParam);

    auto msg = reinterpret_cast<CWPRETSTRUCT*>(lParam);
    auto hook = hHook;

    //Hook Messagebox on Initialization.
    if (!hookCaption.empty() && msg->message == WM_INITDIALOG)
        int nLength = GetWindowTextLength(msg->hwnd);
        char* text = new char[captionLen + 1];

        GetWindowText(msg->hwnd, text, captionLen + 1);

        //If Caption window found Unhook it.
        if (hookCaption == text)
            hookCaption = string("");
            SetTimer(msg->hwnd, (uintptr_t)timerID, hookTimeout, (TIMERPROC)hookTimer);
            hHook = 0;

    return CallNextHookEx(hook, nCode, wParam, lParam);

make *** no targets specified and no makefile found. stop

Unpack the source from a working directory and cd into the file directory as root. Use the commands ./configure then make and make install

ORA-01438: value larger than specified precision allows for this column

This indicates you are trying to put something too big into a column. For example, you have a VARCHAR2(10) column and you are putting in 11 characters. Same thing with number.

This is happening at line 176 of package UMAIN. You would need to go and have a look at that to see what it is up to. Hopefully you can look it up in your source control (or from user_source). Later versions of Oracle report this error better, telling you which column and what value.

SQL alias for SELECT statement

You could store this into a temporary table.

So instead of doing the CTE/sub query you would use a temp table.

Good article on these here

Ruby: How to turn a hash into HTTP parameters?

Update: This functionality was removed from the gem.

Julien, your self-answer is a good one, and I've shameless borrowed from it, but it doesn't properly escape reserved characters, and there are a few other edge cases where it breaks down.

require "addressable/uri"
uri =
uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
# => "a=a&b[0]=c&b[1]=d&b[2]=e"
uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
# => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
# => "a=a&b[c]=c&b[d]=d"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
# => "a=a&b[c]=c&b[d]"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
# => "a=a&b[c]=c&b[d]"

The gem is 'addressable'

gem install addressable

Default value to a parameter while passing by reference in C++

I have a workaround for this, see the following example on default value for int&:

class Helper
    int x;
    operator int&() { return x; }

// How to use it:
void foo(int &x = Helper())


You can do it for any trivial data type you want, such as bool, double ...

Failed to load AppCompat ActionBar with unknown error in android studio

I was also facing the same problem. Nothing like changing theme from Layout preview window helped me.

What helped me was adding this to Apptheme in styles.xml:

dependencies {
    implementation ''
    implementation ''

Still it was giving me the error: "cannot resolve symbol widget...coordinatorLayout". Then I updated my build.gradle(app) with:

dependencies {
    implementation ''
    implementation ''

One more thing:

compileSdkVersion 27
targetSdkVersion 27

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

Try setting the definer for the function!

So instead of

CREATE FUNCTION get_pet_owner

you will write something akin to

CREATE DEFINER=procadmin@% FUNCTION get_pet_owner

which ought to work if the user prodacmin has rights to create functions/procedures.

In my case the function worked when generated through MySQL Workbench but did not work when run directly as an SQL script. Making the changes above fixed the problem.

How to disable a button when an input is empty?

You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.

Example using state:

<meta charset="UTF-8">_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
var App = React.createClass({_x000D_
  getInitialState() {_x000D_
    return {email: ''}_x000D_
  handleChange(e) {_x000D_
  render() {_x000D_
    return <div>_x000D_
      <input name="email" value={} onChange={this.handleChange}/>_x000D_
      <button type="button" disabled={!}>Button</button>_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_

Get the string value from List<String> through loop for display

List<String> al=new ArrayList<string>();

for(String al1:al) //for each construct

O/p will be


#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

Base ond defualt config of 5.7.5 ONLY_FULL_GROUP_BY You should use all the not aggregate column in your group by

select libelle,credit_initial,disponible_v,sum(montant) as montant 
FROM fiche,annee,type 
where type.id_type=annee.id_type 
and annee.id_annee=fiche.id_annee 
and annee = year(current_timestamp) 
GROUP BY libelle,credit_initial,disponible_v order by libelle asc

Calculating arithmetic mean (one type of average) in Python

from statistics import mean

for example

from statistics import mean


and result is


How to use systemctl in Ubuntu 14.04

I ran across this while on a hunt for answers myself after attempting to follow a guide using pm2. The goal is to automatically start a node.js application on a server. Some guides call out using pm2 startup systemd, which is the path that leads to the question of using systemctl on Ubuntu 14.04. Instead, use pm2 startup ubuntu.


How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">

Yes, the meta tag has to be the FIRST tag after HEAD.

How do you use math.random to generate random ints?

double  i = 2+Math.random()*100;
int j = (int)i;

In c# what does 'where T : class' mean?

where T: class literally means that T has to be a class. It can be any reference type. Now whenever any code calls your DoThis<T>() method it must provide a class to replace T. For example if I were to call your DoThis<T>() method then I will have to call it like following:


If your metthod is like like the following:

public IList<T> DoThis<T>() where T : class
   T variablename = new T();

   // other uses of T as a type


Then where ever T appears in your method, it will be replaced by MyClass. So the final method that the compiler calls , will look like the following:

public IList<MyClass> DoThis<MyClass>() 
   MyClass variablename= new MyClass();

  //other uses of MyClass as a type

  // all occurences of T will similarly be replace by MyClass

Checkout subdirectories in Git?

You can revert uncommitted changes only to particular file or directory:

git checkout [some_dir|file.txt]

Can you 'exit' a loop in PHP?

break; leaves your loop.

continue; skips any code for the remainder of that loop and goes on to the next loop, so long as the condition is still true.

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

How to make padding:auto work in CSS?

The simplest supported solution is to either use margin

.element {
  display: block;
  margin: 0px auto;

Or use a second container around the element that has this margin applied. This will somewhat have the effect of padding: 0px auto if it did exist.


.element_wrapper {
  display: block;
  margin: 0px auto;
.element {
  background: blue;


<div class="element_wrapper">
  <div class="element">
    Hello world

How do I set response headers in Flask?

We can set the response headers in Python Flask application using Flask application context using flask.g

This way of setting response headers in Flask application context using flask.g is thread safe and can be used to set custom & dynamic attributes from any file of application, this is especially helpful if we are setting custom/dynamic response headers from any helper class, that can also be accessed from any other file ( say like middleware, etc), this flask.g is global & valid for that request thread only.

Say if i want to read the response header from another api/http call that is being called from this app, and then extract any & set it as response headers for this app.

Sample Code: file:

import flask
from flask import request, g
from multidict import CIMultiDict
from asyncio import TimeoutError as HttpTimeout
from aiohttp import ClientSession

    def _extract_response_header(response)
      extracts response headers from response object 
      and stores that required response header in flask.g app context
      headers = CIMultiDict(response.headers)
      if 'my_response_header' not in g:
        g.my_response_header= {}
        g.my_response_header['x-custom-header'] = headers['x-custom-header']

    async def call_post_api(post_body):
      sample method to make post api call using aiohttp clientsession
        async with ClientSession() as session:
          async with, headers=_headers, json=post_body) as response:
            responseResult = await
            _extract_headers(response, responseResult)
            response_text = await response.text()
      except (HttpTimeout, ConnectionError) as ex:
        raise HttpTimeout(exception_message)


import flask
from flask import request, g

class SimpleMiddleWare(object):
    Simple WSGI middleware

    def __init__(self, app): = app
        self._header_name = "any_request_header"

    def __call__(self, environ, start_response):
        middleware to capture request header from incoming http request
        request_id_header = environ.get(self._header_name)
        environ[self._header_name] = request_id_header

        def new_start_response(status, response_headers, exc_info=None):
            set custom response headers
            # set the request header as response header
            response_headers.append((self._header_name, request_id_header))
            # this is trying to access flask.g values set in helper class & set that as response header
            values = g.get(my_response_header, {})
            if values.get('x-custom-header'):
                response_headers.append(('x-custom-header', values.get('x-custom-header')))
            return start_response(status, response_headers, exc_info)

        return, new_start_response)

Calling the middleware from main class

file :

from flask import Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare

    app = Flask(__name__)
    app.wsgi_app = SimpleMiddleWare(app.wsgi_app)

Facebook Callback appends '#_=_' to Return URL

Adding this to my redirect page fixed the problem for me ...

if (window.location.href.indexOf('#_=_') > 0) {
    window.location = window.location.href.replace(/#.*/, '');

Sublime Text 2 - View whitespace characters

I've several plugins (including Unicode Character Highlighter), but the only one which found the character that was hiding from me today was Highlighter.

You can test to see if it's working by pasting in the text from the readme.

For reference, the character causing me trouble was ?.

For a sanity check, tap your right arrow key over a range of text containing an invisible character, and you'll need to right-arrow twice to move past the character.

I'm also using the following custom regex string (which I don't fully grok):

    // there's an extra range in use [^\\x00-\\x7F]
    // also, don't highlight spaces at the end of the line (my settings take care of that)
    "highlighter_regex": "(\t+ +)|( +\t+)|[^\\x00-\\x7F]|[\u2026\u2018\u2019\u201c\u201d\u2013\u2014]"

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

You defined your method as non-static and you are trying to invoke it as static. That said...

1.if you want to invoke a static method, you should use the :: and define your method as static.

// Defining a static method in a Foo class.
public static function getAll() { /* code */ }

// Invoking that static method

2.otherwise, if you want to invoke an instance method you should instance your class, use ->.

// Defining a non-static method in a Foo class.
public function getAll() { /* code */ }

// Invoking that non-static method.
$foo = new Foo();

Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:

$foos = Foo::all()->take(10)->get();

In that code we are statically calling the all method via Facade. After that, all other methods are being called as instance methods.

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

Including a css file in a blade template?

You should try this :

{{ Html::style('css/styles.css') }}


<link href="{{ asset('css/styles.css') }}" rel="stylesheet">

Hope this help for you !!!

Using msbuild to execute a File System Publish Profile

Still had trouble after trying all of the answers above (I use Visual Studio 2013). Nothing was copied to the publish folder.

The catch was that if I run MSBuild with an individual project instead of a solution, I have to put an additional parameter that specifies Visual Studio version:


12.0 is for VS2013, replace with the version you use. Once I added this parameter, it just worked.

The complete command line looks like this:

MSBuild C:\PathToMyProject\MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile /p:VisualStudioVersion=12.0

I've found it here:

They state:

If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.

Is there a better way to run a command N times in bash?

Using GNU Parallel you can do:

parallel some_command ::: {1..1000}

If you do not want the number as argument and only run a single job at a time:

parallel -j1 -N0 some_command ::: {1..1000}

Watch the intro video for a quick introduction:

Walk through the tutorial ( You command line with love you for it.

How can I debug a HTTP POST in Chrome?

The other people made very nice answers, but I would like to complete their work with an extra development tool. It is called Live HTTP Headers and you can install it into your Firefox, and in Chrome we have the same plug in like this.

Working with it is queit easy.

  1. Using your Firefox, navigate to the website which you want to get your post request to it.

  2. In your Firefox menu Tools->Live Http Headers

  3. A new window pop ups for you, and all the http method details would be saved in this window for you. You don't need to do anything in this step.

  4. In the website, do an activity(log in, submit a form, etc.)

  5. Look at your plug in window. It is all recorded.

Just remember you need to check the Capture.

enter image description here

Django database query: How to get object by id?

In case you don't have some id, e.g.,, you can use get_object_or_404 importing by from django.shortcuts import get_object_or_404.

Use example:

def myFunc(request, my_pk):
    my_var = get_object_or_404(CLASS_NAME, pk=my_pk)

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6 repository. My repository was using jQuery 3, but foundation requires an earlier version. I then changed it and it worked.

If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0".

Can you confirm that you are loading the correct version of jQuery?

I hope this helps.

jQuery text() and newlines

You can use html instead of text and replace each occurrence of \n with <br>. You will have to correctly escape your text though.

x = x.replace(/&/g, '&amp;')
     .replace(/>/g, '&gt;')
     .replace(/</g, '&lt;')
     .replace(/\n/g, '<br>');

How can I calculate the difference between two ArrayLists?

You already have the right answer. And if you want to make more complicated and interesting operations between Lists (collections) use apache commons collections (CollectionUtils) It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things.

Are static methods inherited in Java?

Static members will not be inherited to subclass because inheritance is only for non-static members.. And static members will be loaded inside static pool by class loader. Inheritance is only for those members which are loaded inside the object

Horizontal scroll on overflow of table

   .search-table-outter {border:2px solid red; overflow-x:scroll;}
   .search-table{table-layout: fixed; margin:40px auto 0px auto;   }
   .search-table, td, th{border-collapse:collapse; border:1px solid #777;}
   th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
   td{padding:5px 10px; height:35px;}

You should provide scroll in div.

Does --disable-web-security Work In Chrome Anymore?

Check your windows task manager and make sure you kill all chrome processes before running the command.

Equivalent of Math.Min & Math.Max for Dates?

There's no built in method to do that. You can use the expression:

(date1 > date2 ? date1 : date2)

to find the maximum of the two.

You can write a generic method to calculate Min or Max for any type (provided that Comparer<T>.Default is set appropriately):

public static T Max<T>(T first, T second) {
    if (Comparer<T>.Default.Compare(first, second) > 0)
        return first;
    return second;

You can use LINQ too:

new[]{date1, date2, date3}.Max()

Why do we need the "finally" clause in Python?

Using delphi professionally for some years taught me to safeguard my cleanup routines using finally. Delphi pretty much enforces the use of finally to clean up any resources created before the try block, lest you cause a memory leak. This is also how Java, Python and Ruby works.

resource = create_resource
  use resource

and resource will be cleaned up regardless of what you do between try and finally. Also, it won't be cleaned up if execution never reaches the try block. (i.e. create_resource itself throws an exception) It makes your code "exception safe".

As to why you actually need a finally block, not all languages do. In C++ where you have automatically called destructors which enforce cleanup when an exception unrolls the stack. I think this is a step up in the direction of cleaner code compared to try...finally languages.

  type object1;
  smart_pointer<type> object1(new type());
} // destructors are automagically called here in LIFO order so no finally required.

form confirm before submit

    <form method="post">
        name<input type="text" name="text">
        <input type="submit" value="submit" onclick="return confirm('Are you sure you want to Save?')">

open program minimized via command prompt

You could try using the third-party tool called NirCmd. It is a genuine, free command line utility. If or when you have it, use this code in a batch file:

title Open Word
nircmd win hide title "Open Word"
start "C:\Program" "Files" "(x86)\Microsoft" "Office\Office12\WINWORD.exe
nircmd wait 20
nircmd win min foreground

This program, in order, changes its title, hides itself according to its title, starts Word, waits 20 milliseconds as a buffer for Word to settle, minimizes Word by assuming it is now the top window, and then exits itself. This program should work as intended as long as their are no key presses or clicks in that ~50 millisecond time window, which shouldn't be hard.

As for installing nircmd on your computer, use this link, and click "Download NirCmd" at the bottom of the page. Save the .zip folder to a normal directory (like "My Documents"), extract it, and copy "nircmd.exe" to %systemroot%\system32, and there you go. Now you have nircmd included with your command line utilities.

Python - How to concatenate to a string in a for loop?

That's not how you do it.

>>> ''.join(['first', 'second', 'other'])

is what you want.

If you do it in a for loop, it's going to be inefficient as string "addition"/concatenation doesn't scale well (but of course it's possible):

>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
...    s += item
>>> s

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

PHP multidimensional array search by value

If question i.e.

$a = [
       "_id" => "5a96933414d48831a41901f2",
       "discount_amount" => 3.29,
       "discount_id" => "5a92656a14d488570c2c44a2",
       "_id" => "5a9790fd14d48879cf16a9e8",
       "discount_amount" => 4.53,
       "discount_id" => "5a9265b914d488548513b122",
       "_id" => "5a98083614d488191304b6c3",
       "discount_amount" => 15.24,
       "discount_id" => "5a92806a14d48858ff5c2ec3",
       "_id" => "5a982a4914d48824721eafe3",
       "discount_amount" => 45.74,
       "discount_id" => "5a928ce414d488609e73b443",
       "_id" => "5a982a4914d48824721eafe55",
       "discount_amount" => 10.26,
       "discount_id" => "5a928ce414d488609e73b443",


function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['discount_id'] === $id) {
           $dia +=$val['discount_amount'];
    if($dia != '') {
        echo $dia;
   return null;

How to silence output in a Bash script?

Note: This answer is related to the question "How to turn off echo while executing a shell script Linux" which was in turn marked as duplicated to this one.

To actually turn off the echo the command is:

stty -echo

(this is, for instance; when you want to enter a password and you don't want it to be readable. Remember to turn echo on at the end of your script, otherwise the person that runs your script won't see what he/she types in from then on. To turn echo on run:

stty echo

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));

Java - Convert String to valid URI object

Or perhaps you could use this class:

Which is present in Android since API level 1.

Annoyingly however, it treats spaces specially (replacing them with + instead of %20). To get round this we simply use this fragment:

URLEncoder.encode(value, "UTF-8").replace("+", "%20");

AngularJS $http-post - convert binary to excel file and download

Just noticed you can't use it because of IE8/9 but I'll push submit anyway... maybe someone finds it useful

This can actually be done through the browser, using blob. Notice the responseType and the code in the success promise.

    url: 'your/webservice',
    method: "POST",
    data: json, //this is your json data string
    headers: {
       'Content-type': 'application/json'
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    var objectUrl = URL.createObjectURL(blob);;
}).error(function (data, status, headers, config) {
    //upload failed

There are some problems with it though like:

  1. It doesn't support IE 8 and 9:
  2. It opens a pop up window to open the objectUrl which people might have blocked
  3. Generates weird filenames

It did work!

blob The server side code in PHP I tested this with looks like this. I'm sure you can set similar headers in Java:

$file = "file.xlsx";
header('Content-disposition: attachment; filename='.$file);
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo json_encode(readfile($file));

Edit 20.04.2016

Browsers are making it harder to save data this way. One good option is to use filesaver.js. It provides a cross browser implementation for saveAs, and it should replace some of the code in the success promise above.

Avoid trailing zeroes in printf()

I like the answer of R. slightly tweaked:

float f = 1234.56789;
printf("%d.%.0f", f, 1000*(f-(int)f));

'1000' determines the precision.

Power to the 0.5 rounding.


Ok, this answer was edited a few times and I lost track what I was thinking a few years back (and originally it did not fill all the criteria). So here is a new version (that fills all criteria and handles negative numbers correctly):

double f = 1234.05678900;
char s[100]; 
int decimals = 10;

sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf("10 decimals: %d%s\n", (int)f, s+1);

And the test cases:

#import <stdio.h>
#import <stdlib.h>
#import <math.h>

int main(void){

    double f = 1234.05678900;
    char s[100];
    int decimals;

    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf("10 decimals: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" 3 decimals: %d%s\n", (int)f, s+1);

    f = -f;
    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative 10: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative  3: %d%s\n", (int)f, s+1);

    decimals = 2;
    f = 1.012;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" additional : %d%s\n", (int)f, s+1);

    return 0;

And the output of the tests:

 10 decimals: 1234.056789
  3 decimals: 1234.057
 negative 10: -1234.056789
 negative  3: -1234.057
 additional : 1.01

Now, all criteria are met:

  • maximum number of decimals behind the zero is fixed
  • trailing zeros are removed
  • it does it mathematically right (right?)
  • works (now) also when first decimal is zero

Unfortunately this answer is a two-liner as sprintf does not return the string.

How to match letters only using java regex, matches method?

Three problems here:

  1. Just use String.matches() - if the API is there, use it
  2. In java "matches" means "matches the entire input", which IMHO is counter-intuitive, so let your method's API reflect that by letting callers think about matching part of the input as your example suggests
  3. You regex matches only 1 character

I recommend you use code like this:

public boolean matches(String regex) {
    regex = "^.*" + regex + ".*$"; // pad with regex to allow partial matching
    System.out.println("abcABC   ".matches(regex));
    return "abcABC   ".matches(regex);

public static void main(String[] args) {
    HowEasy words = new HowEasy();
    words.matches("[a-zA-Z]+"); // added "+" (ie 1-to-n of) to character class

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

self.automaticallyAdjustsScrollViewInsets = NO;

This was deprecated in iOS 11, so you should use new property contentInsetAdjustmentBehavior in your code, it should fix the problem.

if #available(iOS 11.0, *) {
    collectionView.contentInsetAdjustmentBehavior = .never

There is a new property on UIScrollView called contentInsetAdjustmentBehavior added in iOS 11 to determine adjust content offset

How to check the maximum number of allowed connections to an Oracle database?

I thought this would work, based on this source.

  'Currently, ' 
  || ' out of ' 
  || ' connections are used.' AS USAGE_MESSAGE

However, Justin Cave is right. This query gives better results:

  'Currently, ' 
  || ' out of ' 
  || VP.VALUE 
  || ' connections are used.' AS USAGE_MESSAGE
WHERE VP.NAME = 'sessions'

I can not find my.cnf on my windows computer

you can search this file : resetroot.bat

just double click it so that your root accout will be reset and all the privileges are turned into YES

PDF to byte array and vice versa

PDFs may contain binary data and chances are it's getting mangled when you do ToString. It seems to me that you want this:

        FileInputStream inputStream = new FileInputStream(sourcePath);

        int numberBytes = inputStream .available();
        byte bytearray[] = new byte[numberBytes];

        inputStream .read(bytearray);

Write to CSV file and export it?

How to write to a file (easy search in Google) ... 1st Search Result

As far as creation of the file each time a user accesses the page ... each access will act on it's own behalf. You business case will dictate the behavior.

Case 1 - same file but does not change (this type of case can have multiple ways of being defined)

  • You would have logic that created the file when needed and only access the file if generation is not needed.

Case 2 - each user needs to generate their own file

  • You would decide how you identify each user, create a file for each user and access the file they are supposed to see ... this can easily merge with Case 1. Then you delete the file after serving the content or not if it requires persistence.

Case 3 - same file but generation required for each access

  • Use Case 2, this will cause a generation each time but clean up once accessed.

Creating .pem file for APNS?

Development Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Development .pem needed for Push Notifications in Development Phase of App.

If 3rd step was performed, run:
cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

If 3rd step was not performed, run:
cat apns-dev-cert.pem apns-dev-key.pem > apns-dev.pem

Step 5: Check certificate validity and connectivity to APNS

If 3rd step was performed, run:
openssl s_client -connect -cert apns-dev-cert.pem -key apns-dev-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect -cert apns-dev-cert.pem -key apns-dev-key.pem

Production Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-pro-cert.pem -in apns-pro-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-pro-key.pem -in apns-pro-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-pro-key.pem -out apns-pro-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Production .pem needed for Push Notifications in Production Phase of App.

If 3rd step was performed, run:
cat apns-pro-cert.pem apns-pro-key-noenc.pem > apns-pro.pem

If 3rd step was not performed, run:
cat apns-pro-cert.pem apns-pro-key.pem > apns-pro.pem

Step 5: Check certificate validity and connectivity to APNS.

If 3rd step was performed, run:
openssl s_client -connect -cert apns-pro-cert.pem -key apns-pro-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect -cert apns-pro-cert.pem -key apns-pro-key.pem

How do you get the width and height of a multi-dimensional array?

Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#

public void ArraysAreRowMajor()
    var myArray = new int[2,3]
            {1, 2, 3},
            {4, 5, 6}

    int rows = myArray.GetLength(0);
    int columns = myArray.GetLength(1);

Maintaining Session through Angular.js

You would use a service for that in Angular. A service is a function you register with Angular, and that functions job is to return an object which will live until the browser is closed/refreshed. So it's a good place to store state in, and to synchronize that state with the server asynchronously as that state changes.

How to get "wc -l" to print just the number of lines without file name?

To do this without the leading space, why not:

wc -l < file.txt | bc

How to change link color (Bootstrap)

I'm fully aware that the code in the original quesiton displays a situation of being navbar related. But as you also dive into other compontents, it maybe helpful to know that the class options for text styling may not work.

But you can still create your own helper classes to keep the "Bootstrap flow" going in your HTML. Here is one idea to help style links that are in panel-title regions.

The following code by itself will not style a warning color on your anchor link...

<div class="panel panel-default my-panel-styles"> 
  <h4 class="panel-title">
    <a class="accordion-toggle btn-block text-warning" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
      My Panel title that is also a link

But you could extend the Bootstrap styling package by adding your own class with appropriate colors like this...

.my-panel-styles .text-muted {color:#777;}
.my-panel-styles .text-primary {color:#337ab7;}
.my-panel-styles .text-success {color:#d44950;}
.my-panel-styles .text-info {color:#31708f;}
.my-panel-styles .text-warning {color:#8a6d3b;}
.my-panel-styles .text-danger {color:#a94442;}

...Now you can continue building out your panel anchor links with the Bootstrap colors you want.

Python conversion from binary string to hexadecimal

On python3 using the hexlify function:

import binascii
def bin2hex(str1):
    bytes_str = bytes(str1, 'utf-8')
    return binascii.hexlify(bytes_str)


Will give you back:


and you can get the string of it like: