Programs & Examples On #G77

The old g77 FORTRAN compiler of GCC which has been replaced by gfortran since release 4.0.

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I end up delete all the data in my table, and run alter again. It works. Not the brilliant one, but it save a lot time, especially your application is still in development stage without any customer data.

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I created a small application which had similar functionality

MainActivity

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.open,
                R.string.close
        )

        {
            public void onDrawerClosed(View view)
            {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }

            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
                syncState();
            }
        };
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //Set the custom toolbar
        if (toolbar != null){
            setSupportActionBar(toolbar);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        actionBarDrawerToggle.syncState();
    }
}

My XML of that Activity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    android:id="@+id/drawer"
    >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <include layout="@layout/toolbar_custom"/>
    </FrameLayout>
    <!-- The navigation drawer -->
    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#457C50"/>


</android.support.v4.widget.DrawerLayout>

My Custom Toolbar XML

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

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimaryDark">
    <TextView android:text="U titel"
        android:textAppearance="@android:style/TextAppearance.Theme"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v7.widget.Toolbar>

My Theme Style

<resources>
    <style name="AppTheme" parent="Base.Theme.AppCompat"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDarker</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

    <color name="primary">#457C50</color>
    <color name="primaryDarker">#580C0C</color>
</resources>

My Styles in values-v21

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

Loop through a comma-separated shell variable

Another solution not using IFS and still preserving the spaces:

$ var="a bc,def,ghij"
$ while read line; do echo line="$line"; done < <(echo "$var" | tr ',' '\n')
line=a bc
line=def
line=ghij

What are the lesser known but useful data structures?

The Region Quadtree

(quoted from Wikipedia)

The region quadtree represents a partition of space in two dimensions by decomposing the region into four equal quadrants, subquadrants, and so on with each leaf node containing data corresponding to a specific subregion. Each node in the tree either has exactly four children, or has no children (a leaf node).

Quadtrees like this are good for storing spatial data, e.g. latitude and longitude or other types of coordinates.

This was by far my favorite data structure in college. Coding this guy and seeing it work was pretty cool. I highly recommend it if you're looking for a project that will take some thought and is a little off the beaten path. Anyway, it's a lot more fun than the standard BST derivatives that you're usually assigned in your data structures class!

In fact, as a bonus, I've found the notes from the lecture leading up to the class project (from Virginia Tech) here (pdf warning).

curl -GET and -X GET

-X [your method]
X lets you override the default 'Get'

** corrected lowercase x to uppercase X

How to stop execution after a certain time in Java?

you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

With this you don't need to program the loop the time measuring by yourself.

public class Starter {

    public static void main(final String[] args) {
        final ExecutorService service = Executors.newSingleThreadExecutor();

        try {
            final Future<Object> f = service.submit(() -> {
                // Do you long running calculation here
                Thread.sleep(1337); // Simulate some delay
                return "42";
            });

            System.out.println(f.get(1, TimeUnit.SECONDS));
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }
    }
}

How to parse JSON Array (Not Json Object) in Android

In this example there are several objects inside one json array. That is,

This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

This is one object: {"name":"name1","url":"url1"}

Assuming that you have got the result to a String variable called jSonResultString:

JSONArray arr = new JSONArray(jSonResultString);

  //loop through each object
  for (int i=0; i<arr.length(); i++){

  JSONObject jsonProductObject = arr.getJSONObject(i);
  String name = jsonProductObject.getString("name");
  String url = jsonProductObject.getString("url");


}

How to create folder with PHP code?

You can create a directory with PHP using the mkdir() function.

mkdir("/path/to/my/dir", 0700);

You can use fopen() to create a file inside that directory with the use of the mode w.

fopen('myfile.txt', 'w');

w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

log4j vs logback

Your decision should be based on

  • your actual need for these "more features"; and
  • your expected cost of implementing the change.

You should resist the urge to change APIs just because it's "newer, shinier, better." I follow a policy of "if it's not broken, don't kick it."

If your application requires a very sophisticated logging framework, you may want to consider why.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Example to use shared_ptr?

#include <memory>
#include <iostream>

class SharedMemory {
    public: 
        SharedMemory(int* x):_capture(x){}
        int* get() { return (_capture.get()); }
    protected:
        std::shared_ptr<int> _capture;
};

int main(int , char**){
    SharedMemory *_obj1= new SharedMemory(new int(10));
    SharedMemory *_obj2 = new SharedMemory(*_obj1);
    std::cout << " _obj1: " << *_obj1->get() << " _obj2: " << *_obj2->get()
    << std::endl;
    delete _obj2;

    std::cout << " _obj1: " << *_obj1->get() << std::endl;
    delete _obj1;
    std::cout << " done " << std::endl;
}

This is an example of shared_ptr in action. _obj2 was deleted but pointer is still valid. output is, ./test _obj1: 10 _obj2: 10 _obj2: 10 done

Detect encoding and make everything UTF-8

Detecting the encoding is hard.

mb_detect_encoding works by guessing, based on a number of candidates that you pass it. In some encodings, certain byte-sequences are invalid, an therefore it can distinguish between various candidates. Unfortunately, there are a lot of encodings, where the same bytes are valid (but different). In these cases, there is no way to determine the encoding; You can implement your own logic to make guesses in these cases. For example, data coming from a Japanese site might be more likely to have a Japanese encoding.

As long as you only deal with Western European languages, the three major encodings to consider are utf-8, iso-8859-1 and cp-1252. Since these are defaults for many platforms, they are also the most likely to be reported wrongly about. Eg. if people use different encodings, they are likely to be frank about it, since else their software would break very often. Therefore, a good strategy is to trust the provider, unless the encoding is reported as one of those three. You should still doublecheck that it is indeed valid, using mb_check_encoding (note that valid is not the same as being - the same input may be valid for many encodings). If it is one of those, you can then use mb_detect_encoding to distinguish between them. Luckily that is fairly deterministic; You just need to use the proper detect-sequence, which is UTF-8,ISO-8859-1,WINDOWS-1252.

Once you've detected the encoding you need to convert it to your internal representation (UTF-8 is the only sane choice). The function utf8_encode transforms ISO-8859-1 to UTF-8, so it can only used for that particular input type. For other encodings, use mb_convert_encoding.

Which ORM should I use for Node.js and MySQL?

May I suggest Node ORM?

https://github.com/dresende/node-orm2

There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.

MongoDB is available since version 2.1.x (released in July 2013)

UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize

Is there a way to specify how many characters of a string to print out using printf()?

The basic way is:

printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

The other, often more useful, way is:

printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");

Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.

You can also use the notation:

printf ("Here are the first 8 chars: %*.*s\n",
        8, 8, "A string that is more than 8 chars");

This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:

printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);

The POSIX specification for printf() defines these mechanisms.

jQuery: How to detect window width on the fly?

Below is what i did to hide some Id element when screen size is below 768px, and show up when is above 768px. It works great.

var screensize= $( window ).width();

if(screensize<=768){
        if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0)
            {
                $('#column-d0f6e77c699556473e4ff2967e9c0251').css('display','none');
            }
}
else{
        if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0)
            {
                $('#column-d0f6e77c699556473e4ff2967e9c0251').removeAttr( "style" );
            }

}
changething = function(screensize){
        if(screensize<=768){
            if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0)
            {
                $('#column-d0f6e77c699556473e4ff2967e9c0251').css('display','none');
            }
        }
        else{
        if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0)
            {
                $('#column-d0f6e77c699556473e4ff2967e9c0251').removeAttr( "style" );
            }

        }
}
$( window ).resize(function() {
 var screensize= $( window ).width();
  changething(screensize);
});

Looping through a hash, or using an array in PowerShell

If you're using PowerShell v3, you can use JSON instead of a hashtable, and convert it to an object with Convert-FromJson:

@'
[
    {
        FileName = "Page";
        ObjectName = "vExtractPage";
    },
    {
        ObjectName = "ChecklistItemCategory";
    },
    {
        ObjectName = "ChecklistItem";
    },
]
'@ | 
    Convert-FromJson |
    ForEach-Object {
        $InputFullTableName = '{0}{1}' -f $TargetDatabase,$_.ObjectName

        # In strict mode, you can't reference a property that doesn't exist, 
        #so check if it has an explicit filename firest.
        $outputFileName = $_.ObjectName
        if( $_ | Get-Member FileName )
        {
            $outputFileName = $_.FileName
        }
        $OutputFullFileName = Join-Path $OutputDirectory $outputFileName

        bcp $InputFullTableName out $OutputFullFileName -T -c $ServerOption
    }

Convert RGBA PNG to RGB with PIL

Here's a solution in pure PIL.

def blend_value(under, over, a):
    return (over*a + under*(255-a)) / 255

def blend_rgba(under, over):
    return tuple([blend_value(under[i], over[i], over[3]) for i in (0,1,2)] + [255])

white = (255, 255, 255, 255)

im = Image.open(object.logo.path)
p = im.load()
for y in range(im.size[1]):
    for x in range(im.size[0]):
        p[x,y] = blend_rgba(white, p[x,y])
im.save('/tmp/output.png')

How to Sort Date in descending order From Arraylist Date in android?

Easier alternative to above answers

  1. If Object(Model Class/POJO) contains the date in String datatype.

    private void sortArray(ArrayList<myObject> arraylist) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
    if (reports != null) {
        Collections.sort(arraylist, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                try {
                    return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
                } catch (ParseException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }
    
  2. If Object(Model Class/POJO) contains date in Date datatype

    private void sortArray(ArrayList<myObject> arrayList) {
    if (arrayList != null) {
        Collections.sort(arrayList, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                return o2.getCreated_at().compareTo(o1.getCreated_at()); }
        });
    } }
    

The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.

move_uploaded_file gives "failed to open stream: Permission denied" error

The solution is so easy. Only right click the IMAGE (destination) folder, go to properties, click the permission tab, and change others access to Create and delete files.

While loop to test if a file exists in bash

I had the same problem, put the ! outside the brackets;

while ! [ -f /tmp/list.txt ];
do
    echo "#"
    sleep 1
done

Also, if you add an echo inside the loop it will tell you if you are getting into the loop or not.

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

Creating for loop until list.length

I'd try to search for the solution by google and the string Python for statement, it is as simple as that. The first link says everything. (A great forum, really, but its usage seems to look sometimes like the usage of the Microsoft understanding of all their GUI products' benefits: windows inside, idiots outside.)

Doctrine findBy 'does not equal'

I used the QueryBuilder to get the data,

$query=$this->dm->createQueryBuilder('AppBundle:DocumentName')
             ->field('fieldName')->notEqual(null);

$data=$query->getQuery()->execute();

C++ Vector of pointers

As far as I understand, you create a Movie class:

class Movie
{
private:
  std::string _title;
  std::string _director;
  int         _year;
  int         _rating;
  std::vector<std::string> actors;
};

and having such class, you create a vector instance:

std::vector<Movie*> movies;

so, you can add any movie to your movies collection. Since you are creating a vector of pointers to movies, do not forget to free the resources allocated by your movie instances OR you could use some smart pointer to deallocate the movies automatically:

std::vector<shared_ptr<Movie>> movies;

Two statements next to curly brace in an equation

To answer also to the comment by @MLT, there is an alternative to the standard cases environment, not too sophisticated really, with both lines numbered. This code:

\documentclass{article}
\usepackage{amsmath}
\usepackage{cases}

\begin{document}

\begin{numcases}{f(x)=}
  1, & if $x<0$\\
  0, & otherwise
\end{numcases}

\end{document}

produces

screenshot of output pdf

Notice that here, math must be delimited by \(...\) or $...$, at least on the right of & in each line (reference).

Html.ActionLink as a button or an image, not a link

use FORMACTION

<input type="submit" value="Delete" formaction="@Url.Action("Delete", new { id = Model.Id })" />

How to copy only a single worksheet to another workbook using vba

You can try this VBA program

Option Explicit 

Sub CopyWorksheetsFomTemplate() 
    Dim NewName As String 
    Dim nm As Name 
    Dim ws As Worksheet 

    If MsgBox("Copy specific sheets to a new workbook" & vbCr & _ 
    "New sheets will be pasted as values, named ranges removed" _ 
    , vbYesNo, "NewCopy") = vbNo Then Exit Sub 

    With Application 
        .ScreenUpdating = False 

         '       Copy specific sheets
         '       *SET THE SHEET NAMES TO COPY BELOW*
         '       Array("Sheet Name", "Another sheet name", "And Another"))
         '       Sheet names go inside quotes, seperated by commas
        On Error GoTo ErrCatcher 
        Sheets(Array("Sheet1", "Sheet2")).Copy 
        On Error GoTo 0 

         '       Paste sheets as values
         '       Remove External Links, Hperlinks and hard-code formulas
         '       Make sure A1 is selected on all sheets
        For Each ws In ActiveWorkbook.Worksheets 
            ws.Cells.Copy 
            ws.[A1].PasteSpecial Paste:=xlValues 
            ws.Cells.Hyperlinks.Delete 
            Application.CutCopyMode = False 
            Cells(1, 1).Select 
            ws.Activate 
        Next ws 
        Cells(1, 1).Select 

         '       Remove named ranges
        For Each nm In ActiveWorkbook.Names 
            nm.Delete 
        Next nm 

         '       Input box to name new file
        NewName = InputBox("Please Specify the name of your new workbook", "New Copy") 

         '       Save it with the NewName and in the same directory as original
        ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & NewName & ".xls" 
        ActiveWorkbook.Close SaveChanges:=False 

        .ScreenUpdating = True 
    End With 
    Exit Sub 

ErrCatcher: 
    MsgBox "Specified sheets do not exist within this workbook" 

End Sub 

How to check existence of user-define table type in SQL Server 2008?

You can look in sys.types or use TYPE_ID:

IF TYPE_ID(N'MyType') IS NULL ...

Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.

Setting environment variables on OS X

Solution for both command line and GUI applications from a single source (works with Mac OS X v10.10 (Yosemite) and Mac OS X v10.11 (El Capitan))

Let's assume you have environment variable definitions in your ~/.bash_profile like in the following snippet:

export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/opt/go/libexec/bin:$GOPATH/bin"
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
export MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"

We need a Launch Agent which will run on each login and anytime on demand which is going to load these variables to the user session. We'll also need a shell script to parse these definitions and build necessary commands to be executed by the agent.

Create a file with plist suffix (e.g. named osx-env-sync.plist) in ~/Library/LaunchAgents/ directory with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>osx-env-sync</string>
  <key>ProgramArguments</key>
  <array>
    <string>bash</string>
    <string>-l</string>
    <string>-c</string>
    <string>
      $HOME/.osx-env-sync.sh
    </string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

-l parameter is critical here; it's necessary for executing the shell script with a login shell so that ~/.bash_profile is sourced in the first place before this script is executed.

Now, the shell script. Create it at ~/.osx-env-sync.sh with the following contents:

grep export $HOME/.bash_profile | while IFS=' =' read ignoreexport envvar ignorevalue; do
  launchctl setenv "${envvar}" "${!envvar}"
done

Make sure the shell script is executable:

chmod +x ~/.osx-env-sync.sh

Now, load the launch agent for current session:

launchctl load ~/Library/LaunchAgents/osx-env-sync.plist

(Re)Launch a GUI application and verify that it can read the environment variables.

The setup is persistent. It will survive restarts and relogins.

After the initial setup (that you just did), if you want to reflect any changes in your ~/.bash_profile to your whole environment again, rerunning the launchctl load ... command won't perform what you want; instead you'll get a warning like the following:

<$HOME>/Library/LaunchAgents/osx-env-sync.plist: Operation already in progress

In order to reload your environment variables without going through the logout/login process do the following:

launchctl unload ~/Library/LaunchAgents/osx-env-sync.plist
launchctl load ~/Library/LaunchAgents/osx-env-sync.plist

Finally make sure that you relaunch your already running applications (including Terminal.app) to make them aware of the changes.

I've also pushed the code and explanations here to a GitHub project: osx-env-sync.

I hope this is going to be the ultimate solution, at least for the latest versions of OS X (Yosemite & El Capitan).

How can I use JQuery to post JSON data?

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

_x000D_
_x000D_
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: '/form/',_x000D_
    data: Data,_x000D_
    success: function(data) { alert('data: ' + data); },_x000D_
    contentType: "application/json",_x000D_
    dataType: 'json'_x000D_
});
_x000D_
_x000D_
_x000D_

Time complexity of Euclid's Algorithm

The suitable way to analyze an algorithm is by determining its worst case scenarios. Euclidean GCD's worst case occurs when Fibonacci Pairs are involved. void EGCD(fib[i], fib[i - 1]), where i > 0.

For instance, let's opt for the case where the dividend is 55, and the divisor is 34 (recall that we are still dealing with fibonacci numbers).

enter image description here

As you may notice, this operation costed 8 iterations (or recursive calls).

Let's try larger Fibonacci numbers, namely 121393 and 75025. We can notice here as well that it took 24 iterations (or recursive calls).

enter image description here

You can also notice that each iterations yields a Fibonacci number. That's why we have so many operations. We can't obtain similar results only with Fibonacci numbers indeed.

Hence, the time complexity is going to be represented by small Oh (upper bound), this time. The lower bound is intuitively Omega(1): case of 500 divided by 2, for instance.

Let's solve the recurrence relation:

enter image description here

We may say then that Euclidean GCD can make log(xy) operation at most.

Timing Delays in VBA

Your code only creates a time without a date. If your assumption is correct that when it runs the application.wait the time actually already reached that time it will wait for 24 hours exactly. I also worry a bit about calling now() multiple times (could be different?) I would change the code to

 application.wait DateAdd("s", 1, Now)

Creating a Menu in Python

This should do it. You were missing a ) and you only need """ not 4 of them. Also you don't need a elif at the end.

ans=True
while ans:
    print("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ")
    if ans=="1":
      print("\nStudent Added")
    elif ans=="2":
      print("\n Student Deleted")
    elif ans=="3":
      print("\n Student Record Found")
    elif ans=="4":
      print("\n Goodbye") 
      ans = None
    else:
       print("\n Not Valid Choice Try again")

Curl Command to Repeat URL Request

You can use any bash looping constructs like FOR, with is compatible to Linux and Mac.

https://tiswww.case.edu/php/chet/bash/bashref.html#Looping-Constructs

In your specific case you can define N iterations, with N is a number defining how many curl executions you want.

for n in {1..N}; do curl <arguments>; done

ex:

for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done

add title attribute from css

Well, although it's not actually possible to change the title attribute, it is possible to show a tooltip completely from css. You can check a working version out at http://jsfiddle.net/HzH3Z/5/.

What you can do is style the label:after selector and give it display:none, and set it's content from css. You can then change the display attribute to display:block on label:hover:after, and it will show. Like this:

label:after{
    content: "my tooltip";
    padding: 2px;
    display:none;
    position: relative;
    top: -20px;
    right: -30px;
    width: 150px;
    text-align: center;
    background-color: #fef4c5;
    border: 1px solid #d4b943;
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    -ms-border-radius: 2px;
    border-radius: 2px;
}
label:hover:after{
    display: block;
}

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Cast the result as TIME and the result will be in time format for duration of the interval.

select CAST(job_end - job_start) AS TIME(0)) from tableA

Javascript split regex question

or just (anything but numbers):

date.split(/\D/);

How to get start and end of previous month in VB

The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:

''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013 
DateSerial(Year(Date),1,0) = 31/12/2012 

You can get the first day from the above like so:

LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1

See also: How to caculate last business day of month in VBScript

How to make readonly all inputs in some div in Angular2?

You can do like this. Open a ts file ad there make an interface with inputs you want and in the page you want to show under export class write

readonly yourinterface = yourinterface
readonly level: number[] = [];

and in your template do like this *ngFor="let yourtype of yourinterface"

How to use ADB in Android Studio to view an SQLite DB

You can use a very nice tool called Stetho by adding this to build.gradle file:

compile 'com.facebook.stetho:stetho:1.4.1'

And initialized it inside your Application or Activity onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Stetho.initializeWithDefaults(this);
    setContentView(R.layout.activity_main);
}

Then you can view the db records in chrome in the address:

chrome://inspect/#devices

For more details you can read my post: How to view easily your db records

Android, getting resource ID from string?

A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);

Android "hello world" pushnotification example

you can follow this tutorial

http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/

it helped me to do a push notification; or you can follow this other tutorial

http://www.tutorialeshtml5.com/2013/10/tutorial-simple-de-gcm-traves-de-php.html

but it's in spanish but you can download the code.

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

How to define global variable in Google Apps Script

You might be better off using the Properties Service as you can use these as a kind of persistent global variable.

click 'file > project properties > project properties' to set a key value, or you can use

PropertiesService.getScriptProperties().setProperty('mykey', 'myvalue');

The data can be retrieved with

var myvalue = PropertiesService.getScriptProperties().getProperty('mykey');

How can I call a method in Objective-C?

Use this:

[self score]; you don't need @sel for calling directly

Can we call the function written in one JavaScript in another JS file?

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

I.e.

File1.js

function alertNumber(number) {
    alert(number);
}

File2.js

function alertOne() {
     alertNumber("one");
}

HTML

<head>
....
    <script src="File1.js" type="text/javascript"></script> 
    <script src="File2.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

The other way won't work. As correctly pointed out by Stuart Wakefield. The other way will also work.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

What will not work would be:

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script type="text/javascript">
       alertOne();
    </script>
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
</body>

Although alertOne is defined when calling it, internally it uses a function that is still not defined (alertNumber).

Git: how to reverse-merge a commit?

git reset --hard HEAD^ 

Use the above command to revert merge changes.

Resize image proportionally with CSS?

You always need something like this

html
{
    width: 100%;
    height: 100%;
}

at the top of your css file

Get the element with the highest occurrence in an array

const mode = (str) => {
  return str
    .split(' ')
    .reduce((data, key) => {
      let counter = data.map[key] + 1 || 1
      data.map[key] = counter

      if (counter > data.counter) {
        data.counter = counter
        data.mode = key
      }

      return data
    }, {
      counter: 0,
      mode: null,
      map: {}
    })
    .mode
}

console.log(mode('the t-rex is the greatest of them all'))

How to find the length of an array list?

System.out.println(myList.size());

Since no elements are in the list

output => 0

myList.add("newString");  // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());

Since one element is added to the list

output => 1

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

This is based on KoZm0kNoT's answer. I modified it to work across drives.

@echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
popd

The two pushd/popds are necessary in case the user's cwd is on a different drive. Without the outer set, the cwd on the drive with the script will get lost.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

What is the use of the square brackets [] in sql statements?

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space)--but then you'd need to use brackets every time you referred to that column.

The newer tools add them everywhere just in case or for consistency.

Rotate axis text in python matplotlib

It will depend on what are you plotting.

import matplotlib.pyplot as plt

 x=['long_text_for_a_label_a',
    'long_text_for_a_label_b',
    'long_text_for_a_label_c']
y=[1,2,3]
myplot = plt.plot(x,y)
for item in myplot.axes.get_xticklabels():
    item.set_rotation(90)

For pandas and seaborn that give you an Axes object:

df = pd.DataFrame(x,y)
#pandas
myplot = df.plot.bar()
#seaborn 
myplotsns =sns.barplot(y='0',  x=df.index, data=df)
# you can get xticklabels without .axes cause the object are already a 
# isntance of it
for item in myplot.get_xticklabels():
    item.set_rotation(90)

If you need to rotate labels you may need change the font size too, you can use font_scale=1.0 to do that.

Changing website favicon dynamically

I use this feature all the time when developing sites ... so I can see at-a-glance which tab has local, dev or prod running in it.

Now that Chrome supports SVG favicons it makes it a whole lot easier.

Tampermonkey Script

Have a gander at https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f for a tampermonkey script that points to a demo site I chucked up at https://elliz.github.io/svg-favicon/

Basic code

Adapted this from another answer ... could be improved but good enough for my needs.

(function() {
    'use strict';

    // play with https://codepen.io/elliz/full/ygvgay for getting it right
    // viewBox is required but does not need to be 16x16
    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
      <circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" />
      <circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" />
    </svg>
    `;

    var favicon_link_html = document.createElement('link');
    favicon_link_html.rel = 'icon';
    favicon_link_html.href = svgToDataUri(svg);
    favicon_link_html.type = 'image/svg+xml';

    try {
        let favicons = document.querySelectorAll('link[rel~="icon"]');
        favicons.forEach(function(favicon) {
            favicon.parentNode.removeChild(favicon);
        });

        const head = document.getElementsByTagName('head')[0];
        head.insertBefore( favicon_link_html, head.firstChild );
    }
    catch(e) { }

    // functions -------------------------------
    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function svgToDataUri(svg) {
        // these may not all be needed - used to be for uri-encoded svg in old browsers
        var encoded = svg.replace(/\s+/g, " ")
        encoded = replaceAll(encoded, "%", "%25");
        encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements
        encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css
        encoded = replaceAll(encoded, "<", "%3c");
        encoded = replaceAll(encoded, ">", "%3e");
        encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text>
        encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox
        encoded = replaceAll(encoded, "{", "%7b");
        encoded = replaceAll(encoded, "}", "%7d");
        encoded = replaceAll(encoded, "|", "%7c");
        encoded = replaceAll(encoded, "^", "%5e");
        encoded = replaceAll(encoded, "`", "%60");
        encoded = replaceAll(encoded, "@", "%40");
        var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();
        return dataUri;
    }

})();

Just pop your own SVG (maybe cleaned with Jake Archibald's SVGOMG if you're using a tool) into the const at the top. Make sure it is square (using the viewBox attribute) and you're good to go.

How do I clone into a non-empty directory?

Warning - this could potentially overwrite files.

git init     
git remote add origin PATH/TO/REPO     
git fetch     
git checkout -t origin/master -f

Modified from @cmcginty's answer - without the -f it didn't work for me

How to set up a PostgreSQL database in Django

This is one of the very good and step by step process to set up PostgreSQL in ubuntu server. I have tried it with Ubuntu 16.04 and its working.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04

How can I increment a char?

For me i made the fallowing as a test.

string_1="abcd"

def test(string_1):
   i = 0
   p = ""
   x = len(string_1)
   while i < x:
    y = (string_1)[i]
    i=i+1
    s = chr(ord(y) + 1)
    p=p+s

   print(p)

test(string_1)

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Tensorflow image reading & display

Load names with tf.train.match_filenames_once get the number of files to iterate over with tf.size open session and enjoy ;-)

import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image

matplotlib.use('Agg')
import matplotlib.pyplot as plt


filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)

reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    num_files = sess.run(count_num_files)
    for i in range(num_files):
        image=img.eval()
        print(image.shape)
        Image.fromarray(np.asarray(image)).save('te.jpeg')

how to remove multiple columns in r dataframe?

Adding answer as this was the top hit when searching for "drop multiple columns in r":

The general version of the single column removal, e.g df$column1 <- NULL, is to use list(NULL):

df[ ,c('column1', 'column2')] <- list(NULL)

This also works for position index as well:

df[ ,c(1,2)] <- list(NULL)

This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:

> iris[ ,-c("Species")]
Error in -"Species" : invalid argument to unary operator

Postgresql - change the size of a varchar column to lower length

Here's the cache of the page described by Greg Smith. In case that dies as well, the alter statement looks like this:

UPDATE pg_attribute SET atttypmod = 35+4
WHERE attrelid = 'TABLE1'::regclass
AND attname = 'COL1';

Where your table is TABLE1, the column is COL1 and you want to set it to 35 characters (the +4 is needed for legacy purposes according to the link, possibly the overhead referred to by A.H. in the comments).

How to run a script as root on Mac OS X?

sudo ./scriptname

sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

I realize this is not related to OSX, but on an embedded system (Beagle Bone Angstrom) I had the exact same error message. Installing the following ipk packages solved it.

opkg install python-setuptools
opkg install python-pip

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

How to make multiple divs display in one line but still retain width?

You can float your column divs using float: left; and give them widths.

And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.

Hope this helps.

Developing C# on Linux

I would suggest using MonoDevelop.

It is pretty much explicitly designed for use with Mono, and all set up to develop in C#.

The simplest way to install it on Ubuntu would be to install the monodevelop package in Ubuntu. (link on Mono on ubuntu.com) (However, if you want to install a more recent version, I am not sure which PPA would be appropriate)

However, I would not recommend developing with the WinForms toolkit - I do not expect it to have the same behavior in Windows and Mono (the implementations are pretty different). For an overview of the UI toolkits that work with Mono, you can go to the information page on Mono-project.

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

An easier way is to use redux-auto.

from the documantasion

redux-auto fixed this asynchronous problem simply by allowing you to create an "action" function that returns a promise. To accompany your "default" function action logic.

  1. No need for other Redux async middleware. e.g. thunk, promise-middleware, saga
  2. Easily allows you to pass a promise into redux and have it managed for you
  3. Allows you to co-locate external service calls with where they will be transformed
  4. Naming the file "init.js" will call it once at app start. This is good for loading data from the server at start

The idea is to have each action in a specific file. co-locating the server call in the file with reducer functions for "pending", "fulfilled" and "rejected". This makes handling promises very easy.

It also automatically attaches a helper object(called "async") to the prototype of your state, allowing you to track in your UI, requested transitions.

How to export html table to excel or pdf in php

Either you can use CSV functions or PHPExcel

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>

The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Capturing count from an SQL query

You'll get converting errors with:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Use instead:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

Error: Java: invalid target release: 11 - IntelliJ IDEA

Just had same error. Problem was that I had empty package-info.java file. As soon as I added package name inside it worked...

What does $(function() {} ); do?

$(function() { ... });

is just jQuery short-hand for

$(document).ready(function() { ... });

What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.

However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?

Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!

Get the value of input text when enter key pressed

Listen the change event.

document.querySelector("input")
  .addEventListener('change', (e) => {
    console.log(e.currentTarget.value);
 });

Downloading a large file using curl

You can use this function, which creates a tempfile in the filesystem and returns the path to the downloaded file if everything worked fine:

function getFileContents($url)
{
    // Workaround: Save temp file
    $img = tempnam(sys_get_temp_dir(), 'pdf-');
    $img .= '.' . pathinfo($url, PATHINFO_EXTENSION);

    $fp = fopen($img, 'w+');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    $result = curl_exec($ch);
    curl_close($ch);

    fclose($fp);

    return $result ? $img : false;
}

Removing special characters VBA Excel

This is what I use, based on this link

Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next


StripAccentb = S

Exit Function
End Function

Usage:

=StripAccentb(B2) ' cell address

Sub version for all cells in a sheet:

Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
    For i = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    S = replace(S, A, B)
    Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub

Using Regular Expressions to Extract a Value in Java

This function collect all matching sequences from string. In this example it takes all email addresses from string.

static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";

public List<String> getAllEmails(String message) {      
    List<String> result = null;
    Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);

    if (matcher.find()) {
        result = new ArrayList<String>();
        result.add(matcher.group());

        while (matcher.find()) {
            result.add(matcher.group());
        }
    }

    return result;
}

For message = "[email protected], <[email protected]>>>> [email protected]" it will create List of 3 elements.

Best way to encode text data for XML in Java?

This has worked well for me to provide an escaped version of a text string:

public class XMLHelper {

/**
 * Returns the string where all non-ascii and <, &, > are encoded as numeric entities. I.e. "&lt;A &amp; B &gt;"
 * .... (insert result here). The result is safe to include anywhere in a text field in an XML-string. If there was
 * no characters to protect, the original string is returned.
 * 
 * @param originalUnprotectedString
 *            original string which may contain characters either reserved in XML or with different representation
 *            in different encodings (like 8859-1 and UFT-8)
 * @return
 */
public static String protectSpecialCharacters(String originalUnprotectedString) {
    if (originalUnprotectedString == null) {
        return null;
    }
    boolean anyCharactersProtected = false;

    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < originalUnprotectedString.length(); i++) {
        char ch = originalUnprotectedString.charAt(i);

        boolean controlCharacter = ch < 32;
        boolean unicodeButNotAscii = ch > 126;
        boolean characterWithSpecialMeaningInXML = ch == '<' || ch == '&' || ch == '>';

        if (characterWithSpecialMeaningInXML || unicodeButNotAscii || controlCharacter) {
            stringBuffer.append("&#" + (int) ch + ";");
            anyCharactersProtected = true;
        } else {
            stringBuffer.append(ch);
        }
    }
    if (anyCharactersProtected == false) {
        return originalUnprotectedString;
    }

    return stringBuffer.toString();
}

}

Determining image file size + dimensions via Javascript?

Edit:

To get the current in-browser pixel size of a DOM element (in your case IMG elements) excluding the border and margin, you can use the clientWidth and clientHeight properties.

var img = document.getElementById('imageId'); 

var width = img.clientWidth;
var height = img.clientHeight;

Now to get the file size, now I can only think about the fileSize property that Internet Explorer exposes for document and IMG elements...

Edit 2: Something comes to my mind...

To get the size of a file hosted on the server, you could simply make an HEAD HTTP Request using Ajax. This kind of request is used to obtain metainformation about the url implied by the request without transferring any content of it in the response.

At the end of the HTTP Request, we have access to the response HTTP Headers, including the Content-Length which represents the size of the file in bytes.

A basic example using raw XHR:

var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'img/test.jpg', true);
xhr.onreadystatechange = function(){
  if ( xhr.readyState == 4 ) {
    if ( xhr.status == 200 ) {
      alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
    } else {
      alert('ERROR');
    }
  }
};
xhr.send(null);

Note: Keep in mind that when you do Ajax requests, you are restricted by the Same origin policy, which allows you to make requests only within the same domain.

Check a working proof of concept here.

Edit 3:

1.) About the Content-Length, I think that a size mismatch could happen for example if the server response is gzipped, you can do some tests to see if this happens on your server.

2.) For get the original dimensions of a image, you could create an IMG element programmatically, for example:

var img = document.createElement('img');

img.onload = function () { alert(img.width + ' x ' + img.height); };

img.src='http://sstatic.net/so/img/logo.png';

How to scroll to top of a div using jQuery?

Special thanks to Stoic for

   $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});

Maven: Command to update repository after adding dependency to POM

Right, click on the project. Go to Maven -> Update Project.

The dependencies will automatically be installed.

What is the difference between MOV and LEA?

MOV can do same thing as LEA [label], but MOV instruction contain the effective address inside the instruction itself as an immediate constant (calculated in advance by the assembler). LEA uses PC-relative to calculate the effective address during the execution of the instruction.

How to add buttons like refresh and search in ToolBar in Android?

Try to do this:

getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);

and if you made your custom toolbar (which i presume you did) then you can use the simplest way possible to do this:

toolbarTitle = (TextView)findViewById(R.id.toolbar_title);
toolbarSubTitle = (TextView)findViewById(R.id.toolbar_subtitle);
toolbarTitle.setText("Title");
toolbarSubTitle.setText("Subtitle");

Same goes for any other views you put in your toolbar. Hope it helps.

Sending credentials with cross-domain posts?

You can use the beforeSend callback to set additional parameters (The XMLHTTPRequest object is passed to it as its only parameter).

Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:

$.ajax({
    url: 'http://bar.other',
    data: { whatever:'cool' },
    type: 'GET',
    beforeSend: function(xhr){
       xhr.withCredentials = true;
    }
});

One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

The Request Payload - or to be more precise: payload body of a HTTP Request - is the data normally send by a POST or PUT Request. It's the part after the headers and the CRLF of a HTTP Request.

A request with Content-Type: application/json may look like this:

POST /some-path HTTP/1.1
Content-Type: application/json

{ "foo" : "bar", "name" : "John" }

If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.

If you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data your request may look like this:

POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded

foo=bar&name=John

In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.

So, they differ in the Content-Type but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.

Calculating bits required to store decimal number

There are a lot of answers here, but I'll add my approach since I found this post while working on the same problem.

Starting with what we know here are the number from 0 to 16.

Number           encoded in bits         minimum number of bits to encode
0                000000                  1
1                000001                  1
2                000010                  2
3                000011                  2
4                000100                  3
5                000101                  3
6                000110                  3
7                000111                  3
8                001000                  4
9                001001                  4
10               001010                  4
11               001011                  4
12               001100                  4
13               001101                  4
14               001110                  4
15               001111                  4
16               010000                  5

looking at the breaks, it shows this table

number <=       number of bits
1               0
3               2
7               3
15              4

So, now how do we compute the pattern?

Remember that log base 2 (n) = log base 10 (n) / log base 10 (2)

number    logb10 (n)   logb2 (n)   ceil[logb2(n)] 
1         0            0           0           (special case)
3         0.477        1.58        2
7         0.845        2.807       3  
8         0.903        3           3           (special case)
15        1.176        3.91        4
16        1.204        4           4           (special case)
31        1.491        4.95        5
63        1.799        5.98        6

Now the desired result matching the first table. Notice how also some values are special cases. 0 and any number which is a powers of 2. These values dont change when you apply ceiling so you know you need to add 1 to get the minimum bit field length.

To account for the special cases add one to the input. The resulting code implemented in python is:

from math import log
from math import ceil
def min_num_bits_to_encode_number(a_number):
    a_number=a_number+1  # adjust by 1 for special cases

    # log of zero is undefined
    if 0==a_number:
        return 0
    num_bits = int(ceil(log(a_number,2)))  # logbase2 is available
    return (num_bits)

Traverse all the Nodes of a JSON Object Tree with JavaScript

Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.

function traverse(o, fn) {
    const stack = [o]

    while (stack.length) {
        const obj = stack.shift()

        Object.keys(obj).forEach((key) => {
            fn(key, obj[key], obj)
            if (obj[key] instanceof Object) {
                stack.unshift(obj[key])
                return
            }
        })
    }
}

const o = {
    name: 'Max',
    legal: false,
    other: {
        name: 'Maxwell',
        nested: {
            legal: true
        }
    }
}

const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)

length and length() in Java

In Java, an Array stores its length separately from the structure that actually holds the data. When you create an Array, you specify its length, and that becomes a defining attribute of the Array. No matter what you do to an Array of length N (change values, null things out, etc.), it will always be an Array of length N.

A String's length is incidental; it is not an attribute of the String, but a byproduct. Though Java Strings are in fact immutable, if it were possible to change their contents, you could change their length. Knocking off the last character (if it were possible) would lower the length.

I understand this is a fine distinction, and I may get voted down for it, but it's true. If I make an Array of length 4, that length of four is a defining characteristic of the Array, and is true regardless of what is held within. If I make a String that contains "dogs", that String is length 4 because it happens to contain four characters.

I see this as justification for doing one with an attribute and the other with a method. In truth, it may just be an unintentional inconsistency, but it's always made sense to me, and this is always how I've thought about it.

how to use DEXtoJar

  1. Download dex2jar https://code.google.com/p/dex2jar/downloads/list
  2. Run dex2jar on apk d2j-dex2jar.sh someApk.apk
  3. open jar file in JD GUI http://jd.benow.ca/

Follow this guide: https://code.google.com/p/dex2jar/wiki/UserGuide

--Update 10/11/2016--

Found this ClassyShark from Google's github pretty easy to view code from APK.

https://github.com/google/android-classyshark

// make sure that you downloaded release https://github.com/pxb1988/dex2jar/releases (for the ppl who coldnt find this link in /dex2jar/downloads/list

How to clear https proxy setting of NPM?

ok, "NPM config delete ..." is the right command for Windows environment, viceversa "NPM config rm ..." it is for Unix-like environment. Moreover, at least for me, it was mandatory to add the option "-g" because the command worked properly

MySQL DROP all tables, ignoring foreign keys

Drop all the tables from database with a single line from command line:

mysqldump -u [user_name] -p[password] -h [host_name] --add-drop-table --no-data [database_name] | grep ^DROP | mysql -u [user_name] -p[password] -h [host_name] [database_name]

Where [user_name], [password], [host_name] and [database_name] have to be replaced with a real data (user, password, host name, database name).

creating json object with variables

Try this to see how you can create a object from strings.

var firstName = "xx";
var lastName  = "xy";
var phone     = "xz";
var adress    = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

If someone has the same issue as I had - make sure that you don't install from the Ubuntu 14.04 repo onto a 12.04 machine - it gives this same error. Reinstalling from the proper repository fixed the issue.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

How to calculate number of days between two dates

This works for me:

_x000D_
_x000D_
const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .startOf('day')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_
);
_x000D_
_x000D_
_x000D_

What is the significance of 1/1/1753 in SQL Server?

Your great great great great great great great grandfather should upgrade to SQL Server 2008 and use the DateTime2 data type, which supports dates in the range: 0001-01-01 through 9999-12-31.

Round a double to 2 decimal places

Rounding a double is usually not what one wants. Instead, use String.format() to represent it in the desired format.

How do you use NSAttributedString?

An easier solution with attributed string extension.

extension NSMutableAttributedString {

    // this function attaches color to string    
    func setColorForText(textToFind: String, withColor color: UIColor) {
        let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

Try this and see (Tested in Swift 3 & 4)

let label = UILabel()
label.frame = CGRect(x: 120, y: 100, width: 200, height: 30)
let first = "first"
let second = "second"
let third = "third"
let stringValue = "\(first)\(second)\(third)"  // or direct assign single string value like "firstsecondthird"

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textToFind: first, withColor: UIColor.red)   // use variable for string "first"
attributedString.setColorForText(textToFind: "second", withColor: UIColor.green) // or direct string like this "second"
attributedString.setColorForText(textToFind: third, withColor: UIColor.blue)
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

Here is expected result:

enter image description here

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Goto Advanced tab----> data type of column---> Here change data type from DT_STR to DT_TEXT and column width 255. Now you can check it will work perfectly.

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

Self-references in object literals / initializers

The obvious, simple answer is missing, so for completeness:

But is there any way to have values in an object literal's properties depend on other properties declared earlier?

No. All of the solutions here defer it until after the object is created (in various ways) and then assign the third property. The simplest way is to just do this:

var foo = {
    a: 5,
    b: 6
};
foo.c = foo.a + foo.b;

All others are just more indirect ways to do the same thing. (Felix's is particularly clever, but requires creating and destroying a temporary function, adding complexity; and either leaves an extra property on the object or [if you delete that property] impacts the performance of subsequent property accesses on that object.)

If you need it to all be within one expression, you can do that without the temporary property:

var foo = function(o) {
    o.c = o.a + o.b;
    return o;
}({a: 5, b: 6});

Or of course, if you need to do this more than once:

function buildFoo(a, b) {
    var o = {a: a, b: b};
    o.c = o.a + o.b;
    return o;
}

then where you need to use it:

var foo = buildFoo(5, 6);

What is the difference between aggregation, composition and dependency?

An object associated with a composition relationship will not exist outside the containing object. Examples are an Appointment and the owner (a Person) or a Calendar; a TestResult and a Patient.

On the other hand, an object that is aggregated by a containing object can exist outside that containing object. Examples are a Door and a House; an Employee and a Department.

A dependency relates to collaboration or delegation, where an object requests services from another object and is therefor dependent on that object. As the client of the service, you want the service interface to remain constant, even if future services are offered.

Simple jQuery, PHP and JSONP example?

First of all you can't make a POST request using JSONP.

What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.

Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.

This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.

The best thing to do is adding &callback=? to you url.

At the server side you've got to make sure that your data is wrapped in this callback function.

ie.

echo $_GET['callback'] . '(' . $data . ')';

EDIT:

Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.

Replace Liam's line

 echo "{'fullname' : 'Jeff Hansen'}";

with

 echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

Anaconda Installed but Cannot Launch Navigator

I too faced a similar issue when I was not able to find the Anaconda Navigator Desktop app in the start menu. But do not worry , Go to start Menu and Type Anaconda Navigator. Now within the apps menu you will find anaconda navigator with its icon. Click on that. After clicking you will find a command prompt dialog opened and a .exe file runs on your machine. Wait till it completes.

The Anaconda Navigator app opens on your machine.

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

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.

Get a list of dates between two dates

This solution is working with MySQL 5.0
Create a table - mytable.
The schema does not material. What matters is the number of rows in it.
So, you can keep just one column of type INT with 10 rows, values - 1 to 10.

SQL:

set @tempDate=date('2011-07-01') - interval 1 day;
select
date(@tempDate := (date(@tempDate) + interval 1 day)) as theDate
from mytable x,mytable y
group by theDate
having theDate <= '2011-07-31';

Limitation: The maximum number of dates returned by above query will be
(rows in mytable)*(rows in mytable) = 10*10 = 100.

You can increase this range by changing form part in sql:
from mytable x,mytable y, mytable z
So, the range be 10*10*10 =1000 and so on.

C# Java HashMap equivalent

Let me help you understand it with an example of "codaddict's algorithm"

'Dictionary in C#' is 'Hashmap in Java' in parallel universe.

Some implementations are different. See the example below to understand better.

Declaring Java HashMap:

Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

Declaring C# Dictionary:

Dictionary<int, int> Pairs = new Dictionary<int, int>();

Getting a value from a location:

pairs.get(input[i]); // in Java
Pairs[input[i]];     // in C#

Setting a value at location:

pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i];    // in C#

An Overall Example can be observed from below Codaddict's algorithm.

codaddict's algorithm in Java:

import java.util.HashMap;

public class ArrayPairSum {

    public static void printSumPairs(int[] input, int k)
    {
        Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

        for (int i = 0; i < input.length; i++)
        {
            if (pairs.containsKey(input[i]))
                System.out.println(input[i] + ", " + pairs.get(input[i]));
            else
                pairs.put(k - input[i], input[i]);
        }

    }

    public static void main(String[] args)
    {
        int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
        printSumPairs(a, 10);

    }
}

Codaddict's algorithm in C#

using System;
using System.Collections.Generic;

class Program
{
    static void checkPairs(int[] input, int k)
    {
        Dictionary<int, int> Pairs = new Dictionary<int, int>();

        for (int i = 0; i < input.Length; i++)
        {
            if (Pairs.ContainsKey(input[i]))
            {
                Console.WriteLine(input[i] + ", " + Pairs[input[i]]);
            }
            else
            {
                Pairs[k - input[i]] = input[i];
            }
        }
    }
    static void Main(string[] args)
    {
        int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
        //method : codaddict's algorithm : O(n)
        checkPairs(a, 10);
        Console.Read();
    }
}

Removing time from a Date object?

May be the below code may help people who are looking for zeroHour of the day :

    Date todayDate = new Date();
    GregorianCalendar todayDate_G = new GregorianCalendar();
    gcd.setTime(currentDate);
    int _Day    = todayDate_GC.get(GregorianCalendar.DAY_OF_MONTH);
    int _Month  = todayDate_GC.get(GregorianCalendar.MONTH);
    int _Year   = todayDate_GC.get(GregorianCalendar.YEAR);

    GregorianCalendar newDate = new GregorianCalendar(_Year,_Month,_Day,0,0,0);
    zeroHourDate = newDate.getTime();
    long zeroHourDateTime = newDate.getTimeInMillis();

Hope this will be helpful.

Quicksort: Choosing the pivot

I recommend using the middle index, as it can be calculated easily.

You can calculate it by rounding (array.length / 2).

How to select rows for a specific date, ignoring time in SQL Server

Try this:

true
select cast(salesDate as date) [date] from sales where salesDate = '2010/11/11'
false
select cast(salesDate as date) [date] from sales where salesDate = '11/11/2010'

Get the time difference between two datetimes

DATE TIME BASED INPUT

    var dt1 = new Date("2019-1-8 11:19:16");
    var dt2 = new Date("2019-1-8 11:24:16");


    var diff =(dt2.getTime() - dt1.getTime()) ;
    var hours = Math.floor(diff / (1000 * 60 * 60));
    diff -= hours * (1000 * 60 * 60);
    var mins = Math.floor(diff / (1000 * 60));
    diff -= mins * (1000 * 60);


    var response = {
        status : 200,
        Hour : hours,
        Mins : mins
    }

OUTPUT

{
"status": 200,
"Hour": 0,
"Mins": 5
}

Laravel Check If Related Model Exists

Not sure if this has changed in Laravel 5, but the accepted answer using count($data->$relation) didn't work for me, as the very act of accessing the relation property caused it to be loaded.

In the end, a straightforward isset($data->$relation) did the trick for me.

EOL conversion in notepad ++

In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.

(\r?\n)|(\r\n?)

to

\n

This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)

To operate on multiple files, either:

  • Use "Replace All in all opened document" in "Replace" tab. You will have to drag and drop all files into Notepad++ first. It's good that you will have control over which file to operate on but can be slow if there several hundreds or thousands files.
  • "Replace in files" in "Find in files" tab, by file filter of you choice, e.g., *.cpp *.cs under one specified directory.

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Jquery: Checking to see if div contains text, then action

Why not simply

var item = $('.field-item');
for (var i = 0; i <= item.length; i++) {
       if ($(item[i]).text() == 'someText') {
             $(item[i]).addClass('thisClass');
             //do some other stuff here
          }
     }

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):

public static bool CheckObjectImpl(object o)
{
    return o != null;
}

public static bool CheckNullableImpl<T>(T? o) where T: struct
{
    return o.HasValue;
}

Benchmark test:

BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Clr    : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Core   : .NET Core 4.6.25009.03, 64bit RyuJIT


        Method |  Job | Runtime |       Mean |     Error |    StdDev |        Min |        Max |     Median | Rank |  Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
   CheckObject |  Clr |     Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns |    3 | 0.0060 |      24 B |
 CheckNullable |  Clr |     Clr |  0.0029 ns | 0.0088 ns | 0.0082 ns |  0.0000 ns |  0.0315 ns |  0.0000 ns |    1 |      - |       0 B |
   CheckObject | Core |    Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns |    2 | 0.0060 |      24 B |
 CheckNullable | Core |    Core |  0.0007 ns | 0.0021 ns | 0.0016 ns |  0.0000 ns |  0.0054 ns |  0.0000 ns |    1 |      - |       0 B |

Benchmark code:

public class BenchmarkNullableCheck
{
    static int? x = (new Random()).Next();

    public static bool CheckObjectImpl(object o)
    {
        return o != null;
    }

    public static bool CheckNullableImpl<T>(T? o) where T: struct
    {
        return o.HasValue;
    }

    [Benchmark]
    public bool CheckObject()
    {
        return CheckObjectImpl(x);
    }

    [Benchmark]
    public bool CheckNullable()
    {
        return CheckNullableImpl(x);
    }
}

https://github.com/dotnet/BenchmarkDotNet was used

So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object - and use their specific properties - do it and use Nullable specific properties. So from consistent thinking point of view HasValue should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.

PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?

public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
    return t != null; // or t.HasValue?
}

PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl. I will tell you: there compiler will not help you replacing !=null with HasValue. HasValue should be used directly if you are interested in performance.

How do you round UP a number in Python?

I'm surprised I haven't seen this answer yet round(x + 0.4999), so I'm going to put it down. Note that this works with any Python version. Changes made to the Python rounding scheme has made things difficult. See this post.

Without importing, I use:

def roundUp(num):
    return round(num + 0.49)

testCases = list(x*0.1 for x in range(0, 50))

print(testCases)
for test in testCases:
    print("{:5.2f}  -> {:5.2f}".format(test, roundUp(test)))

Why this works

From the docs

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done toward the even choice

Therefore 2.5 gets rounded to 2 and 3.5 gets rounded to 4. If this was not the case then rounding up could be done by adding 0.5, but we want to avoid getting to the halfway point. So, if you add 0.4999 you will get close, but with enough margin to be rounded to what you would normally expect. Of course, this will fail if the x + 0.4999 is equal to [n].5000, but that is unlikely.

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

how to select rows based on distinct values of A COLUMN only

Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:

;WITH DistinctMails AS
(
    SELECT ID, MailID, EMailAddress, NAME,
        ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'
    FROM dbo.YourMailTable
)
SELECT *
FROM DistinctMails
WHERE RowNum = 1

This works on SQL Server 2005 and newer (you didn't mention what version you're using...)

Convert String[] to comma separated string in java

This my be helpful!!!

private static String convertArrayToString(String [] strArray) {
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i<= strArray.length-1; i++) {
                if(i == strArray.length-1) {
                    builder.append("'"+strArray[i]+"'");
                }else {
                    builder.append("'"+strArray[i]+"'"+",");
                }
            }
            return builder.toString();
        }

Convert an integer to an array of digits

I can not add comments to the decision of Vladimir, but you can immediately make an array deployed in the right direction. Here is my solution:

public static int[] splitAnIntegerIntoAnArrayOfNumbers (int a) {
    int temp = a;
    ArrayList<Integer> array = new ArrayList<Integer>();
    do{
        array.add(temp % 10);
        temp /= 10;
    } while  (temp > 0);

    int[] arrayOfNumbers = new int[array.size()];
    for(int i = 0, j = array.size()-1; i < array.size(); i++,j--) 
        arrayOfNumbers [j] = array.get(i);
    return arrayOfNumbers;
}

Important: This solution will not work for negative integers.

Calling a JSON API with Node.js

Another solution is to user axios:

npm install axios

Code will be like:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;

Executing JavaScript without a browser?

Main Answer

Yes, to answer your question, it is possible to use JavaScript as a "regular" scripting language from the command line, without a browser. Since others have not mentioned it yet, I see that it is worth mentioning:

On Debian-based systems (and this includes Ubuntu, Linux Mint, and aptosid/sidux, at least), besides the options of installing Rhino and others already mentioned, you have have other options:

  • Install the libmozjs-24-bin package, which will provide you with Mozilla's Spidermonkey engine on the command line as a simple js24, which can be used also as an interactive interpreter. (The 24 in the name means that it corresponds to version 24 of Firefox).

  • Install the libv8-dev package, which will provide you Google's V8 engine. It has, as one of its examples, the file /usr/share/doc/libv8-dev/examples/shell.cc.gz which you can uncompress and compile very simply (e.g., g++ -Os shell.cc -o shell -lv8).

  • Install the package nodejs and it will be available both as the executable nodejs and as an alternative (in the Debian-sense) to provide the js executable. JIT compilation is provided as a courtesy of V8.

  • Install the package libjavascriptcoregtk-3.0-bin and use WebKit's JavaScriptCore interpreter (jsc) as a regular interpreter from the command-line. And this is without needing to have access to a Mac. On many platforms (e.g., x86 and x86_64), this interpreter will come with a JIT compiler.

So, with almost no compilation you will have three of the heavy-weight JavaScript engines at your disposal.

Addendum

Once you have things installed, you can simply create files with the #!/usr/bin/js shebang line and things will just work:

$ cat foo.js 
#!/usr/bin/js

console.log("Hello, world!");
$ ls -lAF /usr/bin/js /etc/alternatives/js /usr/bin/nodejs
lrwxrwxrwx 1 root root      15 Jul 16 04:26 /etc/alternatives/js -> /usr/bin/nodejs*
lrwxrwxrwx 1 root root      20 Jul 16 04:26 /usr/bin/js -> /etc/alternatives/js*
-rwxr-xr-x 1 root root 1422004 Apr 28 20:31 /usr/bin/nodejs*
$ chmod a+x foo.js 
$ ./foo.js 
Hello, world!
$ js ./foo.js
Hello, world!
$

Handling exceptions from Java ExecutorService tasks

I'm using VerboseRunnable class from jcabi-log, which swallows all exceptions and logs them. Very convenient, for example:

import com.jcabi.log.VerboseRunnable;
scheduler.scheduleWithFixedDelay(
  new VerboseRunnable(
    Runnable() {
      public void run() { 
        // the code, which may throw
      }
    },
    true // it means that all exceptions will be swallowed and logged
  ),
  1, 1, TimeUnit.MILLISECONDS
);

Visual Studio SignTool.exe Not Found

Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.

Laravel 5 Carbon format datetime

Just use the date() and strtotime() function and save your time

$suborder['payment_date'] = date('d-m-Y', strtotime($item['created_at']));

Don't stress!!!

Kill Attached Screen in Linux

None of the screen commands were killing or reattaching the screen for me. Any screen command would just hang. I found another approach.

Each running screen has a file associated with it in:

/var/run/screen/S-{user_name}

The files in that folder will match the names of the screens when running the screen -list. If you delete the file, it kills the associated running screen (detached or attached).

Is Python faster and lighter than C++?

Source size is not really a sensible thing to measure. For example, the following shell script:

cat foobar

is much shorter than either its Python or C++ equivalents.

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

Here's simple solution for those who want a quick filter against an object:

<select>
  <option ng-repeat="card in deck.Cards | filter: {Type: 'Face'}">{{card.Name}}</option>
</select>

The array filter lets you mimic the object you are trying to filter. In the above case, the following classes would work just fine:

var card = function(name, type) {
  var _name = name;
  var _type = type;

  return {
    Name: _name,
    Type: _type
  };
};

And where the deck might look like:

var deck = function() {
  var _cards = [new card('Jack', 'Face'),
                new card('7', 'Numeral')];

  return {
    Cards: _cards
  };
};

And if you want to filter multiple properties of the object just separate field names by a comma:

<select>
  <option ng-repeat="card in deck.Cards | filter: {Type: 'Face', Name: 'Jack'}">{{card.Name}}</option>
</select>

EDIT: Here's a working plnkr that provides an example of single and multiple property filters:

http://embed.plnkr.co/i0wCx6l1WPYljk57SXzV/

Avoid dropdown menu close on click inside

$('body').on("click", ".dropdown-menu", function (e) {
    $(this).parent().is(".open") && e.stopPropagation();
});

This may work for any conditions.

How to add and get Header values in WebApi

Suppose we have a API Controller ProductsController : ApiController

There is a Get function which returns some value and expects some input header (for eg. UserName & Password)

[HttpGet]
public IHttpActionResult GetProduct(int id)
{
    System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
    string token = string.Empty;
    string pwd = string.Empty;
    if (headers.Contains("username"))
    {
        token = headers.GetValues("username").First();
    }
    if (headers.Contains("password"))
    {
        pwd = headers.GetValues("password").First();
    }
    //code to authenticate and return some thing
    if (!Authenticated(token, pwd)
        return Unauthorized();
    var product = products.FirstOrDefault((p) => p.Id == id);
    if (product == null)
    {
        return NotFound();
    }
    return Ok(product);
}

Now we can send the request from page using JQuery:

$.ajax({
    url: 'api/products/10',
    type: 'GET',
    headers: { 'username': 'test','password':'123' },
    success: function (data) {
        alert(data);
    },
    failure: function (result) {
        alert('Error: ' + result);
    }
});

Hope this helps someone ...

Laravel where on relationship object

@Cermbo's answer is not related to this question. In their answer, Laravel will give you all Events if each Event has 'participants' with IdUser of 1.

But if you want to get all Events with all 'participants' provided that all 'participants' have a IdUser of 1, then you should do something like this :

Event::with(["participants" => function($q){
    $q->where('participants.IdUser', '=', 1);
}])

N.B:

in where use your table name, not Model name.

IOError: [Errno 2] No such file or directory trying to open a file

Just as an FYI, here is my working code:

src_dir = "C:\\temp\\CSV\\"
target_dir = "C:\\temp\\output2\\"
keyword = "KEYWORD"

for f in os.listdir(src_dir):
    file_name = os.path.join(src_dir, f)
    out_file = os.path.join(target_dir, f)
    with open(file_name, "r+") as fi, open(out_file, "w") as fo:
        for line in fi:
            if keyword not in line:
                fo.write(line)

Thanks again to everyone for all the great feedback!

Difference between an API and SDK

How about... It's like if you wanted to install a home theatre system in your house. Using an API is like getting all the wires, screws, bits, and pieces. The possibilities are endless (constrained only by the pieces you receive), but sometimes overwhelming. An SDK is like getting a kit. You still have to put it together, but it's more like getting pre-cut pieces and instructions for an IKEA bookshelf than a box of screws.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

It is possible for the TCP socket to be "closing" and your code to not have yet been notified.

Here is a animation for the life cycle. http://tcp.cs.st-andrews.ac.uk/index.shtml?page=connection_lifecycle

Basically, the connection was closed by the client. You already have throws IOException and SocketException extends IOException. This is working just fine. You just need to properly handle IOException because it is a normal part of the api.

EDIT: The RST packet occurs when a packet is received on a socket which does not exist or was closed. There is no difference to your application. Depending on the implementation the reset state may stick and closed will never officially occur.

SQL Server - stop or break execution of a SQL script

you could wrap your SQL statement in a WHILE loop and use BREAK if needed

WHILE 1 = 1
BEGIN
   -- Do work here
   -- If you need to stop execution then use a BREAK


    BREAK; --Make sure to have this break at the end to prevent infinite loop
END

X-Frame-Options: ALLOW-FROM in firefox and chrome

ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?

Generate a unique id

This question seems to be answered, however for completeness, I would add another approach.

You can use a unique ID number generator which is based on Twitter's Snowflake id generator. C# implementation can be found here.

var id64Generator = new Id64Generator();

// ...

public string generateID(string sourceUrl)
{
    return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}

Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.

// node 0
var id64Generator = new Id64Generator(0);

// node 1
var id64Generator = new Id64Generator(1);

// ... node 10
var id64Generator = new Id64Generator(10);

How to make a smooth image rotation in Android?

In Android, if you want to animate an object and make it move an object from location1 to location2, the animation API figures out the intermediate locations (tweening) and then queues onto the main thread the appropriate move operations at the appropriate times using a timer. This works fine except that the main thread is usually used for many other things — painting, opening files, responding to user inputs etc. A queued timer can often be delayed. Well written programs will always try to do as many operations as possible in background (non main) threads however you can’t always avoid using the main thread. Operations that require you to operate on a UI object always have to be done on the main thread. Also, many APIs will funnel operations back to the main thread as a form of thread-safety.

Views are all drawn on the same GUI thread which is also used for all user interaction.

So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use SurfaceView.

Example of rotation image:

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    private DrawThread drawThread;

    public MySurfaceView(Context context) {
        super(context);
        getHolder().addCallback(this);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {   
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        drawThread = new DrawThread(getHolder(), getResources());
        drawThread.setRunning(true);
        drawThread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        drawThread.setRunning(false);
        while (retry) {
            try {
                drawThread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
    }
}


class DrawThread extends Thread{
    private boolean runFlag = false;
    private SurfaceHolder surfaceHolder;
    private Bitmap picture;
    private Matrix matrix;
    private long prevTime;

    public DrawThread(SurfaceHolder surfaceHolder, Resources resources){
        this.surfaceHolder = surfaceHolder;

        picture = BitmapFactory.decodeResource(resources, R.drawable.icon);

        matrix = new Matrix();
        matrix.postScale(3.0f, 3.0f);
        matrix.postTranslate(100.0f, 100.0f);

        prevTime = System.currentTimeMillis();
    }

    public void setRunning(boolean run) {
        runFlag = run;
    }

    @Override
    public void run() {
        Canvas canvas;
        while (runFlag) {
            long now = System.currentTimeMillis();
            long elapsedTime = now - prevTime;
            if (elapsedTime > 30){

                prevTime = now;
                matrix.preRotate(2.0f, picture.getWidth() / 2, picture.getHeight() / 2);
            }
            canvas = null;
            try {
                canvas = surfaceHolder.lockCanvas(null);
                synchronized (surfaceHolder) {
                    canvas.drawColor(Color.BLACK);
                    canvas.drawBitmap(picture, matrix, null);
                }
            } 
            finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }
            }
        }
    }
}

activity:

public class SurfaceViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MySurfaceView(this));
    }
}

How to use NSJSONSerialization

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

In above JSON data, you are showing that we have an array contaning the number of dictionaries.

You need to use this code for parsing it:

NSError *e = nil;
NSArray *JSONarray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
        for(int i=0;i<[JSONarray count];i++)
        {
            NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"id"]);
             NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"name"]);
        }

For swift 3/3+

   //Pass The response data & get the Array
    let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
    print(jsonData)
    // considering we are going to get array of dictionary from url

    for  item  in jsonData {
        let dictInfo = item as! [String:AnyObject]
        print(dictInfo["id"])
        print(dictInfo["name"])
    }

How to determine day of week by passing specific date?

This works correctly...

java.time.LocalDate; //package related to time and date

It provides inbuilt method getDayOfWeek() to get the day of a particular week:

int t;
Scanner s = new Scanner(System.in);
t = s.nextInt();
s.nextLine();
 while(t-->0) { 
    int d, m, y;
    String ss = s.nextLine();
    String []sss = ss.split(" ");
    d=Integer.parseInt(sss[0]);
    m = Integer.parseInt(sss[1]);
    y = Integer.parseInt(sss[2]);

    LocalDate l = LocalDate.of(y, m, d); //method to get the localdate instance
    System.out.println(l.getDayOfWeek()); //this returns the enum DayOfWeek

To assign the value of enum l.getDayOfWeek() to a string, you could probably use the method of Enum called name() that returns the value of enum object.

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

GlobalConfiguration class is part of Microsoft.AspNet.WebApi.WebHost nuget package...Have you upgraded this package to Web API 2?

Remove substring from the string

If you are using Rails there's also remove.

E.g. "Testmessage".remove("message") yields "Test".

Warning: this method removes all occurrences

Why is Python running my module when I import it, and how do I stop it?

Put the code inside a function and it won't run until you call the function. You should have a main function in your main.py. with the statement:

if __name__ == '__main__':
  main()

Then, if you call python main.py the main() function will run. If you import main.py, it will not. Also, you should probably rename main.py to something else for clarity's sake.

App crashing when trying to use RecyclerView on android 5.0

I got this issue due to wrong reference of RecyclerView id.

recyclerView = (RecyclerView) findViewById(R.id.rv_followers_list);

to

recyclerView = (RecyclerView) findViewById(R.id.rv_search_list);

How do I register a .NET DLL file in the GAC?

I tried just about everything in the comments and it didn't work. So I did gacutil /i "path to my dll" from Powershell and it worked.

Also remember the trick of pressing Shift when you right-click on a file in Windows Explorer to get the option of Copy path.

Random color generator

function getRandomColor()
{
    var color = "#";

    for (var i = 0; i < 3; i++)
    {
        var part = Math.round(Math.random() * 255).toString(16);

        color += (part.length > 1) ? part : "0" + part;
    }

    return color;
}

Attaching click to anchor tag in angular

You can use routerLink which is an alternative of href for angular 2.** Use routerLink as below in html

<a routerLink="/dashboard">My Link</a>

and make sure you register your routerLink in modules.ts or router.ts like this

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent }
]

Java - What does "\n" mean?

Its is a new line

Escape Sequences
Escape Sequence Description
\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

Searching for file in directories recursively

You could use this overload of Directory.GetFiles which searches subdirectories for you, for example:

string[] files = Directory.GetFiles(sDir, "*.xml", SearchOption.AllDirectories);

Only one extension can be searched for like that, but you could use something like:

var extensions = new List<string> { ".txt", ".xml" };
string[] files = Directory.GetFiles(sDir, "*.*", SearchOption.AllDirectories)
                    .Where(f => extensions.IndexOf(Path.GetExtension(f)) >= 0).ToArray();

to select files with the required extensions (N.B. that is case-sensitive for the extension).


In some cases it can be desirable to enumerate over the files with the Directory.EnumerateFiles Method:

foreach(string f in Directory.EnumerateFiles(sDir, "*.xml", SearchOption.AllDirectories))
{
    // do something
}

Consult the documentation for exceptions which can be thrown, such as UnauthorizedAccessException if the code is running under an account which does not have appropriate access permissions.

How to upgrade Angular CLI to the latest version

This command works fine:

npm upgrade -g @angular/cli

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Like @Mullins said "
I both added the items and called notifyDataSetChanged() in the UI thread and I resolved this. – Mullins".

In my case I have asynctask and I called notifyDataSetChanged() in the doInBackground() method and the problem is solved, when I called from onPostExecute() I received the exception.

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

I am using Spring Boot 2.2.6(Windows) and faced the same issue when I tried the run the application: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

What solved my problem:

  1. Create a new user (from the MySQL workbench or a similar GUI which you might be using)
  2. Grant DBA priviledges (Tick the DBA checkbox) also from the GUI
  3. Run the spring boot application.

Or follow the @evg solution to grant privilegdes from command line in Linux env.

Can't change table design in SQL Server 2008

Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".

Check if a key exists inside a json object

This code causes esLint issue: no-prototype-builtins

foo.hasOwnProperty("bar") 

The suggest way here is:

Object.prototype.hasOwnProperty.call(foo, "bar");

How can I use grep to show just filenames on Linux?

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case.

How to get PID of process by specifying process name and store it in a variable to use further?

If you want to kill -9 based on a string (you might want to try kill first) you can do something like this:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'

This will show you what you're about to kill (very, very important) and just pipe it to sh when the time comes to execute:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh

git discard all changes and pull from upstream

while on branch master: git reset --hard origin/master

then do some clean up with git gc (more about this in the man pages)

Update: You will also probably need to do a git fetch origin (or git fetch origin master if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)

Count the number of occurrences of a string in a VARCHAR field?

A little bit simpler and more effective variation of @yannis solution:

SELECT 
    title,
    description,    
    CHAR_LENGTH(description) - CHAR_LENGTH( REPLACE ( description, 'value', '1234') ) 
        AS `count`    
FROM <table> 

The difference is that I replace the "value" string with a 1-char shorter string ("1234" in this case). This way you don't need to divide and round to get an integer value.

Generalized version (works for every needle string):

SET @needle = 'value';
SELECT 
    description,    
    CHAR_LENGTH(description) - CHAR_LENGTH(REPLACE(description, @needle, SPACE(LENGTH(@needle)-1))) 
        AS `count`    
FROM <table> 

How to launch an application from a browser?

Some applications launches themselves by protocols. like itunes with "itms://" links. I don't know however how you can register that with windows.

How can I check if a date is the same day as datetime.today()?

If you want to just compare dates,

yourdatetime.date() < datetime.today().date()

Or, obviously,

yourdatetime.date() == datetime.today().date()

If you want to check that they're the same date.

The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about. Unless your question is about a function/module named "snake".

Basically, the datetime module has three types for storing a point in time:

  • date for year, month, day of month
  • time for hours, minutes, seconds, microseconds, time zone info
  • datetime combines date and time. It has the methods date() and time() to get the corresponding date and time objects, and there's a handy combine function to combine date and time into a datetime.

How to resolve git's "not something we can merge" error

I had this issue as well. The branch looked like 'username/master' which seemed to confuse git as it looked like a remote address I defined. For me using this

git merge origin/username/master

worked perfectly fine.

Disposing WPF User Controls

You have to be careful using the destructor. This will get called on the GC Finalizer thread. In some cases the resources that your freeing may not like being released on a different thread from the one they were created on.

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

Copy struct to struct in C

memcpy expects the first two arguments to be void*.

Try: memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );

P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.

How to check version of python modules?

Building on Jakub Kukul's answer I found a more reliable way to solve this problem.

The main problem of that approach is that requires the packages to be installed "conventionally" (and that does not include using pip install --user), or be in the system PATH at Python initialisation.

To get around that you can use pkg_resources.find_distributions(path_to_search). This basically searches for distributions that would be importable if path_to_search was in the system PATH.

We can iterate through this generator like this:

avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
    avail_modules[d.key] = d.version

This will return a dictionary having modules as keys and their version as value. This approach can be extended to a lot more than version number.

Thanks to Jakub Kukul for pointing to the right direction

How do you easily horizontally center a <div> using CSS?

you can use margin: 0 auto on your css instead of margin-left: auto; margin-right: auto;

How do I time a method's execution in Java?

I go with the simple answer. Works for me.

long startTime = System.currentTimeMillis();

doReallyLongThing();

long endTime = System.currentTimeMillis();

System.out.println("That took " + (endTime - startTime) + " milliseconds");

It works quite well. The resolution is obviously only to the millisecond, you can do better with System.nanoTime(). There are some limitations to both (operating system schedule slices, etc.) but this works pretty well.

Average across a couple of runs (the more the better) and you'll get a decent idea.

Iterating over dictionaries using 'for' loops

When you iterate through dictionaries using the for .. in ..-syntax, it always iterates over the keys (the values are accessible using dictionary[key]).

To iterate over key-value pairs, in Python 2 use for k,v in s.iteritems(), and in Python 3 for k,v in s.items().

How do shift operators work in Java?

It will shift the bits by padding that many 0's.

For ex,

  • binary 10 which is digit 2 left shift by 2 is 1000 which is digit 8
  • binary 10 which is digit 2 left shift by 3 is 10000 which is digit 16

Android 6.0 Marshmallow. Cannot write to SD Card

Maybe you cannot use manifest class from generated code in your project. So, you can use manifest class from android sdk "android.Manifest.permission.WRITE_EXTERNAL_STORAGE". But in Marsmallow version have 2 permission must grant are WRITE and READ EXTERNAL STORAGE in storage category. See my program, my program will request permission until user choose yes and do something after permissions is granted.

            if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(LoginActivity.this,
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                            1);
                } else {
                    //do something
                }
            } else {
                    //do something
            }

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

How can I use iptables on centos 7?

Last month I tried to configure iptables on a LXC VM container, but every time after reboot the iptables configuration was not automatically loaded.

The only way for me to get it working was by running the following command:

yum -y install iptables-services; systemctl disable firewalld; systemctl mask firewalld; service iptables restart; service iptables save

Download and install an ipa from self hosted url on iOS

NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&amp;url=https://xxxxxx.com/rest/images/apps/ipa/dev/xyz.plist"]];
[[UIApplication sharedApplication] openURL:url];

openUrl method was deprecated.

[[UIApplication sharedApplication] openURL: url options:@{} completionHandler:nil];

This method latest openUrl method and it will display prompt dialog.The dialog will show

xxxxxx.com would like to install "YOUR_APP_NAME"

this messages. If you click the "install" button application will close and ipa will download.

How to add font-awesome to Angular 2 + CLI project

UPDATE Feb 2020:
fortawesome package now supports ng add but it is available only for angular 9:

ng add @fortawesome/angular-fontawesome

UPDATE 8 Oct 2019:

You can use a new package https://www.npmjs.com/package/@fortawesome/angular-fontawesome

npm install @fortawesome/angular-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons

Add FontAwesomeModule to imports in src/app/app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
 
@NgModule({
  imports: [
    BrowserModule,
    FontAwesomeModule
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

Tie the icon to the property in your component src/app/app.component.ts:

import { Component } from '@angular/core';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  faCoffee = faCoffee;
}

Use the icon in the template src/app/app.component.html:

<fa-icon [icon]="faCoffee"></fa-icon>

ORIGINAL ANSWER:

Option 1:

You can use angular-font-awesome npm module

npm install --save font-awesome angular-font-awesome

Import the module:

...
//
import { AngularFontAwesomeModule } from 'angular-font-awesome';
@NgModule({
  //...
  imports: [
    //...
    AngularFontAwesomeModule
  ],
  //...
})
export class AppModule { }

If you're using Angular CLI, add the font-awesome CSS to styles inside the angular-cli.json

"styles": [
    "styles.css",
    "../node_modules/font-awesome/css/font-awesome.css"
],

NOTE: If using SCSS preprocessor just change the css for scss

Example Use:

<fa name="cog" animation="spin"></fa>

Option 2:

There is an official story for that now

Install the font-awesome library and add the dependency to package.json

npm install --save font-awesome

Using CSS

To add Font Awesome CSS icons to your app...

// in .angular-cli.json

"styles": [
  "styles.css",
  "../node_modules/font-awesome/css/font-awesome.css"
]

Using SASS

Create an empty file _variables.scss in src/.

Add the following to _variables.scss:

$fa-font-path : '../node_modules/font-awesome/fonts'; In styles.scss add the following:

@import 'variables';
@import '../node_modules/font-awesome/scss/font-awesome';

Test

Run ng serve to run your application in develop mode, and navigate to http://localhost:4200.

To verify Font Awesome has been set up correctly, change src/app/app.component.html to the following...

<h1>
  {{title}} <i class="fa fa-check"></i>
</h1>

After saving this file, return to the browser to see the Font Awesome icon next to the app title.

Also there is a related question Angular CLI outputs the font-awesome font files the dist root as by default angular cli outputs the fonts in to the dist root, which is by the way not an issue at all.

How to convert seconds to time format?

Use modulo:

$hours = $time_in_seconds / 3600;
$minutes = ($time_in_seconds / 60) % 60;

How do I disable the security certificate check in Python requests

If you want to send exactly post request with verify=False option, fastest way is to use this code:

import requests

requests.api.request('post', url, data={'bar':'baz'}, json=None, verify=False)

HtmlSpecialChars equivalent in Javascript?

I am elaborating a bit on o.k.w.'s answer.

You can use the browser's DOM functions for that.

var utils = {
    dummy: document.createElement('div'),
    escapeHTML: function(s) {
        this.dummy.textContent = s
        return this.dummy.innerHTML
    }
}

utils.escapeHTML('<escapeThis>&')

This returns &lt;escapeThis&gt;&amp;

It uses the standard function createElement to create an invisible element, then uses the function textContent to set any string as its content and then innerHTML to get the content in its HTML representation.

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

Cocoa: What's the difference between the frame and the bounds?

Frame vs bounds

  • If you create a view at X:0, Y:0, width:400, height:400, its frame and bounds are the same.
  • If you move that view to X:400, its frame will reflect that change but its bounds will not. Remember, the bounds is relative to the view’s own space, and internally to the view nothing has changed.
  • If you transform the view, e.g. rotating it or scaling it up, the frame will change to reflect that, but the bounds still won’t – as far as the view is concerned internally, it hasn’t changed.
  • If you change the bounds then it will change the content inside the frame because the origin of the bounds rectangle starts at a different part of the view.

SQL Server Configuration Manager not found

Go to this location C:\Windows\System32 and find SQLServerManager . Worked for me. Configuration manager was there but somehow wasn't showing up in search results.

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

If you are using windows 8.1, you might want to make sure that you are installing your npm modules with the correct visual studio compiler.

I have Visual Studio 2012 installed, this command works for me. (after deleting node_modules dir)

npm install --msvs_version=2012

For some reason, node-gyp is trying to use the incorrect version of Visual Studio compiler. I also noticed that the "npm install" command was printing out a warnings about not node-gyp dependencies when installing the mongodb and mongoose modules.

After using the correct msvs_version, the npm install warnings went away as well as the console warning when running my nodejs app.

You might also want to make sure that you have the correct Python 2.7.X version installed and not Python 3.0.X.

You will also need to make sure that python is in your env path.

Link to "pin it" on pinterest without generating a button

I Found some code for wordpress:

 <script type="text/javascript">

    function insert_pinterest($content) {
        global $post;
        $posturl = urlencode(get_permalink()); //Get the post URL
        $pinspan = '<span class="pinterest-button">';
     $pinurl = '';
     $pinend = '</span>';
        $pattern = '//i';
        $replacement = $pinspan.$pinurl.'$2.$3'.$pindescription.$pinfinish.''.$pinend;
        $content = preg_replace( $pattern, $replacement, $content );
        //Fix the link problem
        $newpattern = '/<span class="pinterest-button"><\/a><\/span><\/a>/i';
     $replacement = '';
     $content = preg_replace( $newpattern, $replacement, $content );
     return $content;
    }
    add_filter( 'the_content', 'insert_pinterest' );

    </script>

Then you put the following in your PHP:

<?php $pinterestimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); ?>
<a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php echo $pinterestimage[0]; ?>&description=<?php the_title(); ?>">Pin It</a>

Clone private git repo with dockerfile

Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.

As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY the required files into your final image.

Additionally if we LABEL our intermediate layers, we can even delete them from the machine when finished.

# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate

# Take an SSH key as a build argument.
ARG SSH_KEY

# Install dependencies required to git clone.
RUN apk update && \
    apk add --update git && \
    apk add --update openssh

# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
    echo "$SSH_KEY" > /root/.ssh/id_rsa && \
    chmod -R 600 /root/.ssh/ && \
    ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git

# Choose the base image for our final image
FROM alpine

# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md

We can then build:

MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .

Prove our SSH keys are gone:

docker run -ti --rm clone-example cat /root/.ssh/id_rsa

Clean intermediate images from the build machine:

docker rmi -f $(docker images -q --filter label=stage=intermediate)

Callback functions in Java

When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

Display tooltip on Label's hover?

You could use the title attribute in html :)

<label title="This is the full title of the label">This is the...</label>

When you keep the mouse over for a brief moment, it should pop up with a box, containing the full title.

If you want more control, I suggest you look into the Tipsy Plugin for jQuery - It can be found at http://onehackoranother.com/projects/jquery/tipsy/ and is fairly simple to get started with.

How to convert a String into an array of Strings containing one character each

You can use String.split(String regex):

String input = "aabbab";
String[] parts = input.split("(?!^)");

How to beautifully update a JPA entity in Spring Data?

Simple JPA update..

Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);

python selenium click on button

For python, use the

from selenium.webdriver import ActionChains

and

ActionChains(browser).click(element).perform()

Difference between Static and final?

Static is something that any object in a class can call, that inherently belongs to an object type.

A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.

Some example code:

class someClass
{
   public static int count=0;
   public final String mName;

   someClass(String name)
   {
     mname=name;
     count=count+1;
   }

  public static void main(String args[])
  {
    someClass obj1=new someClass("obj1");
    System.out.println("count="+count+" name="+obj1.mName);
    someClass obj2=new someClass("obj2");
    System.out.println("count="+count+" name="+obj2.mName);
  }
}

Wikipedia contains the complete list of java keywords.