Programs & Examples On #Return value optimization

C++ copy-elision of return-values.

How to change heatmap.2 color range in R?

I think you need to set symbreaks = FALSE That should allow for asymmetrical color scales.

Change navbar color in Twitter Bootstrap

Using Less

You could also consider to compile your own version. Try (which has a apart section for the Navbars settings (Default navbar and Inverted Navbar)) or download your own copy from

You will find the navbar settings in variables.less. navbar.less is used to compile the navbar (depends on variables.less and mixins.less).

Copy the 'navbar-default section' and fill in your own color settings. Changing the variables in variables.less will be the easiest way (changing the default or inverse navbar won't be a problem because you have one navbar per page only).

You won't change all settings in most cases:

// Navbar
// -------------------------

// Basics of a navbar
@navbar-height:                    50px;
@navbar-margin-bottom:             @line-height-computed;
@navbar-default-color:             #777;
@navbar-default-bg:                #f8f8f8;
@navbar-default-border:            darken(@navbar-default-bg, 6.5%);
@navbar-border-radius:             @border-radius-base;
@navbar-padding-horizontal:        floor(@grid-gutter-width / 2);
@navbar-padding-vertical:          ((@navbar-height - @line-height-computed) / 2);

// Navbar links
@navbar-default-link-color:                #777;
@navbar-default-link-hover-color:          #333;
@navbar-default-link-hover-bg:             transparent;
@navbar-default-link-active-color:         #555;
@navbar-default-link-active-bg:            darken(@navbar-default-bg, 6.5%);
@navbar-default-link-disabled-color:       #ccc;
@navbar-default-link-disabled-bg:          transparent;

// Navbar brand label
@navbar-default-brand-color:               @navbar-default-link-color;
@navbar-default-brand-hover-color:         darken(@navbar-default-link-color, 10%);
@navbar-default-brand-hover-bg:            transparent;

// Navbar toggle
@navbar-default-toggle-hover-bg:           #ddd;
@navbar-default-toggle-icon-bar-bg:        #ccc;
@navbar-default-toggle-border-color:       #ddd;

You could also try This tool generates CSS code for your custom navbar. Optionally, you could also add gradient colors and borders to the navbar.

One line if in VB .NET

Just add Then:

If A = 1 Then A = 2


If A = 1 Then _
    A = 2

How to replace sql field value

It depends on what you need to do. You can use replace since you want to replace the value:

select replace(email, '.com', '.org')
from yourtable

Then to UPDATE your table with the new ending, then you would use:

update yourtable
set email = replace(email, '.com', '.org')

You can also expand on this by checking the last 4 characters of the email value:

update yourtable
set email = replace(email, '.com', '.org')
where right(email, 4) = '.com'

However, the issue with replace() is that .com can be will in other locations in the email not just the last one. So you might want to use substring() the following way:

update yourtable
set email = substring(email, 1, len(email) -4)+'.org'
where right(email, 4) = '.com';

See SQL Fiddle with Demo

Using substring() will return the start of the email value, without the final .com and then you concatenate the .org to the end. This prevents the replacement of .com elsewhere in the string.

Alternatively you could use stuff(), which allows you to do both deleting and inserting at the same time:

update yourtable
set email = stuff(email, len(email) - 3, 4, '.org')
where right(email, 4) = '.com';

This will delete 4 characters at the position of the third character before the last one (which is the starting position of the final .com) and insert .org instead.

See SQL Fiddle with Demo for this method as well.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

Your command is wrong.


java -- version


java -version

You can't use those commands other way around.

Difference between Apache CXF and Axis

Keep in mind, I'm completely biased (PMC Chair of CXF), but my thoughts:

From a strictly "can the project do what I need it to do" perspective, both are pretty equivalent. There some "edge case" things that CXF can do that Axis 2 cannot and vice versa. But for 90% of the use cases, either will work fine.

Thus, it comes down to a bunch of other things other than "check box features".

  • API - CXF pushes "standards based" API's (JAX-WS compliant) whereas Axis2 general goes toward proprietary things. That said, even CXF may require uses of proprietary API's to configure/control various things outside the JAX-WS spec. For REST, CXF also uses standard API's (JAX-RS compliant) instead of proprietary things. (Yes, I'm aware of the JAX-WS runtime in Axis2, but the tooling and docs and everything doesn't target it)

  • Community aspects and supportability - CXF prides itself on responding to issues and making "fixpacks" available to users. CXF did 12 fixpacks for 2.0.x (released two years ago, so about every 2 months), 6 fixpacks to 2.1.x, and now 3 for 2.2.x. Axis2 doesn't really "support" older versions. Unless a "critical" issue is hit, you may need to wait till the next big release (they average about every 9-10 months or so) to get fixes. (although, with either, you can grab the source code and patch/fix yourself. Gotta love open source.)

  • Integration - CXF has much better Spring integration if you use Spring. All the configuration and such is done through Spring. Also, people tend to consider CXF as more "embeddable" (I've never looked at Axis2 from this perspective) into other applications. Not sure if things like that matter to you.

  • Performance - they both perform very well. I think Axis2's proprietary ADB databinding is a bit faster than CXF, but if you use JAXB (standards based API's again), CXF is a bit faster. When using more complex scenarios like WS-Security, the underlying security "engine" (WSS4J) is the same for both so the performance is completely comparable.

Not sure if that answers the question at all. Hope it at least provides some information.



Parsing date string in Go

If you have worked with time/date formatting/parsing in other languages you might have noticed that the other languages use special placeholders for time/date formatting. For eg ruby language uses

%d for day
%Y for year

etc. Golang, instead of using codes such as above, uses date and time format placeholders that look like date and time only. Go uses standard time, which is:

Mon Jan 2 15:04:05 MST 2006  (MST is GMT-0700)
01/02 03:04:05PM '06 -0700

So if you notice Go uses

01 for the day of the month,
02 for the month
03 for hours,
04 for minutes
05 for second
and so on

Therefore for example for parsing 2020-01-29, layout string should be 06-01-02 or 2006-01-02.

You can refer to the full placeholder layout table at this link -

What is the equivalent to getLastInsertId() in Cakephp?

$this->Model->field('id', null, 'id DESC')

FTP/SFTP access to an Amazon S3 Bucket

Filezilla just released a Pro version of their FTP client. It connects to S3 buckets in a streamlined FTP like experience. I use it myself (no affiliation whatsoever) and it works great.

Using WGET to run a cronjob PHP

you can just use this code to hit the script using cron job using cpanel:


Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful:

How to get an absolute file path in Python

>>> import os
>>> os.path.abspath("mydir/myfile.txt")

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")

ASP.NET GridView RowIndex As CommandArgument

I think this will work.


            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />

git: updates were rejected because the remote contains work that you do not have locally

I had this error and it was because there was an update on the server but SourceTree was not showing any updates available (possibly because I was offline when it last checked). So I did a refresh in source tree and now it shows 2 items to push instead of 1 item.

So be sure to press refresh or pull if you get this error and then try again.

How to recursively find and list the latest modified files in a directory with subdirectories and times

Try this one:

find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

Execute it with the path to the directory where it should start scanning recursively (it supports filenames with spaces).

If there are lots of files it may take a while before it returns anything. Performance can be improved if we use xargs instead:

find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head

which is a bit faster.

I forgot the password I entered during postgres installation

Just a note, on Linux You can simply run sudo su - postgres to become the postgres user and from there change what required using psql.

.NET Console Application Exit Event

As a good example may be worth it to navigate to this project and see how to handle exiting processes grammatically or in this snippet from VM found in here

                ConsoleOutputStream = new ObservableCollection<string>();

                var startInfo = new ProcessStartInfo(FilePath)
                    WorkingDirectory = RootFolderPath,
                    Arguments = StartingArguments,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                ConsoleProcess = new Process {StartInfo = startInfo};

                ConsoleProcess.EnableRaisingEvents = true;

                ConsoleProcess.OutputDataReceived += (sender, args) =>
                    App.Current.Dispatcher.Invoke((System.Action) delegate
                        ConsoleOutputStream.Insert(0, args.Data);
                ConsoleProcess.Exited += (sender, args) =>
                    InProgress = false;


    private void RegisterProcessWatcher()
        startWatch = new ManagementEventWatcher(
            new WqlEventQuery($"SELECT * FROM Win32_ProcessStartTrace where ProcessName = '{FileName}'"));
        startWatch.EventArrived += new EventArrivedEventHandler(startProcessWatch_EventArrived);

        stopWatch = new ManagementEventWatcher(
            new WqlEventQuery($"SELECT * FROM Win32_ProcessStopTrace where ProcessName = '{FileName}'"));
        stopWatch.EventArrived += new EventArrivedEventHandler(stopProcessWatch_EventArrived);

    private void stopProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
        InProgress = false;

    private void startProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
        InProgress = true;

Is mongodb running?

I know this is for php, but I got here looking for a solution for node. Using mongoskin:

mongodb.admin().ping(function(err) {
    if(err === null)
        // true - you got a conntion, congratulations
    else if(err.message.indexOf('failed to connect') !== -1)
        // false - database isn't around
        // actual error, do something about it

With other drivers, you can attempt to make a connection and if it fails, you know the mongo server's down. Mongoskin needs to actually make some call (like ping) because it connects lazily. For php, you can use the try-to-connect method. Make a script!


$dbIsRunning = true
try {
  $m = new MongoClient('localhost:27017');
} catch($e) {
  $dbIsRunning = false

Putting text in top left corner of matplotlib plot

One solution would be to use the plt.legend function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc keyterm. More information can be found at this website but I've also included an example showing how to place a legend:

ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2) 

Note that because loc=2, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize, which will then make the legend smaller.

Concatenate two slices in Go

Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:

func append

func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

Sort a List of objects by multiple fields

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
        return value1;

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

How to set image in imageview in android?

Instead of setting drawable resource through code in your activity class you can also set in XML layout:

Code is as follows:

        android:src="@drawable/apple" />

How to center content in a bootstrap column?

[Updated Dec 2020]: Tested and Included 5.0 version of Bootstrap.

I know this question is old. And the question did not mentioned which version of Bootstrap he was using. So i'll assume the answer to this question is resolved.

If any of you (like me) stumbled upon this question and looking for answer using current bootstrap 5.0 (2020) and 4.5 (2019) framework, then here's the solution.

Bootstrap 4.5 and 5.0

Use d-flex justify-content-center on your column div. This will center everything inside that column.

<div class="row">
    <div class="col-4 d-flex justify-content-center">
        // Image

If you want to align the text inside the col just use text-center

<div class="row">
    <div class="col-4 text-center">
        // text only

If you have text and image inside the column, you need to use d-flex justify-content-center and text-center.

<div class="row">
    <div class="col-4 d-flex justify-content-center text-center">
        // for image and text

What is the difference between docker-compose ports vs expose


The ports section will publish ports on the host. Docker will setup a forward for a specific port from the host network into the container. By default this is implemented with a userspace proxy process (docker-proxy) that listens on the first port, and forwards into the container, which needs to listen on the second point. If the container is not listening on the destination port, you will still see something listening on the host, but get a connection refused if you try to connect to that host port, from the failed forward into your container.

Note, the container must be listening on all network interfaces since this proxy is not running within the container's network namespace and cannot reach inside the container. The IPv4 method for that is to configure your application to listen on

Also note that published ports do not work in the opposite direction. You cannot connect to a service on the host from the container by publishing a port. Instead you'll find docker errors trying to listen to the already-in-use host port.


Expose is documentation. It sets metadata on the image, and when running, on the container too. Typically you configure this in the Dockerfile with the EXPOSE instruction, and it serves as documentation for the users running your image, for them to know on which ports by default your application will be listening. When configured with a compose file, this metadata is only set on the container. You can see the exposed ports when you run a docker inspect on the image or container.

There are a few tools that rely on exposed ports. In docker, the -P flag will publish all exposed ports onto ephemeral ports on the host. There are also various reverse proxies that will default to using an exposed port when sending traffic to your application if you do not explicitly set the container port.

Other than those external tools, expose has no impact at all on the networking between containers. You only need a common docker network, and connecting to the container port, to access one container from another. If that network is user created (e.g. not the default bridge network named bridge), you can use DNS to connect to the other containers.

Getting IPV4 address from a sockaddr structure

You can use getnameinfo for Windows and for Linux.

Assuming you have a good (i.e. it's members have appropriate values) sockaddr* called pSockaddr:

char clienthost[NI_MAXHOST];  //The clienthost will hold the IP address.
char clientservice[NI_MAXSERV];
int theErrorCode = getnameinfo(pSockaddr, sizeof(*pSockaddr), clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV);

if( theErrorCode != 0 )
    //There was an error.
    cout << gai_strerror(e1) << endl;
    //Print the info.
    cout << "The ip address is = " << clienthost << endl;
    cout << "The clientservice = " << clientservice << endl;

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to remove pip package after deleting it manually

  1. Go to the site-packages directory where pip is installing your packages.
  2. You should see the egg file that corresponds to the package you want to uninstall. Delete the egg file (or, to be on the safe side, move it to a different directory).
  3. Do the same with the package files for the package you want to delete (in this case, the psycopg2 directory).
  4. pip install YOUR-PACKAGE

Github Windows 'Failed to sync this branch'

When it says that, just open the shell and do git status. That will give you a decent idea of what could be wrong and the state of your repo.

I can't give you a specific error for this as it happens for many reasons in Github for Windows, like say some problem in updating submodules etc.

How to effectively work with multiple files in Vim

Vim (but not the original Vi!) has tabs which I find (in many contexts) superior to buffers. You can say :tabe [filename] to open a file in a new tab. Cycling between tabs is done by clicking on the tab or by the key combinations [n]gt and gT. Graphical Vim even has graphical tabs.

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
    public string Name { get; set; }
    public string Adres { get; set; }

    public MyStruct(string name, string adress)
        Name = name;
        Adres = adress;

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

How does the "position: sticky;" property work?

Here's what was tripping ME up... my sticky div was inside another div so that parent div needed some additional content AFTER the sticky div, to make the parent div "tall enough" for the sticky div to "slide over" other content as you scroll down.

So in my case, right after the sticky div, I had to add:


(My application has two side-by-side divs, with a "tall" image on the left, and a short data entry form on the right, and I wanted the data entry form to float next to the image as you scroll down, so the form is always on the screen. It would not work until I added the above "extra content" so the sticky div has something to "slide over"

How to detect if JavaScript is disabled?

Adding a refresh in meta inside noscript is not a good idea.

  1. Because noscript tag is not XHTML compliant

  2. The attribute value "Refresh" is nonstandard, and should not be used. "Refresh" takes the control of a page away from the user. Using "Refresh" will cause a failure in W3C's Web Content Accessibility Guidelines --- Reference

The declared package does not match the expected package ""

Solution 1 : One solution that worked for me when this error "The declared package does not match the expected package" occured for a project I checked-out from eclipse CVS :

1.Right click the project in the navigation bar and click 'delete'
2.Make sure 'Delete project contents on disk' option is NOT checked, and click OK.
3.Now after the project is deleted, go to File -> Import -> General -> Existing Projects into Workspace
4.Select your workspace from the directory listing and check the box next to your project name. Click 'Finish'

Solution 2 : Once again I got this error with the following message

Eclipse build errors - java.lang.Object cannot be resolved I had to follow another route mention here and the error went away.

In the mean time, the work around is to remove the JRE System Library from the project and then add it back again. Here are the steps:

  1. Go to properties of project with the build error (right click > Properties) View the "Libraries" tab in the "Build Path" section Find the "JRE System Library" in the list (if this is missing then this error message is not an eclipse bug but a mis-configured project)
  2. Remove the "JRE System Library"
  3. Hit "Add Library ...", Select "JRE System Library" and add the appropriate JRE for the project (eg. 'Workspace default JRE')
  4. Hit "Finish" in the library selection and "OK" in the project properties and then wait for the re-build of the project

Hopefully the error will be resolved ...

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

It seems like there may be a issue to dump numpy.int64 into json string in Python 3 and the python team already have a conversation about it. More details can be found here.

There is a workaround provided by Serhiy Storchaka. It works very well so I paste it here:

def convert(o):
    if isinstance(o, numpy.int64): return int(o)  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

How to initialize const member variable in a class?

In C++ you cannot initialize any variables directly while the declaration. For this we've to use the concept of constructors.
See this example:-

#include <iostream>

using namespace std;

class A
  const int x;  
  A():x(0) //initializing the value of x to 0

int main()
    A a; //creating object
   cout << "Value of x:- " <<a.x<<endl; 
   return 0;

Hope it would help you!

UIAlertView first deprecated IOS 9

 UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"Are you sure you want to logout?"

    UIAlertAction* yesButton = [UIAlertAction
                                handler:^(UIAlertAction * action)


    UIAlertAction* noButton = [UIAlertAction
                               handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button

    [alert addAction:noButton];
    [alert addAction:yesButton];

    [self presentViewController:alert animated:YES completion:nil];

How do you kill all current connections to a SQL Server 2005 database?

The reason that the approach that Adam suggested won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback:

-- set your current connection to use master otherwise you might get an error

use master

--do you stuff here 


Change color of Back button in navigation bar

If you tried many times but could not work, you may try :

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).tintColor = .red

Actually, I tried many times, only found this way will work.

Which SchemaType in Mongoose is Best for Timestamp?

The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.

Date to milliseconds and back to date in Swift

As @Travis Solution works but in some cases

var millisecondsSince1970:Int WILL CAUSE CRASH APPLICATION ,

with error

Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64

Here is Updated Answer

extension Date {
 var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 

    init(milliseconds:Int) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))

About Int definitions.

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

Generally, I encounter this problem in iPhone 5, which runs in 32-bit env. New devices run 64-bit env now. Their Int will be Int64.

Hope it is helpful to someone who also has same problem

How do I concatenate a string with a variable?

This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.


var str = 'horseThumb_'+id;

str = str.replace(/^\s+|\s+$/g,"");

function AddBorder(id){

    document.getElementById(str).className='hand positionLeft'


Can I add jars to maven 2 build classpath without installing them?

For throw away code only

set scope == system and just make up a groupId, artifactId, and version


Note: system dependencies are not copied into resulted jar/war
(see How to include system dependencies in war built using maven)


CROSS JOIN = (INNER) JOIN = comma (",")

TL;DR The only difference between SQL CROSS JOIN, (INNER) JOIN and comma (",") (besides comma having lower precedence for evaluation order) is that (INNER) JOIN has an ON while CROSS JOIN and comma don't.

Re intermediate products

All three produce an intermediate conceptual SQL-style relational "Cartesian" product, aka cross join, of all possible combinations of a row from each table. It is ON and/or WHERE that reduce the number of rows. SQL Fiddle

The SQL Standard defines <comma> via product (7.5 1.b.ii), <cross join> aka CROSS JOIN via <comma> (7.7 1.a) and (INNER) JOIN ON <search condition> via <comma> plus WHERE (7.7 1.b).

As Wikipedia puts it:

Cross join
CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it will produce rows which combine each row from the first table with each row from the second table.

Inner join
[...] The result of the join can be defined as the outcome of first taking the Cartesian product (or Cross join) of all records in the tables (combining every record in table A with every record in table B) and then returning all records which satisfy the join predicate.

The "implicit join notation" simply lists the tables for joining, in the FROM clause of the SELECT statement, using commas to separate them. Thus it specifies a cross join

Re OUTER JOIN see my answer What is the difference between “INNER JOIN” and “OUTER JOIN”?.

Re OUTER JOINs and using ON vs WHERE in them see my answer Conditions in LEFT JOIN (OUTER JOIN) vs INNER JOIN.

Why compare columns between tables?

When there are no duplicate rows:

Every table holds the rows that make a true statement from a certain fill-in-the-[named-]blanks statement template. (It makes a true proposition from--satisfies--a certain (characteristic) predicate.)

  • A base table holds the rows that make a true statement from some DBA-given statement template:

      /* rows where
      customer C.CustomerID has age C.Age and ...
      FROM Customers C
  • A join's intermediate product holds the rows that make a true statement from the AND of its operands' templates:

      /* rows where
          customer C.CustomerID has age C.Age and ...
      AND movie M.Movie is rented by customer M.CustomerID and ...
      FROM Customers C CROSS JOIN Movies M
  • ON & WHERE conditions are ANDed in to give a further template. The value is again the rows that satisfy that template:

      /* rows where
          customer C.CustomerID has age C.Age and ...
      AND movie M.Movie is rented by customer M.CustomerID and ...
      AND C.CustomerID = M.CustomerID
      AND C.Age >= M.[Minimum Age]
      AND C.Age = 18
      FROM Customers C INNER JOIN Movies M
      ON C.CustomerID = M.CustomerID
      AND C.Age >= M.[Minimum Age]
      WHERE C.Age = 18

In particular, comparing columns for (SQL) equality between tables means that the rows kept from the product from the joined tables' parts of the template have the same (non-NULL) value for those columns. It's just coincidental that a lot of rows are typically removed by equality comparisons between tables--what is necessary and sufficient is to characterize the rows you want.

Just write SQL for the template for the rows you want!

Re the meaning of queries (and tables vs conditions) see:
How to get matching data from another SQL table for two different columns: Inner Join and/or Union?
Is there any rule of thumb to construct SQL query from a human-readable description?

Overloading "cross join"

Unfortunately the term "cross join" gets used for:

  • The intermediate product.
  • (INNER) JOIN with an ON or WHERE that doesn't compare any columns from one table to any columns of another. (Since that tends to return so many of the intermediate product rows.)

These various meanings get confounded. (Eg as in other answers and comments here.)

Using CROSS JOIN vs (INNER) JOIN vs comma

The common convention is:

  • Use CROSS JOIN when and only when you don't compare columns between tables. That is to show that the lack of comparisons was intentional.
  • Use (INNER) JOIN with ON when and only when you compare columns between tables. (Plus possibly other conditions.)
  • Don't use comma.

Typically also conditions not on pairs of tables are kept for a WHERE. But they may have to be put in a(n INNER) JOIN ON to get appropriate rows for the argument to a RIGHT, LEFT or FULL (OUTER) JOIN.

Re "Don't use comma" Mixing comma with explicit JOIN can mislead because comma has lower precedence. But given the role of the intermediate product in the meaning of CROSS JOIN, (INNER) JOIN and comma, arguments for the convention above of not using it at all are shaky. A CROSS JOIN or comma is just like an (INNER) JOIN that's ON a TRUE condition. An intermediate product, ON and WHERE all introduce an AND in the corresponding predicate. However else INNER JOIN ON can be thought of--say, generating an output row only when finding a pair of input rows that satisfies the ON condition--it nevertheless returns the cross join rows that satisfy the condition. The only reason ON had to supplement comma in SQL was to write OUTER JOINs. Of course, an expression should make its meaning clear; but what is clear depends on what things are taken to mean.

Re Venn diagrams A Venn diagram with two intersecting circles can illustrate the difference between output rows for INNER, LEFT, RIGHT & FULL JOINs for the same input. And when the ON is unconditionally TRUE, the INNER JOIN result is the same as CROSS JOIN. Also it can illustrate the input and output rows for INTERSECT, UNION & EXCEPT. And when both inputs have the same columns, the INTERSECT result is the same as for standard SQL NATURAL JOIN, and the EXCEPT result is the same as for certain idioms involving LEFT & RIGHT JOIN. But it does not illustrate how (INNER) JOIN works in general. That just seems plausible at first glance. It can identify parts of input and/or output for special cases of ON, PKs (primary keys), FKs (foreign keys) and/or SELECT. All you have to do to see this is to identify what exactly are the elements of the sets represented by the circles. (Which muddled presentations never make clear.) Remember that in general for joins output rows have different headings from input rows. And SQL tables are bags not sets of rows with NULLs.

ORA-00972 identifier is too long alias column name

No, prior to Oracle version 12.2, identifiers are not allowed to exceed 30 characters in length. See the Oracle SQL Language Reference.

However, from version 12.2 they can be up to 128 bytes long. (Note: bytes, not characters).

How do I copy the contents of one stream to another?

Unfortunately, there is no really simple solution. You can try something like that:

Stream s1, s2;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);
s1.Close(); s2.Close();

But the problem with that that different implementation of the Stream class might behave differently if there is nothing to read. A stream reading a file from a local harddrive will probably block until the read operaition has read enough data from the disk to fill the buffer and only return less data if it reaches the end of file. On the other hand, a stream reading from the network might return less data even though there are more data left to be received.

Always check the documentation of the specific stream class you are using before using a generic solution.

How to change Rails 3 server default port in develoment?

Create alias in your shell for command with a specified port.

What's the difference between TRUNCATE and DELETE in SQL

TRUNCATE can be rolled back if wrapped in a transaction.

Please see the two references below and test yourself:-

The TRUNCATE vs. DELETE is one of the infamous questions during SQL interviews. Just make sure you explain it properly to the Interviewer or it might cost you the job. The problem is that not many are aware so most likely they will consider the answer as wrong if you tell them that YES Truncate can be rolled back.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Using python's eval() vs. ast.literal_eval()?

I was stuck with ast.literal_eval(). I was trying it in IntelliJ IDEA debugger, and it kept returning None on debugger output.

But later when I assigned its output to a variable and printed it in code. It worked fine. Sharing code example:

import ast
sample_string = '[{"id":"XYZ_GTTC_TYR", "name":"Suction"}]'
output_value = ast.literal_eval(sample_string)

Its python version 3.6.

jQuery: How to get the HTTP status code from within the $.ajax.error method?

If you're using jQuery 1.5, then statusCode will work.

If you're using jQuery 1.4, try this:

error: function(jqXHR, textStatus, errorThrown) {

You should see the status code from the first alert.

Function passed as template argument

Yes, it is valid.

As for making it work with functors as well, the usual solution is something like this instead:

template <typename F>
void doOperation(F f)
  int temp=0;
  std::cout << "Result is " << temp << std::endl;

which can now be called as either:


See it live

The problem with this is that if it makes it tricky for the compiler to inline the call to add2, since all the compiler knows is that a function pointer type void (*)(int &) is being passed to doOperation. (But add3, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3 is passed to the function, which means that the function to call is add3::operator(), and not just some unknown function pointer.)

How to convert a Java String to an ASCII byte array?

String s = "ASCII Text";
byte[] bytes = s.getBytes("US-ASCII");

casting int to char using C++ style casting

You should use static_cast<char>(i) to cast the integer i to char.

reinterpret_cast should almost never be used, unless you want to cast one type into a fundamentally different type.

Also reinterpret_cast is machine dependent so safely using it requires complete understanding of the types as well as how the compiler implements the cast.

For more information about C++ casting see:

Set the maximum character length of a UITextField in Swift

Modern Swift

Note that much of the example code online regarding this problem is extremely out of date.

Paste the following into any Swift file in your project. (You can name the file anything, for example, "Handy.swift".)

This finally fixes one of the stupidest problems in iOS:

enter image description here

Your text fields now have a .maxLength.

It is completely OK to set that value in storyboard during development, or, set it in code while the app is running.

// simply have this in any Swift file, say, Handy.swift

import UIKit
private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            return l
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
    func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength).string

It's that simple.

Footnote - these days to safely truncate a String in swift, you simply .prefix(n)

An even simpler one-off version...

The above fixes all text fields in your project.

If you just want one particular text field to simply be limited to say "4", and that's that...

class PinCodeEntry: UITextField {
    override func didMoveToSuperview() {
        addTarget(self, action: #selector(fixMe), for: .editingChanged)
    @objc private func fixMe() { text = text?.prefix(4) }

Phew! That's all there is to it.

(Just BTW, here's a similar very useful tip relating to UITextView, )

For the OCD programmer (like me)...

As @LeoDabus reminds, .prefix returns a substring. If you're incredibly caring, this

let t = textField.text
textField.text = t?.prefix(maxLength)

would be

if let t: String = textField.text {
    textField.text = String(t.prefix(maxLength))


Bound method error

Your helpful comments led me to the following solution:

class Word_Parser:
    """docstring for Word_Parser"""
    def __init__(self, sentences):
        self.sentences = sentences

    def parser(self):
        self.word_list = self.sentences.split()
        word_list = []
        word_list = self.word_list
        return word_list

    def sort_word_list(self):
        self.sorted_word_list = sorted(self.sentences.split())
        sorted_word_list = self.sorted_word_list
        return sorted_word_list

    def get_num_words(self):
        self.num_words = len(self.word_list)
        num_words = self.num_words
        return num_words

test = Word_Parser("mary had a little lamb")
print test.word_list
print test.sorted_word_list
print test.num_words

and returns: ['mary', 'had', 'a', 'little', 'lamb'] ['a', 'had', 'lamb', 'little', 'mary'] 5

Thank you all.

Difference between | and || or & and && for comparison

& and | are bitwise operators that can operate on both integer and Boolean arguments, and && and || are logical operators that can operate only on Boolean arguments. In many languages, if both arguments are Boolean, the key difference is that the logical operators will perform short circuit evaluation and not evaluate the second argument if the first argument is enough to determine the answer (e.g. in the case of &&, if the first argument is false, the second argument is irrelevant).

Center the content inside a column in Bootstrap 4

.row>.col, .row>[class^=col-] {_x000D_
    padding-top: .75rem;_x000D_
    padding-bottom: .75rem;_x000D_
    background-color: rgba(86,61,124,.15);_x000D_
    border: 1px solid rgba(86,61,124,.2);_x000D_
<link href="" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row justify-content-md-center">_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 3_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 2_x000D_
    <div class="col col-lg-2">_x000D_
      3 of 3_x000D_

How to achieve function overloading in C?

As already stated, overloading in the sense that you mean isn't supported by C. A common idiom to solve the problem is making the function accept a tagged union. This is implemented by a struct parameter, where the struct itself consists of some sort of type indicator, such as an enum, and a union of the different types of values. Example:

#include <stdio.h>

typedef enum {
} my_type;

typedef struct {
    my_type type;
    union {
        int a; 
        float b; 
        char c;
    } my_union;
} my_struct;

void set_overload (my_struct *whatever) 
    switch (whatever->type) 
        case T_INT:
            whatever->my_union.a = 1;
        case T_FLOAT:
            whatever->my_union.b = 2.0;
        case T_CHAR:
            whatever->my_union.c = '3';

void printf_overload (my_struct *whatever) {
    switch (whatever->type) 
        case T_INT:
            printf("%d\n", whatever->my_union.a);
        case T_FLOAT:
            printf("%f\n", whatever->my_union.b);
        case T_CHAR:
            printf("%c\n", whatever->my_union.c);


int main (int argc, char* argv[])
    my_struct s;




How do I plot list of tuples in Python?

In matplotlib it would be:

import matplotlib.pyplot as plt

data =  [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x_val = [x[0] for x in data]
y_val = [x[1] for x in data]

print x_val

which would produce:

enter image description here

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that


#Front Two(Left)

#Last Two(Right)# edited

mid = len(thadari) //2

lefthalf = thadari[:mid]
righthalf = thadari[mid:]

Hope it will help

How do I compile jrxml to get jasper?

There are three ways to compile jrxml to jasper.

  1. You can do direct compile via compile button (hammer logo) on iReport designer.

  2. You can use ant to compile as shown in the Ant Compile Sample.

    <target name="compile1"> 
      <mkdir dir="./build/reports"/> 
       <classpath refid="runClasspath"/>
       <include name="**/*.jrxml"/>

    Below is the report compile task on my current project.

    alt text

    addition from Daniel Rikowski :

  3. You can also use the JasperCompileManager class to compile from your java code.

                    "our_jasper_template.jrxml", // the path to the jrxml file to compile
                    "our_compiled_template.jasper"); // the path and name we want to save the compiled file to

How to have stored properties in Swift, the same way I had on Objective-C?

The solution pointed out by jou doesn't support value types, this works fine with them as well


import ObjectiveC

final class Lifted<T> {
    let value: T
    init(_ x: T) {
        value = x

private func lift<T>(x: T) -> Lifted<T>  {
    return Lifted(x)

func setAssociatedObject<T>(object: AnyObject, value: T, associativeKey: UnsafePointer<Void>, policy: objc_AssociationPolicy) {
    if let v: AnyObject = value as? AnyObject {
        objc_setAssociatedObject(object, associativeKey, v,  policy)
    else {
        objc_setAssociatedObject(object, associativeKey, lift(value),  policy)

func getAssociatedObject<T>(object: AnyObject, associativeKey: UnsafePointer<Void>) -> T? {
    if let v = objc_getAssociatedObject(object, associativeKey) as? T {
        return v
    else if let v = objc_getAssociatedObject(object, associativeKey) as? Lifted<T> {
        return v.value
    else {
        return nil

A possible Class extension (Example of usage):

extension UIView {

    private struct AssociatedKey {
        static var viewExtension = "viewExtension"

    var referenceTransform: CGAffineTransform? {
        get {
            return getAssociatedObject(self, associativeKey: &AssociatedKey.viewExtension)

        set {
            if let value = newValue {
                setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.viewExtension, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

This is really such a great solution, I wanted to add another usage example that included structs and values that are not optionals. Also, the AssociatedKey values can be simplified.

struct Crate {
    var name: String

class Box {
    var name: String

    init(name: String) { = name

extension UIViewController {

    private struct AssociatedKey {
        static var displayed:   UInt8 = 0
        static var box:         UInt8 = 0
        static var crate:       UInt8 = 0

    var displayed: Bool? {
        get {
            return getAssociatedObject(self, associativeKey: &AssociatedKey.displayed)

        set {
            if let value = newValue {
                setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.displayed, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

    var box: Box {
        get {
            if let result:Box = getAssociatedObject(self, associativeKey: & {
                return result
            } else {
                let result = Box(name: "")
       = result
                return result

        set {
            setAssociatedObject(self, value: newValue, associativeKey: &, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

    var crate: Crate {
        get {
            if let result:Crate = getAssociatedObject(self, associativeKey: &AssociatedKey.crate) {
                return result
            } else {
                let result = Crate(name: "")
                self.crate = result
                return result

        set {
            setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.crate, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:


How to get the number of characters in a std::string?

for an actual string object:




How can I reverse a list in Python?

Using some logic

Using some old school logic to practice for interviews.

Swapping numbers front to back. Using two pointers index[0] and index[last]

def reverse(array):
    n = array
    first = 0
    last = len(array) - 1
    while first < last:
      holder = n[first]
      n[first] = n[last]
      n[last] = holder
      first += 1
      last -= 1
    return n

input -> [-1 ,1, 2, 3, 4, 5, 6]
output -> [6, 1, 2, 3, 4, 5, -1]

How to Convert double to int in C?

This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.

double a;
int b;
b=a+ 1e-9;

How to calculate the IP range when the IP address and the netmask is given?

You might already know this, but to check that you're getting this stuff right have a look at - you can see there how the bits represent the network and host portions of the address.

JavaScript: clone a function

If you want to create a clone using the Function constructor, something like this should work:

_cloneFunction = function(_function){
    var _arguments, _body, _result;
    var _regexFunction = /^function[\s]+[\w]*\(([\w\s,_\$]*)?\)\{(.*)\}$/;
    var _regexArguments = /((?!=^|,)([\w\$_]))+/g;
    var _matches = _function.toString().match(_regexFunction)
            _result = _matches[1].match(_regexArguments);
            _result = [];
        _result = [];
    var _clone = Function.apply(Function, _result);
    // if you want to add attached properties
    for(var _key in _function){
        _clone[_key] = _function[_key];
    return _clone;

A simple test:

    var _clone, _functions, _key, _subKey;
    _functions = [
        function(){ return 'anonymous function'; }
        ,function Foo(){ return 'named function'; }
        ,function Bar(){ var a = function(){ return 'function with internal function declaration'; }; return a; }
        ,function Biz(a,boo,c){ return 'function with parameters'; }
    _functions[0].a = 'a';
    _functions[0].b = 'b';
    _functions[1].b = 'b';
    for(_key in _functions){
        _clone = window._cloneFunction(_functions[_key]);
        console.log(_clone.toString(), _clone);
        for(_subKey in _clone){
            console.log('\t', _subKey, ': ', _clone[_subKey]);

These clones will lose their names and scope for any closed over variables though.

C# DateTime.ParseExact

Your format string is wrong. Change it to

insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);

Writing a dictionary to a csv file with one line for every 'key: value'

Easiest way is to ignore the csv module and format it yourself.

with open('my_file.csv', 'w') as f:
    [f.write('{0},{1}\n'.format(key, value)) for key, value in my_dict.items()]

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
    timerId = setTimeout(keepAlive, timeout);  
function cancelKeepAlive() {  
    if (timerId) {  

Convert String to equivalent Enum value

Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");

Set selected radio from radio group with a value

$("input[name='RadioTest'][value='2']").prop('checked', true);

JS fiddle Demo

CodeIgniter 404 Page Not Found, but why?

If you installed new Codeigniter, please check if you added .htaccess file on root directory. If you didn't add it yet, please add it. You can put default content it the .htaccess file like below.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php

How to pass html string to webview on android

i have successfully done by below line

 //data == html data which you want to load
 String data = "Your data which you want to load";

 WebView webview = (WebView)this.findViewById(;
 webview.loadData(data, "text/html; charset=utf-8", "UTF-8");

Or You can try

 webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

Work for me in CentOS:

$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

$ service mysql restart

How to get current time in python and break up into year, month, day, hour, minute?

By unpacking timetuple of datetime object, you should get what you want:

from datetime import datetime

n =
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t

Error: Local workspace file ('angular.json') could not be found

For me the problem was because of global @angular/cli version and @angular/compiler-cli were different. Look into package.json.

"@angular/cli": "6.0.0-rc.3",
"@angular/compiler-cli": "^5.2.0",

And if they don’t match, update or downgrade one of them.

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
        //action for sms received
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:


and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

Neither BindingResult nor plain target object for bean name available as request attribute

Just add

model.addAttribute("login", new Login());

to your method ..

it will work..

Using SUMIFS with multiple AND OR conditions

You can use SUMIFS like this


The SUMIFS function will return an "array" of 3 values (one total each for "Oct-13", "Nov-13" and "Dec-13"), so you need SUM to sum that array and give you the final result.

Be careful with this syntax, you can only have at most two criteria within the formula with "OR" conditions...and if there are two then in one you must separate the criteria with commas, in the other with semi-colons.

If you need more you might use SUMPRODUCT with MATCH, e.g. in your case


In that version you can add any number of "OR" criteria using ISNUMBER/MATCH

Getting a count of rows in a datatable that meet certain criteria

int numberOfRecords = DTb.Rows.Count;
int numberOfColumns = DTb.Columns.Count;

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

For those who are still stuck...

Using NetBeans 8.1 and GlassFish 4.1 with CDI, for some reason I had this issue only locally, not on the remote server. What did the trick:

-> using javaee-web-api 7.0 instead of the default pom version provided by NetBeans, which is javaee-web-api 6.0, so:


-> upload this javaee-web-api-7.0.jar as a lib to on the server (lib folder in the domain1 folder) and restart the server.

CSS - display: none; not working

Try add this to your css

#tfl {
display: none !important;

Adding new column to existing DataFrame in Python pandas

I would like to add a new column, 'e', to the existing data frame and do not change anything in the data frame. (The series always got the same length as a dataframe.)

I assume that the index values in e match those in df1.

The easiest way to initiate a new column named e, and assign it the values from your series e:

df['e'] = e.values

assign (Pandas 0.16.0+)

As of Pandas 0.16.0, you can also use assign, which assigns new columns to a DataFrame and returns a new object (a copy) with all the original columns in addition to the new ones.

df1 = df1.assign(e=e.values)

As per this example (which also includes the source code of the assign function), you can also include more than one column:

df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
>>> df.assign(mean_a=df.a.mean(), mean_b=df.b.mean())
   a  b  mean_a  mean_b
0  1  3     1.5     3.5
1  2  4     1.5     3.5

In context with your example:

df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = pd.Series(np.random.randn(sLength))

>>> df1
          a         b         c         d
0  1.764052  0.400157  0.978738  2.240893
2 -0.103219  0.410599  0.144044  1.454274
3  0.761038  0.121675  0.443863  0.333674
7  1.532779  1.469359  0.154947  0.378163
9  1.230291  1.202380 -0.387327 -0.302303

>>> e
0   -1.048553
1   -1.420018
2   -1.706270
3    1.950775
4   -0.509652
dtype: float64

df1 = df1.assign(e=e.values)

>>> df1
          a         b         c         d         e
0  1.764052  0.400157  0.978738  2.240893 -1.048553
2 -0.103219  0.410599  0.144044  1.454274 -1.420018
3  0.761038  0.121675  0.443863  0.333674 -1.706270
7  1.532779  1.469359  0.154947  0.378163  1.950775
9  1.230291  1.202380 -0.387327 -0.302303 -0.509652

The description of this new feature when it was first introduced can be found here.

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.


Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

What does your configuration file say?

$ grep dbpath /etc/mongodb.conf

If it is not correct, try this, your database files will be present on the list:

$ sudo lsof -p `ps aux | grep mongodb | head -n1 | tr -s ' ' | cut -d' ' -f 2` | grep REG

It's /var/lib/mongodb/* on my default installation (Ubuntu 11.04).

Note that there is also a /var/lib/mongodb/mongod.lock file holding mongod PID for convenience, however it is located in the data directory - which we are looking for...

How to display a loading screen while site content loads

#Pure css method

Place this at the top of your code (before header tag)

<style> .loader {_x000D_
  position: fixed;_x000D_
  background-color: #FFF;_x000D_
  opacity: 1;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 10;_x000D_
<div class="loader">_x000D_
  Your Content For Load Screen_x000D_

And This At The Bottom after all other code (except /html tag)

.loader {_x000D_
    -webkit-animation: load-out 1s;_x000D_
    animation: load-out 1s;_x000D_
    -webkit-animation-fill-mode: forwards;_x000D_
    animation-fill-mode: forwards;_x000D_
@-webkit-keyframes load-out {_x000D_
    from {_x000D_
        top: 0;_x000D_
        opacity: 1;_x000D_
    to {_x000D_
        top: 100%;_x000D_
        opacity: 0;_x000D_
@keyframes load-out {_x000D_
    from {_x000D_
        top: 0;_x000D_
        opacity: 1;_x000D_
    to {_x000D_
        top: 100%;_x000D_
        opacity: 0;_x000D_

This always works for me 100% of the time

Calculate distance between 2 GPS coordinates

Here's a Haversine function in Python that I use:

from math import pi,sqrt,sin,cos,atan2

def haversine(pos1, pos2):
    lat1 = float(pos1['lat'])
    long1 = float(pos1['long'])
    lat2 = float(pos2['lat'])
    long2 = float(pos2['long'])

    degree_to_rad = float(pi / 180.0)

    d_lat = (lat2 - lat1) * degree_to_rad
    d_long = (long2 - long1) * degree_to_rad

    a = pow(sin(d_lat / 2), 2) + cos(lat1 * degree_to_rad) * cos(lat2 * degree_to_rad) * pow(sin(d_long / 2), 2)
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    km = 6367 * c
    mi = 3956 * c

    return {"km":km, "miles":mi}

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

Please add in the bottom of the script:

if(this.value.length == 1 && this.value == 0)
 this.value = "";

"Proxy server connection failed" in google chrome

I had the same problem with a freshly installed copy of Chrome. If nothing works, and your Use a proxy server your LAN setting is unchecked, check it and then uncheck it . Believe it or not it might work. I don't know if I should consider it a bug or not.

How to remove unwanted space between rows and columns in table?

Adding to vectran's answer: You also have to set cellspacing attribute on the table element for cross-browser compatibility.

<table cellspacing="0">

EDIT (for the sake of completeness I'm expanding this 5 years later:):

Internet Explorer 6 and Internet Explorer 7 required you to set cellspacing directly as a table attribute, otherwise the spacing wouldn't vanish.

Internet Explorer 8 and later versions and all other versions of popular browsers - Chrome, Firefox, Opera 4+ - support the CSS property border-spacing.

So in order to make a cross-browser table cell spacing reset (supporting IE6 as a dinosaur browser), you can follow the below code sample:

  border: 1px solid black;_x000D_
table td {_x000D_
  border: 1px solid black; /* Style just to show the table cell boundaries */_x000D_
_x000D_ {_x000D_
  border-spacing:0; /* Removes the cell spacing via CSS */_x000D_
  border-collapse: collapse;  /* Optional - if you don't want to have double border where cells touch */_x000D_
<p>Default table:</p>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
<p>Removed spacing:</p>_x000D_
<table class="no-spacing" cellspacing="0"> <!-- cellspacing 0 to support IE6 and IE7 -->_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_

MySQL, Check if a column exists in a table with SQL


Thanks for the SQL example. I tried the query and I think it needs a small alteration to get it working properly.

FROM information_schema.COLUMNS 
    TABLE_SCHEMA = 'db_name' 
AND TABLE_NAME = 'table_name' 
AND COLUMN_NAME = 'column_name'

That worked for me.


Trust Anchor not found for Android SSL Connection

I had the same problem what i found was that the certificate .crt file i provided missing an intermediate certificate. So I asked all .crt files from my server admin, then concatinated them in reverse order.

Ex. 1. Root.crt 2. Inter.crt 3. myCrt.crt

in windows i executed copy Inter.crt + Root.crt newCertificate.crt

(Here i ignored myCrt.crt)

Then i provided newCertificate.crt file into code via inputstream. Work done.

How to move all files including hidden files into parent directory via *

You can find a comprehensive set of solutions on this in UNIX & Linux's answer to How do you move all files (including hidden) from one directory to another?. It shows solutions in Bash, zsh, ksh93, standard (POSIX) sh, etc.

You can use these two commands together:

mv /path/subfolder/* /path/   # your current approach
mv /path/subfolder/.* /path/  # this one for hidden files

Or all together (thanks pfnuesel):

mv /path/subfolder/{.,}* /path/

Which expands to:

mv /path/subfolder/* /path/subfolder/.* /path/

(example: echo a{.,}b expands to a.b ab)

Note this will show a couple of warnings:

mv: cannot move ‘/path/subfolder/.’ to /path/.’: Device or resource busy
mv: cannot remove /path/subfolder/..’: Is a directory

Just ignore them: this happens because /path/subfolder/{.,}* also expands to /path/subfolder/. and /path/subfolder/.., which are the directory and the parent directory (See What do “.” and “..” mean when in a folder?).

If you want to just copy, you can use a mere:

cp -r /path/subfolder/. /path/
#                     ^
#                     note the dot!

This will copy all files, both normal and hidden ones, since /path/subfolder/. expands to "everything from this directory" (Source: How to copy with cp to include hidden files and hidden directories and their contents?)

Join/Where with LINQ and Lambda

Daniel has a good explanation of the syntax relationships, but I put this document together for my team in order to make it a little simpler for them to understand. Hope this helps someoneenter image description here

Access-Control-Allow-Origin and Angular.js $http

@Swapnil Niwane

I was able to solve this issue by calling an ajax request and formatting the data to 'jsonp'.

          method: 'GET',
          url: url,
          defaultHeaders: {
              'Content-Type': 'application/json',
              "Access-Control-Allow-Origin": "*",
              'Accept': 'application/json'

          dataType: 'jsonp',

          success: function (response) {
            console.log("success ");
          error: function (xhr) {
            console.log("error ");

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

For SQL server 2000:

      SELECT valueid, valuename
               (SELECT 0
                FROM   t1 as t2
                WHERE  t2.ID = valueid AND = valuename)

Get only the Date part of DateTime in mssql

Another nifty way is:

DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))

Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.

Edit - other date calculations:

First Day of Month:

DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)

First Day of the Year:

DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)

First Day of the Quarter:

DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)

Last Day of Prior Month:

DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))

Last Day of Current Month:

DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))

Last Day of Current Year:

DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))

First Monday of the Month:

DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)        

Edit: True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.

Check time difference in Javascript

The time diff in milliseconds

firstDate.getTime() - secondDate.getTime() 

How to verify CuDNN installation?

I have cuDNN 8.0 and none of the suggestions above worked for me. The desired information was in /usr/include/cudnn_version.h, so

cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2

did the trick.

What are some alternatives to ReSharper?

I think that CodeRush has a free, limited version, too. I ended up going with ReSharper, and I still recommend it, even though some of the functionality is in Visual Studio 2010. There are just some things that make it worth it.

Keep in mind that you don't need the full ReSharper license if you only code in one language. I have the C# version, and it's cheaper.

Check if string contains \n Java

If the string was constructed in the same program, I would recommend using this:

String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);

But if you are specced to use \n, this driver illustrates what to do:

class NewLineTest {
    public static void main(String[] args) {
        String hasNewline = "this has a newline\n.";
        String noNewline = "this doesn't";




Resulted in


In reponse to your comment:

class NewLineTest {
    public static void main(String[] args) {
        String word = "test\n.";
        word = word.replace("\n","\n ");



Results in


Maven does not find JUnit tests to run

In my case we are migration multimodule application to Spring Boot. Unfortunately maven didnt execute all tests anymore in the modules. The naming of the Test Classes didnt change, we are following the naming conventions.

At the end it helped, when I added the dependency surefire-junit47 to the plugin maven-surefire-plugin. But I could not explain, why, it was trial and error:


Configuring RollingFileAppender in log4j

I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras source, no less...)

The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)

Here is an example:

log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log

BTW the ${instanceId} bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure(), as follow:

p.setProperty("instanceId", EC2Util.getMyInstanceId());

Kubernetes pod gets recreated when deleted

If you have a job that continues running, you need to search the job and delete it:

kubectl get job --all-namespaces | grep <name>


kubectl delete job <job-name>

How can I count text lines inside an DOM element? Can I?

Following @BobBrunius 2010 suggestion I created this with jQuery. No doubt it could be improved but it may help some.

$(document).ready(function() {_x000D_
  alert("Number of lines: " + getTextLinesNum($("#textbox")));_x000D_
function getTextLinesNum($element) {_x000D_
  var originalHtml = $element.html();_x000D_
  var words = originalHtml.split(" ");_x000D_
  var linePositions = [];_x000D_
  // Wrap words in spans_x000D_
  for (var i in words) {_x000D_
    words[i] = "<span>" + words[i] + "</span>";_x000D_
  // Temporarily replace element content with spans. Layout should be identical._x000D_
  $element.html(words.join(" "));_x000D_
  // Iterate through words and collect positions of text lines_x000D_
  $element.children("span").each(function () {_x000D_
    var lp = $(this).position().top;_x000D_
    if (linePositions.indexOf(lp) == -1) linePositions.push(lp);_x000D_
  // Revert to original html content_x000D_
  // Return number of text lines_x000D_
  return linePositions.length;_x000D_
#textbox {_x000D_
  width: 200px;_x000D_
  text-align: center;_x000D_
<script src=""></script>_x000D_
<div id="textbox">Lorem ipsum dolor sit amet, consectetuer adipiscing elit,_x000D_
  <br>sed diam nonummy</div>

Python regular expressions return true/false

Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identifier to the server) in API:

  1. Create photo object on server:

     POST: /projects/{project_id}/photos   
     body: { name: "some_schema.jpg", comment: "blah"}
     response: photo_id
  2. Upload file (note that file is in singular form because it is only one per photo):

     POST: /projects/{project_id}/photos/{photo_id}/file
     body: file to upload
     response: -

And then for instance:

  1. Read photos list

     GET: /projects/{project_id}/photos
     response: [ photo, photo, photo, ... ] (array of objects)
  2. Read some photo details

     GET: /projects/{project_id}/photos/{photo_id}
     response: { id: 666, name: 'some_schema.jpg', comment:'blah'} (photo object)
  3. Read photo file

     GET: /projects/{project_id}/photos/{photo_id}/file
     response: file content

So the conclusion is that, first you create an object (photo) by POST, and then you send second request with the file (again POST). To not have problems with CACHE in this approach we assume that we can only delete old photos and add new - no update binary photo files (because new binary file is in fact... NEW photo). However if you need to be able to update binary files and cache them, then in point 4 return also fileId and change 5 to GET: /projects/{project_id}/photos/{photo_id}/files/{fileId}.

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */

// Open serial port
HANDLE serialHandle;


// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:


TCPDF Save file to folder?

If you still get

TCPDF ERROR: Unable to create output file: myfile.pdf

you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:

$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);

Why does an image captured using camera intent gets rotated on some devices on Android?

Most phone cameras are landscape, meaning if you take the photo in portrait, the resulting photos will be rotated 90 degrees. In this case, the camera software should populate the Exif data with the orientation that the photo should be viewed in.

Note that the below solution depends on the camera software/device manufacturer populating the Exif data, so it will work in most cases, but it is not a 100% reliable solution.

ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,

Bitmap rotatedBitmap = null;
switch(orientation) {

    case ExifInterface.ORIENTATION_ROTATE_90:
        rotatedBitmap = rotateImage(bitmap, 90);

    case ExifInterface.ORIENTATION_ROTATE_180:
        rotatedBitmap = rotateImage(bitmap, 180);

    case ExifInterface.ORIENTATION_ROTATE_270:
        rotatedBitmap = rotateImage(bitmap, 270);

    case ExifInterface.ORIENTATION_NORMAL:
        rotatedBitmap = bitmap;

Here is the rotateImage method:

public static Bitmap rotateImage(Bitmap source, float angle) {
    Matrix matrix = new Matrix();
    return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
                               matrix, true);

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -




(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

How to concatenate strings in a Windows batch file?

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

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

renames all PDF files to "filename_old.pdf"

Dynamically select data frame columns using $ and a character value

Using dplyr provides an easy syntax for sorting the data frames

mtcars %>% arrange(gear, desc(mpg))

It might be useful to use the NSE version as shown here to allow dynamically building the sort list

sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)

How to grep recursively, but only in files with certain extensions?

Some of these answers seemed too syntax-heavy, or they produced issues on my Debian Server. This worked perfectly for me:

grep -r --include=\*.txt 'searchterm' ./

...or case-insensitive version...

grep -r -i --include=\*.txt 'searchterm' ./
  • grep: command

  • -r: recursively

  • -i: ignore-case

  • --include: all *.txt: text files (escape with \ just in case you have a directory with asterisks in the filenames)

  • 'searchterm': What to search

  • ./: Start at current directory.

Source: PHP Revolution: How to Grep files in Linux, but only certain file extensions?

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

gcc actually can do this optimization, even for floating-point numbers. For example,

double foo(double a) {
  return a*a*a*a*a*a;


    mulsd   %xmm0, %xmm0
    movapd  %xmm0, %xmm1
    mulsd   %xmm0, %xmm1
    mulsd   %xmm1, %xmm0

with -O -funsafe-math-optimizations. This reordering violates IEEE-754, though, so it requires the flag.

Signed integers, as Peter Cordes pointed out in a comment, can do this optimization without -funsafe-math-optimizations since it holds exactly when there is no overflow and if there is overflow you get undefined behavior. So you get

    movq    %rdi, %rax
    imulq   %rdi, %rax
    imulq   %rdi, %rax
    imulq   %rax, %rax

with just -O. For unsigned integers, it's even easier since they work mod powers of 2 and so can be reordered freely even in the face of overflow.

What is the difference between single-quoted and double-quoted strings in PHP?

Some might say that I'm a little off-topic, but here it is anyway:

You don't necessarily have to choose because of your string's content between:
echo "It's \"game\" time."; or echo 'It\'s "game" time.';

If you're familiar with the use of the english quotation marks, and the correct character for the apostrophe, you can use either double or single quotes, because it won't matter anymore:
echo "It’s “game” time."; and echo 'It’s “game” time.';

Of course you can also add variables if needed. Just don't forget that they get evaluated only when in double quotes!

Rock, Paper, Scissors Game Java

I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.

public enum Type{


  public static Type parseType(String value){
     //if /else logic here to return either ROCK, PAPER or SCISSOR

     //if value is not either, you can return null

The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.

Type person=null;

      System.out.println("Enter your play: "); 
      person= Type.parseType(;
      if(person ==null){
         System.out.println("invalid try again");

Furthermore, your type enum can determine what beats what by having each Type object know:

public enum Type{


    //each type will implement this method differently
    public abstract boolean beats(Type other);


each type will implement this method differently to see what beats what:


   public boolean beats(Type other){            
        return other ==  SCISSOR;



Then in your code

 Type person, computer;
   if (person.equals(computer)) 
   System.out.println("It's a tie!");
  }else if({
     System.out.println(person+ " beats " + computer + "You win!!"); 
     System.out.println(computer + " beats " + person+ "You lose!!");

HttpURLConnection timeout settings

If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period

public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {

private static final int HTTP_REQUEST_TIMEOUT = 30000;

protected Result doInBackground(Params... params) {
    return doInBackgroundImpl(params);

private void createTimeoutListener() {
    Thread timeout = new Thread() {
        public void run() {

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {

                    if (AsyncTaskWithTimer.this != null
                            && AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
            }, HTTP_REQUEST_TIMEOUT);


abstract protected Result doInBackgroundImpl(Params... params);

A Sample for this

public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {

    protected void onCancelled(Void void) {
        Log.d(TAG, "Async Task onCancelled With Result");

    protected void onCancelled() {
        Log.d(TAG, "Async Task onCancelled");

    protected Void doInBackgroundImpl(Void... params) {
        // Do background work
        return null;

SQL how to increase or decrease one for a int column in one command

UPDATE Orders Order
SET Order.Quantity =  Order.Quantity - 1
WHERE SomeCondition(Order)

As far as I know there is no build-in support for INSERT-OR-UPDATE in SQL. I suggest to create a stored procedure or use a conditional query to achiev this. Here you can find a collection of solutions for different databases.

How to match a substring in a string, ignoring case

you can also use: s.lower() in str.lower()

Set markers for individual points on a line in Matplotlib

Hello There is an example:

import numpy as np
import matplotlib.pyplot as ptl

def grafica_seno_coseno():
    x = np.arange(-4,2*np.pi, 0.3)
    y = 2*np.sin(x)
    y2 = 3*np.cos(x)
    ptl.plot(x, y,  '-gD')
    ptl.plot(x, y2, '-rD')
    for xitem,yitem in np.nditer([x,y]):
        etiqueta = "{:.1f}".format(xitem)
        ptl.annotate(etiqueta, (xitem,yitem), textcoords="offset points",xytext=(0,10),ha="center")
    for xitem,y2item in np.nditer([x,y2]):
        etiqueta2 = "{:.1f}".format(xitem)
        ptl.annotate(etiqueta2, (xitem,y2item), textcoords="offset points",xytext=(0,10),ha="center")

How to wait until an element exists?

A cleaner example using MutationObserver:

new MutationObserver( mutation => {
    if (!mutation.addedNodes) return
    mutation.addedNodes.forEach( node => {
        // do stuff with node

Values of disabled inputs will not be submitted

Yes, all browsers should not submit the disabled inputs, as they are read-only.

More information (section 17.12.1)

Attribute definitions

disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in tabbing navigation.
  • Disabled controls cannot be successful.

The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.

This attribute is inherited but local declarations override the inherited value.

How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

<INPUT disabled name="fred" value="stone">

Note. The only way to modify dynamically the value of the disabled attribute is through a script.

How to update Ruby to 1.9.x on Mac?

I know it's an older post, but i wanna add some extra informations about that. Firstly, i think that rvm does great BUT it wasn't updating ruby from my system (MAC OS Yosemite).

What rvmwas doing : installing to another location and setting up the path there to my environment variable ... And i was kinda bored, because i had two ruby now on my system.

So to fix that, i uninstalled the rvm, then used the Homebrew package manager available here and installed ruby throw terminal command by doing brew install ruby.

And then, everything was working perfectly ! The ruby from my system was updated ! Hope it will help for the next adventurers !

Inserting NOW() into Database with CodeIgniter's Active Record

Unless I am greatly mistaken, the answer is, "No, there is no way."

The basic problem in situations like that is the fact that you are calling a MySQL function and you're not actually setting a value. CI escapes values so that you can do a clean insert but it does not test to see if those values happen to be calling functions like aes_encrypt, md5, or (in this case) now(). While in most situations this is wonderful, for those situations raw sql is the only recourse.

On a side, date('Y-m-d'); should work as a PHP version of NOW() for MySQL. (It won't work for all versions of SQL though).

Fatal error: Call to undefined function imap_open() in PHP

On Mac OS X with Homebrew, as obviously, PHP is already installed due to provided error we cannot run:

Update: Tha latest version brew instal php --with-imap will not work any more!!!

$ brew install php72 --with-imap
Warning: homebrew/php/php72 is already installed

Also, installing module only, here will not work:

$ brew install php72-imap
Error: No available formula with the name "php72-imap"

So, we must reinstall it:

$ brew reinstall php72 --with-imap

It will take a while :-) (built in 8 minutes 17 seconds)

How to take column-slices of dataframe in pandas

Also, Given a DataFrame


as in your example, if you would like to extract column a and d only (e.i. the 1st and the 4th column), iloc mothod from the pandas dataframe is what you need and could be used very effectively. All you need to know is the index of the columns you would like to extract. For example:

>>> data.iloc[:,[0,3]]

will give you

          a         d
0  0.883283  0.100975
1  0.614313  0.221731
2  0.438963  0.224361
3  0.466078  0.703347
4  0.955285  0.114033
5  0.268443  0.416996
6  0.613241  0.327548
7  0.370784  0.359159
8  0.692708  0.659410
9  0.806624  0.875476

Remove white space below image

.youtube-thumb img {display:block;} or .youtube-thumb img {float:left;}

6 digits regular expression

You can use range quantifier {min,max} to specify minimum of 1 digit and maximum of 6 digits as:



^     : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$     : End anchor

Why did your regex not work ?

You were almost close on the regex:


Since you had escaped the ? by preceding it with the \, the ? was no more acting as a regex meta-character ( for 0 or 1 repetitions) but was being treated literally.

To fix it just remove the \ and you are there.

See it on rubular.

The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.

Your second regex:


is equivalent to:


which matches strings with exactly one digit. They are equivalent because a character class [aaaab] is same as [ab].

Get value of multiselect box using jQuery or pure JS

You could do like this too.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
     <input type="submit"/> 

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.



How to copy Outlook mail message into excel using VBA or Macros

New introduction 2

In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:

Set FolderTgt = CreateObject("Outlook.Application"). _

I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.

This macro, outputs the name of the store holding the default Inbox to the Immediate Window:

Sub DsplUsernameOfDefaultStore()

  Dim NS As Outlook.NameSpace
  Dim DefaultInboxFldr As MAPIFolder

  Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
  Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)

  Debug.Print DefaultInboxFldr.Parent.Name

End Sub

On my installation, this outputs: "Outlook Data File".

I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.

New introduction 1

A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.

The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)

Original text

There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.

For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.

What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.

The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.

The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:

Example of worksheet created by macro

Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.

All other comments containing hashes suggest amendments to adapt the macro to your requirements.

How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed".

The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.

This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:

Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on

Extracting the values from the original of this string should not be difficult.

I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.

Good luck.

Latest version of macro included within the original text

Option Explicit
Public Sub SaveEmailDetails()

  ' This macro creates a new Excel workbook and writes to it details
  ' of every email in the Inbox.

  ' Lines starting with hashes either MUST be changed before running the
  ' macro or suggest changes you might consider appropriate.

  Dim AttachCount As Long
  Dim AttachDtl() As String
  Dim ExcelWkBk As Excel.Workbook
  Dim FileName As String
  Dim FolderTgt As MAPIFolder
  Dim HtmlBody As String
  Dim InterestingItem As Boolean
  Dim InxAttach As Long
  Dim InxItemCrnt As Long
  Dim PathName As String
  Dim ReceivedTime As Date
  Dim RowCrnt As Long
  Dim SenderEmailAddress As String
  Dim SenderName As String
  Dim Subject As String
  Dim TextBody As String
  Dim xlApp As Excel.Application

  ' The Excel workbook will be created in this folder.
  ' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
  PathName = "C:\DataArea\SO"

  ' This creates a unique filename.
  ' #### If you use a version of Excel 2003, change the extension to "xls".
  FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"

  ' Open own copy of Excel
  Set xlApp = Application.CreateObject("Excel.Application")
  With xlApp
    ' .Visible = True         ' This slows your macro but helps during debugging
    .ScreenUpdating = False ' Reduces flash and increases speed
    ' Create a new workbook
    ' #### If updating an existing workbook, replace with an
    ' #### Open workbook statement.
    Set ExcelWkBk = xlApp.Workbooks.Add
    With ExcelWkBk
      ' #### None of this code will be useful if you are adding
      ' #### to an existing workbook.  However, it demonstrates a
      ' #### variety of useful statements.
      .Worksheets("Sheet1").Name = "Inbox"    ' Rename first worksheet
      With .Worksheets("Inbox")
        ' Create header line
        With .Cells(1, "A")
          .Value = "Field"
          .Font.Bold = True
        End With
        With .Cells(1, "B")
          .Value = "Value"
          .Font.Bold = True
        End With
        .Columns("A").ColumnWidth = 18
        .Columns("B").ColumnWidth = 150
      End With
    End With
    RowCrnt = 2
  End With

  ' FolderTgt is the folder I am going to search.  This statement says
  ' I want to seach the Inbox.  The value "olFolderInbox" can be replaced
  ' to allow any of the standard folders to be searched.
  ' See FindSelectedFolder() for a routine that will search for any folder.
  Set FolderTgt = CreateObject("Outlook.Application"). _
  ' #### Use the following the access a non-default Inbox.
  ' #### Change "Xxxx" to name of one of your store you want to access.
  Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")

  ' This examines the emails in reverse order. I will explain why later.
  For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
    With FolderTgt.Items.Item(InxItemCrnt)
      ' A folder can contain several types of item: mail items, meeting items,
      ' contacts, etc.  I am only interested in mail items.
      If .Class = olMail Then
        ' Save selected properties to variables
        ReceivedTime = .ReceivedTime
        Subject = .Subject
        SenderName = .SenderName
        SenderEmailAddress = .SenderEmailAddress
        TextBody = .Body
        HtmlBody = .HtmlBody
        AttachCount = .Attachments.Count
        If AttachCount > 0 Then
          ReDim AttachDtl(1 To 7, 1 To AttachCount)
          For InxAttach = 1 To AttachCount
            ' There are four types of attachment:
            '  *   olByValue       1
            '  *   olByReference   4
            '  *   olEmbeddedItem  5
            '  *   olOLE           6
            Select Case .Attachments(InxAttach).Type
              Case olByValue
            AttachDtl(1, InxAttach) = "Val"
              Case olEmbeddeditem
            AttachDtl(1, InxAttach) = "Ebd"
              Case olByReference
            AttachDtl(1, InxAttach) = "Ref"
              Case olOLE
            AttachDtl(1, InxAttach) = "OLE"
              Case Else
            AttachDtl(1, InxAttach) = "Unk"
            End Select
            ' Not all types have all properties.  This code handles
            ' those missing properties of which I am aware.  However,
            ' I have never found an attachment of type Reference or OLE.
            ' Additional code may be required for them.
            Select Case .Attachments(InxAttach).Type
              Case olEmbeddeditem
                AttachDtl(2, InxAttach) = ""
              Case Else
                AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
            End Select
            AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
            AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
            AttachDtl(5, InxAttach) = "--"
            ' I suspect Attachment had a parent property in early versions
            ' of Outlook. It is missing from Outlook 2016.
            On Error Resume Next
            AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
            On Error GoTo 0
            AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
            ' Class 5 is attachment.  I have never seen an attachment with
            ' a different class and do not see the purpose of this property.
            ' The code will stop here if a different class is found.
            Debug.Assert .Attachments(InxAttach).Class = 5
            AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
        End If
        InterestingItem = True
        InterestingItem = False
      End If
    End With
    ' The most used properties of the email have been loaded to variables but
    ' there are many more properies.  Press F2.  Scroll down classes until
    ' you find MailItem.  Look through the members and note the name of
    ' any properties that look useful.  Look them up using VB Help.

    ' #### You need to add code here to eliminate uninteresting items.
    ' #### For example:
    'If SenderEmailAddress <> "[email protected]" Then
    '  InterestingItem = False
    'End If
    'If InStr(Subject, "Accounts payable") = 0 Then
    '  InterestingItem = False
    'End If
    'If AttachCount = 0 Then
    '  InterestingItem = False
    'End If

    ' #### If the item is still thought to be interesting I
    ' #### suggest extracting the required data to variables here.

    ' #### You should consider moving processed emails to another
    ' #### folder.  The emails are being processed in reverse order
    ' #### to allow this removal of an email from the Inbox without
    ' #### effecting the index numbers of unprocessed emails.

    If InterestingItem Then
      With ExcelWkBk
        With .Worksheets("Inbox")
          ' #### This code creates a dividing row and then
          ' #### outputs a property per row.  Again it demonstrates
          ' #### statements that are likely to be useful in the final
          ' #### version
          ' Create dividing row between emails
          .Rows(RowCrnt).RowHeight = 5
          .Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
                                      .Interior.Color = RGB(0, 255, 0)
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender name"
          .Cells(RowCrnt, "B").Value = SenderName
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender email address"
          .Cells(RowCrnt, "B").Value = SenderEmailAddress
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Received time"
          With .Cells(RowCrnt, "B")
            .NumberFormat = "@"
            .Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
          End With
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Subject"
          .Cells(RowCrnt, "B").Value = Subject
          RowCrnt = RowCrnt + 1
          If AttachCount > 0 Then
            .Cells(RowCrnt, "A").Value = "Attachments"
            .Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
            RowCrnt = RowCrnt + 1
            For InxAttach = 1 To AttachCount
              .Cells(RowCrnt, "B").Value = InxAttach & "|" & _
                                           AttachDtl(1, InxAttach) & "|" & _
                                           AttachDtl(2, InxAttach) & "|" & _
                                           AttachDtl(3, InxAttach) & "|" & _
                                           AttachDtl(4, InxAttach) & "|" & _
                                           AttachDtl(5, InxAttach) & "|" & _
                                           AttachDtl(6, InxAttach) & "|" & _
                                           AttachDtl(7, InxAttach)
              RowCrnt = RowCrnt + 1
          End If
          If TextBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the text body.  See below
            ' This outputs the text body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "text body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  ' The maximum size of a cell 32,767
            '  .Value = Mid(TextBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the text body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "text body"
              .VerticalAlignment = xlTop
            End With
            TextBody = Replace(TextBody, Chr(160), "[NBSP]")
            TextBody = Replace(TextBody, vbCr, "[CR]")
            TextBody = Replace(TextBody, vbLf, "[LF]")
            TextBody = Replace(TextBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              ' The maximum size of a cell 32,767
              .Value = Mid(TextBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1
          End If

          If HtmlBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the html body.  See below
            ' This outputs the html body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "Html body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  .Value = Mid(HtmlBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the html body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "Html body"
              .VerticalAlignment = xlTop
            End With
            HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
            HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
            HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
            HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              .Value = Mid(HtmlBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1

          End If
        End With
      End With
    End If

  With xlApp
    With ExcelWkBk
      ' Write new workbook to disc
      If Right(PathName, 1) <> "\" Then
        PathName = PathName & "\"
      End If
      .SaveAs FileName:=PathName & FileName
    End With
    .Quit   ' Close our copy of Excel
  End With

  Set xlApp = Nothing       ' Clear reference to Excel

End Sub

Macros not included in original post but which some users of above macro have found useful.

Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
                              ByVal NameTgt As String, ByVal NameSep As String)

  ' This routine (and its sub-routine) locate a folder within the hierarchy and
  ' returns it as an object of type MAPIFolder

  ' NameTgt   The name of the required folder in the format:
  '              FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
  '           If NameSep is "|", an example value is "Personal Folders|Inbox"
  '           FolderName1 must be an outer folder name such as
  '           "Personal Folders". The outer folder names are typically the names
  '           of PST files.  FolderName2 must be the name of a folder within
  '           Folder1; in the example "Inbox".  FolderName2 is compulsory.  This
  '           routine cannot return a PST file; only a folder within a PST file.
  '           FolderName3, FolderName4 and so on are optional and allow a folder
  '           at any depth with the hierarchy to be specified.
  ' NameSep   A character or string used to separate the folder names within
  '           NameTgt.
  ' FolderTgt On exit, the required folder.  Set to Nothing if not found.

  ' This routine initialises the search and finds the top level folder.
  ' FindSelectedSubFolder() is used to find the target folder within the
  ' top level folder.

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long
  Dim TopLvlFolderList As Folders

  Set FolderTgt = Nothing   ' Target folder not found

  Set TopLvlFolderList = _

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    ' I need at least a level 2 name
    Exit Sub
  End If
  NameCrnt = Mid(NameTgt, 1, Pos - 1)
  NameChild = Mid(NameTgt, Pos + 1)

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To TopLvlFolderList.Count
    If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
      ' Have found current name. Call FindSelectedSubFolder() to
      ' look for its children
      Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      Exit For
    End If

End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
                      ByRef FolderTgt As MAPIFolder, _
                      ByVal NameTgt As String, ByVal NameSep As String)

  ' See FindSelectedFolder() for an introduction to the purpose of this routine.
  ' This routine finds all folders below the top level

  ' FolderCrnt The folder to be seached for the target folder.
  ' NameTgt    The NameTgt passed to FindSelectedFolder will be of the form:
  '               A|B|C|D|E
  '            A is the name of outer folder which represents a PST file.
  '            FindSelectedFolder() removes "A|" from NameTgt and calls this
  '            routine with FolderCrnt set to folder A to search for B.
  '            When this routine finds B, it calls itself with FolderCrnt set to
  '            folder B to search for C.  Calls are nested to whatever depth are
  '            necessary.
  ' NameSep    As for FindSelectedSubFolder
  ' FolderTgt  As for FindSelectedSubFolder

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    NameCrnt = NameTgt
    NameChild = ""
    NameCrnt = Mid(NameTgt, 1, Pos - 1)
    NameChild = Mid(NameTgt, Pos + 1)
  End If

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
    If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
      ' Have found current name.
      If NameChild = "" Then
        ' Have found target folder
        Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
        'Recurse to look for children
        Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      End If
      Exit For
    End If

  ' If NameCrnt not found, FolderTgt will be returned unchanged.  Since it is
  ' initialised to Nothing at the beginning, that will be the returned value.

End Sub

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

How do you make a HTTP request with C++?

C and C++ don't have a standard library for HTTP or even for socket connections. Over the years some portable libraries have been developed. The most widely used, as others have said, is libcurl.

Here is a list of alternatives to libcurl (coming from the libcurl's web site).

Also, for Linux, this is a simple HTTP client. You could implement your own simple HTTP GET client, but this won't work if there are authentication or redirects involved or if you need to work behind a proxy. For these cases you need a full-blown library like libcurl.

For source code with libcurl, this is the closest to what you want (Libcurl has many examples). Look at the main function. The html content will be copied to the buffer, after a successfully connection. Just replace parseHtml with your own function.

How to solve maven 2.6 resource plugin dependency?

Right Click on Project go to -> Maven -> Update project ->select Force update project check box and click on Finish.

React Checkbox not sending onChange

In case someone is looking for a universal event handler the following code can be used more or less (assuming that name property is set for every input):

    this.handleInputChange = (e) => {
        item[] = === "checkbox" ? :;

SQL Error with Order By in Subquery

A subquery (nested view) as you have it returns a dataset that you can then order in your calling query. Ordering the subquery itself will make no (reliable) difference to the order of the results in your calling query.

As for your SQL itself: a) I seen no reason for an order by as you are returning a single value. b) I see no reason for the sub query anyway as you are only returning a single value.

I'm guessing there is a lot more information here that you might want to tell us in order to fix the problem you have.

Convert timestamp to date in Oracle SQL

This may not be the correct way to do it. But I have solved the problem using substring function.

Select max(start_ts), min(start_ts)from db where SUBSTR(start_ts, 0,9) ='13-may-2016'

using this I was able to retrieve the max and min timestamp.

How to check if a string contains a substring in Bash

This also works:

if printf -- '%s' "$haystack" | egrep -q -- "$needle"
  printf "Found needle in haystack"

And the negative test is:

if ! printf -- '%s' "$haystack" | egrep -q -- "$needle"
  echo "Did not find needle in haystack"

I suppose this style is a bit more classic -- less dependent upon features of Bash shell.

The -- argument is pure POSIX paranoia, used to protected against input strings similar to options, such as --abc or -a.

Note: In a tight loop this code will be much slower than using internal Bash shell features, as one (or two) separate processes will be created and connected via pipes.

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

Sometimes the columns will have commas within themselves, such as:

"Some item", "Another Item", "Also, One more item"

In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):

private IList<string> GetColumns(string columns)
    IList<string> list = new List<string>();

    if (!string.IsNullOrWhiteSpace(columns))
        if (columns[0] != '\"')
            // treat as just one item
            bool gettingItemName = true;
            bool justChanged = false;
            string itemName = string.Empty;

            for (int index = 1; index < columns.Length; index++)
                justChanged = false;
                if (subIndustries[index] == '\"')
                    gettingItemName = !gettingItemName;
                    justChanged = true;

                if ((gettingItemName == false) &&
                (justChanged == true))
                    itemName = string.Empty;
                    justChanged = false;

                if ((gettingItemName == true) && (justChanged == false))
                    itemName += columns[index];

    return list;

UML class diagram enum

Typically you model the enum itself as a class with the enum stereotype

How to get a list of all valid IP addresses in a local network?

Try following steps:

  1. Type ipconfig (or ifconfig on Linux) at command prompt. This will give you the IP address of your own machine. For example, your machine's IP address is So your broadcast IP address is
  2. Ping your broadcast IP address ping (may require -b on Linux)
  3. Now type arp -a. You will get the list of all IP addresses on your segment.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

How to really read text file from classpath in Java

My answer is not exactly what is asked in the question. Rather I am giving a solution exactly how easily we can read a file into out java application from our project class path.

For example suppose a config file name example.xml is located in a path like below:-

and our java executable class file is in the below path:-


now just check in both the above path which is the nearest common directory/folder from where you can access both dev and main directory/folder (com.myproject.server.main - where our application’s java executable class is existed) – We can see that it is myproject folder/directory which is the nearest common directory/folder from where we can access our example.xml file. Therefore from a java executable class resides in folder/directory main we have to go back two steps like ../../ to access myproject. Now following this, see how we can read the file:-

package com.myproject.server.main;

class Example {

  File xmlFile;

  public Example(){
       String filePath = this.getClass().getResource("../../config/dev/example.xml").getPath();
       this.xmlFile = new File(filePath);

  public File getXMLFile() {
      return this.xmlFile;
   public static void main(String args[]){
      Example ex = new Example();
      File xmlFile = ex.getXMLFile();

What should I do when 'svn cleanup' fails?

(Before you try moving folders and doing a new checkout.)

Delete the folder the offending file(s) are in - yes, even the .svn folder, then do an svn cleanup on the very top / parent folder.

Threads vs Processes in Linux

If you want to create a pure a process as possible, you would use clone() and set all the clone flags. (Or save yourself the typing effort and call fork())

If you want to create a pure a thread as possible, you would use clone() and clear all the clone flags (Or save yourself the typing effort and call pthread_create())

There are 28 flags that dictate the level of sharing. This means that there are over 268 million flavors of tasks that you can create, depending on what you want to share.

This is what we mean when we say that Linux does not distinguish between a process and a thread, but rather alludes to any flow of control within a program as a task. The rationale for not distinguishing between the two is, well, not uniquely defining over 268 million flavors!

Therefore, making the "perfect decision" of whether to use a process or thread is really about deciding which of the 28 resources to clone

enter image description here

AttributeError: 'module' object has no attribute 'model'

As the error message says in the last line: the module models in the file c:\projects\mysite..\mysite\polls\ contains no class model. This error occurs in the definition of the Poll class:

class Poll(models.model):

Either the class model is misspelled in the definition of the class Poll or it is misspelled in the module models. Another possibility is that it is completely missing from the module models. Maybe it is in another module or it is not yet implemented in models.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Try this:

jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

Or this:

yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 

Find indices of elements equal to zero in a NumPy array

numpy.where() is my favorite.

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])

Compare two files line by line and generate the difference in another file

Use the Diff utility and extract only the lines starting with < in the output

Facebook user url by id

I've collected info together:

And finaly: it doen't work without additional Facebook permission check:(

How to use MySQLdb with Python and Django in OSX 10.6?

Adding to other answers, the following helped me finish the installation mysql-python:

virtualenv, mysql-python, pip: anyone know how?

On Ubuntu...

apt-get install libmysqlclient-dev
apt-get install python-dev
pip install mysql-python

Don't forget to add 'sudo' to the beginning of commands if you don't have the proper permissions.

jQuery post() with serialize and extra data

    type: 'POST',  
    url: 'test.php',  
     beforeSend:function(xhr, settings){ += '&moreinfo=MoreData';
            //  json response  
    error: function(data) { 
        // if error occured

Stop jQuery .load response from being cached

Do NOT use timestamp to make an unique URL as for every page you visit is cached in DOM by jquery mobile and you soon run into trouble of running out of memory on mobiles.

$jqm(document).bind('pagebeforeload', function(event, data) {
    var url = data.url;
    var savePageInDOM = true;

    if (url.toLowerCase().indexOf("vacancies") >= 0) {
        savePageInDOM = false;

    $ =  savePageInDOM;

This code activates before page is loaded, you can use url.indexOf() to determine if the URL is the one you want to cache or not and set the cache parameter accordingly.

Do not use window.location = ""; to change URL otherwise you will navigate to the address and pagebeforeload will not fire. In order to get around this problem simply use window.location.hash = "";

Ubuntu, how do you remove all Python 3 but not 2

neither try any above ways nor sudo apt autoremove python3 because it will remove all gnome based applications from your system including gnome-terminal. In case if you have done that mistake and left with kernal only than trysudo apt install gnome on kernal.

try to change your default python version instead removing it. you can do this through bashrc file or export path command.

Convert an integer to a byte array

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)

jQuery: serialize() form and other parameters

You can create an auxiliar form using jQuery with the content of another form and then add thath form other params so you only have to serialize it in the ajax call.

function createInput(name,value){
    return $('<input>').attr({
        name: name,
        value: value
$form = $("<form></form>");
$form.append($("#your_form input").clone());
$form.append(createInput('input_name', 'input_value'));
$form.append(createInput('input_name_2', 'input_value_2'));

    type : 'POST',
    url : 'url',
    data : $form.serialize()

Force IE9 to emulate IE8. Possible?

You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer:

Edit: in case something happens to kill the msdn link, here is the content:

Specifying Document Compatibility Modes

You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.

  <!-- Enable IE9 Standards mode -->
  <meta http-equiv="X-UA-Compatible" content="IE=9" >
  <title>My webpage</title>
  <p>Content goes here.</p>

If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.

The following example specifies EmulateIE7 mode.

  <!-- Mimic Internet Explorer 7 -->
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
  <title>My webpage</title>
  <p>Content goes here.</p>

In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As Kaboing mentioned, MAXDOP(n) actually controls the number of CPU cores that are being used in the query processor.

On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER) which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN) reduce a query from 26 seconds to 1 second of execution time.

Books Online goes on to say that possible values for MAXDOP are:

0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting.

1 - Suppresses parallel plan generation. The operation will be executed serially.

2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.

I'm not sure what the best usage of MAXDOP is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8) due to I/O limitations, but I could be wrong.

Here are a few quick links I found about MAXDOP:

Books Online: Degree of Parallelism

General guidelines to use to configure the MAXDOP option

How to drop columns by name in a data frame

df = mtcars 
remove vs and am because they are categorical. In the dataset vs is in column number 8, am is in column number 9

dfnum = df[,-c(8,9)]

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
        this.Name = name;
        this.Artist = artist;
        this.Year = year;

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

What is a monad?

Another attempt at explaining monads, using just Python lists and the map function. I fully accept this isn't a full explanation, but I hope it gets at the core concepts.

I got the basis of this from the funfunfunction video on Monads and the Learn You A Haskell chapter 'For a Few Monads More'. I highly recommend watching the funfunfunction video.

At it's very simplest, Monads are objects that have a map and flatMap functions (bind in Haskell). There are some extra required properties, but these are the core ones.

flatMap 'flattens' the output of map, for lists this just concatenates the values of the list e.g.

concat([[1], [4], [9]]) = [1, 4, 9]

So in Python we can very basically implement a Monad with just these two functions:

def flatMap(func, lst):
    return concat(map(func, lst))

def concat(lst):
    return sum(lst, [])

func is any function that takes a value and returns a list e.g.

lambda x: [x*x]


For clarity I created the concat function in Python via a simple function, which sums the lists i.e. [] + [1] + [4] + [9] = [1, 4, 9] (Haskell has a native concat method).

I'm assuming you know what the map function is e.g.:

>>> list(map(lambda x: [x*x], [1,2,3]))
[[1], [4], [9]]

Flattening is the key concept of Monads and for each object which is a Monad this flattening allows you to get at the value that is wrapped in the Monad.

Now we can call:

>>> flatMap(lambda x: [x*x], [1,2,3])
[1, 4, 9]

This lambda is taking a value x and putting it into a list. A monad works with any function that goes from a value to a type of the monad, so a list in this case.

That's your monad defined.

I think the question of why they're useful has been answered in other questions.

More explanation

Other examples that aren't lists are JavaScript Promises, which have the then method and JavaScript Streams which have a flatMap method.

So Promises and Streams use a slightly different function which flattens out a Stream or a Promise and returns the value from within.

The Haskell list monad has the following definition:

instance Monad [] where  
    return x = [x]  
    xs >>= f = concat (map f xs)  
    fail _ = [] 

i.e. there are three functions return (not to be confused with return in most other languages), >>= (the flatMap) and fail.

Hopefully you can see the similarity between:

xs >>= f = concat (map f xs)


def flatMap(f, xs):
    return concat(map(f, xs))

How to attach a file using mail command on Linux?

mailx -a /path/to/file email@address

You might go into interactive mode (it will prompt you with "Subject: " and then a blank line), enter a subject, then enter a body and hit Ctrl+D (EOT) to finish.

How to show matplotlib plots in python

In case anyone else ends up here using Jupyter Notebooks, you just need

%matplotlib inline

Purpose of "%matplotlib inline"

Resolving IP Address from hostname with PowerShell

Use Resolve-DnsName cmdlet.

Resolve-DnsName computername | FT Name, IPAddress -HideTableHeaders | Out-File -Append c:\filename.txt

PS C:\> Resolve-DnsName

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------                              A      130   Answer                              A      130   Answer                              A      130   Answer                              A      130   Answer

PS C:\> Resolve-DnsName | Format-Table Name, IPAddress -HideTableHeaders

PS C:\> Resolve-DnsName -Type A

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------                                     A      16    Answer

PS C:\> Resolve-DnsName -Type AAAA

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------                                     AAAA   223   Answer     2607:f8b0:400e:c04::64

What's the difference between a word and byte?

The terms of BYTE and WORD are relative to the size of the processor that is being referred to. The most common processors are/were 8 bit, 16 bit, 32 bit or 64 bit. These are the WORD lengths of the processor. Actually half of a WORD is a BYTE, whatever the numerical length is. Ready for this, half of a BYTE is a NIBBLE.

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application ( to


and installed your shop application (sub web as virtual directory in IIS, marked as application) in


For example, if you call Server.MapPath() in following request:


  • Server.MapPath(".")1 returns D:\WebApps\shop\products
  • Server.MapPath("..") returns D:\WebApps\shop
  • Server.MapPath("~") returns D:\WebApps\shop
  • Server.MapPath("/") returns C:\Inetpub\wwwroot
  • Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward slash (/) or backward slash (\), the MapPath() returns a path as if Path was a full, virtual path.

If Path doesn't start with a slash, the MapPath() returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.


  1. Server.MapPath(null) and Server.MapPath("") will produce this effect too.

How get an apostrophe in a string in javascript

This is plain Javascript and has nothing to do with the jQuery library.

You simply escape the apostrophe with a backslash:

theAnchorText = 'I\'m home';

Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:

theAnchorText = "I'm home";

How to get current memory usage in android?

I looked at Android Source Tree.

Inside (internal service exposed by

public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
    final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
    final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
    outInfo.availMem = Process.getFreeMemory();
    outInfo.totalMem = Process.getTotalMemory();
    outInfo.threshold = homeAppMem;
    outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
    outInfo.hiddenAppThreshold = hiddenAppMem;
    outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
    outInfo.visibleAppThreshold = mProcessList.getMemLevel(
    outInfo.foregroundAppThreshold = mProcessList.getMemLevel(


/** @hide */
public static final native long getFreeMemory();

/** @hide */
public static final native long getTotalMemory();

It calls JNI method from android_util_Process.cpp


MemoryInfo.availMem = MemFree + Cached in /proc/meminfo.


Total Memory is added in API level 16.

How to set the title text color of UIButton?

You have to use func setTitleColor(_ color: UIColor?, for state: UIControlState) the same way you set the actual title text. Docs

isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), for: .normal)

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

Who is listening on a given TCP port on Mac OS X?

For macOS I use two commands together to show information about the processes listening on the machine and process connecting to remote servers. In other words, to check the listening ports and the current (TCP) connections on a host you could use the two following commands together

1. netstat -p tcp -p udp 

2. lsof -n -i4TCP -i4UDP 

Thought I would add my input, hopefully it can end up helping someone.

PHP Composer behind http proxy

on Windows insert:

set http_proxy=<proxy>
set https_proxy=<proxy>


php "%~dp0composer.phar" %*

or on Linux insert:

export http_proxy=<proxy>
export https_proxy=<proxy>


php "${dir}/composer.phar" "$@"

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I was able to handle this in Spring 2 as following

 private boolean isInPath(ServletRequest request) {
   String PATH_TO_VALIDATE = "/path/";
   String path = ((HttpServletRequest) request).getRequestURI();
   return path != null && path.toLowerCase().contains(PATH_TO_VALIDATE);

Grouping into interval of 5 minutes within a time range

You're probably going to have to break up your timestamp into ymd:HM and use DIV 5 to split the minutes up into 5-minute bins -- something like

select year(a.timestamp), 
       minute(a.timestamp) DIV 5,
FROM time a, id b
WHERE a.user = b.user AND = AND = 'John' 
      AND a.timestamp BETWEEN '2010-11-16 10:30:00' AND '2010-11-16 11:00:00'
GROUP BY year(a.timestamp), 
       minute(a.timestamp) DIV 12

...and then futz the output in client code to appear the way you like it. Or, you can build up the whole date string using the sql concat operatorinstead of getting separate columns, if you like.

select concat(year(a.timestamp), "-", month(a.timestamp), "-" ,day(a.timestamp), 
       " " , lpad(hour(a.timestamp),2,'0'), ":", 
       lpad((minute(a.timestamp) DIV 5) * 5, 2, '0'))

...and then group on that

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

A simpler version of your code would be:

dict(zip(names, d.values()))

If you want to keep the same structure, you can change it to:

vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}

(You can just as easily put list(d.values()) inside the comprehension instead of vlst; it's just wasteful to do so since it would be re-generating the list every time).

Java - How to convert type collection into ArrayList?

As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

So you need to do:

ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());

However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

I think your code should look like this:

public V getNode(int nodeId){
        ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
        return myNodeList(nodeId);

But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

Angular 1.6.0: "Possibly unhandled rejection" error

Please check the answer here:

Possibly unhandled rejection in Angular 1.6

This has been fixed with 316f60f and the fix is included in the v1.6.1 release.

JS strings "+" vs concat method

In JS, "+" concatenation works by creating a new String object.

For example, with...

var s = "Hello";

...we have one object s.


s = s + " World";

Now, s is a new object.

2nd method: String.prototype.concat

Casting interfaces for deserialization in JSON.NET

Several years on and I had a similar issue. In my case there were heavily nested interfaces and a preference for generating the concrete classes at runtime so that It would work with a generic class.

I decided to create a proxy class at run time that wraps the object returned by Newtonsoft.

The advantage of this approach is that it does not require a concrete implementation of the class and can handle any depth of nested interfaces automatically. You can see more about it on my blog.

using Castle.DynamicProxy;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;

namespace LL.Utilities.Std.Json
    public static class JObjectExtension
        private static ProxyGenerator _generator = new ProxyGenerator();

        public static dynamic toProxy(this JObject targetObject, Type interfaceType) 
            return _generator.CreateInterfaceProxyWithoutTarget(interfaceType, new JObjectInterceptor(targetObject));

        public static InterfaceType toProxy<InterfaceType>(this JObject targetObject)

            return toProxy(targetObject, typeof(InterfaceType));

    public class JObjectInterceptor : IInterceptor
        private JObject _target;

        public JObjectInterceptor(JObject target)
            _target = target;
        public void Intercept(IInvocation invocation)

            var methodName = invocation.Method.Name;
            if(invocation.Method.IsSpecialName && methodName.StartsWith("get_"))
                var returnType = invocation.Method.ReturnType;
                methodName = methodName.Substring(4);

                if (_target == null || _target[methodName] == null)
                    if (returnType.GetTypeInfo().IsPrimitive || returnType.Equals(typeof(string)))

                        invocation.ReturnValue = null;


                if (returnType.GetTypeInfo().IsPrimitive || returnType.Equals(typeof(string)))
                    invocation.ReturnValue = _target[methodName].ToObject(returnType);
                    invocation.ReturnValue = ((JObject)_target[methodName]).toProxy(returnType);
                throw new NotImplementedException("Only get accessors are implemented in proxy");




var jObj = JObject.Parse(input);
InterfaceType proxyObject = jObj.toProxy<InterfaceType>();

java.lang.ClassNotFoundException: HttpServletRequest

I have just deleted the declaration of the servlet in the web.xml file and it works for me.

Good luck

Could not resolve this reference. Could not locate the assembly

If the project is check out to different PC through team foundation server with different location of same library file, there will be no yellow icon mark in Reference but when change to Release build and build the project, it will give an error. Just like what @C.Evenhuis said, it will use back old one in previous build (eg: Debug build) so I didn't notice the mistake.

Now I know it is a bad habit to put library files in different location on different PC.

Just need to delete the reference and re-add the same reference from correct location.

Remove all classes that begin with a certain string[email protected]/msg03998.html says:

...and .removeClass() would remove all classes...

It works for me ;)


Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.


interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking


interface Model {
  name: string;
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});


interface Model {
  name: string;
  [others: string]: any;
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
interface UserProperties {
  [key: string]: any;
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also

JQuery Number Formatting

If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric. Works a treat. Have been using it successfully for several years now.

How do I use HTML as the view engine in Express?

To make the render engine accept html instead of jade you can follow the following steps;

Install consolidate and swig to your directory.

 npm install consolidate
 npm install swig

add following lines to your app.js file

var cons = require('consolidate');

// view engine setup
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

add your view templates as .html inside “views” folder. Restart you node server and start the app in the browser.

This should work

Highlight all occurrence of a selected word?

First (or in your .vimrc):

:set hlsearch

Then position your cursor over the word you want highlighted, and hit *.

hlsearch means highlight all occurrences of the current search, and * means search for the word under the cursor.

Git and nasty "error: cannot lock existing info/refs fatal"

In my case I had to manually delete old tags which had been removed on remote.

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

DataSet panel (Report Data) in SSRS designer is gone

If you are working with SQL 2008 R2 then from View---->Report Data option at bottom

Compare two date formats in javascript/jquery

To comapre dates of string format (mm-dd-yyyy).

    var job_start_date = "10-1-2014"; // Oct 1, 2014
    var job_end_date = "11-1-2014"; // Nov 1, 2014
    job_start_date = job_start_date.split('-');
    job_end_date = job_end_date.split('-');

    var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
    var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);

    if(new_end_date <= new_start_date) {
      // your code