Programs & Examples On #Addition

Addition is a mathematical operation that represents combining collections of objects together into a larger collection. It is signified by the plus sign (+).

How to find difference between two columns data?

Yes, you can select the data, calculate the difference, and insert all values in the other table:

insert into #temp2 (Difference)
select previous - Present
from #TEMP1

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response


This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to


You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        total += parseFloat(myInt1 + myInt2 + myInt3);

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example

Time calculation in php (add 10 hours)?

In order to increase or decrease time using strtotime you could use a Relative format in the first argument.

In your case to increase the current time by 10 hours:

$date = date('h:i:s A', strtotime('+10 hours'));

In case you need to apply the change to another timestamp, the second argument can be specified.


Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

So, the recommended way since PHP 5.3:

$dt = new DateTime(); // assuming we need to add to the current time
$dt->add(new DateInterval('PT10H'));
$date = $dt->format('h:i:s A');

or using aliases:

$dt = date_create(); // assuming we need to add to the current time
date_add($dt, date_interval_create_from_date_string('10 hours')); 
$date = date_format($dt, 'h:i:s A');

In all cases the default time zone will be used unless a time zone is specified.

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value


var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number


+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

Getting the object's property name

you can easily iterate in objects

eg: if the object is var a = {a:'apple', b:'ball', c:'cat', d:'doll', e:'elephant'};

Object.keys(a).forEach(key => {
   console.log(key) // returns the keys in an object
   console.log(a[key])  // returns the appropriate value 

Android TextView Justify Text

This line of code will make your text justified


how to avoid extra blank page at end while printing?

Check if there is any white space after the html tag at the bottom. Remove any whitespace below helped me

How to create custom button in Android using XML Styles

Have a look at Styled Button it will surely help you. There are lots examples please search on INTERNET.


<style name="Widget.Button" parent="android:Widget">
    <item name="android:background">@drawable/red_dot</item>

you can use your selector instead of red_dot


<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android=""
    android:shape="oval"  >

    <solid android:color="#f00"/>
    <size android:width="55dip"


        android:text="Button" />

How to get row index number in R?

See row in ?base::row. This gives the row indices for any matrix-like object.

Need to navigate to a folder in command prompt

I prefer to use

pushd d:\windows\movie

because it requires no switches yet the working directory will change to the correct drive and path in one step.

Added plus:

  • also works with UNC paths if an unused drive letter is available for automatic drive mapping,
  • easy to go back to the previous working directory: just enter popd.

Replace whitespaces with tabs in linux

Using Perl:

perl -p -i -e 's/ /\t/g' file.txt

Sum one number to every element in a list (or array) in Python

If you don't want list comprehensions:

a = [1,1,1,1,1]
b = []
for i in a:

Pushing value of Var into an Array

Perhaps $('#fruit').val(); is not returning an array and you need something like:

$("#fruit").val() || []

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

How to update/modify an XML file in python?

Useful Python XML parsers:

  1. Minidom - functional but limited
  2. ElementTree - decent performance, more functionality
  3. lxml - high-performance in most cases, high functionality including real xpath support

Any of those is better than trying to update the XML file as strings of text.

What that means to you:

Open your file with an XML parser of your choice, find the node you're interested in, replace the value, serialize the file back out.

ORA-00979 not a group by expression

Include in the GROUP BY clause all SELECT expressions that are not group function arguments.

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

suppose you need a label with text customername than you can achive it using 2 ways


[2]@Html.LabelFor(a => a.CustomerName)  //strongly typed

2nd method used a property from your model. If your view implements a model then you can use the 2nd method.

More info please visit below link

getString Outside of a Context or Activity

In MyApplication, which extends Application:

public static Resources resources;

In MyApplication's onCreate:

resources = getResources();

Now you can use this field from anywhere in your application.

How to view file history in Git?

Use git log to view the commit history. Each commit has an associated revision specifier that is a hash key (e.g. 14b8d0982044b0c49f7a855e396206ee65c0e787 and b410ad4619d296f9d37f0db3d0ff5b9066838b39). To view the difference between two different commits, use git diff with the first few characters of the revision specifiers of both commits, like so:

# diff between commits 14b8... and b410...
git diff 14b8..b410
# only include diff of specified files
git diff 14b8..b410 path/to/file/a path/to/file/b

If you want to get an overview over all the differences that happened from commit to commit, use git log or git whatchanged with the patch option:

# include patch displays in the commit history
git log -p
git whatchanged -p
# only get history of those commits that touch specified paths
git log path/a path/b
git whatchanged path/c path/d

How to download/checkout a project from Google Code in Windows?

If you have a github account and don't want to download software, you can export to github, then download a zip from github.

How to resize a custom view programmatically?

I used this way to increase width of custom view Runnable() {
                            public void run() {
                                View view_instance = customDrawingView;
                                android.view.ViewGroup.LayoutParams params = view_instance
                                int newLayoutWidth = customDrawingView
                                        + customDrawingView.getWidth();
                                params.width = newLayoutWidth;
                                screenWidthBackup = params.width;

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.


convert ArrayList<MyCustomClass> to JSONArray

If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:

ArrayList<String> list = new ArrayList<String>();
JSONArray jsArray = new JSONArray(list);


how to read a text file using scanner in Java?

If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)

If not, you should specify the absolute path to that file.

You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.

If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.

How do I create a MongoDB dump of my database?

There is a utility called : mongodump On the mongo command line you can type :


The above will create a dump of all the databases on your localhost. To make dump of a single collection use:

./mongodump --db blog --collection posts

Have a look at : mongodump

How do I escape a single quote in SQL Server?

The following syntax will escape you ONLY ONE quotation mark:


The result will be a single quote. Might be very helpful for creating dynamic SQL :). enter image description here

MySQL equivalent of DECODE function in Oracle

You can use a CASE statement...however why don't you just create a table with an integer for ages between 0 and 150, a varchar for the written out age and then you can just join on that

PHP: If internet explorer 6, 7, 8 , or 9

You can as well look into PHP's get_browser();

Maybe you'll find it useful for more features.

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());

    private static void failingMethod() {
        throw new RuntimeException("Just the message");


Error: Just the message

How do I make a newline after a twitter bootstrap element?

Like KingCronus mentioned in the comments you can use the row class to make the list or heading on its own line. You could use the row class on either or both elements:

<ul class="nav nav-tabs span2 row">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>

<div class="well span6 row">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>

How do I test a website using XAMPP?

create a folder inside htdocs, place your website there, access it via localhost or Internal IP (if you're behind a router) - check out this video demo here

Difference between malloc and calloc?

calloc() gives you a zero-initialized buffer, while malloc() leaves the memory uninitialized.

For large allocations, most calloc implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS) or Windows VirtualAlloc) so it doesn't need to write them in user-space. This is how normal malloc gets more pages from the OS as well; calloc just takes advantage of the OS's guarantee.

This means calloc memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.)

Some compilers even can optimize malloc + memset(0) into calloc for you, but you should use calloc explicitly if you want the memory to read as 0.

If you aren't going to ever read memory before writing it, use malloc so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).

Embedded implementations of calloc may leave it up to calloc itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.

On embedded Linux, malloc could mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS), which is only enabled for some embedded kernels because it's insecure on a multi-user system.

How can I remove an element from a list?

Removing Null elements from a list in single line :



Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.


Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:



Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like


All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this


NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.


After adding all five (5) JAR files the "Libraries" folder should look something like this:


IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:



That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while ( {



At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

I have just run into the same issue with VS2013, creating device drivers in C++ , and none of the above seemed to fix the issue. However, I have just discovered that in my case the issue appears to have been VMWare-related.

I was running a VMWare workstation client with a shared folder defined on the VM on my entire C: drive. When I disabled the shared folders on the VM Settings, VS2013 was able to happily build my .exe files.

My new process is:

1) Disable the shared folder on the vm (VM Settings | Options | Shared Folders - and uncheck the checkbox) 2) Run the build on the host PC 3) RE-enable the shared folder (and proceed from there)

Hopefully this might help someone else.

(BTW, the errors you receive are that the .exe (or other files) are locked or require Administrator permission, but that is a red herring - It seems to me that the VMWare share is causing those files to appear as locked.)

How to filter multiple values (OR operation) in angularJS

I believe this is what you're looking for:

<div>{{ (collection | fitler1:args) + (collection | filter2:args) }}</div>

How to both read and write a file in C#

This thread seems to answer your question : simultaneous-read-write-a-file

Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.

Why would one omit the close tag?

Sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:

  1. While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.

  2. You may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.

  3. You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.

  4. If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).

  5. Finally, many PHP frameworks including Symfony, Zend and Laravel (there is no mention of this in the coding guidelines but it follows the suit) and the PSR-2 standard (item 2.2) require omission of the closing tag. PHP manual itself (1,2), Wordpress, Drupal and many other PHP software I guess, advise to do so. If you simply make a habit of following the standard (and setup PHP-CS-Fixer for your code) you can forget the issue. Otherwise you will always need to keep the issue in your mind.

Bonus: a few gotchas (actually currently one) related to these 2 characters:

  1. Even some well-known libraries may contain excess line endings after ?>. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (\s*\?>\s*)$ with empty text in all files that contain PHP code.

How to get temporary folder for current user



jQuery: read text file from file system

If you include a file input box you can access the file as a base64 encoded string by using the FileReader object. If it's a text file a simple base64 decode will work to get the text.

Assuming the following HTML:

<input type="file" id="myfile" />

You can access using the following JQuery JS:

var file = $('#myfile').get(0).files[0];
var reader = new FileReader();
reader.onload = function (e) {
    //get the file result, split by comma to remove the prefix, then base64 decode the contents
    var decodedText = atob(',')[1]);
    //show the file contents

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.

Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet


' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")

Application.EnableEvents = False

End Sub

How print out the contents of a HashMap<String, String> in ascending order based on its values?

Java 8


How to use regex in String.contains() method in Java

As of Java 11 one can use Pattern#asMatchPredicate which returns Predicate<String>.

String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();

boolean match = matchesRegex.test(string);                   // true

The method enables chaining with other String predicates, which is the main advantage of this method as long as the Predicate offers and, or and negate methods.

String string = "stores$store$product";
String regex = "stores.*store.*product.*";

Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;

boolean match = hasLength.and(matchesRegex).test(string);    // false

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.

AFAIK, these are your options:

  1. Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters

  2. There also executable wrappers - see How can I convert my Java program to an .exe file?

See also: Convert Java to EXE: Why, When, When Not and How

SQL Bulk Insert with FIRSTROW parameter skips the following line

You can use the below snippet

FROM 'E:\filefromabove.txt'
FIELDTERMINATOR = '|',  --CSV field delimiter
ROWTERMINATOR = '\n',   --Use to shift the control to next row
ERRORFILE = 'E:\ErrorRows.csv',

Chart.js - Formatting Y axis

An undocumented feature of the ChartJS library is that if you pass in a function instead of a string, it will use your function to render the y-axis's scaleLabel.

So while, "<%= Number(value).toFixed(2).replace('.',',') + ' $' %>" works, you could also do:

scaleLabel: function (valuePayload) {
    return Number(valuePayload.value).toFixed(2).replace('.',',') + '$';

If you're doing anything remotely complicated, I'd recommend doing this instead.

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
    public void MyMethodTest()
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

How do I "break" out of an if statement?

You probably need to break up your if statement into smaller pieces. That being said, you can do two things:

  • wrap the statement into do {} while (false) and use real break (not recommended!!! huge kludge!!!)

  • put the statement into its own subroutine and use return This may be the first step to improving your code.

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/"
     href="" />


<link rel="icon" type="image/png"
     href="" />


<link rel="apple-touch-icon"

for the shortcut icon:

<link rel="shortcut icon"
     href="" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Convert Select Columns in Pandas Dataframe to Numpy Array

Please use the Pandas to_numpy() method. Below is an example--

>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1, 2], "B":[3, 4], "C":[5, 6]})
>>> df 
    A  B  C
 0  1  3  5
 1  2  4  6
>>> s_array = df[["A", "B", "C"]].to_numpy()
>>> s_array

array([[1, 3, 5],
   [2, 4, 6]]) 

>>> t_array = df[["B", "C"]].to_numpy() 
>>> print (t_array)

[[3 5]
 [4 6]]

Hope this helps. You can select any number of columns using

columns = ['col1', 'col2', 'col3']
df1 = df[columns]

Then apply to_numpy() method.

Pdf.js: rendering a pdf file using a base64 file source instead of url

Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS

        Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
        convertDataURIToBinary: function(dataURI) {_x000D_
          var BASE64_MARKER = ';base64,',_x000D_
            base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
            base64 = dataURI.substring(base64Index),_x000D_
            raw = window.atob(base64),_x000D_
            rawLength = raw.length,_x000D_
            array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
          for (var i = 0; i < rawLength; i++) {_x000D_
            array[i] = raw.charCodeAt(i);_x000D_
          return array;_x000D_

What is log4j's default log file dumping path

You can see the log info in the console view of your IDE if you are not using any log4j properties to generate log file. You can define in your project so that those properties would be used to generate log file. A quick sample is listed below.

# Global logging configuration
log4j.rootLogger=DEBUG, stdout, R

# SQL Map logging configuration... MapClientDelegate=INFO


# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n


# Keep one backup file

log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F\:%L) - %m%n

How can I convert string to double in C++?

There is not a single function that will do that, because 0 is a valid number and you need to be able to catch when the string is not a valid number.

You will need to check the string first (probably with a regular expression) to see if it contains only numbers and numerical punctuation. You can then decide to return 0 if that is what your application needs or convert it to a double.

After looking up atof() and strtod() I should rephrase my statement to "there shouldn't be" instead of "there is not" ... hehe

How to create python bytes object from long hex string?

result = bytes.fromhex(some_hex_string)

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

Have you recently changed your MySQL Server root password? If answer is YES, than this is the cause of the error / warning inside phpMyAdmin console. To fix the problem, simply edit your phpMyAdmin’s config-db.php file and setup the proper database password.

First answer is messing too much in my view and second answer did not work for me. So:

In Linux-based servers the file is usually located in:




Example: (My File looked like this and I changed the user fromphpmyadmin to admin, the username I created for maintaining my database through phpmyadmin, and put in the appropriate password.

$dbpass=''; // set current password between quotes ' '


Getting only Month and Year from SQL DATE

select convert(varchar(11), transfer_date, 106) 

got me my desired result of date formatted as 07 Mar 2018

My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure

gem install: Failed to build gem native extension (can't find header files)

For those who may be confused by the accepted answer, as I was, you also need to have the ruby headers installed [ruby-devel].

The article that saved my hide is here.

And this is the revised solution (note that I'm on Fedora 13):

yum -y install gcc mysql-devel ruby-devel rubygems
gem install -y mysql -- --with-mysql-config=/usr/bin/mysql_config

For Debian, and other distributions using Debian style packaging the ruby development headers are installed by:

sudo apt-get install ruby-dev

For Ubuntu the ruby development headers are installed by:

sudo apt-get install ruby-all-dev

If you are using a earlier version of ruby (such as 2.2), then you will need to run:

sudo apt-get install ruby2.2-dev

(where 2.2 is your desired Ruby version)

Use of alloc init instead of new

+new is equivalent to +alloc/-init in Apple's NSObject implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%

undefined reference to 'std::cout'

Compile the program with:

g++ -Wall -Wextra -Werror -c main.cpp -o main.o
     ^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled.

as cout is present in the C++ standard library, which would need explicit linking with -lstdc++ when using gcc; g++ links the standard library by default.

With gcc, (g++ should be preferred over gcc)

gcc main.cpp -lstdc++ -o main.o

How does Access-Control-Allow-Origin header work?

If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe. From MAC OS you can do this from the terminal line:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

Instantly detect client disconnection from server socket

i had same problem , try this :

void client_handler(Socket client) // set 'KeepAlive' true
    while (true)
            if (client.Connected)

            { // client disconnected
        catch (Exception)
            client.Poll(4000, SelectMode.SelectRead);// try to get state

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

SQL left join vs multiple tables on FROM line?

To the database, they end up being the same. For you, though, you'll have to use that second syntax in some situations. For the sake of editing queries that end up having to use it (finding out you needed a left join where you had a straight join), and for consistency, I'd pattern only on the 2nd method. It'll make reading queries easier.

Which one is the best PDF-API for PHP?

From the mpdf site: "mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF, with a number of enhancements."

mpdf is superior to FPDF for language handling and UTF-8 support. For CJK support it not only supports font embedding, but font subsetting (so your CJK PDFs are not oversized). TCPDF and FPDF have nothing on the UTF-8 and Font support of mpdf. It even comes with some open source fonts as of version 5.0.

Gets byte array from a ByteBuffer in java

This is a simple way to get a byte[], but part of the point of using a ByteBuffer is avoiding having to create a byte[]. Perhaps you can get whatever you wanted to get from the byte[] directly from the ByteBuffer.

Print Currency Number Format in PHP

sprintf() is the PHP function for all sorts of string formatting

I use this function:

function formatDollars($dollars){
  return '$ '.sprintf('%0.2f', $dollars);

Passing bash variable to jq

I know is a bit later to reply, sorry. But that works for me.

export K8S_public_load_balancer_url="$(kubectl get services -n ${TENANT}-production -o wide | grep "ingress-nginx-internal$" | awk '{print $4}')"

And now I am able to fetch and pass the content of the variable to jq

export TF_VAR_public_load_balancer_url="$(aws elbv2 describe-load-balancers --region eu-west-1 | jq -r '.LoadBalancers[] | select (.DNSName == "'$K8S_public_load_balancer_url'") | .LoadBalancerArn')"

In my case I needed to use double quote and quote to access the variable value.


Find first element in a sequence that matches a predicate

J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.

For Python version < 2.6, here's the best I can come up with:

from itertools import repeat,ifilter,chain

Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:

from itertools import islice,ifilter

UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:

from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()

set div height using jquery (stretch div height)

Off the top of my head:

    $(window).height() - $('#header').height() - $('#footer').height()

Is that what you mean?

VBA module that runs other modules

As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.

So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:

Sub MasterMacro()
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

How to avoid Sql Query Timeout

Please check your Windows system event log for any errors specifically for the "Event Source: Dhcp". It's very likely a networking error related to DHCP. Address lease time expired or so. It shouldn't be a problem related to the SQL Server or the query itself.

Just search the internet for "The semaphore timeout period has expired" and you'll get plenty of suggestions what might be a solution for your problem. Unfortunately there doesn't seem to be the solution for this problem.

Getting the count of unique values in a column in bash

To see a frequency count for column two (for example):

awk -F '\t' '{print $2}' * | sort | uniq -c | sort -nr


z    z    a
a    b    c
w    d    e


t    r    e
z    d    a
a    g    c


z    r    a
v    d    c
a    m    c


  3 d
  2 r
  1 z
  1 m
  1 g
  1 b

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

Update: This is no longer a bug or a workaround, it is required if your app targets API Level 28 (Android 9.0) or above and uses the Google Maps SDK for Android 16.0.0 or below (or if your app uses the Apache HTTP Legacy library). It is now included in the official docs. The public issue has been closed as intended behavior.

This is a bug on the Google Play Services side, until it's fixed, you should be able to workaround by adding this to your AndroidManifest.xml inside the <application> tag:

<uses-library android:name="org.apache.http.legacy" android:required="false" />

Vue template or render function not defined yet I am using neither?

If someone else keeps getting the same error. Just add one extra div in your component template.

As the documentation says:

Component template should contain exactly one root element

Check this simple example:

 import yourComponent from '{path to component}'
    export default {
        components: {

 // Child component
     <div> This is the one! </div>

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity =

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    return result;

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

Create a date from day month and year with T-SQL



How to pick an image from gallery (SD Card) for my app?

call chooseImage method like-

public void chooseImage(ImageView v)
    Intent intent = new Intent(Intent.ACTION_PICK);
    startActivityForResult(intent, SELECT_PHOTO);

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    if(imageReturnedIntent != null)
        Uri selectedImage = imageReturnedIntent.getData();
    switch(requestCode) { 
    case SELECT_PHOTO:
        if(resultCode == RESULT_OK)
            Bitmap datifoto = null;
            Uri picUri = null;
            picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
             if(picUri !=null){
               try {
                   datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(),                                 picUri);
               } catch (FileNotFoundException e) {
                  throw new RuntimeException(e);
               } catch (IOException e) {
                  throw new RuntimeException(e);
               } catch (OutOfMemoryError e) {
                Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();


        //Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();

When to use which design pattern?

Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.

Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.

How can I start PostgreSQL server on Mac OS X?

If you installed PostgreSQL using the EnterpriseDB installer, then what Kenial suggested is the way to go:

sudo -u postgres pg_ctl -D /Library/PostgreSQL/{version}/data start
sudo -u postgres pg_ctl -D /Library/PostgreSQL/{version}/data stop

Why use @PostConstruct?

The main problem is that:

in a constructor, the injection of the dependencies has not yet occurred*

*obviously excluding Constructor Injection

Real-world example:

public class Foo {

    Logger LOG;

    public void fooInit(){"This will be printed; LOG has already been injected");

    public Foo() {"This will NOT be printed, LOG is still null");
        // NullPointerException will be thrown here

IMPORTANT: @PostConstruct and @PreDestroy have been completely removed in Java 11.

To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.


<!-- -->


compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'

How to copy directory recursively in python and overwrite all?

In Python 3.8 the dirs_exist_ok keyword argument was added to shutil.copytree():

dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.

So, the following will work in recent versions of Python, even if the destination directory already exists:

shutil.copytree(src, dest, dirs_exist_ok=True)  # 3.8+ only!

One major benefit is that it's more flexible than distutils.dir_util.copy_tree() as it takes additional arguments on files to ignore, etc. There is also a draft PEP (PEP 632, associated discussion), which suggests that distutils may be deprecated and then removed in future versions of Python 3.

How to close off a Git Branch?

We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).

My fingers have memorized our process:

git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>

A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.

AngularJS - ng-if check string empty value

You don't need to explicitly use qualifiers like == '' or != ''. Like in JavaScript, an empty string will be evaluated as false.

Your views will be much cleaner and readable as well.

<script src=""></script>_x000D_
<div ng-app init="item = {photo: ''}">_x000D_
   <div ng-if=""> show if photo is not empty</div>_x000D_
   <div ng-if="!"> show if photo is empty</div>_x000D_
   <input type=text ng-model="" placeholder="photo" />_x000D_

Updated to remove bug in Angular

Convert int to ASCII and back in Python

Use hex(id)[2:] and int(urlpart, 16). There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.

Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode and b32decode. You should give True for both the casefold and map01 options to b32decode in case people write down your shortened URLs.

Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. :-)

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.

If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this.

    Set-ExecutionPolicy RemoteSigned
  2. Run this python script on your powershell script

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    p = subprocess.Popen(["powershell.exe", 

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

Hello World

Adding a Scrollable JTextArea (Java)

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

This started happening to me when my database size grew and I was doing a lot of transactions on it.

Truth is there is probably some way to optimize either your queries or your DB but try these 2 queries for a work around fix.

Run this:

SET GLOBAL innodb_lock_wait_timeout = 5000; 

And then this:

SET innodb_lock_wait_timeout = 5000; 

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

VirtualBox Cannot register the hard disk already exists

If there is no possibility to remove or change path to a hard disc file using Virtual Media Manager (in my case) then:

  1. Open '.vbox' and '.vbox-prev' (if exist) files in any text editor.
  2. Edit 'location' attribute of the element 'HardDisk' to your path, for example: "d:/VM/VirtualBox/Win10/Win10.vmdk" (screenshot).

How to Query Database Name in Oracle SQL Developer?

DESCRIBE DATABASE NAME; you need to specify the name of the database and the results will include the data type of each attribute.

Raise an event whenever a property's value changed?

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

public class TheClass : INotifyPropertyChanged {
    private int _property1;
    private string _property2;
    private double _property3;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null) {
            handler(this, e);

    protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
        if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
            field = newValue;
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));

    public int Property1 {
        get { return _property1; }
        set { SetPropertyField("Property1", ref _property1, value); }
    public string Property2 {
        get { return _property2; }
        set { SetPropertyField("Property2", ref _property2, value); }
    public double Property3 {
        get { return _property3; }
        set { SetPropertyField("Property3", ref _property3, value); }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;


Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

'react-scripts' is not recognized as an internal or external command

Running the npm update command solved my problem.

TSQL CASE with if comparison in SELECT statement

Please select the same in the outer select. You can't access the alias name in the same query.

        WHEN articleNumber < 2 THEN 'Ama'
        WHEN articleNumber < 5 THEN 'SemiAma' 
        WHEN articleNumber < 7 THEN 'Good'  
        WHEN articleNumber < 9 THEN 'Better' 
        WHEN articleNumber < 12 THEN 'Best'
        ELSE 'Outstanding'
        END) AS ranking 
    SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber, 
    hobbies, etc...

Adding asterisk to required fields in Bootstrap 3

I modified the css, as i am using bootstrap 3.3.6

.form-group.required label:after{   
color: #d00;   
font-family: 'FontAwesome'; 
font-weight: normal;
font-size: 10px;
content: "\f069"; 
position: absolute;   
 margin-left: 8px;

the HTML

<div class="form-group required">
 <label for="return_notes"><?= _lang('notes') ?></label>
 <textarea class="form-control" name="return_notes" id="return_notes"  required="required"></textarea>

catch forEach last iteration

The 2018 ES6+ ANSWER IS:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if ( - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 

Copy a table from one database to another in Postgres

I tried some of the solutions here and they were really helpful. In my experience best solution is to use psql command line, but sometimes i don't feel like using psql command line. So here is another solution for pgAdminIII

create table table1 as(
 select t1.* 
 from dblink(
   'dbname=dbSource user=user1 password=passwordUser1',
   'select * from table1'  
  ) as t1(
    fieldName1 as bigserial,
    fieldName2 as text,
    fieldName3 as double precision 

The problem with this method is that the name of the fields and their types of the table you want to copy must be written.

Creating the checkbox dynamically using JavaScript?

The last line should read


Appending the text (label?) to the same container as the checkbox, not the checkbox itself

jQuery: set selected value of dropdown list?

You can select dropdown option value by name

 if( jQuery(this).text() == 'Monday' )

How to request Administrator access inside a batch file

@echo off 
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause

The above works on my Windows 10 Version 1903

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

It occurred because you tried to create a foreign key from tblDomare.PersNR to tblBana.BanNR but/and the values in tblDomare.PersNR didn't match with any of the values in tblBana.BanNR. You cannot create a relation which violates referential integrity.

Can you get a Windows (AD) username in PHP?

I've got php mysql running on IIS - I can use $_SERVER["AUTH_USER"] if I turn on Windows Authentication in IIS -> Authentication and turn off Anonymous authentication (important)

I've used this to get my user and domain:

$user = $_SERVER['AUTH_USER'];

$user will return a value like: DOMAIN\username on our network, and then it's just a case of removing the DOMAIN\ from the string.

This has worked in IE, FF, Chrome, Safari (tested) so far.

How can I run a html file from terminal?

we could open html file from linux/unix by using firefox .html

Make more than one chart in same IPython Notebook cell

Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.


If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].

Element-wise addition of 2 lists?

Perhaps this is pythonic and slightly useful if you have an unknown number of lists, and without importing anything.

As long as the lists are of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each).

The * is used again in the returned list to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  



[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])


[19, 19, 19, 19, 19]

How to access POST form fields

Request streaming worked for me

req.on('end', function() {
    var paramstring = postdata.split("&");

var postdata = "";
req.on('data', function(postdataChunk){
    postdata += postdataChunk;

Activity transition in Android

I overwrite my default activity animation. I test it in api 15 that it work smoothly. Here is the solution that I use:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>


<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
    <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
    <item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
    <item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>

Create anim folder under res folder and then create this four animation files:


<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="">
    <translate android:fromXDelta="100%p" android:toXDelta="0"


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="">
    <translate android:fromXDelta="0" android:toXDelta="-100%p"


<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"


<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="">
    <translate android:fromXDelta="0" android:toXDelta="100%p"

You can download my sample project.

That's all... :)

Keep SSH session alive

The ssh daemon (sshd), which runs server-side, closes the connection from the server-side if the client goes silent (i.e., does not send information). To prevent connection loss, instruct the ssh client to send a sign-of-life signal to the server once in a while.

The configuration for this is in the file $HOME/.ssh/config, create the file if it does not exist (the config file must not be world-readable, so run chmod 600 ~/.ssh/config after creating the file). To send the signal every e.g. four minutes (240 seconds) to the remote host, put the following in that configuration file:

Host remotehost
    ServerAliveInterval 240

To enable sending a keep-alive signal for all hosts, place the following contents in the configuration file:

Host *
    ServerAliveInterval 240

Iterating over Numpy matrix rows to apply a function each?

While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:

import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
  print str(row)

window.onload vs $(document).ready()

window.onload is the built-in JavaScript event, but as its implementation had subtle quirks across browsers (Firefox, Internet Explorer 6, Internet Explorer 8, and Opera), jQuery provides document.ready, which abstracts those away, and fires as soon as the page's DOM is ready (doesn't wait for images, etc.).

$(document).ready (note that it's not document.ready, which is undefined) is a jQuery function, wrapping and providing consistency to the following events:

  • document.ondomcontentready / document.ondomcontentloaded - a newish event which fires when the document's DOM is loaded (which may be some time before the images, etc. are loaded); again, slightly different in Internet Explorer and in rest of the world
  • and window.onload (which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)

How do I get the computer name in .NET

Try this one.

public static string GetFQDN()
    string domainName = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
    string hostName = Dns.GetHostName();
    string fqdn;
    if (!hostName.Contains(domainName))
        fqdn = hostName + "." +domainName;
        fqdn = hostName;

    return fqdn;

How to execute an .SQL script file using c#

I tried this solution with Microsoft.SqlServer.Management but it didn't work well with .NET 4.0 so I wrote another solution using .NET libs framework only.

string script = File.ReadAllText(@"E:\someSqlScript.sql");

// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

foreach (string commandString in commandStrings)
    if (!string.IsNullOrWhiteSpace(commandString.Trim()))
        using(var command = new SqlCommand(commandString, Connection))

Get contentEditable caret index position

Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:

function cursor_position() {_x000D_
    var sel = document.getSelection();_x000D_
    sel.modify("extend", "backward", "paragraphboundary");_x000D_
    var pos = sel.toString().length;_x000D_
    if(sel.anchorNode != undefined) sel.collapseToEnd();_x000D_
    return pos;_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
function printCaretPosition(){_x000D_
  console.log( cursor_position(), 'length:', this.textContent.trim().length )_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>

It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary to documentboundary or whatever granularity for your case. Check out the API for more details. Cheers! :)

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.

Regular expression search replace in Sublime Text 2

Looking at Sublime Text Unofficial Documentation's article on Search and Replace, it looks like +(.+) is the capture group you might want... but I personally used (.*) and it worked well. To REPLACE in the way you are saying, you might like this conversation in the forums, specifically this post which says to simply use $1 to use the first captured group.

And since pictures are better than words...

Before: before find/replace

After: after find/replace

How do I get a class instance of generic type T?

I'm using workaround for this:

class MyClass extends Foo<T> {

MyClass myClassInstance = MyClass.class.newInstance();

vim line numbers - how to have them on by default?

Terminal > su > password > vim /etc/vimrc

Click here and edit as in line number (13):

set nu

click here and Edit as "Line number (13)"

when exactly are we supposed to use "public static final String"?

? public makes it accessible across the other classes. You can use it without instantiate of the class or using any object.

? static makes it uniform value across all the class instances. It ensures that you don't waste memory creating many of the same thing if it will be the same value for all the objects.

? final makes it non-modifiable value. It's a "constant" value which is same across all the class instances and cannot be modified.

RESTful Authentication

To answer this question from my understanding...

An authentication system that uses REST so that you do not need to actually track or manage the users in your system. This is done by using the HTTP methods POST, GET, PUT, DELETE. We take these 4 methods and think of them in terms of database interaction as CREATE, READ, UPDATE, DELETE (but on the web we use POST and GET because that is what anchor tags support currently). So treating POST and GET as our CREATE/READ/UPDATE/DELETE (CRUD) then we can design routes in our web application that will be able to deduce what action of CRUD we are achieving.

For example, in a Ruby on Rails application we can build our web app such that if a user who is logged in visits then the GET of that page can viewed as the user attempting to logout. In our rails controller we would build an action in that logs the user out and sends them back to the home page.

A GET on the login page would yield a form. a POST on the login page would be viewed as a login attempt and take the POST data and use it to login.

To me, it is a practice of using HTTP methods mapped to their database meaning and then building an authentication system with that in mind you do not need to pass around any session id's or track sessions.

I'm still learning -- if you find anything I have said to be wrong please correct me, and if you learn more post it back here. Thanks.

Finding absolute value of a number without using Math.abs()

You can use :

abs_num = (num < 0) ? -num : num;

Is there a simple way to delete a list element by value?

With a for loop and a condition:

def cleaner(seq, value):    
    temp = []                      
    for number in seq:
        if number != value:
    return temp

And if you want to remove some, but not all:

def cleaner(seq, value, occ):
    temp = []
    for number in seq:
        if number == value and occ:
            occ -= 1
    return temp

Consistency of hashCode() on a Java string

Just to answer your question and not to continue any discussions. The Apache Harmony JDK implementation seems to use a different algorithm, at least it looks totally different:


public int hashCode() {
    int h = hash;
    if (h == 0) {
        int off = offset;
        char val[] = value;
        int len = count;

        for (int i = 0; i < len; i++) {
            h = 31*h + val[off++];
        hash = h;
    return h;

Apache Harmony

public int hashCode() {
    if (hashCode == 0) {
        int hash = 0, multiplier = 1;
        for (int i = offset + count - 1; i >= offset; i--) {
            hash += value[i] * multiplier;
            int shifted = multiplier << 5;
            multiplier = shifted - multiplier;
        hashCode = hash;
    return hashCode;

Feel free to check it yourself...

Regex for numbers only

^\d+$, which is "start of string", "1 or more digits", "end of string" in English.

In Rails, how do you render JSON using a view?

Just to update this answer for the sake of others who happen to end up on this page.

In Rails 3, you just need to create a file at views/users/show.json.erb. The @user object will be available to the view (just like it would be for html.) You don't even need to_json anymore.

To summarize, it's just

# users contoller
def show
  @user = User.find( params[:id] )
  respond_to do |format|


/* views/users/show.json.erb */
    "name" : "<%= %>"

How to use pip on windows behind an authenticating proxy

I ran into the same issue on windows 7. I managed to get it working by creating a "pip" folder with a "pip.ini" file inside it. I put this folder inside "C:\Users\{my.username}\AppData\Roaming", because according to the Python documentation:

On Windows the configuration file is %APPDATA%\pip\pip.ini

In the pip.ini file I have only:

proxy = [proxy address]:[proxy port]

So no username:password. And it is working just fine.

Sql connection-string for localhost server

Do You have Internal Connection or External Connection. If you did Internal Connection then try this:

"Data Source=.\SQLEXPRESS;AttachDbFilename="Your PAth .mdf";Integrated Security=True;User Instance=True";


You will only see the difference if you have ties within a partition for a particular ordering value.

RANK and DENSE_RANK are deterministic in this case, all rows with the same value for both the ordering and partitioning columns will end up with an equal result, whereas ROW_NUMBER will arbitrarily (non deterministically) assign an incrementing result to the tied rows.

Example: (All rows have the same StyleID so are in the same partition and within that partition the first 3 rows are tied when ordered by ID)

         SELECT 1,1 UNION ALL
         SELECT 1,1 UNION ALL
         SELECT 1,2)
FROM   T  


StyleID     ID       RANK      ROW_NUMBER      DENSE_RANK
----------- -------- --------- --------------- ----------
1           1        1         1               1
1           1        1         2               1
1           1        1         3               1
1           2        4         4               2

You can see that for the three identical rows the ROW_NUMBER increments, the RANK value remains the same then it leaps to 4. DENSE_RANK also assigns the same rank to all three rows but then the next distinct value is assigned a value of 2.

shell init issue when click tab, what's wrong with getcwd?

Just change the directory to another one and come back. Probably that one has been deleted or moved.

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

Add to model:

using System.Web.Mvc;

And to your property

        [Display(Name = "Body")]
        public String Body { get; set; }

This code from my point the best way avoid this error. If you are using HTML editor you will not have security issues because it already restricted.

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:


namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

How do I change the font size and color in an Excel Drop Down List?

You cannot change the default but there is a codeless workaround.

Select the whole sheet and change the font size on your data to something small, like 10 or 12. When you zoom in to view the data you will find that the drop down box entries are now visible.

To emphasize, the issue is not so much with the size of the font in the drop down, it is the relative size between drop down and data display font sizes.

CSS container div not getting height

The best and the most bulletproof solution is to add ::before and ::after pseudoelements to the container. So if you have for example a list like:

<ul class="clearfix">

And every elements in the list has float:left property, then you should add to your css:

.clearfix::after, .clearfix::before {
     content: '';
     clear: both;
     display: table;

Or you could try display:inline-block; property, then you don't need to add any clearfix.

Retrofit 2: Get JSON from Response body

try {                                                                           
    JSONObject jsonObject = new JSONObject(response.body().string());           
} catch (JSONException | IOException e ) {                                      

How can I wait for set of asynchronous callback functions?

Use an control flow library like after, function (value, done) {
    // do something async
    setTimeout(function () {
        // do something with the value
        done(null, value * 2)
    }, 10)
}, function (err, mappedArray) {
    // all done, continue here

How to properly make a http web GET request

var request = (HttpWebRequest)WebRequest.Create("sendrequesturl");
var response = (HttpWebResponse)request.GetResponse();
string responseString;
using (var stream = response.GetResponseStream())
    using (var reader = new StreamReader(stream))
        responseString = reader.ReadToEnd();

Facebook share button and custom text

use this function derived from link provided by IJas

function openFbPopUp() {
    var fburl = '';
    var fbimgurl = 'http://';
    var fbtitle = 'Your title';
    var fbsummary = "your description";
    var sharerURL = "[url]=" + encodeURI(fburl) + "&p[images][0]=" + encodeURI(fbimgurl) + "&p[title]=" + encodeURI(fbtitle) + "&p[summary]=" + encodeURI(fbsummary);
    return  false;

Or you can also use the latest FB.ui Function if using FB JavaScript SDK for more controlled callback function.

refer: FB.ui

    function openFbPopUp() {
            method: 'feed',
            name: 'Facebook Dialogs',
            link: '',
            picture: '',
            caption: 'Reference Documentation',
            description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
          function(response) {
            if (response && response.post_id) {
              alert('Post was published.');
            } else {
              alert('Post was not published.');

Why is 22 the default port number for SFTP?

It's the default SSH port and SFTP is usually carried over an SSH tunnel.

Simulate string split function in Excel formula

Highlight the cell, use Dat => Text to Columns and the DELIMITER is space. Result will appear in as many columns as the split find the space.

How to convert a Kotlin source file to a Java source file

As @Vadzim said, in IntelliJ or Android Studio, you just have to do the following to get java code from kotlin:

  1. Menu > Tools > Kotlin > Show Kotlin Bytecode
  2. Click on the Decompile button
  3. Copy the java code


With a recent version (1.2+) of the Kotlin plugin you also can directly do Menu > Tools > Kotlin -> Decompile Kotlin to Java.

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

How do I remove an object from an array with JavaScript?

we have an array of objects, we want to remove one object using only the id property

var apps = [
       {id:34,name:'My App',another:'thing'},
       {id:37,name:'My New App',another:'things'

get the index of the object with id:37

var removeIndex = { return; }).indexOf(37);

// remove object

apps.splice(removeIndex, 1);

Restart android machine

Have you tried simply 'reboot' with adb?

  adb reboot

Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:

 adb shell <command>

The official docs can be found here.

Sharing link on WhatsApp from mobile website (not application) for Android

The official docs say to use: Don't use I apologize for the length of these results, but it's been a rapidly-evolving issue....

April, 2020 Results

Share Link

This link is incorrect. Close this window and try a different link.

May, 2020 Results

Share Link GitHub Ticket: WhatsApp short link without phone number not working anymore

We couldn't find the page you were looking for

Looks like you're looking for a page that doesn't exist. Or a page we might have just deleted. Either way, go back or be sure to check the url, your spelling and try again.

August, 2020 Results

Share Link

Works as expected!

LATEST - October, 2020 Results

Share Link

(Broken again!) og:image tag previews are disabled when using

Based on some of the comments I'm seeing, it seems like this still be an intermittent problem, so, going forward, I recommend you stick to the URL!

If you want to share, you must absolutely use one of the two following URL formats:

If you are interested in watching a project that keeps track of these URLs, then check us out!:

Social Share URLs

Getting path of captured image in Android using camera intent

There is a solution to create file (on external cache dir or anywhere else) and put this file's uri as output extra to camera intent - this will define path where taken picture will be stored.

Here is an example:

File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(getActivity().getExternalCacheDir(), 
                String.valueOf(System.currentTimeMillis()) + ".jpg");
        fileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {

                //do whatever you need with taken photo using file or fileUri


Then if you don't need the file anymore, you can delete it using file.delete();

By the way, files from cache dir will be removed when user clears app's cache from apps settings.

How can I check which version of Angular I'm using?

There are many way, you check angular version Just pent the comand prompt(for windows) and type

1. ng version
2. ng v
3. ng -v

check the angular version using comand line

4. You can pakage.json file

check the angular version on pakage.json file

5.You can check in browser by presing F12 then goto elements tab

check the angular version on your browser

Full understanding of subversion about(x.x.x) please see angular documentation angularJS and angular 2+

Working with select using AngularJS's ng-options

It can be useful. Bindings do not always work.

<select id="product" class="form-control" name="product" required
        ng-options=" as p.shortName for p in products"></select>

For example, you fill the options list source model from a REST service. A selected value was known before filling the list, and it was set. After executing the REST request with $http, the list option is done.

But the selected option is not set. For unknown reasons AngularJS in shadow $digest executing does not bind selected as it should be. I have got to use jQuery to set the selected. It`s important! AngularJS, in shadow, adds the prefix to the value of the attr "value" for generated by ng-repeat options. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
       .then(function (response) {
           $scope.products =;

           if (productId) {
               console.log("" + $("#product option").length);//for clarity
               $timeout(function () {
                   console.log("" + $("#product option").length);//for clarity

               }, 200);

How to use Google App Engine with my own naked domain (not subdomain)?

For App Engine in 2019, googles has made it easier to set up a custom domain.

  1. Google App Engine -> Settings -> Custom Domains

  2. Verify your domain

  3. Select Your Domain Name Registra

Reminder: Use TXT Record with the value Google provides without a existing CNAME record, otherwise TXT Record will be override

  1. Follow the steps on the page, which includes the configuration of your subdomain, CNAME Record, A Record, AAAA Record, and you'll be good to go.

Spring schemaLocation fails when there is no internet connection

I had the same problem when I'm using spring-context version 4.0.6 and spring-security version 4.1.0.

When changing spring-security version to 4.0.4 (because 4.0.6 of spring-security not available) in my pom and security xml-->schemaLocation, it gets compiled without internet.

So that mean you can also solve this by:

  • changing spring-security to a older or same version than spring-context.

  • changing spring-context to a newer or same version than spring-security.

(any way spring-context to be newer or same version to spring-security)

kill a process in bash

Please check "top" command then if your script or any are running please note 'PID'

 1384 root      20   0  514m  32m 2188 S  0.3  5.4  55:09.88 example
14490 root      20   0 15140 1216  920 R  0.3  0.2   0:00.02 example2

kill <you process ID>

Example : kill 1384

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

Simply u can add this to jquery.validationEngine-en.js file

    "onlyLetterNumberSp": {
                "regex": ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$,
                "alertText": "* No special characters allowed"

and call it in text field as

<input type="text" class="form-control validate[required,custom[onlyLetterNumberSp]]"  id="title" name="title" placeholder="Title"/>

Angular is automatically adding 'ng-invalid' class on 'required' fields

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
    <label class="col-sm-2 control-label" for="username">Username*</label>
    <div class="col-sm-10 col-md-9">
        <input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>

It is also important, that your form has the ng-submit="" attribute:

<form name="myForm" ng-submit="checkSubmit()" novalidate>
 <!-- input fields here -->

  <button type="submit">Submit</button>

You can also add an optional function for validation to the form:

//within your controller (some extras...)

$scope.checkSubmit = function () {

   if ($scope.myForm.$valid) {
        alert('All good...'); //next step!

   else {
        alert('Not all fields valid! Do something...');


Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:

You could also use:

Redirecting to a new page after successful login

You need to set the location header as follows:


Replacing of course with the url of your landing page.

Add this where you have finished logging the user in.

Note: When redirecting the user will be immediately redirected so you're message probably won't display.

Additionally, you need to move your PHP code to the top of the file for this solution to work.

On another side note, please see my comment above regarding the use of the deprecated mysql statements and consider using the newer, safer and improved mysqli or PDO statements.

How can one run multiple versions of PHP 5.x on a development LAMP server?

Rasmus Lerdorf, who created PHP, is maintaining an active Vagrant solution that seems to solve your needs. It allows for quickly switching between PHP versions, currently supporting more than 20 different versions. It comes out of the box with an nginx server, but can easily be switched to apache2 with a preconfigured setting. It also supports MySQL out of the box.

This way you will have access to all versions of PHP, deployable on two of the main web servers, in a nice vagrant box, maintained by the big man behind PHP.

For more information I would like to refer to the talk given by mr. Lerdorf at

The github repository containing the Vagrant solution is found at

How do I tell if an object is a Promise?

Update: This is no longer the best answer. Please vote up my other answer instead.

obj instanceof Promise

should do it. Note that this may only work reliably with native es6 promises.

If you're using a shim, a promise library or anything else pretending to be promise-like, then it may be more appropriate to test for a "thenable" (anything with a .then method), as shown in other answers here.

How do I escape spaces in path for scp copy in Linux?

I had huge difficulty getting this to work for a shell variable containing a filename with whitespace. For some reason using:

file="foo bar/baz"
scp [email protected]:"'$file'"

as in @Adrian's answer seems to fail.

Turns out that what works best is using a parameter expansion to prepend backslashes to the whitespace as follows:

file="foo bar/baz"
file=${file// /\\ }
scp [email protected]:"$file"

Catch a thread's exception in the caller thread in Python

Using naked excepts is not a good practice because you usually catch more than you bargain for.

I would suggest modifying the except to catch ONLY the exception that you would like to handle. I don't think that raising it has the desired effect, because when you go to instantiate TheThread in the outer try, if it raises an exception, the assignment is never going to happen.

Instead you might want to just alert on it and move on, such as:

def run(self):
       shul.copytree(self.sourceFolder, self.destFolder)
    except OSError, err:
       print err

Then when that exception is caught, you can handle it there. Then when the outer try catches an exception from TheThread, you know it won't be the one you already handled, and will help you isolate your process flow.


DISTINCT: will gives you unique values.

SELECT GROUP_CONCAT(DISTINCT(categories )) AS categories FROM table

Setting table column width

Depending on your body (or the div which is wrapping your table) 'settings' you should be able to do this:

body {
  width: 98%;

table {
  width: 100%;

th {
  border: 1px solid black;

th.From, th.Date {
  width: 15%;

th.Date {
  width: 70%;

      <th class="From">From</th>
      <th class="Subject">Subject</th>
      <th class="Date">Date</th>
       <td>Your question</td>
       <td>5/30/2009 2:41:40 AM UTC</td>


Start a fragment via Intent within a Fragment

You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

Pass in an array of Deferreds to $.when()

To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply, so in this case you need:

$.when.apply($, my_array).then( ___ );


In ES6, you can use the ... spread operator instead:

$.when(...my_array).then( ___ );

In either case, since it's unlikely that you'll known in advance how many formal parameters the .then handler will require, that handler would need to process the arguments array in order to retrieve the result of each promise.

How to format strings in Java

public class StringFormat {

    public static void main(String[] args) {
            Scanner sc=new Scanner(;
            for(int i=0;i<3;i++){
                int x=sc.nextInt();


outpot "================================"
ved15space123 ved15space123 ved15space123 "================================

Java solution

  • The "-" is used to left indent

  • The "15" makes the String's minimum length it takes up be 15

  • The "s" (which is a few characters after %) will be substituted by our String
  • The 0 pads our integer with 0s on the left
  • The 3 makes our integer be a minimum length of 3

Should C# or C++ be chosen for learning Games Programming (consoles)?

It depends

It depends on a lot of things - your goals, your experience, your timeframe, etc.

The majority of game programming isn't language specific. 3D math is 3D math in C# as much as it is in C++. While the APIs may be different, and different 'bookkeeping' may be required, the fundamental logic and math will remain the same.

And it's true that most AAA game engines are C++ with a scripting language on top of them. That is undeniable. However, most AAA engines also have a bunch of in-house tools supporting them, and those may be in anything - Java, C#, C++, etc.

If you want to write a game, and are an experienced developer then C++ and C# have a lot going for them. C# has less housekeeping, while C++ has more available libraries and tools. For anything highly complex, however, you'd be best off trying to use an existing engine as a starting point.

If you want to write a game, and are a new developer then don't write an engine. Use an existing engine, and mod it or use its facilities to write your game. Trust me.

If you want to learn how to write an engine, and are an experienced developer you should probably think about C++. C# is possible as well, but the amount of code and ease of integration of C++ probably puts it over the top.

If you want to learn how to write an engine, and are a new developer I'd probably recommend C#/XNA. You'll get to the game 'stuff' faster, with less headache of learning the ins and outs of C++.

If you want a job in the industry then you need to figure out what kind of job you want. A high-level language can help get a foot in the door dealing with tools and/or web development, which can lead to opportunities on actual game work. Even knowledge of scripting languages can help if you want to go for more of the game designer/scripter position. Chances are that you will not get a job working on core engine stuff immediately, as the skills required to do so are pretty high. Strong C++ development skills are always helpful, especially in real-time or networked scenarios.

AAA game engine development involves some serious brain-twisting code.

If you want to start a professional development house then you probably aren't reading this, but already know that C++ is probably the only viable answer.

If you want to do casual game development then you should probably consider Flash or a similar technology.

How do I correctly setup and teardown for my pytest class with tests?

As @Bruno suggested, using pytest fixtures is another solution that is accessible for both test classes or even just simple test functions. Here's an example testing python2.7 functions:

import pytest

def some_resource(request):
    stuff_i_setup = ["I setup"]

    def some_teardown():
        stuff_i_setup[0] += " ... but now I'm torn down..."
        print stuff_i_setup[0]

    return stuff_i_setup[0]

def test_1_that_needs_resource(some_resource):
    print some_resource + "... and now I'm testing things..."

So, running test_1... produces:

I setup... and now I'm testing things...
I setup ... but now I'm torn down...

Notice that stuff_i_setup is referenced in the fixture, allowing that object to be setup and torn down for the test it's interacting with. You can imagine this could be useful for a persistent object, such as a hypothetical database or some connection, that must be cleared before each test runs to keep them isolated.

How do you clear your Visual Studio cache on Windows Vista?

I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.

So I cleared the .Net Temp folder.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.

My issue was sorted.

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
echo Done!

Usage of the backtick character (`) in JavaScript

Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.


  • we can interpolate any kind of expression in the template literals.
  • They can be multi-line.

Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).


var nameStr = `I'm "Rohit" Jindal`;

To interpolate the variables or expression we can use the ${expression} notation for that.

var name = 'Rohit Jindal';
var text = `My name is ${name}`;
console.log(text); // My name is Rohit Jindal

Multi-line strings means that you no longer have to use \n for new lines anymore.


const name = 'Rohit';
console.log(`Hello ${name}!
How are you?`);


Hello Rohit!
How are you?

fatal: The current branch master has no upstream branch

Please try this scenario

git push -f --set-upstream origin master

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

You can use attributes of html tag instead of validation from html input type ="date" can be used instead of validating it. That's the benifits html 5 gives you

Reimport a module in python while interactive

Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:

# Python >= 3.5
import importlib
import types

def walk_reload(module: types.ModuleType) -> None:
    if hasattr(module, "__all__"):
        for submodule_name in module.__all__:
            walk_reload(getattr(module, submodule_name))


The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
                // Save the file here

What does "Could not find or load main class" mean?

Try -Xdiag.

Steve C's answer covers the possible cases nicely, but sometimes to determine whether the class could not be found or loaded might not be that easy. Use java -Xdiag (since JDK 7). This prints out a nice stacktrace which provides a hint to what the message Could not find or load main class message means.

For instance, it can point you to other classes used by the main class that could not be found and prevented the main class to be loaded.

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
pause >nul

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
pause >nul

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
color a
echo Choose the file that you want to read.
set file=
set /p file=File:
echo Reading from %file%
type %file%
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A

Static array vs. dynamic array in C++

Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.

int arr[] = { 1, 3, 4 }; // static integer array.   
int* arr = new int[3]; // dynamic integer array.

How to build PDF file from binary string returned from a web-service using javascript

You can use PDF.js to create PDF files from javascript... it's easy to code... hope this solve your doubt!!!


How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

Taken from Retrieving File information | Android developers

Retrieving a File's name.

private String queryName(ContentResolver resolver, Uri uri) {
    Cursor returnCursor =
            resolver.query(uri, null, null, null, null);
    assert returnCursor != null;
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    String name = returnCursor.getString(nameIndex);
    return name;

How to escape special characters in building a JSON string?

I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

Image showing the definition of a string from the JSON spec

The pretty picture also lists all of the legitimate escape sequences within a JSON string:

  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u followed by four-hex-digits

Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.

jQuery window scroll event does not fire up

The solution is:


Shrink a YouTube video to responsive width

If you are using Bootstrap you can also use a responsive embed. This will fully automate making the video(s) responsive.

There's some example code below.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="..."></iframe>

Resize image with javascript canvas (smoothly)

I created a library that allows you to downstep any percentage while keeping all the color data.

That file you can include in the browser. The results will look like photoshop or image magick, preserving all the color data, averaging pixels, rather than taking nearby ones and dropping others. It doesn't use a formula to guess the averages, it takes the exact average.

Is it necessary to assign a string to a variable before comparing it to another?

Do I really have to create an NSString for "Wrong"?

No, why not just do:

if([statusString isEqualToString:@"Wrong"]){

Using @"" simply creates a string literal, which is a valid NSString.

Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?

Yes, you can do something like:

UILabel *label = ...;
if([someString isEqualToString:label.text]) {
    // Do stuff here 

How to remove the bottom border of a box with CSS

Just add in: border-bottom: none;

#index-03 {
    border: .1px solid #900;
    border-bottom: none;

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);

getValue('myFile.txt').then(function(res) {
  // do whatever with res here

(although this is a bit redundant, I'm sure your actual code is more complicated)

Property 'value' does not exist on type EventTarget in TypeScript

you can also create your own interface as well.

    export interface UserEvent {
      target: HTMLInputElement;


    onUpdatingServerName(event: UserEvent) {

AngularJS : When to use service instead of factory

allernhwkim originally posted an answer on this question linking to his blog, however a moderator deleted it. It's the only post I've found which doesn't just tell you how to do the same thing with service, provider and factory, but also tells you what you can do with a provider that you can't with a factory, and with a factory that you can't with a service.

Directly from his blog:

app.service('CarService', function() {"Bad";
    this.numCylinder = 4;

app.factory('CarFactory', function() {
    return function(numCylinder) {"Bad";
        this.numCylinder = numCylinder

app.provider('CarProvider', function() {
    this.dealerName = 'Bad';
    this.$get = function() {
        return function(numCylinder) {
            this.numCylinder = numCylinder;
   = this.dealerName;
    this.setDealerName = function(str) {
      this.dealerName = str;

This shows how the CarService will always a produce a car with 4 cylinders, you can't change it for individual cars. Whereas CarFactory returns a function so you can do new CarFactory in your controller, passing in a number of cylinders specific to that car. You can't do new CarService because CarService is an object not a function.

The reason factories don't work like this:

app.factory('CarFactory', function(numCylinder) {"Bad";
      this.numCylinder = numCylinder

And automatically return a function for you to instantiate, is because then you can't do this (add things to the prototype/etc):

app.factory('CarFactory', function() {
    function Car(numCylinder) {"Bad";
        this.numCylinder = numCylinder
    Car.prototype.breakCylinder = function() {
        this.numCylinder -= 1;
    return Car;

See how it is literally a factory producing a car.

The conclusion from his blog is pretty good:

In conclusion,

| Provider| Singleton| Instantiable | Configurable|
| Factory | Yes      | Yes          | No          |
| Service | Yes      | No           | No          |
| Provider| Yes      | Yes          | Yes         |       
  1. Use Service when you need just a simple object such as a Hash, for example {foo;1, bar:2} It’s easy to code, but you cannot instantiate it.

  2. Use Factory when you need to instantiate an object, i.e new Customer(), new Comment(), etc.

  3. Use Provider when you need to configure it. i.e. test url, QA url, production url.

If you find you're just returning an object in factory you should probably use service.

Don't do this:

app.factory('CarFactory', function() {
    return {
        numCylinder: 4

Use service instead:

app.service('CarService', function() {
    this.numCylinder = 4;

How get total sum from input box values using Javascript?

To sum with decimal use this:

In the javascript change parseInt with parseFloat and add this line tot.toFixed(2); for this result:

    function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
            tot += parseFloat(arr[i].value);
    document.getElementById('total').value = tot;

Use step=".01" min="0" type="number" in the input filed

Qty1 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty1"/><br>
Qty2 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty2"/><br>
Qty3 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty3"/><br>
Qty4 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty4"/><br>
Qty5 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty5"/><br>
Qty6 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty6"/><br>
Qty7 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty7"/><br>
Qty8 : <input onblur="findTotal()" step=".01" min="0" type="number" name="qty" id="qty8"/><br>
Total : <input type="number" step=".01" min="0" name="total" id="total"/>

href overrides ng-click in Angular.js

//for dynamic elements - if you want it in ng-repeat do below code

angular.forEach($, function(value, key) {
     //add new value to object
    value.new_url  = "your url";

 <div ng-repeat="row in data"><a ng-href="{{ row.url_content }}"></a></div>

Use stored procedure to insert some data into a table

If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY() would be a better approach. I would not advice to use @@IDENTITY, as this can return any ID.

CREATE PROC [dbo].[sp_Test] (
  @myID int output,
  @myFirstName nvarchar(50),
  @myLastName nvarchar(50),
  @myAddress nvarchar(50),
  @myPort int
) AS
    INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
    VALUES (@myFirstName, @myLastName, @myAddress, @myPort);


Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I have build a sample android studio project for this question.

output screen shots :-

enter image description here

enter image description here

enter image description here

Download full project source code Click here

Please note: you have to add your API key in Androidmanifest.xml

Beautiful Soup and extracting a div and its contents by ID

I think there is a problem when the 'div' tags are too much nested. I am trying to parse some contacts from a facebook html file, and the Beautifulsoup is not able to find tags "div" with class "fcontent".

This happens with other classes as well. When I search for divs in general, it turns only those that are not so much nested.

The html source code can be any page from facebook of the friends list of a friend of you (not the one of your friends). If someone can test it and give some advice I would really appreciate it.

This is my code, where I just try to print the number of tags "div" with class "fcontent":

from BeautifulSoup import BeautifulSoup 
f = open('/Users/myUserName/Desktop/contacts.html')
soup = BeautifulSoup(f) 
list = soup.findAll('div', attrs={'class':'fcontent'})
print len(list)

How to compare data between two table in different databases using Sql Server 2008?

select * from DB1.dbo.Table a inner join DB2.dbo.Table b on b.PrimKey = a.PrimKey 
where a.FirstColumn <> b.FirstColumn ...

Checksum that Matt recommended is probably a better approach to compare columns rather than comparing each column

How to store Emoji Character in MySQL Database

If you are using Solr + Mysql + Java, you can use:

This can be Used :

  • case1: When you don`t want to alter DB.
  • case2: when you have to import emoticons from your Mysql to Solr core.

In above case this is one of the solutions to store your emoticons in your system.

Steps to use it:

Library used: import; import;

  1. Use urlEncoder to encode your String having emoticons.
  2. Store it in DB without altering the MysqlDB.
  3. You can store it in solr core(decoded form)if you want or you can store encoded form.
  4. When fetching these emoticons from DB or Solr core you can now decode it Using urlDecoder.

Code example:


public static void main(String[] args) {
    //, args);
    System.out.println(encodeStringUrl("3?5?3?????????????     "));

public static String encodeStringUrl(String url) {
    String encodedUrl =null;
    try {
         encodedUrl = URLEncoder.encode(url, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return encodedUrl;
    return encodedUrl;

public static String decodeStringUrl(String encodedUrl) {
    String decodedUrl =null;
    try {
         decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return decodedUrl;
    return decodedUrl;

'Class' does not contain a definition for 'Method'

I just ran into this problem; the issue seems different from the other answers posted here, so I'll mention it in case it helps someone.

In my case, I have an internal base class defined in one assembly ("A"), an internal derived class defined in a second assembly ("B"), and a test assembly ("TEST"). I exposed internals defined in assembly "B" to "TEST" using InternalsVisibleToAttribute, but neglected to do so for assembly "A". This produced the error mentioned at top with no further indication of the problem; using InternalsVisibleToAttribute to expose assembly "A" to "TEST" resolved the issue.

assign value using linq

You can create a extension method:

public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
    foreach(var item in self) {
        yield return item;

And then use it in code:

listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);

Android EditText for password with android:hint

Actually, I found that if you put the the android:gravity="center" at the end of your xml line, the hint text shows up fine with the android:inputType="textVisiblePassword"


How about..

var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)

Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest

How to use the priority queue STL for objects?

A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.

The C++ standard library defines a class template priority_queue, with the following operations:

push: Insert an element into the prioity queue.

top: Return (without removing it) a highest priority element from the priority queue.

pop: Remove a highest priority element from the priority queue.

size: Return the number of elements in the priority queue.

empty: Return true or false according to whether the priority queue is empty or not.

The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:

#include <queue>

priority_queue<int> q1;
priority_queue<string> q2;

The following is an example of priority queue usage:

#include <string>
#include <queue>
#include <iostream>

using namespace std;  // This is to make available the names of things defined in the standard library.

int main()
    piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.

    pq.push("the quick");
    pq.push("jumped over");
    pq.push("the lazy dog");

    // The strings are ordered inside the priority queue in lexicographic (dictionary) order:
    // "fox", "jumped over", "the lazy dog", "the quick"
    //  The lowest priority string is "fox", and the highest priority string is "the quick"

    while (!pq.empty()) {
       cout << << endl;  // Print highest priority string
       pq.pop();                    // Remmove highest priority string

    return 0;

The output of this program is:

the quick
the lazy dog
jumped over

Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.

Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:

struct Time {
    int h; 
    int m; 
    int s;

class CompareTime {
    bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;

A priority queue to store times according the the above comparison criterion would be defined as follows:

priority_queue<Time, vector<Time>, CompareTime> pq;

Here is a complete program:

#include <iostream>
#include <queue>
#include <iomanip>

using namespace std;

struct Time {
    int h; // >= 0
    int m; // 0-59
    int s; // 0-59

class CompareTime {
    bool operator()(Time& t1, Time& t2)
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;

int main()
    priority_queue<Time, vector<Time>, CompareTime> pq;

    // Array of 4 time objects:

    Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};

    for (int i = 0; i < 4; ++i)

    while (! pq.empty()) {
       Time t2 =;
       cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
       setw(3) << t2.s << endl;

    return 0;

The program prints the times from latest to earliest:

5  16  13
5  14  20
3   2  40
3   2  26

If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:

class CompareTime {
    bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
       if (t2.h < t1.h) return true;
       if (t2.h == t1.h && t2.m < t1.m) return true;
       if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
       return false;