Programs & Examples On #C10k

c10k describes the ability of a server to handle 10,000 simultaneous clients.

How to check if a Java 8 Stream is empty?

The other answers and comments are correct in that to examine the contents of a stream, one must add a terminal operation, thereby "consuming" the stream. However, one can do this and turn the result back into a stream, without buffering up the entire contents of the stream. Here are a couple examples:

static <T> Stream<T> throwIfEmpty(Stream<T> stream) {
    Iterator<T> iterator = stream.iterator();
    if (iterator.hasNext()) {
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
    } else {
        throw new NoSuchElementException("empty stream");
    }
}

static <T> Stream<T> defaultIfEmpty(Stream<T> stream, Supplier<T> supplier) {
    Iterator<T> iterator = stream.iterator();
    if (iterator.hasNext()) {
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
    } else {
        return Stream.of(supplier.get());
    }
}

Basically turn the stream into an Iterator in order to call hasNext() on it, and if true, turn the Iterator back into a Stream. This is inefficient in that all subsequent operations on the stream will go through the Iterator's hasNext() and next() methods, which also implies that the stream is effectively processed sequentially (even if it's later turned parallel). However, this does allow you to test the stream without buffering up all of its elements.

There is probably a way to do this using a Spliterator instead of an Iterator. This potentially allows the returned stream to have the same characteristics as the input stream, including running in parallel.

join on multiple columns

Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".

Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA, 
INNER JOIN TableB
 ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2

Passing data between controllers in Angular JS?

I saw the answers here, and it is answering the question of sharing data between controllers, but what should I do if I want one controller to notify the other about the fact that the data has been changed (without using broadcast)? EASY! Just using the famous visitor pattern:

myApp.service('myService', function() {

    var visitors = [];

    var registerVisitor = function (visitor) {
        visitors.push(visitor);
    }

    var notifyAll = function() {
        for (var index = 0; index < visitors.length; ++index)
            visitors[index].visit();
    }

    var myData = ["some", "list", "of", "data"];

    var setData = function (newData) {
        myData = newData;
        notifyAll();
    }

    var getData = function () {
        return myData;
    }

    return {
        registerVisitor: registerVisitor,
        setData: setData,
        getData: getData
    };
}

myApp.controller('firstController', ['$scope', 'myService',
    function firstController($scope, myService) {

        var setData = function (data) {
            myService.setData(data);
        }

    }
]);

myApp.controller('secondController', ['$scope', 'myService',
    function secondController($scope, myService) {

        myService.registerVisitor(this);

        this.visit = function () {
            $scope.data = myService.getData();
        }

        $scope.data = myService.getData();
    }
]);

In this simple manner, one controller can update another controller that some data has been updated.

How to capture and save an image using custom camera in Android?

Following Snippet will help you

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.cameara.api"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="de.vogella.camera.api.MakePhotoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/captureFront"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="onClick"
        android:text="Make Photo" />

</RelativeLayout>

PhotoHandler.java

package org.sample;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {

    private final Context context;

    public PhotoHandler(Context context) {
        this.context = context;
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFileDir = getDir();

        if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

            Log.d(Constants.DEBUG_TAG, "Can't create directory to save image.");
            Toast.makeText(context, "Can't create directory to save image.",
                    Toast.LENGTH_LONG).show();
            return;

        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoFile = "Picture_" + date + ".jpg";

        String filename = pictureFileDir.getPath() + File.separator + photoFile;

        File pictureFile = new File(filename);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
            Toast.makeText(context, "New Image saved:" + photoFile,
                    Toast.LENGTH_LONG).show();
        } catch (Exception error) {
            Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: "
                    + error.getMessage());
            Toast.makeText(context, "Image could not be saved.",
                    Toast.LENGTH_LONG).show();
        }
    }

    private File getDir() {
        File sdDir = Environment
          .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return new File(sdDir, "CameraAPIDemo");
    }
}

MakePhotoActivity.java

package org.sample;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import de.vogella.cameara.api.R;

public class MakePhotoActivity extends Activity {
    private final static String DEBUG_TAG = "MakePhotoActivity";
    private Camera camera;
    private int cameraId = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // do we have a camera?
        if (!getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
                    .show();
        } else {
            cameraId = findFrontFacingCamera();
            camera = Camera.open(cameraId);
            if (cameraId < 0) {
                Toast.makeText(this, "No front facing camera found.",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    public void onClick(View view) {
        camera.takePicture(null, null,
                new PhotoHandler(getApplicationContext()));
    }

    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                Log.d(DEBUG_TAG, "Camera found");
                cameraId = i;
                break;
            }
        }
        return cameraId;
    }

    @Override
    protected void onPause() {
        if (camera != null) {
            camera.release();
            camera = null;
        }
        super.onPause();
    }

}

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

make sure you're using the newest jquery, and problem solved

I met this problem with this code:

<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

After change it to this:

<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

It works fine

There is already an object named in the database

I had same problem and after three hour struggling I find out what's going on

In my case, when I wanted to migrate for the first time in up() method, the default code wants to create the tables that already existed so I got same error as you

To solve it, just delete those code and write want you want. For example, I wanted to add a column so i just write

migrationBuilder.AddColumn<string>(
            name: "fieldName",
            table: "tableName",
            nullable: true);

What's the valid way to include an image with no src?

Use a truly blank, valid and highly compatible SVG, based on this article:

src="data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E"

It will default in size to 300x150px as any SVG does, but you can work with that in your img element default styles, as you would possibly need in any case in the practical implementation.

Attach a file from MemoryStream to a MailMessage in C#

If all you're doing is attaching a string, you could do it in just 2 lines:

mail.Attachments.Add(Attachment.CreateAttachmentFromString("1,2,3", "text/csv");
mail.Attachments.Last().ContentDisposition.FileName = "filename.csv";

I wasn't able to get mine to work using our mail server with StreamWriter.
I think maybe because with StreamWriter you're missing a lot of file property information and maybe our server didn't like what was missing.
With Attachment.CreateAttachmentFromString() it created everything I needed and works great!

Otherwise, I'd suggest taking your file that is in memory and opening it using MemoryStream(byte[]), and skipping the StreamWriter all together.

How can I assign the output of a function to a variable using bash?

VAR=$(scan)

Exactly the same way as for programs.

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

Android center view in FrameLayout doesn't work

To center a view in Framelayout, there are some available tricks. The simplest one I used for my Webview and Progressbar(very similar to your two object layout), I just added android:layout_gravity="center"

Here is complete XML in case if someone else needs the same thing to do

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebviewPDFActivity"
    android:layout_gravity="center"
    >
    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        />
    <ProgressBar
        android:id="@+id/progress_circular"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:visibility="visible"
        android:layout_gravity="center"
        />


</FrameLayout>

Here is my output

screenshot

Text-decoration: none not working

I had lots of headache when I tried to customize a WordPress theme and the text-decoration didn't help me. In my case I had to remove the box-shadow as well.

a:hover {
    text-decoration: none;
    box-shadow: none;
} 

Measuring function execution time in R

Although other solutions are useful for a single function, I recommend the following piece of code where is more general and effective:

Rprof(tf <- "log.log", memory.profiling = TRUE)
# the code you want to profile must be in between
Rprof (NULL) ; print(summaryRprof(tf))

Java: Add elements to arraylist with FOR loop where element name has increasing number

why you need a for-loop for this? the solution is very obvious:

answers.add(answer1);
answers.add(answer2);
answers.add(answer3);

that's it. no for-loop needed.

Twitter Bootstrap: Print content of modal window

This is a revised solution that will also work for modal windows rendered using a Grails template, where you can have the same modal template called multiple times (with different values) in the same body. This thread helped me immensely, so I thought I'd share it in case other Grails users found their way here.

For those who are curious, the accepted solution didn't work for me because I am rendering a table; each row has a button that opens a modal window with more details about the record. This led to multiple printSection divs being created and printed on top of each other. Therefore I had to revise the js to clean up the div after it was done printing.

CSS

I added this CSS directly to my modal gsp, but adding it to the parent has the same effect.

<style type="text/css">
   @media screen {
        #printSection {
           display: none;
        }
   }

   @media print {
        body > *:not(#printSection) {
           display: none;
        }
        #printSection, #printSection * {
            visibility: visible;
        }
        #printSection {
            position:absolute;
            left:0;
            top:0;
        }
   }
</style>

Adding it to the site-wide CSS killed the print functionality in other parts of the site. I got this from ComFreak's accepted answer (based on Bennett McElwee answer), but it is revised using ':not' functionality from fanfavorite's answer on Print <div id=printarea></div> only? . I opted for 'display' rather than 'visibility' because my invisible body content was creating extra blank pages, which was unacceptable to my users.

js

And this to my javascript, revised from ComFreak's accepted answer to this question.

function printDiv(div) {    
    // Create and insert new print section
    var elem = document.getElementById(div);
    var domClone = elem.cloneNode(true);
    var $printSection = document.createElement("div");
    $printSection.id = "printSection";
    $printSection.appendChild(domClone);
    document.body.insertBefore($printSection, document.body.firstChild);

    window.print(); 

    // Clean up print section for future use
    var oldElem = document.getElementById("printSection");
    if (oldElem != null) { oldElem.parentNode.removeChild(oldElem); } 
                          //oldElem.remove() not supported by IE

    return true;
}

I had no need for appending elements, so I removed that aspect and changed the function to specifically print a div.

HTML (gsp)

And the modal template. This prints the modal header & body and excludes the footer, where the buttons were located.

<div class="modal-content">
    <div id="print-me"> <!-- This is the div that is cloned and printed -->
        <div class="modal-header">
            <!-- HEADER CONTENT -->
        </div>
        <div class="modal-body">
             <!-- BODY CONTENT -->
        </div>
    </div>
    <div class="modal-footer">
                                 <!-- This is where I specify the div to print -->
        <button type="button" class="btn btn-default" onclick="printDiv('print-me')">Print</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
</div>

I hope that helps someone!

How can I measure the similarity between two images?

How to measure similarity between two images entirely depends on what you would like to measure, for example: contrast, brightness, modality, noise... and then choose the best suitable similarity measure there is for you. You can choose from MAD (mean absolute difference), MSD (mean squared difference) which are good for measuring brightness...there is also available CR (correlation coefficient) which is good in representing correlation between two images. You could also choose from histogram based similarity measures like SDH (standard deviation of difference image histogram) or multimodality similarity measures like MI (mutual information) or NMI (normalized mutual information).

Because this similarity measures cost much in time, it is advised to scale images down before applying these measures on them.

How to properly compare two Integers in Java?

No, == between Integer, Long etc will check for reference equality - i.e.

Integer x = ...;
Integer y = ...;

System.out.println(x == y);

this will check whether x and y refer to the same object rather than equal objects.

So

Integer x = new Integer(10);
Integer y = new Integer(10);

System.out.println(x == y);

is guaranteed to print false. Interning of "small" autoboxed values can lead to tricky results:

Integer x = 10;
Integer y = 10;

System.out.println(x == y);

This will print true, due to the rules of boxing (JLS section 5.1.7). It's still reference equality being used, but the references genuinely are equal.

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

Personally I'd use:

if (x.intValue() == y.intValue())

or

if (x.equals(y))

As you say, for any comparison between a wrapper type (Integer, Long etc) and a numeric type (int, long etc) the wrapper type value is unboxed and the test is applied to the primitive values involved.

This occurs as part of binary numeric promotion (JLS section 5.6.2). Look at each individual operator's documentation to see whether it's applied. For example, from the docs for == and != (JLS 15.21.1):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

and for <, <=, > and >= (JLS 15.20.1)

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

Note how none of this is considered as part of the situation where neither type is a numeric type.

How can I get the order ID in WooCommerce?

This is quite an old question now, but someone may come here looking for an answer:

echo $order->id;

This should return the order id without "#".

EDIT (feb/2018)

The current way of accomplishing this is by using:

$order->get_id();

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

'any' vs 'Object'

Adding to Alex's answer and simplifying it:

Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

If your h:commandLink is inside a h:dataTable there is another reason why the h:commandLink might not work:

The underlying data-source which is bound to the h:dataTable must also be available in the second JSF-Lifecycle that is triggered when the link is clicked.

So if the underlying data-source is request scoped, the h:commandLink does not work!

Checkout one file from Subversion

The simple answer is that you svn export the file instead of checking it out.

But that might not be what you want. You might want to work on the file and check it back in, without having to download GB of junk you don't need.

If you have Subversion 1.5+, then do a sparse checkout:

svn checkout <url_of_big_dir> <target> --depth empty
cd <target>
svn up <file_you_want>

For an older version of SVN, you might benefit from the following:

  • Checkout the directory using a revision back in the distant past, when it was less full of junk you don't need.
  • Update the file you want, to create a mixed revision. This works even if the file didn't exist in the revision you checked out.
  • Profit!

An alternative (for instance if the directory has too much junk right from the revision in which it was created) is to do a URL->URL copy of the file you want into a new place in the repository (effectively this is a working branch of the file). Check out that directory and do your modifications.

I'm not sure whether you can then merge your modified copy back entirely in the repository without a working copy of the target - I've never needed to. If so then do that.

If not then unfortunately you may have to find someone else who does have the whole directory checked out and get them to do it. Or maybe by the time you've made your modifications, the rest of it will have finished downloading...

What's the difference between a web site and a web application?

A web application is a website in the same way that a square is a rectangle.

The application part is the model-controller combo. The web part (the view) is why it qualifies as a website.

Something that is only a website and not a web application is simply missing the dynamic aspect.

Of course, it can be difficult to decide on how much server-side processing is required to qualify it as a web application. Probably when it has a data store.

Thus, you have the primary role of webapps confused. A website's primary role is to inform. A web app's primary role is to inform using dynamic content (the do something part).

Converting a value to 2 decimal places within jQuery

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})

How to format x-axis time scale values in Chart.js v2

as per the Chart js documentation page tick configuration section. you can format the value of each tick using the callback function. for example I wanted to change locale of displayed dates to be always German. in the ticks parts of the axis options

ticks: {
    callback: function(value) { 
        return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'}); 
    },
},

Fastest way to tell if two files have the same contents in Unix/Linux?

Because I suck and don't have enough reputation points I can't add this tidbit in as a comment.

But, if you are going to use the cmp command (and don't need/want to be verbose) you can just grab the exit status. Per the cmp man page:

If a FILE is '-' or missing, read standard input. Exit status is 0 if inputs are the same, 1 if different, 2 if trouble.

So, you could do something like:

STATUS="$(cmp --silent $FILE1 $FILE2; echo $?)"  # "$?" gives exit status for each comparison

if [[ $STATUS -ne 0 ]]; then  # if status isn't equal to 0, then execute code
    DO A COMMAND ON $FILE1
else
    DO SOMETHING ELSE
fi

EDIT: Thanks for the comments everyone! I updated the test syntax here. However, I would suggest you use Vasili's answer if you are looking for something similar to this answer in readability, style, and syntax.

Change content of div - jQuery

$('a').click(function(){
 $('#content-container').html('My content here :-)');
});

Have a div cling to top of screen if scrolled down past it

The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.

This is done with something like this, attaching a handler to the window.scroll event

   // Cache selectors outside callback for performance. 
   var $window = $(window),
       $stickyEl = $('#the-sticky-div'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    });

This simply adds a sticky CSS class when the page has scrolled past it, and removes the class when it's back up.

And the CSS class looks like this

  #the-sticky-div.sticky {
     position: fixed;
     top: 0;
  }

EDIT- Modified code to cache jQuery objects, faster now.

mvn command not found in OSX Mavrerick

steps to install maven :

  1. download the maven file from http://maven.apache.org/download.cgi
  2. $tar xvf apache-maven-3.5.4-bin.tar.gz
  3. copy the apache folder to desired place $cp -R apache-maven-3.5.4 /Users/locals
  4. go to apache directory $cd /Users/locals/apache-maven-3.5.4/
  5. create .bash_profile $vim ~/.bash_profile
  6. write these two command : export M2_HOME=/Users/manisha/apache-maven-3.5.4 export PATH=$PATH:$M2_HOME/bin 7 save and quit the vim :wq!
  7. restart the terminal and type mvn -version

How to prevent robots from automatically filling up a form?

I actually find that a simple Honey Pot field works well. Most bots fill in every form field they see, hoping to get around required field validators.

http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx

If you create a text box, hide it in javascript, then verify that the value is blank on the server, this weeds out 99% of robots out there, and doesn't cause 99% of your users any frustration at all. The remaining 1% that have javascript disabled will still see the text box, but you can add a message like "Leave this field blank" for those such cases (if you care about them at all).

(Also, noting that if you do style="display:none" on the field, then it's way too easy for a robot to just see that and discard the field, which is why I prefer the javascript approach).

PHP header(Location: ...): Force URL change in address bar

Try changing:

header("Location : blabla")
                ^
                |
           (whitespace)

To

header("Location: blabla")

How to get Python requests to trust a self signed SSL certificate?

Setting export SSL_CERT_FILE=/path/file.crt should do the job.

npx command not found

if you are using macOS, use sudo command

sudo npm install -g npx

enter image description here

how to change any data type into a string in python

myvariable = 4
mystring = str(myvariable)  # '4'

also, alternatively try repr:

mystring = repr(myvariable) # '4'

This is called "conversion" in python, and is quite common.

How do I change the default library path for R packages

See help(Startup) and help(.libPaths) as you have several possibilities where this may have gotten set. Among them are

  • setting R_LIBS_USER
  • assigning .libPaths() in .Rprofile or Rprofile.site

and more.

In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want is set.

To otherwise ignore it you need to override it use explicitly i.e. via

library("somePackage", lib.loc=.libPaths()[-1])

when loading a package.

Eclipse plugin for generating a class diagram

Try eUML2. its a single click generator no need to drag n drop.

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

In my case the issue was solved by removing the log file.

sudo rm /log/mongod.log

Although the error message refers specifically to the lock file:

exception in initAndListen: 10309 Unable to create/open lock file: 
/data/mongod.lock errno:13 Permission denied 
Is a mongod instance already running?, terminating

Config Error: This configuration section cannot be used at this path

You could also use the IIS Manager to edit those settings.

Care of this Learn IIS article:

Using the Feature Delegation from the root of IIS:

Feature delegation icon in IIS Manager

You can then control each of machine-level read/write permissions, which will otherwise give you the overrideMode="Deny" errors.

Example use of Feature Delegation

It says that TypeError: document.getElementById(...) is null

All these results in null:

document.getElementById('volume');
document.getElementById('bytesLoaded');
document.getElementById('startBytes');
document.getElementById('bytesTotal');

You need to do a null check in updateHTML like this:

function updateHTML(elmId, value) {
  var elem = document.getElementById(elmId);
  if(typeof elem !== 'undefined' && elem !== null) {
    elem.innerHTML = value;
  }
}

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

How do I get monitor resolution in Python?

On Windows 8.1 I am not getting the correct resolution from either ctypes or tk. Other people are having this same problem for ctypes: getsystemmetrics returns wrong screen size To get the correct full resolution of a high DPI monitor on windows 8.1, one must call SetProcessDPIAware and use the following code:

import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]

Full Details Below:

I found out that this is because windows is reporting a scaled resolution. It appears that python is by default a 'system dpi aware' application. Types of DPI aware applications are listed here: http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor

Basically, rather than displaying content the full monitor resolution, which would make fonts tiny, the content is scaled up until the fonts are big enough.

On my monitor I get:
Physical resolution: 2560 x 1440 (220 DPI)
Reported python resolution: 1555 x 875 (158 DPI)

Per this windows site: http://msdn.microsoft.com/en-us/library/aa770067%28v=vs.85%29.aspx The formula for reported system effective resolution is: (reported_px*current_dpi)/(96 dpi) = physical_px

I'm able to get the correct full screen resolution, and current DPI with the below code. Note that I call SetProcessDPIAware() to allow the program to see the real resolution.

import tkinter as tk
root = tk.Tk()

width_px = root.winfo_screenwidth()
height_px = root.winfo_screenheight() 
width_mm = root.winfo_screenmmwidth()
height_mm = root.winfo_screenmmheight() 
# 2.54 cm = in
width_in = width_mm / 25.4
height_in = height_mm / 25.4
width_dpi = width_px/width_in
height_dpi = height_px/height_in 

print('Width: %i px, Height: %i px' % (width_px, height_px))
print('Width: %i mm, Height: %i mm' % (width_mm, height_mm))
print('Width: %f in, Height: %f in' % (width_in, height_in))
print('Width: %f dpi, Height: %f dpi' % (width_dpi, height_dpi))

import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
print('Size is %f %f' % (w, h))

curr_dpi = w*96/width_px
print('Current DPI is %f' % (curr_dpi))    

Which returned:

Width: 1555 px, Height: 875 px
Width: 411 mm, Height: 232 mm
Width: 16.181102 in, Height: 9.133858 in
Width: 96.099757 dpi, Height: 95.797414 dpi
Size is 2560.000000 1440.000000
Current DPI is 158.045016

I am running windows 8.1 with a 220 DPI capable monitor. My display scaling sets my current DPI to 158.

I'll use the 158 to make sure my matplotlib plots are the right size with: from pylab import rcParams rcParams['figure.dpi'] = curr_dpi

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

Setting the selected value on a Django forms.ChoiceField

To be sure I need to see how you're rendering the form. The initial value is only used in a unbound form, if it's bound and a value for that field is not included nothing will be selected.

using facebook sdk in Android studio

I deployed Facebook Android SDK to Sonatype repository.

You can include this library as Gradle dependency:

repositories {
    maven {
        url 'https://oss.sonatype.org/content/groups/public'
    }
}

dependencies {
    compile 'com.shamanland:facebook-android-sdk:3.15.0-SNAPSHOT'
}

Original post here.

Include another JSP file

1.<a href="index.jsp?p=products">Products</a> when user clicks on Products link,you can directly call products.jsp.

I mean u can maintain name of the JSP file same as parameter Value.

<%
 if(request.getParameter("p")!=null)
 { 
   String contextPath="includes/";
   String p = request.getParameter("p");
   p=p+".jsp";
   p=contextPath+p;

%>    

<%@include file="<%=p%>" %>

<% 
 }
%>

or

2.you can maintain external resource file with key,value pairs. like below

products : products.jsp

customer : customers.jsp

you can programatically retrieve the name of JSP file from properies file.

this way you can easily change the name of JSP file

How to get active user's UserDetails

You can try this: By Using Authentication Object from Spring we can get User details from it in the controller method . Below is the example , by passing Authentication object in the controller method along with argument.Once user is authenticated the details are populated in the Authentication Object.

@GetMapping(value = "/mappingEndPoint") <ReturnType> methodName(Authentication auth) {
   String userName = auth.getName(); 
   return <ReturnType>;
}

PDOException SQLSTATE[HY000] [2002] No such file or directory

If you are using Laravel Homestead, here is settings

(include Vagrant-Virtual Machine)

.bash-profile

alias vm="ssh [email protected] -p 2222"

database.php

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '127.0.0.1'),
        'database'  => env('DB_DATABASE', 'homestead'),
        'username'  => env('DB_USERNAME', 'homestead'),
        'password'  => env('DB_PASSWORD', 'secret'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Terminal

vm

vagrant@homestead:~/Code/projectFolder  php artisan migrate:install

How to stop text from taking up more than 1 line?

Using ellipsis will add the ... at the last.

   <style type="text/css">
    div {
      white-space: nowrap;
      overflow: hidden;
text-overflow: ellipsis;
    }
    </style>

How to overlay image with color in CSS?

You could use the hue-rotate function in the filter property. It's quite an obscure measurement though, you'd need to know how many degrees round the colour wheel you need to move in order to arrive at your desired hue, for example:

header {
    filter: hue-rotate(90deg);
}

Once you'd found the correct hue, you could combine the brightness and either grayscale or saturate functions to find the correct shade, for example:

header {
    filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}

The filter property has a vendor prefix in Webkit, so the final code would be:

header {
  -webkit-filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
          filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}

Remove large .pack file created by git

this is more of a handy solution than a coding one. zip the file. Open the zip in file view format (different from unzipping). Delete the .pack file. Unzip and replace the folder. Works like a charm!

How to convert a Date to a formatted string in VB.net?

I like:

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
myDate.ToString(timeFormat)

Easy to maintain if you need to use it in several parts of your code, date formats always seem to change sooner or later.

Error You must specify a region when running command aws ecs list-container-instances

Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add

"--profile" option.

For example:

Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,

[profile playground] region=us-east-1

then, use something like below

aws ecs list-container-instances --cluster default --profile playground

SQL DROP TABLE foreign key constraint

If it is SQL Server you must drop the constraint before you can drop the table.

CSS: Position text in the middle of the page

Try this CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}

jsFiddle: http://jsfiddle.net/wprw3/

Angular 2 Cannot find control with unspecified name attribute on formArrays

The problem for me was that I had

[formControlName]=""

Instead of

formControlName=""

Call int() function on every list element?

Another way to make it in Python 3:

numbers = [*map(int, numbers)]

How to create a batch file to run cmd as administrator

(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)

You need to enclose your code within this wrapper:

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload
    echo %~nx0: running payload with parameters:
    echo %*
    echo ---------------------------------------------------
    cd /d %2
    shift
    shift
    rem put your code here
    rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof

This makes batch file run itself as elevated user. It adds two parameters to the privileged code:

  • word payload, to indicate this is payload call, i.e. already elevated. Otherwise it would just open new processes over and over.

  • directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)

Note: Unfortunately, for some reason shift does not work for %*, so if you need to pass actual arguments on, you will have to resort to the ugly notation I used in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9), which also brings in the limit of maximum of 9 arguments

Compare two columns using pandas

You can use .equals for columns or entire dataframes.

df['col1'].equals(df['col2'])

If they're equal, that statement will return True, else False.

When to catch java.lang.Error?

In an Android application I am catching a java.lang.VerifyError. A library that I am using won't work in devices with an old version of the OS and the library code will throw such an error. I could of course avoid the error by checking the version of OS at runtime, but:

  • The oldest supported SDK may change in future for the specific library
  • The try-catch error block is part of a bigger falling back mechanism. Some specific devices, although they are supposed to support the library, throw exceptions. I catch VerifyError and all Exceptions to use a fall back solution.

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Checking if a textbox is empty in Javascript

onchange will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.

So it is better to use onblur event or on submitting the form.

_x000D_
_x000D_
function checkTextField(field) {_x000D_
  document.getElementById("error").innerText =_x000D_
    (field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
_x000D_
_x000D_

(Or old live demo.)

Invalid column count in CSV input on line 1 Error

The dumbest thing ever that will fix this error in Microsoft Excel (assuming you actually have everything else right):

Select your data and click "Borders All" in Excel (puts visual borders around your data) before saving the CSV. Sound pointless? I completely agree! However, it will fix this error. I use this trick at least three times a week.

How to git reset --hard a subdirectory?

For the case of simply discarding changes, the git checkout -- path/ or git checkout HEAD -- path/ commands suggested by other answers work great. However, when you wish to reset a directory to a revision other than HEAD, that solution has a significant problem: it doesn't remove files which were deleted in the target revision.

So instead, I have begun using the following command:

git diff --cached commit -- subdir | git apply -R --index

This works by finding the diff between the target commit and the index, then applying that diff in reverse to the working directory and index. Basically, this means that it makes the contents of the index match the contents of the revision you specified. The fact that git diff takes a path argument allows you to limit this effect to a specific file or directory.

Since this command fairly long and I plan on using it frequently, I have set up an alias for it which I named reset-checkout:

git config --global alias.reset-checkout '!f() { git diff --cached "$@" | git apply -R --index; }; f'

You can use it like this:

git reset-checkout 451a9a4 -- path/to/directory

Or just:

git reset-checkout 451a9a4

Is there a way to programmatically minimize a window

this.MdiParent.WindowState = FormWindowState.Minimized;

How to avoid annoying error "declared and not used"

According to the FAQ:

Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.

There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.

I don't necessarily agree with this for various reasons not worth going into. It is what it is, and it's not likely to change in the near future.

For packages, there's the goimports tool which automatically adds missing packages and removes unused ones. For example:

# Install it
$ go get golang.org/x/tools/cmd/goimports

# -w to write the source file instead of stdout
$ goimports -w my_file.go

You should be able to run this from any half-way decent editor - for example for Vim:

:!goimports -w %

The goimports page lists some commands for other editors, and you typically set it to be run automatically when you save the buffer to disk.

Note that goimports will also run gofmt.


As was already mentioned, for variables the easiest way is to (temporarily) assign them to _ :

// No errors
tasty := "ice cream"
horrible := "marmite"

// Commented out for debugging
//eat(tasty, horrible)

_, _ = tasty, horrible

How can I generate an MD5 hash?

private String hashuj(String dane) throws ServletException{
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] bufor = dane.getBytes();
        m.update(bufor,0,bufor.length);
        BigInteger hash = new BigInteger(1,m.dige`enter code here`st());
        return String.format("%1$032X", hash);

    } catch (NoSuchAlgorithmException nsae) {
        throw new ServletException("Algorytm szyfrowania nie jest obslugiwany!");
    }
}

cmake and libpthread

@Manuel was part way there. You can add the compiler option as well, like this:

If you have CMake 3.1.0+, this becomes even easier:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)

If you are using CMake 2.8.12+, you can simplify this to:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

Older CMake versions may require:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
  set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.

How to pass the -D System properties while testing on Eclipse?

Run -> Run configurations, select project, second tab: “Arguments”. Top box is for your program, bottom box is for VM arguments, e.g. -Dkey=value.

How do I set default value of select box in angularjs

  <select ng-model="selectedCar" ><option ng-repeat="car in cars "  value="{{car.model}}">{{car.model}}</option></select>
<script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = [{model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"},{model : "Volvo XC90", color : "black"}];
$scope.selectedCar=$scope.cars[0].model ;});

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Correct way to quit a Qt program?

While searching this very question I discovered this example in the documentation.

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);

Mutatis mutandis for your particular action of course.

Along with this note.

It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()

What is the difference between res.end() and res.send()?

I would like to make a little bit more emphasis on some key differences between res.end() & res.send() with respect to response headers and why they are important.

1. res.send() will check the structure of your output and set header information accordingly.


    app.get('/',(req,res)=>{
       res.send('<b>hello</b>');
    });

enter image description here


     app.get('/',(req,res)=>{
         res.send({msg:'hello'});
     });

enter image description here

Where with res.end() you can only respond with text and it will not set "Content-Type"

      app.get('/',(req,res)=>{
           res.end('<b>hello</b>');
      }); 

enter image description here

2. res.send() will set "ETag" attribute in the response header

      app.get('/',(req,res)=>{
            res.send('<b>hello</b>');
      });

enter image description here

¿Why is this tag important?
The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed.

res.end() will NOT set this header attribute

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

http://linuxcommand.org/lc3_man_pages/readh.html

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

How to mount a host directory in a Docker container

To get this working in Windows 10 I had to open the Docker Settings window from the system tray and go to the Shared Drives section.

I then checked the box next to C. Docker asked for my desktop credentials to gain authorisation to write to my Users folder.

Then I ran the docker container following examples above and also the example on that settings page, attaching to /data in the container.

docker run -v c:/Users/<user.name>/Desktop/dockerStorage:/data -other -options

How to understand nil vs. empty vs. blank in Ruby

Just a little note about the any? recommendation: He's right that it's generally equivalent to !empty?. However, any? will return true to a string of just whitespace (ala " ").

And of course, see the 1.9 comment above, too.

How to display an error message in an ASP.NET Web Application

Roughly you can do it like that :

try
{
    //do something
}
catch (Exception ex)
{
    string script = "<script>alert('" + ex.Message + "');</script>";
    if (!Page.IsStartupScriptRegistered("myErrorScript"))
    {
         Page.ClientScript.RegisterStartupScript("myErrorScript", script);
    }
}

But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.

Visual Studio 2010 - recommended extensions

VS10x Code Map That is very cool. Easy jumping to property, method. And easy expand collapse region and more.

alt text

Sass calculate percent minus px

$var:25%;
$foo:5px;
.selector {
    height:unquote("calc( #{$var} - #{$foo} )");
}

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

Case insensitive 'Contains(string)'

These are the easiest solutions.

  1. By Index of

    string title = "STRING";
    
    if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        // contains 
    }
    
  2. By Changing case

    string title = "STRING";
    
    bool contains = title.ToLower().Contains("string")
    
  3. By Regex

    Regex.IsMatch(title, "string", RegexOptions.IgnoreCase);
    

Detecting when user scrolls to bottom of div with jQuery

this worked for me though

$(window).scroll(function() {
  if ($(window).scrollTop() >= (($(document).height() - $(window).height()) - $('#divID').innerHeight())) {
    console.log('div reached');
  }
});

Reading binary file and looping over each byte

Python 3, read all of the file at once:

with open("filename", "rb") as binary_file:
    # Read the whole file at once
    data = binary_file.read()
    print(data)

You can iterate whatever you want using data variable.

Dropping Unique constraint from MySQL table

You can DROP a unique constraint from a table using phpMyAdmin as requested as shown in the table below. A unique constraint has been placed on the Wingspan field. The name of the constraint is the same as the field name, in this instance.

alt text

unknown type name 'uint8_t', MinGW

Try including stdint.h or inttypes.h.

Put request with simple string as request body

Another simple solution is to surround the content variable in your given code with braces like this:

 let content = 'Hello world' 
 axios.put(url, {content}).then(response => {
    resolve(response.data.content)
  }, response => {
    this.handleEditError(response)
  })

Caveat: But this will not send it as string; it will wrap it in a json body that will look like this: {content: "Hello world"}

RegEx - Match Numbers of Variable Length

What regex engine are you using? Most of them will support the following expression:

\{\d+:\d+\}

The \d is actually shorthand for [0-9], but the important part is the addition of + which means "one or more".

Color different parts of a RichTextBox string

I think modifying a "selected text" in a RichTextBox isn't the right way to add colored text. So here a method to add a "color block" :

        Run run = new Run("This is my text");
        run.Foreground = new SolidColorBrush(Colors.Red); // My Color
        Paragraph paragraph = new Paragraph(run);
        MyRichTextBlock.Document.Blocks.Add(paragraph);

From MSDN :

The Blocks property is the content property of RichTextBox. It is a collection of Paragraph elements. Content in each Paragraph element can contain the following elements:

  • Inline

  • InlineUIContainer

  • Run

  • Span

  • Bold

  • Hyperlink

  • Italic

  • Underline

  • LineBreak

So I think you have to split your string depending on parts color, and create as many Run objects as needed.

Detect when an image fails to load in Javascript

just like below:

var img = new Image(); 
img.src = imgUrl; 

if (!img.complete) {

//has picture
}
else //not{ 

}

How do I get a specific range of numbers from rand()?

double scale = 1.0 / ((double) RAND_MAX + 1.0);
int min, max;
...
rval = (int)(rand() * scale * (max - min + 1) + min);

How to redirect the output of a PowerShell to a file during its execution

One possible solution, if your situation allows it:

  1. Rename MyScript.ps1 to TheRealMyScript.ps1
  2. Create a new MyScript.ps1 that looks like:

    .\TheRealMyScript.ps1 > output.txt

How can I push a specific commit to a remote, and not previous commits?

Cherry-pick works best compared to all other methods while pushing a specific commit.

The way to do that is:

Create a new branch -

git branch <new-branch>

Update your new-branch with your origin branch -

git fetch

git rebase

These actions will make sure that you exactly have the same stuff as your origin has.

Cherry-pick the sha id that you want to do push -

git cherry-pick <sha id of the commit>

You can get the sha id by running

git log

Push it to your origin -

git push

Run gitk to see that everything looks the same way you wanted.

Java ArrayList of Arrays?

  1. Create the ArrayList like ArrayList action.

    In JDK 1.5 or higher use ArrayList <string[]> reference name.

    In JDK 1.4 or lower use ArrayList reference name.

  2. Specify the access specifiers:

    • public, can be accessed anywhere
    • private, accessed within the class
    • protected, accessed within the class and different package subclasses
  3. Then specify the reference it will be assigned in

    action = new ArrayList<String[]>();
    
  4. In JVM new keyword will allocate memory in runtime for the object.

    You should not assigned the value where declared, because you are asking without fixed size.

  5. Finally you can be use the add() method in ArrayList. Use like

    action.add(new string[how much you need])
    

    It will allocate the specific memory area in heap.

Google Chrome forcing download of "f.txt" file

FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

df.sort_values(by=['Date'])

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

Head and tail in one line

Under Python 3.x, you can do this nicely:

>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

A new feature in 3.x is to use the * operator in unpacking, to mean any extra values. It is described in PEP 3132 - Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.

It's also really readable.

As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:

it = iter(iterable)
head, tail = next(it), list(it)

As noted in the comments, this also provides an opportunity to get a default value for head rather than throwing an exception. If you want this behaviour, next() takes an optional second argument with a default value, so next(it, None) would give you None if there was no head element.

Naturally, if you are working on a list, the easiest way without the 3.x syntax is:

head, tail = seq[0], seq[1:]

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

Which port we can use to run IIS other than 80?

you can configure IIS in IIS Mgr to use EVERY port between 1 and 65535 as long it is not used by any other application

how does multiplication differ for NumPy Matrix vs Array classes?

the key things to know for operations on NumPy arrays versus operations on NumPy matrices are:

  • NumPy matrix is a subclass of NumPy array

  • NumPy array operations are element-wise (once broadcasting is accounted for)

  • NumPy matrix operations follow the ordinary rules of linear algebra

some code snippets to illustrate:

>>> from numpy import linalg as LA
>>> import numpy as NP

>>> a1 = NP.matrix("4 3 5; 6 7 8; 1 3 13; 7 21 9")
>>> a1
matrix([[ 4,  3,  5],
        [ 6,  7,  8],
        [ 1,  3, 13],
        [ 7, 21,  9]])

>>> a2 = NP.matrix("7 8 15; 5 3 11; 7 4 9; 6 15 4")
>>> a2
matrix([[ 7,  8, 15],
        [ 5,  3, 11],
        [ 7,  4,  9],
        [ 6, 15,  4]])

>>> a1.shape
(4, 3)

>>> a2.shape
(4, 3)

>>> a2t = a2.T
>>> a2t.shape
(3, 4)

>>> a1 * a2t         # same as NP.dot(a1, a2t) 
matrix([[127,  84,  85,  89],
        [218, 139, 142, 173],
        [226, 157, 136, 103],
        [352, 197, 214, 393]])

but this operations fails if these two NumPy matrices are converted to arrays:

>>> a1 = NP.array(a1)
>>> a2t = NP.array(a2t)

>>> a1 * a2t
Traceback (most recent call last):
   File "<pyshell#277>", line 1, in <module>
   a1 * a2t
   ValueError: operands could not be broadcast together with shapes (4,3) (3,4) 

though using the NP.dot syntax works with arrays; this operations works like matrix multiplication:

>> NP.dot(a1, a2t)
array([[127,  84,  85,  89],
       [218, 139, 142, 173],
       [226, 157, 136, 103],
       [352, 197, 214, 393]])

so do you ever need a NumPy matrix? ie, will a NumPy array suffice for linear algebra computation (provided you know the correct syntax, ie, NP.dot)?

the rule seems to be that if the arguments (arrays) have shapes (m x n) compatible with the a given linear algebra operation, then you are ok, otherwise, NumPy throws.

the only exception i have come across (there are likely others) is calculating matrix inverse.

below are snippets in which i have called a pure linear algebra operation (in fact, from Numpy's Linear Algebra module) and passed in a NumPy array

determinant of an array:

>>> m = NP.random.randint(0, 10, 16).reshape(4, 4)
>>> m
array([[6, 2, 5, 2],
       [8, 5, 1, 6],
       [5, 9, 7, 5],
       [0, 5, 6, 7]])

>>> type(m)
<type 'numpy.ndarray'>

>>> md = LA.det(m)
>>> md
1772.9999999999995

eigenvectors/eigenvalue pairs:

>>> LA.eig(m)
(array([ 19.703+0.j   ,   0.097+4.198j,   0.097-4.198j,   5.103+0.j   ]), 
array([[-0.374+0.j   , -0.091+0.278j, -0.091-0.278j, -0.574+0.j   ],
       [-0.446+0.j   ,  0.671+0.j   ,  0.671+0.j   , -0.084+0.j   ],
       [-0.654+0.j   , -0.239-0.476j, -0.239+0.476j, -0.181+0.j   ],
       [-0.484+0.j   , -0.387+0.178j, -0.387-0.178j,  0.794+0.j   ]]))

matrix norm:

>>>> LA.norm(m)
22.0227

qr factorization:

>>> LA.qr(a1)
(array([[ 0.5,  0.5,  0.5],
        [ 0.5,  0.5, -0.5],
        [ 0.5, -0.5,  0.5],
        [ 0.5, -0.5, -0.5]]), 
 array([[ 6.,  6.,  6.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]))

matrix rank:

>>> m = NP.random.rand(40).reshape(8, 5)
>>> m
array([[ 0.545,  0.459,  0.601,  0.34 ,  0.778],
       [ 0.799,  0.047,  0.699,  0.907,  0.381],
       [ 0.004,  0.136,  0.819,  0.647,  0.892],
       [ 0.062,  0.389,  0.183,  0.289,  0.809],
       [ 0.539,  0.213,  0.805,  0.61 ,  0.677],
       [ 0.269,  0.071,  0.377,  0.25 ,  0.692],
       [ 0.274,  0.206,  0.655,  0.062,  0.229],
       [ 0.397,  0.115,  0.083,  0.19 ,  0.701]])
>>> LA.matrix_rank(m)
5

matrix condition:

>>> a1 = NP.random.randint(1, 10, 12).reshape(4, 3)
>>> LA.cond(a1)
5.7093446189400954

inversion requires a NumPy matrix though:

>>> a1 = NP.matrix(a1)
>>> type(a1)
<class 'numpy.matrixlib.defmatrix.matrix'>

>>> a1.I
matrix([[ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028]])
>>> a1 = NP.array(a1)
>>> a1.I

Traceback (most recent call last):
   File "<pyshell#230>", line 1, in <module>
   a1.I
   AttributeError: 'numpy.ndarray' object has no attribute 'I'

but the Moore-Penrose pseudoinverse seems to works just fine

>>> LA.pinv(m)
matrix([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
        [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
        [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
        [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
        [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

>>> m = NP.array(m)

>>> LA.pinv(m)
array([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
       [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
       [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
       [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
       [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

How to send email to multiple recipients with addresses stored in Excel?

Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :

                Dim Splitter() As String
                Splitter = Split(AddrMail, ";")
                For Each Dest In Splitter
                    .Recipients.Add (Trim(Dest))
                Next

How to add subject alernative name to ssl certs?

Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1

Example:

keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1

What is a simple C or C++ TCP server and client example?

I've used Beej's Guide to Network Programming in the past. It's in C, not C++, but the examples are good. Go directly to section 6 for the simple client and server example programs.

Error including image in Latex

I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:

\includegraphics[height=60mm, width=100mm]{number2.png}

works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.

Incidentally, you can change this in TexShop from the "Typeset" menu.

Hope this helps.

Getting index value on razor foreach

 @{int i = 0;}
 @foreach(var myItem in Model.Members)
 {
     <span>@i</span>
     @{i++;
      }
 }

// Use @{i++ to increment value}

event Action<> vs event EventHandler<>

If you follow the standard event pattern, then you can add an extension method to make the checking of event firing safer/easier. (i.e. the following code adds an extension method called SafeFire() which does the null check, as well as (obviously) copying the event into a separate variable to be safe from the usual null race-condition that can affect events.)

(Although I am in kind of two minds whether you should be using extension methods on null objects...)

public static class EventFirer
{
    public static void SafeFire<TEventArgs>(this EventHandler<TEventArgs> theEvent, object obj, TEventArgs theEventArgs)
        where TEventArgs : EventArgs
    {
        if (theEvent != null)
            theEvent(obj, theEventArgs);
    }
}

class MyEventArgs : EventArgs
{
    // Blah, blah, blah...
}

class UseSafeEventFirer
{
    event EventHandler<MyEventArgs> MyEvent;

    void DemoSafeFire()
    {
        MyEvent.SafeFire(this, new MyEventArgs());
    }

    static void Main(string[] args)
    {
        var x = new UseSafeEventFirer();

        Console.WriteLine("Null:");
        x.DemoSafeFire();

        Console.WriteLine();

        x.MyEvent += delegate { Console.WriteLine("Hello, World!"); };
        Console.WriteLine("Not null:");
        x.DemoSafeFire();
    }
}

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

What is Common Gateway Interface (CGI)?

CGI is an interface specification between a web server (HTTP server) and an executable program of some type that is to handle a particular request.

It describes how certain properties of that request should be communicated to the environment of that program and how the program should communicate the response back to the server and how the server should 'complete' the response to form a valid reply to the original HTTP request.

For a while CGI was an IETF Internet Draft and as such had an expiry date. It expired with no update so there was no CGI 'standard'. It is now an informational RFC, but as such documents common practice and isn't a standard itself. rfc3875.txt, rfc3875.html

Programs implementing a CGI interface can be written in any language runnable on the target machine. They must be able to access environment variables and usually standard input and they generate their output on standard output.

Compiled languages such as C were commonly used as were scripting languages such as perl, often using libraries to make accessing the CGI environment easier.

One of the big disadvantages of CGI is that a new program is spawned for each request so maintaining state between requests could be a major performance issue. The state might be handled in cookies or encoded in a URL, but if it gets to large it must be stored elsewhere and keyed from encoded url information or a cookie. Each CGI invocation would then have to reload the stored state from a store somewhere.

For this reason, and for a greatly simple interface to requests and sessions, better integrated environments between web servers and applications are much more popular. Environments like a modern php implementation with apache integrate the target language much better with web server and provide access to request and sessions objects that are needed to efficiently serve http requests. They offer a much easier and richer way to write 'programs' to handle HTTP requests.

Whether you wrote a CGI script rather depends on interpretation. It certainly did the job of one but it is much more usual to run php as a module where the interface between the script and the server isn't strictly a CGI interface.

jQuery: Slide left and slide right

You can do this with the additional effects in jQuery UI: See here for details

Quick example:

$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);

Cannot create PoolableConnectionFactory

This is the actual cause of the problem:

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

You have a database communication link problem. Make sure that your application have network access to your database (and the firewall isn't blocking ports to your database).

How to add/update an attribute to an HTML element using JavaScript?

What seems easy is actually tricky if you want to be completely compatible.

var e = document.createElement('div');

Let's say you have an id of 'div1' to add.

e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).

But there are contingencies, of course. Will not work in IE prior to 8:e.attributes['style'] Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']

In summary, think of attributes as literal and object-oriented.

In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.

Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.

It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.

This was longer than I wanted, but CSS manipulation in JS is tricky business.

How to apply filters to *ngFor?

Pipe would be best approach. but below one would also work.

<div *ng-for="#item of itemsList">
  <ng-container *ng-if="conditon(item)">
    // my code
  </ng-container>
</div>

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

How can I decode HTML characters in C#?

For .net 4.0

Add a reference to System.net.dll to the project with using System.Net; then use the following extensions

// Html encode/decode
    public static string HtmDecode(this string htmlEncodedString)
    {
        if(htmlEncodedString.Length > 0)
        {
            return System.Net.WebUtility.HtmlDecode(htmlEncodedString);
        }
        else
        {
            return htmlEncodedString;
        }
    }

    public static string HtmEncode(this string htmlDecodedString)
    {
        if(htmlDecodedString.Length > 0)
        {
            return System.Net.WebUtility.HtmlEncode(htmlDecodedString);
        }
        else
        {
            return htmlDecodedString;
        }
    }

How to reload a page using JavaScript

This should work:

window.location.href = window.location.href.split( '#' )[0];

or

var x = window.location.href;
x = x.split( '#' );
window.location.href = x[0];

I prefer this for the following reasons:

  • Removes the part after the #, ensuring the page reloads on browsers that won't reload content that has it.
  • It doesn't ask you if want to repost last content if you recently submit a form.
  • It should work even on most recent browsers. Tested on Lasted Firefox and Chrome.

Alternatively, you may use the most recent official method for this task

window.location.reload()

JQuery confirm dialog

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>?

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

?

Set date input field's max date to today

In lieu of Javascript, a shorter PHP-based solution could be:

 <input type="date" name="date1" max=
     <?php
         echo date('Y-m-d');
     ?>
 >

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

HTTP response header content disposition for attachments

Problems

The code has the following issues:

  • An Ajax call (<a4j:commandButton .../>) does not work with attachments.
  • Creating the output content must happen first.
  • Displaying the error messages also cannot use Ajax-based a4j tags.

Solution

  1. Change <a4j:commandButton .../> to <h:commandButton .../>.
  2. Update the source code:
    1. Change bw.write( getDomainDocument() ); to bw.write( document );.
    2. Add String document = getDomainDocument(); to the first line of the try/catch.
  3. Change the <a4j:outputPanel.../> (not shown) to <h:messages showDetail="false"/>.

Essentially, remove all the Ajax facilities related to the commandButton. It is still possible to display error messages and leverage the RichFaces UI style.

References

Password must have at least one non-alpha character

  function randomPassword(length) {
        var chars = "abcdefghijklmnopqrstuvwxyz#$%ABCDEFGHIJKLMNOP1234567890";
        var pass = "";
        for (var x = 0; x < length; x++) {
            var i = Math.floor(Math.random() * chars.length);
            pass += chars.charAt(i);
        }
        var pattern = false;
        var passwordpattern = new RegExp("[^a-zA-Z0-9+]+[0-9+]+[A-Z+]+[a-z+]");
        pattern = passwordpattern.test(pass);
        if (pattern == true)
            { alert(pass); }
        else
         { randomPassword(length); }
    }

try this to create the random password with atleast one special character

How can I round a number in JavaScript? .toFixed() returns a string?

To supply an example of why it has to be a string:

If you format 1.toFixed(2) you would get '1.00'.

This is not the same as 1, as 1 does not have 2 decimals.


I know JavaScript isn't exactly a performance language, but chances are you'd get better performance for a rounding if you use something like: roundedValue = Math.round(value * 100) * 0.01

How can I read the contents of an URL with Python?

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Setting this seems to fix it:

  this$1.player = new YouTube.Player(this$1.elementId, {
    videoId: videoId,
    host: 'https://www.youtube.com',

Local storage in Angular 2

Install "angular-2-local-storage"

import { LocalStorageService } from 'angular-2-local-storage';

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I had the same symptoms as described here. I could connect once to a bluetooth printer but subsequent connects failed with "socket closed" no matter what I did.

I found it a bit strange that the workarounds described here would be necessary. After going through my code I found that I had forgot to close the socket's InputStream and OutputSteram and not terminated the ConnectedThreads properly.

The ConnectedThread I use is the same as in the example here:

http://developer.android.com/guide/topics/connectivity/bluetooth.html

Note that ConnectThread and ConnectedThread are two different classes.

Whatever class that starts the ConnectedThread must call interrupt() and cancel() on the thread. I added mmInStream.close() and mmOutStream.close() in the ConnectedTread.cancel() method.

After closing the threads/streams/sockets properly I could create new sockets without any problem.

Check existence of input argument in a Bash shell script

In some cases you need to check whether the user passed an argument to the script and if not, fall back to a default value. Like in the script below:

scale=${2:-1}
emulator @$1 -scale $scale

Here if the user hasn't passed scale as a 2nd parameter, I launch Android emulator with -scale 1 by default. ${varname:-word} is an expansion operator. There are other expansion operators as well:

  • ${varname:=word} which sets the undefined varname instead of returning the word value;
  • ${varname:?message} which either returns varname if it's defined and is not null or prints the message and aborts the script (like the first example);
  • ${varname:+word} which returns word only if varname is defined and is not null; returns null otherwise.

How do I convert a decimal to an int in C#?

Use Convert.ToInt32 from mscorlib as in

decimal value = 3.14m;
int n = Convert.ToInt32(value);

See MSDN. You can also use Decimal.ToInt32. Again, see MSDN. Finally, you can do a direct cast as in

decimal value = 3.14m;
int n = (int) value;

which uses the explicit cast operator. See MSDN.

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

Two onClick actions one button

Give your button an id something like this:


<input id="mybutton" type="button" value="Dont show this again! " />

Then use jquery (to make this unobtrusive) and attach click action like so:


$(document).ready(function (){
    $('#mybutton').click(function (){
       fbLikeDump();
       WriteCookie();
    });
});

(this part should be in your .js file too)

I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>

The reason to add just before body closing tag is for performance of perceived page loading times

Reload .profile in bash shell script (in unix)?

Try:

#!/bin/bash
# .... some previous code ...
# help set exec | less
set -- 1 2 3 4 5  # fake command line arguments
exec bash --login -c '
echo $0
echo $@
echo my script continues here
' arg0 "$@"

How to use AND in IF Statement

If you are simply looking for the occurrence of "Miami" or "Florida" inside a string (since you put * at both ends), it's probably better to use the InStr function instead of Like. Not only are the results more predictable, but I believe you'll get better performance.

Also, VBA is not short-circuited so when you use the AND keyword, it will test both sides of the AND, regardless if the first test failed or not. In VBA, it is more optimal to use 2 if-statements in these cases, that way you aren't checking for "Florida" if you don't find "Miami".

The other advice I have is that a for-each loop is faster than a for-loop. Using .offset, you can achieve the same thing, but with better effeciency. Of course there are even better ways (like variant arrays), but those will add a layer of complexity not needed in this example.

Here is some sample code:

Sub test()

Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row

For Each cell In Range("A1:A" & lastRow)
    If InStr(1, cell.Value, "Miami") <> 0 Then
        If InStr(1, cell.Offset(, 3).Value, "Florida") <> 0 Then
            cell.Offset(, 2).Value = "BA"
        End If
    End If
Next

Application.ScreenUpdating = True
End Sub

I hope you find some of this helpful, and keep at it with VBA! ^^

Why is my JavaScript function sometimes "not defined"?

If you're changing the prototype of the built-in 'function' object it's possible you're running into a browser bug or race condition by modifying a fundamental built-in object.

Test it in multiple browsers to find out.

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

Print range of numbers on same line

Another single-line Python 3 option but with explicit separator:

print(*range(1,11), sep=' ')

Why is the use of alloca() not considered good practice?

One of the most memorable bugs I had was to do with an inline function that used alloca. It manifested itself as a stack overflow (because it allocates on the stack) at random points of the program's execution.

In the header file:

void DoSomething() {
   wchar_t* pStr = alloca(100);
   //......
}

In the implementation file:

void Process() {
   for (i = 0; i < 1000000; i++) {
     DoSomething();
   }
}

So what happened was the compiler inlined DoSomething function and all the stack allocations were happening inside Process() function and thus blowing the stack up. In my defence (and I wasn't the one who found the issue; I had to go and cry to one of the senior developers when I couldn't fix it), it wasn't straight alloca, it was one of ATL string conversion macros.

So the lesson is - do not use alloca in functions that you think might be inlined.

Java abstract interface

Be aware that in Spring it has non academic meaning. The abstract interface is a warning to the developer not to use it for @Autowired. I hope that spring/eclipse @Autowired will look at this attribute and warn/fail about usages of such.

A real example: @Service proxy under @Transnational to a @Repository need to use same basic methods however they should use different interfaces that extends this abstract interface due to @Autowired. (I call this XXXSpec interface)

Two color borders

This produces a nice effect.

<div style="border: 1px solid gray; padding: 1px">
<div style="border: 1px solid gray">
   internal stuff
</div>
</div>

LaTeX Optional Arguments

Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.

\newcount\seccount

\def\sec{%
    \seccount0%
    \let\go\secnext\go
}

\def\secnext#1{%
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\secparse{%
    \ifx\next\bgroup
        \let\go\secparseii
    \else
        \let\go\seclast
    \fi
    \go
}

\def\secparseii#1{%
    \ifnum\seccount>0, \fi
    \advance\seccount1\relax
    \last
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\seclast{\ifnum\seccount>0{} and \fi\last}%

\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"

\sec{a}
% outputs "a"

\sec{a}{b}
% outputs "a and b"

How to get query params from url in Angular 2?

I hope it will help someone else.

Question above states that query param value is needed after page has been redirected and we can assume that snapshot value (the no-observable alternative) would be sufficient.

No one here mentioned about snapshot.paramMap.get from the official documentation.

this.route.snapshot.paramMap.get('id')

So before sending it add this in sending/re-directing component:

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

then re-direct as either (documented here):

this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);

or simply:

this.router.navigate(['/heroes', heroId ]);

Make sure you have added this in your routing module as documented here:

 { path: 'hero/:id', component: HeroDetailComponent }

And finally, in your component which needs to use the query param

  • add imports (documented here):

    import { Router, ActivatedRoute, ParamMap } from '@angular/router';
    
  • inject ActivatedRoute

( documentation also imports switchMap and also injects Router and HeroService - but they are needed for observable alternative only - they are NOT needed when you use snapshot alternative as in our case ):

    constructor(
      private route: ActivatedRoute
    ) {}
  • and get the value you need ( documented here):

    ngOnInit() {
      const id = this.route.snapshot.paramMap.get('id');
    }
    

NOTE: IF YOU ADD ROUTING-MODULE TO A FEATURE MODULE (AS SHOWN IN DOCUMENTATION) MAKE SURE THAT IN APP.MODULE.ts THAT ROUTING MODULE COMES BEFORE AppRoutingModule (or other file with root-level app routes) IN IMPORTS: [] . OTHERWISE FEATURE ROUTES WILL NOT BE FOUND (AS THEY WOULD COME AFTER { path: '**', redirectTo: '/not-found' } and you would see only not-found message).

Python: Importing urllib.quote

urllib went through some changes in Python3 and can now be imported from the parse submodule

>>> from urllib.parse import quote  
>>> quote('"')                      
'%22'                               

Using Custom Domains With IIS Express

The invalid hostname indicates that the actual site you configured in the IIS Express configuration file is (most likely) not running. IIS Express doesn't have a process model like IIS does.


For your site to run it would need to be started explicitly (either by opening and accessing from webmatrix, or from command line calling iisexpress.exe (from it's installation directory) with the /site parameter.


In general, the steps to allow fully qualified DNS names to be used for local access are Let's use your example of the DNS name dev.example.com

  1. edit %windows%\system32\drivers\etc\hosts file to map dev.example.com to 127.0.0.1 (admin privilege required). If you control DNS server (like in Nick's case) then the DNS entry is sufficient as this step is not needed.
  2. If you access internet through proxy, make sure the dev.example.com will not be forwared to proxy (you have to put in on the exception list in your browser (for IE it would be Tools/Internet Options/Connections/Lan Settings, then go to Proxy Server/Advanced and put dev.example.com on the exeption list.
  3. Configure IIS Express binding for your site (eg:Site1) to include dev.example.com. Administrative privilege will be needed to use the binding. Alternatively, a one-time URL reservation can be made with http.sys using

    netsh http add urlacl url=http://dev.example.com:<port>/ user=<user_name>

  4. start iisexpress /site:Site1 or open Site1 in WebMatrix

Format decimal for percentage values?

If you want to use a format that allows you to keep the number like your entry this format works for me: "# \\%"

Get list of all input objects using JavaScript, without accessing a form object

(See update at end of answer.)

You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it:

var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

There I've used it on the document, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:

var container, inputs, index;

// Get the container element
container = document.getElementById('container');

// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

...but you've said you don't want to use the parent form, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).


Update: getElementsByTagName is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input elements?

That's where the useful querySelectorAll comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:

var checkboxes = document.querySelectorAll("input[type=checkbox]");

You can also use it at the element level. For instance, if we have a div element in our element variable, we can find all of the spans with the class foo that are inside that div like this:

var fooSpans = element.querySelectorAll("span.foo");

querySelectorAll and its cousin querySelector (which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

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

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

Only on Firefox "Loading failed for the <script> with source"

I had the same problem (different web app though) with the error message and it turned out to be the MIME-Type for .js files was text/x-js instead of application/javascript due to a duplicate entry in mime.types on the server that was responsible for serving the js files. It seems that this is happening if the header X-Content-Type-Options: nosniff is set, which makes Firefox (and Chrome) block the content of the js files.

Preventing multiple clicks on button

If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.

First set add a style to your button:

<h:commandButton id="SaveBtn" value="Save"
    styleClass="hideOnClick"
    actionListener="#{someBean.saveAction()}"/>

Then make it hide when clicked.

$(document).ready(function() {
    $(".hideOnClick").click(function(e) {
        $(e.toElement).hide();
    });
});

Getting the current date in visual Basic 2008

Dim regDate As Date = Date.Now.date

This should fix your problem, though it's 2 years old!

For loop example in MySQL

You can exchange this local variable for a global, it would be easier.

DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      SET @a = 0;
      simple_loop: LOOP
         SET @a=@a+1;
         select @a;
         IF @a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

How do you make a div follow as you scroll?

You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)

.Fixed
{
    position: fixed;
    top: 20px;
}

or with jQuery:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').css('top', $(this).scrollTop());
});

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

If you have any problems with the "not like" query, Consider that you may have a null in the database. In this case, Use:

IFNULL(word, '') NOT LIKE '%something%'

How can I create download link in HTML?

The download attribute is new for the <a> tag in HTML5

<a href="http://www.odin.com/form.pdf" download>Download Form</a>
or
<a href="http://www.odin.com/form.pdf" download="Form">Download Form</a>

I prefer the first one it is preferable in respect to any extension.

How to get data from Magento System Configuration

you should you use following code

$configValue = Mage::getStoreConfig(
                   'sectionName/groupName/fieldName',
                   Mage::app()->getStore()
               ); 

Mage::app()->getStore() this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.

if we have more then one store or multiple views configured then this will insure that we are getting values for current store

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

that is the right behavior.

if you set @item1 to a value the below expression will be true

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)

Anyway in SQL Server there is not a such function but you can create your own:

CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
    RETURN 0
ELSE
    RETURN 1
END

Checking images for similarity with OpenCV

A little bit off topic but useful is the pythonic numpy approach. Its robust and fast but just does compare pixels and not the objects or data the picture contains (and it requires images of same size and shape):

A very simple and fast approach to do this without openCV and any library for computer vision is to norm the picture arrays by

import numpy as np
picture1 = np.random.rand(100,100)
picture2 = np.random.rand(100,100)
picture1_norm = picture1/np.sqrt(np.sum(picture1**2))
picture2_norm = picture2/np.sqrt(np.sum(picture2**2))

After defining both normed pictures (or matrices) you can just sum over the multiplication of the pictures you like to compare:

1) If you compare similar pictures the sum will return 1:

In[1]: np.sum(picture1_norm**2)
Out[1]: 1.0

2) If they aren't similar, you'll get a value between 0 and 1 (a percentage if you multiply by 100):

In[2]: np.sum(picture2_norm*picture1_norm)
Out[2]: 0.75389941124629822

Please notice that if you have colored pictures you have to do this in all 3 dimensions or just compare a greyscaled version. I often have to compare huge amounts of pictures with arbitrary content and that's a really fast way to do so.

Default value in Doctrine

Here is how I solved it for myself. Below is an Entity example with default value for MySQL. However, this also requires the setup of a constructor in your entity, and for you to set the default value there.

Entity\Example:
  type: entity
  table: example
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    label:
      type: string
      columnDefinition: varchar(255) NOT NULL DEFAULT 'default_value' COMMENT 'This is column comment'

127 Return code from $?

A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:

   For  the shell’s purposes, a command which exits with a zero exit status has succeeded.  An exit status
   of zero indicates success.  A non-zero exit status indicates failure.  When a command terminates  on  a
   fatal signal N, bash uses the value of 128+N as the exit status.
   If  a command is not found, the child process created to execute it returns a status of 127.  If a com-
   mand is found but is not executable, the return status is 126.

   If a command fails because of an error during expansion or redirection, the exit status is greater than
   zero.

   Shell  builtin  commands  return  a  status of 0 (true) if successful, and non-zero (false) if an error
   occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.

   Bash itself returns the exit status of the last command executed, unless  a  syntax  error  occurs,  in
   which case it exits with a non-zero value.  See also the exit builtin command below.

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

Math constant PI value in C

anyway you have not a unlimited accuracy so C define a constant in this way:

#define PI 3.14159265358979323846

import math.h to use this

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

RadioGroup: How to check programmatically

I use this code piece while working with indexes for radio group:

radioGroup.check(radioGroup.getChildAt(index).getId());

How can I make content appear beneath a fixed DIV element?

#nav{
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 0;
    margin: 0 auto;
    z-index: 9999;
    background-color: white;
}

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Command to escape a string in bash

You can use perl to replace various characters, for example:

$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world

Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.

Failed to add the host to the list of know hosts

It may be due to the fact that the known_hosts file is owned by another user i.e root in most cases. You can visit the path directory given (/home/taimoor/.ssh/known_hosts in my case) and check if the root is the owner and change it to the default owner.

Example:

Error Description - Error Description

Before changing the owner - Before changing the owner

After changing the owner - enter image description here

Read CSV file column by column

To read some specific column I did something like this:

dpkcs.csv content:
FN,LN,EMAIL,CC
Name1,Lname1,[email protected],CC1
Nmae2,Lname2,[email protected],CC2

The function to read it:

private void getEMailRecepientList() {
                List<EmailRecepientData> emailList = null;// Blank list of POJO class
                Scanner scanner = null;
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader("dpkcs.csv"));
                    Map<String, Integer> mailHeader = new HashMap<String, Integer>();
                    // read file line by line
                    String line = null;
                    int index = 0;
                    line = reader.readLine();
                    // Get header from 1st row of csv
                    if (line != null) {
                        StringTokenizer str = new StringTokenizer(line, ",");
                        int headerCount = str.countTokens();
                        for (int i = 0; i < headerCount; i++) {
                            String headerKey = str.nextToken();
                            mailHeader.put(headerKey.toUpperCase(), new Integer(i));

                        }
                    }
                    emailList = new ArrayList<EmailRecepientData>();

                    while ((line = reader.readLine()) != null) {
                    // POJO class for getter and setters
                        EmailRecepientData email = new EmailRecepientData();
                        scanner = new Scanner(line);
                        scanner.useDelimiter(",");
                    //Use Specific key to get value what u want
                        while (scanner.hasNext()) {
                            String data = scanner.next();
                            if (index == mailHeader.get("EMAIL"))
                                email.setEmailId(data);
                            else if (index == mailHeader.get("FN"))
                                email.setFirstName(data);
                            else if (index == mailHeader.get("LN"))
                                email.setLastName(data);
                            else if (index == mailHeader.get("CC"))
                                email.setCouponCode(data);

                            index++;
                        }
                        index = 0;
                        emailList.add(email);
                    }
                    reader.close();
                } catch (Exception e) {
                    StringWriter stack = new StringWriter();
                    e.printStackTrace(new PrintWriter(stack));

                } finally {
                    scanner.close();
                }

                System.out.println("list--" + emailList);

            }

The POJO Class:

public class EmailRecepientData {
    private String emailId;
    private String firstName;
    private String lastName;
    private String couponCode;

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getCouponCode() {
        return couponCode;
    }

    public void setCouponCode(String couponCode) {
        this.couponCode = couponCode;
    }

    @Override
    public String toString() {
        return "Email Id=" + emailId + ", First Name=" + firstName + " ,"
                + " Last Name=" + lastName + ", Coupon Code=" + couponCode + "";
    }

}

How to use Python's "easy_install" on Windows ... it's not so easy

For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:

easy_install -U packageName

Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.

Import Google Play Services library in Android Studio

I got the same problem. I just tried to rebuild, clean and restart but no luck. Then I just remove

compile 'com.google.android.gms:play-services:8.3.0'

from build.gradle and resync. After that I put it again and resync. Next to that, I clean the project and the problem is gone!!

I hope it will help any of you facing the same.

int *array = new int[n]; what is this function actually doing?

The new operator is allocating space for a block of n integers and assigning the memory address of that block to the int* variable array.

The general form of new as it applies to one-dimensional arrays appears as follows:

array_var = new Type[desired_size];

Lombok added but getters and setters not recognized in Intellij IDEA

i had this issue, just make sure

  1. Lombok pulgin is added.
  2. Annotation processor is ticked.
  3. In your build.gradle/ pom.xml, you have set lombok to be the annotation processor.

Eg. for gradle->

annotationProcessor 'org.projectlombok:lombok:1.18.12'

Change a column type from Date to DateTime during ROR migration

In Rails 3.2 and Rails 4, Benjamin's popular answer has a slightly different syntax.

First in your terminal:

$ rails g migration change_date_format_in_my_table

Then in your migration file:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
   change_column :my_table, :my_column, :datetime
  end

  def down
   change_column :my_table, :my_column, :date
  end
end

Checking from shell script if a directory contains files

Try with command find. Specify the directory hardcoded or as argument. Then initiate find to search all files inside the directory. Check if return of find is null. Echo the data of find

#!/bin/bash

_DIR="/home/user/test/"
#_DIR=$1
_FIND=$(find $_DIR -type f )
if [ -n "$_FIND" ]
then
   echo -e "$_DIR contains files or subdirs with files \n\n "
   echo "$_FIND"
else
echo "empty (or does not exist)"
fi

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

urlencoded Forward slash is breaking URL

In Apache, AllowEncodedSlashes On would prevent the request from being immediately rejected with a 404.

Just another idea on how to fix this.

Why are empty catch blocks a bad idea?

You should never have an empty catch block. It is like hiding a mistake you know about. At the very least you should write out an exception to a log file to review later if you are pressed for time.

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

Insert default value when parameter is null

chrisofspades,

As far as I know that behavior is not compatible with the way the db engine works, but there is a simple (i don't know if elegant, but performant) solution to achive your two objectives of DO NOT

  1. maintain the default value in multiple places, and
  2. use multiple insert statements.

The solution is to use two fields, one nullable for insert, and other one calculated to selections:

CREATE TABLE t (
    insValue VARCHAR(50) NULL
    , selValue AS ISNULL(insValue, 'something')
)

DECLARE @d VARCHAR(10)
INSERT INTO t (insValue) VALUES (@d) -- null
SELECT selValue FROM t

This method even let You centralize the management of business defaults in a parameter table, placing an ad hoc function to do this, vg changing:

selValue AS ISNULL(insValue, 'something')

for

selValue AS ISNULL(insValue, **getDef(t,1)**)

I hope this helps.

Install msi with msiexec in a Specific Directory

Here's my attempt to install .msi using msiexec in Administrative PowerShell.

I've made it 7 times for each of 2 drives, C: and D: (14 total) with different arguments in place of ARG and the same desirable path value.

Template: PS C:\WINDOWS\system32> msiexec /a D:\users\username\downloads\soft\publisher\softwarename\software.msi /passive ARG="D:\Soft\publisher\softwarename"

ARGs:

  • TARGETDIR
    • Works OK-ish, but produces redundand ProgramFilesFolder (with an additional folders similar to the default installation path, e.g. D:\Soft\BlenderFoundation\Blender\ProgramFilesFolder\Blender Foundation\Blender\2.81\) and a copy of the .msi at the target folder.
  • INSTALLDIR, INSTALLPATH, INSTALLFOLDER, INSTALLLOCATION, APPLICATIONFOLDER, APPDIR
    • When running on the same drive as set in the parameter: installs on this drive in a default folder (e.g. D:\Blender Foundation\Blender\2.81\)
    • When running from a differnet drive: seems to do nothing

How to center a navigation bar with CSS or HTML?

The best way to fix it I have looked for the code or trick how to center nav menu and found the real solutions it works for all browsers and for my friends ;)

Here is how I have done:

body {
    margin: 0;
    padding: 0;
}

div maincontainer {
    margin: 0 auto;
    width: ___px;
    text-align: center;
}

ul {
    margin: 0;
    padding: 0;
}

ul li {
    margin-left: auto;
    margin-right: auto;
}

and do not forget to set doctype html5

Use dynamic variable names in `dplyr`

While I enjoy using dplyr for interactive use, I find it extraordinarily tricky to do this using dplyr because you have to go through hoops to use lazyeval::interp(), setNames, etc. workarounds.

Here is a simpler version using base R, in which it seems more intuitive, to me at least, to put the loop inside the function, and which extends @MrFlicks's solution.

multipetal <- function(df, n) {
   for (i in 1:n){
      varname <- paste("petal", i , sep=".")
      df[[varname]] <- with(df, Petal.Width * i)
   }
   df
}
multipetal(iris, 3) 

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

Deleting my node modules folder and running a normal npm install did it for me

SSRS expression to format two decimal places does not show zeros

Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))

Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.

Docker: Copying files from Docker container to host

As a more general solution, there's a CloudBees plugin for Jenkins to build inside a Docker container. You can select an image to use from a Docker registry or define a Dockerfile to build and use.

It'll mount the workspace into the container as a volume (with appropriate user), set it as your working directory, do whatever commands you request (inside the container). You can also use the docker-workflow plugin (if you prefer code over UI) to do this, with the image.inside() {} command.

Basically all of this, baked into your CI/CD server and then some.

PHPExcel auto size column width

Here a more flexible variant based on @Mark Baker post:

foreach (range('A', $phpExcelObject->getActiveSheet()->getHighestDataColumn()) as $col) {
        $phpExcelObject->getActiveSheet()
                ->getColumnDimension($col)
                ->setAutoSize(true);
    } 

Hope this helps ;)

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:

ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)

If you are doing CE development, i would recomend this FAQ:

EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.

Android Service needs to run always (Never pause or stop)

You can implement startForeground for the service and even if it dies you can restart it by using START_STICKY on startCommand(). Not sure though this is the right implementation.

Replacing few values in a pandas dataframe column with another value

Replace

DataFrame object has powerful and flexible replace method:

DataFrame.replace(
        to_replace=None,
        value=None,
        inplace=False,
        limit=None,
        regex=False, 
        method='pad',
        axis=None)

Note, if you need to make changes in place, use inplace boolean argument for replace method:

Inplace

inplace: boolean, default False If True, in place. Note: this will modify any other views on this object (e.g. a column form a DataFrame). Returns the caller if this is True.

Snippet

df['BrandName'].replace(
    to_replace=['ABC', 'AB'],
    value='A',
    inplace=True
)

How can I write an anonymous function in Java?

if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)

IE prompts to open or save json result from server

Sadly, this is just another annoying quirk of using Internet Explorer.

enter image description here

The simple solution is to run a small .reg file on your PC, to tell IE to automatically open .json files, rather than nag about whether to open/save it.

I've put a copy of the file you'll need here:

JSON mime type

You'll need to have Admin rights to run this.

Get file from project folder java

If you don't specify any path and put just the file (Just like you did), the default directory is always the one of your project (It's not inside the "src" folder. It's just inside the folder of your project).

How to fix SSL certificate error when running Npm on Windows?

This is what you can do to avoid npm and use yarn in window machine.

yarn config set "strict-ssl" false

C++ Vector of pointers

I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?

I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new, fill the object in with the data, and then push the address of the data onto the vector (probably not the best design, but most likely what's intended anyway).

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

As in Swift 3.x for upload image with parameter we can use below alamofire upload method-

static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) {

        let imageData = UIImageJPEGRepresentation(imageFile , 0.5)

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg")

            for key in parameters.keys{
                let name = String(key)
                if let val = parameters[name!] as? String{
                    multipartFormData.append(val.data(using: .utf8)!, withName: name!)
                }
            }
        }, to:inputUrl)
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (Progress) in
                })

                upload.responseJSON { response in

                    if let JSON = response.result.value {
                        completion(JSON)
                    }else{
                        completion(nilValue)
                    }
                }

            case .failure(let encodingError):
                completion(nilValue)
            }

        }

    }

Note: Additionally if our parameter is array of key-pairs then we can use

 var arrayOfKeyPairs = [[String:Any]]()
 let json = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted])
 let jsonPresentation = String(data: json!, encoding: .utf8)

How do I paste multi-line bash codes into terminal and run it all at once?

In addition to backslash, if a line ends with | or && or ||, it will be continued on the next line.

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).