Programs & Examples On #Waveform

Waveform means the shape and form of a signal such as a wave moving in a physical medium or an abstract representation

ASP.Net MVC 4 Form with 2 submit buttons/actions

We can have this in 2 ways,

Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within

ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons

Or

Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code

if (Request.Form["btnSubmit1"] != null)
{
 //
}
if (Request.Form["btnSubmit2"] != null)
{
 //
}

Close pre-existing figures in matplotlib when running from eclipse

You can close a figure by calling matplotlib.pyplot.close, for example:

from numpy import *
import matplotlib.pyplot as plt
from scipy import *

t = linspace(0, 0.1,1000)
w = 60*2*pi


fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)

You can also close all open figures by calling matplotlib.pyplot.close("all")

HTML5 Canvas background image

Why don't you style it out:

<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
  Your browser does not support the canvas element.
</canvas>

double free or corruption (!prev) error in c program

I didn't check all the code but my guess is that the error is in the malloc call. You have to replace

 double *ptr = malloc(sizeof(double*) * TIME);

for

 double *ptr = malloc(sizeof(double) * TIME);

since you want to allocate size for a double (not the size of a pointer to a double).

Play audio from a stream using C#

I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.

I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.

How to run Visual Studio post-build events for debug build only

Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName).

For instance

if $(ConfigurationName) == Debug xcopy something somewhere

How to determine if OpenSSL and mod_ssl are installed on Apache2

Usually, when you compile your apache2 server (or install it by packages facility stuff), you can check any directive that're available to be used by tapping this command:

~# $(which httpd) -L | grep SSL # on RHEL/CentOS/Fedora
~# $(which apache2) -L | grep SSL # on Ubuntu/Debian

If you don't see any SSL* directive, it means that you don't have apache2 with mod_ssl compiled.

Hopes it helps ;)

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

Altering a column: null to not null

For Oracle 11g, I was able to change the column attribute as follows:

ALTER TABLE tablename MODIFY columnname datatype NOT NULL;

Otherwise abatichev's answer seemed good. You can't repeat the alter - it complains (at least in SQL Developer) that the column is already not null.

HTTP Status 404 - The requested resource (/) is not available

Following steps helped me solve the issue.

  1. In the eclipse right click on server and click on properties.
  2. If Location is set workspace/metadata click on switch location and so that it refers to /servers/tomcatv7server at localhost.server
  3. Save and close
  4. Next double click on server
  5. Under server locations mostly it would be selected as use workspace metadata Instead, select use tomcat installation
  6. Save changes
  7. Restart server and verify localhost:8080 works.

Get timezone from DateTime

There is a public domain TimeZone library for .NET. Really useful. It will answer your needs.

Solving the general-case timezone problem is harder than you think.

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Propagation Delay vs Transmission delay

Obviously , packet length * propagation delay = trasmission delay is wrong.

Let us assume that you have a packet which has 4 bits 1010.You have to send it from A to B.

For this scenario,Transmission delay is the time taken by the sender to place the packet on the link(Transmission medium).Because the bits(1010) has to be converted in to signals.So it takes some time.Note that here only the packet is placed.It is not moving to receiver.

Propagation delay is the time taken by a bit(Mostly MSB ,Here 1) to reach from sender(A) to receiver(B).

How to put a delay on AngularJS instant search?

Why does everyone wants to use watch? You could also use a function:

var tempArticleSearchTerm;
$scope.lookupArticle = function (val) {
    tempArticleSearchTerm = val;

    $timeout(function () {
        if (val == tempArticleSearchTerm) {
            //function you want to execute after 250ms, if the value as changed

        }
    }, 250);
}; 

How to get the current location latitude and longitude in android

IMPORTANT:

Please notice this solution is from 2015 might be too old and deprecated.


None of the above worked for me so I made a tutorial and wrote it for myself since I lost many hours trying to implement this. Hope this helps someone:

How to use Google Play Services LOCATION API to get current latitude & longitude

1) Add to your AndroidManifest.xml file the ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >

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

        <application...

2) Go to app/build.gradlefile and add the following dependency (make sure to use the latest available version):

    dependencies {
        //IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
        compile 'com.google.android.gms:play-services-location:11.0.1
    }

3) In your activity implement the following:

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.GoogleMap;

    public class HomeActivity extends AppCompatActivity implements
            ConnectionCallbacks,
            OnConnectionFailedListener,
            LocationListener {

        //Define a request code to send to Google Play services
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private double currentLatitude;
        private double currentLongitude;


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

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    // The next two lines tell the new client that “this” current class will handle connection stuff
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    //fourth line adds the LocationServices API endpoint from GooglePlayServices
                    .addApi(LocationServices.API)
                    .build();

            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        }

        @Override
        protected void onResume() {
            super.onResume();
            //Now lets connect to the API
            mGoogleApiClient.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.v(this.getClass().getSimpleName(), "onPause()");

            //Disconnect from API onPause()
            if (mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                mGoogleApiClient.disconnect();
            }


        }

        /**
         * If connected get lat and long
         * 
         */
        @Override
        public void onConnected(Bundle bundle) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {
                //If everything went fine lets get latitude and longitude
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
            }
        }


        @Override
        public void onConnectionSuspended(int i) {}

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
                Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }

        /**
         * If locationChanges change lat and long
         * 
         * 
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }

    }

If you need more info just go to:

The Beginner’s Guide to Location in Android

Note: This doesn't seem to work in the emulator but works just fine on a device

How to sort List<Integer>?

To sort in ascending order :

Collections.sort(lList);

And for reverse order :

Collections.reverse(lList);

How do I dump the data of some SQLite3 tables?

The best method would be to take the code the sqlite3 db dump would do, excluding schema parts.

Example pseudo code:

SELECT 'INSERT INTO ' || tableName || ' VALUES( ' || 
  {for each value} ' quote(' || value || ')'     (+ commas until final)
|| ')' FROM 'tableName' ORDER BY rowid DESC

See: src/shell.c:838 (for sqlite-3.5.9) for actual code

You might even just take that shell and comment out the schema parts and use that.

Can you detect "dragging" in jQuery?

On mousedown, start set the state, if the mousemove event is fired record it, finally on mouseup, check if the mouse moved. If it moved, we've been dragging. If we've not moved, it's a click.

var isDragging = false;
$("a")
.mousedown(function() {
    isDragging = false;
})
.mousemove(function() {
    isDragging = true;
 })
.mouseup(function() {
    var wasDragging = isDragging;
    isDragging = false;
    if (!wasDragging) {
        $("#throbble").toggle();
    }
});

Here's a demo: http://jsfiddle.net/W7tvD/1399/

Swap two variables without using a temporary variable

Very simple code for swapping two variables:

static void Main(string[] args)
{
    Console.WriteLine("Prof.Owais ahmed");
    Console.WriteLine("Swapping two variables");

    Console.WriteLine("Enter your first number ");
    int x = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter your first number ");
    int y = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("your vlaue of x is="+x+"\nyour value of y is="+y);

    int z = x;
    x = y;
    y = z;

    Console.WriteLine("after Swapping value of x is="+x+"/nyour value of y is="+y);
    Console.ReadLine();
}

SQL Plus change current directory

Have you tried creating a windows shortcut for sql plus and set the working directory?

Breadth First Vs Depth First

Understanding the terms:

This picture should give you the idea about the context in which the words breadth and depth are used.

Understanding Breadth and Depth


Depth-First Search:

Depth-First Search

  • Depth-first search algorithm acts as if it wants to get as far away from the starting point as quickly as possible.

  • It generally uses a Stack to remember where it should go when it reaches a dead end.

  • Rules to follow: Push first vertex A on to the Stack

    1. If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
    2. If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
    3. If you can’t follow Rule 1 or Rule 2, you’re done.
  • Java code:

    public void searchDepthFirst() {
        // Begin at vertex 0 (A)
        vertexList[0].wasVisited = true;
        displayVertex(0);
        stack.push(0);
        while (!stack.isEmpty()) {
            int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
            // If no such vertex
            if (adjacentVertex == -1) {
                stack.pop();
            } else {
                vertexList[adjacentVertex].wasVisited = true;
                // Do something
                stack.push(adjacentVertex);
            }
        }
        // Stack is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Depth-first searches are often used in simulations of games (and game-like situations in the real world). In a typical game you can choose one of several possible actions. Each choice leads to further choices, each of which leads to further choices, and so on into an ever-expanding tree-shaped graph of possibilities.


Breadth-First Search:

Breadth-First Search

  • The breadth-first search algorithm likes to stay as close as possible to the starting point.
  • This kind of search is generally implemented using a Queue.
  • Rules to follow: Make starting Vertex A the current vertex
    1. Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
    2. If you can’t carry out Rule 1 because there are no more unvisited vertices, remove a vertex from the queue (if possible) and make it the current vertex.
    3. If you can’t carry out Rule 2 because the queue is empty, you’re done.
  • Java code:

    public void searchBreadthFirst() {
        vertexList[0].wasVisited = true;
        displayVertex(0);
        queue.insert(0);
        int v2;
        while (!queue.isEmpty()) {
            int v1 = queue.remove();
            // Until it has no unvisited neighbors, get one
            while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
                vertexList[v2].wasVisited = true;
                // Do something
                queue.insert(v2);
            }
        }
        // Queue is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++) 
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Breadth-first search first finds all the vertices that are one edge away from the starting point, then all the vertices that are two edges away, and so on. This is useful if you’re trying to find the shortest path from the starting vertex to a given vertex.

Hopefully that should be enough for understanding the Breadth-First and Depth-First searches. For further reading I would recommend the Graphs chapter from an excellent data structures book by Robert Lafore.

How to Add a Dotted Underline Beneath HTML Text

It's not impossible without CSS. For example as a list item:

<li style="border-bottom: 1px dashed"><!--content --></li>

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

Here is a simple expressjs solution if you just want to run this app locally and security is not a concern:

On your server.js or app.js file, add the following:

app.use('/local-files', express.static('/'));

That will serve your ENTIRE root directory under /local-files. Needless to say this is a really bad idea if you're planning to deploy this app anywhere other than your local machine.

Now, you can simply do:

<img src="/local-files/images/mypic.jps"/> 

note: I'm running macOS. If you're using Windows you may have to search and remove 'C:\' from the path string

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

Actually php://input allows you to read raw POST data.

It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives.

php://input is not available with enctype="multipart/form-data".

Reference: http://php.net/manual/en/wrappers.php.php

Is it possible to specify a different ssh port when using rsync?

The correct syntax is to tell Rsync to use a custom SSH command (adding -p 2222), which creates a secure tunnel to remote side using SSH, then connects via localhost:873

rsync -rvz --progress --remove-sent-files -e "ssh -p 2222" ./dir user@host/path

Rsync runs as a daemon on TCP port 873, which is not secure.

From Rsync man:

Push: rsync [OPTION...] SRC... [USER@]HOST:DEST

Which misleads people to try this:

rsync -rvz --progress --remove-sent-files ./dir user@host:2222/path

However, that is instructing it to connect to Rsync daemon on port 2222, which is not there.

How to verify that a specific method was not called using Mockito?

Use the second argument on the Mockito.verify method, as in:

Mockito.verify(dependency, Mockito.times(0)).someMethod()

Deleting DataFrame row in Pandas based on column value

I compiled and run my code. This is accurate code. You can try it your own.

data = pd.read_excel('file.xlsx')

If you have any special character or space in column name you can write it in '' like in the given code:

data = data[data['expire/t'].notnull()]
print (date)

If there is just a single string column name without any space or special character you can directly access it.

data = data[data.expire ! = 0]
print (date)

Combining a class selector and an attribute selector with jQuery

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

C++ equivalent of java's instanceof

dynamic_cast is known to be inefficient. It traverses up the inheritance hierarchy, and it is the only solution if you have multiple levels of inheritance, and need to check if an object is an instance of any one of the types in its type hierarchy.

But if a more limited form of instanceof that only checks if an object is exactly the type you specify, suffices for your needs, the function below would be a lot more efficient:

template<typename T, typename K>
inline bool isType(const K &k) {
    return typeid(T).hash_code() == typeid(k).hash_code();
}

Here's an example of how you'd invoke the function above:

DerivedA k;
Base *p = &k;

cout << boolalpha << isType<DerivedA>(*p) << endl;  // true
cout << boolalpha << isType<DerivedB>(*p) << endl;  // false

You'd specify template type A (as the type you're checking for), and pass in the object you want to test as the argument (from which template type K would be inferred).

How to pause for specific amount of time? (Excel/VBA)

I usually use the Timer function to pause the application. Insert this code to yours

T0 = Timer
Do
    Delay = Timer - T0
Loop Until Delay >= 1 'Change this value to pause time for a certain amount of seconds

Using 'sudo apt-get install build-essentials'

Try

sudo apt-get update
sudo apt-get install build-essential

(If I recall correctly the package name is without the extra s at the end).

Excel VBA Run-time error '13' Type mismatch

For future readers:

This function was abending in Run-time error '13': Type mismatch

Function fnIsNumber(Value) As Boolean
  fnIsNumber = Evaluate("ISNUMBER(0+""" & Value & """)")
End Function

In my case, the function was failing when it ran into a #DIV/0! or N/A value.

To solve it, I had to do this:

Function fnIsNumber(Value) As Boolean
   If CStr(Value) = "Error 2007" Then '<===== This is the important line
      fnIsNumber = False
   Else
      fnIsNumber = Evaluate("ISNUMBER(0+""" & Value & """)")
   End If
End Function

System.out.println() shortcut on Intellij IDEA

Yeah, you can do it. Just open Settings -> Live Templates. Create new one with syso as abbreviation and System.out.println($END$); as Template text.

Remove empty elements from an array in Javascript

If you've got Javascript 1.6 or later you can use Array.filter using a trivial return true callback function, e.g.:

arr = arr.filter(function() { return true; });

since .filter automatically skips missing elements in the original array.

The MDN page linked above also contains a nice error-checking version of filter that can be used in JavaScript interpreters that don't support the official version.

Note that this will not remove null entries nor entries with an explicit undefined value, but the OP specifically requested "missing" entries.

How to check if element in groovy array/hash/collection/list?

IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this...

import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(includes = "settingNameId, value")

then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results.

C# Return Different Types?

Here is how you might do it with generics:

public T GetAnything<T>()
{
   T t = //Code to create instance

   return t;
}

But you would have to know what type you wanted returned at design time. And that would mean that you could just call a different method for each creation...

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

Install opencv for Python 3.3

Spent 3 hours trying the various options on Ubuntu 14.04LTS mentioned here and in another referenced tutorial to no avail. For a while tried with OpenCV3.0.0 but eventually switched to 3.1.0. The following worked:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.4m.so \
-D PYTHON3_EXECUTABLE=/usr/bin/python3.4m \
-D PYTHON3_INCLUDE_DIR=/usr/include/python3.4m/ \
-D PYTHON_INCLUDE_DIR=/usr/include/python3.4m/ \
-D PYTHON3_INCLUDE_DIRS=/usr/include/python3.4m/ \
-D PYTHON_INCLUDE_DIRS=/usr/include/python3.4m/ \
-D BUILD_opencv_python3=ON \
.

output:

--   OpenCV modules:
--     To be built:                 core flann imgproc ml photo video imgcodecs shape videoio highgui objdetect superres ts features2d calib3d stitching videostab python3
--     Disabled:                    java world
--     Disabled by dependency:      -
--     Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev python2 viz

--   Python 3:
--     Interpreter:                 /usr/bin/python3.4m (ver 3.4.3)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.4m.so (ver 3.4.3)
--     numpy:                       /usr/lib/python3/dist-packages/numpy/core/include (ver 1.8.2)
--     packages path:               /usr/lib/python3/dist-packages
-- 
--   Python (for build):      

And with virtualenv used the following cmake options:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=$VIRTUAL_ENV \
-D PYTHON3_EXECUTABLE=$VIRTUAL_ENV/bin/python3 \
-D PYTHON3_PACKAGES_PATH=$VIRTUAL_ENV/lib/python3.4/site-packages \
-D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.4m.so \
-D PYTHON3_INCLUDE_DIR=$VIRTUAL_ENV/include/python3.4m \
-D PYTHON_INCLUDE_DIR=$VIRTUAL_ENV/include/python3.4m \
-D PYTHON3_INCLUDE_DIRS=$VIRTUAL_ENV/include/python3.4m \
-D PYTHON_INCLUDE_DIRS=$VIRTUAL_ENV/include/python3.4m \
-D BUILD_opencv_python3=ON \
.

If you have issues with ffmpeg includes add the following to remove video support:

-D WITH_FFMPEG=OFF \
-D WITH_GSTREAMER=OFF \
-D WITH_V4L=OFF \
-D WITH_1394=OFF \

Also take heed of the warning from cmake about using make clean. If you ran make clean you might have to uncompress the original package anew. Cmake is dead, long live the Cmake

Replacing .NET WebBrowser control with a better browser, like Chrome?

You can use registry to set IE version for webbrowser control. Go to: HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add "yourApplicationName.exe" with value of browser_emulation To see value of browser_emulation, refer link: http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation

How do I drag and drop files into an application?

In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.

When the DragEnter event fires, set the argument's AllowedEffect to something other than none (e.g. e.Effect = DragDropEffects.Move).

When the DragDrop event fires, you'll get a list of strings. Each string is the full path to the file being dropped.

Android ADT error, dx.jar was not loaded from the SDK folder

sometimes you need just to restart Eclipse after the update, it worked for me to fix that error

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank also returns true for just whitespace:

isBlank(String str)

Checks if a String is whitespace, empty ("") or null.

Send mail via CMD console

From Linux you can use 'swaks' which is available as an official packages on many distros including Debian/Ubuntu and Redhat/CentOS on EPEL:

swaks -f [email protected] -t [email protected] \
    --server mail.example.com

Checking if a double (or float) is NaN in C++

There is an std::isnan if you compiler supports c99 extensions, but I'm not sure if mingw does.

Here is a small function which should work if your compiler doesn't have the standard function:

bool custom_isnan(double var)
{
    volatile double d = var;
    return d != d;
}

How can I remove leading and trailing quotes in SQL Server?

The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].

-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters 
-- (from the 2nd character and the LEN([Description]) - 2th character)

UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'

How do I convert a factor into date format?

You were close. format= needs to be added to the as.Date call:

mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"

StringIO in Python3

On Python 3 numpy.genfromtxt expects a bytes stream. Use the following:

numpy.genfromtxt(io.BytesIO(x.encode()))

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

How to style the menu items on an Android action bar

Instead of having the android:actionMenuTextAppearance item under your action bar style, move it under your app theme.

POST Content-Length exceeds the limit

Try pasting this to .htaccess and it should work.

php_value post_max_size 2000M
php_value upload_max_filesize 2500M
php_value max_execution_time 6000000
php_value max_input_time 6000000
php_value memory_limit 2500M

getch and arrow codes

I'm Just a starter, but i'v created a char(for example "b"), and I do b = _getch(); (its a conio.h library's command) And check

If (b == -32)
b = _getch();

And do check for the keys (72 up, 80 down, 77 right, 75 left)

Extract file basename without path and extension in bash

The basename command has two different invocations; in one, you specify just the path, in which case it gives you the last component, while in the other you also give a suffix that it will remove. So, you can simplify your example code by using the second invocation of basename. Also, be careful to correctly quote things:

fbname=$(basename "$1" .txt)
echo "$fbname"

React.js: onChange event for contentEditable

Edit 2015

Someone has made a project on NPM with my solution: https://github.com/lovasoa/react-contenteditable

Edit 06/2016: I've just encoutered a new problem that occurs when the browser tries to "reformat" the html you just gave him, leading to component always re-rendering. See

Edit 07/2016: here's my production contentEditable implementation. It has some additional options over react-contenteditable that you might want, including:

  • locking
  • imperative API allowing to embed html fragments
  • ability to reformat the content

Summary:

FakeRainBrigand's solution has worked quite fine for me for some time until I got new problems. ContentEditables are a pain, and are not really easy to deal with React...

This JSFiddle demonstrates the problem.

As you can see, when you type some characters and click on Clear, the content is not cleared. This is because we try to reset the contenteditable to the last known virtual dom value.

So it seems that:

  • You need shouldComponentUpdate to prevent caret position jumps
  • You can't rely on React's VDOM diffing algorithm if you use shouldComponentUpdate this way.

So you need an extra line so that whenever shouldComponentUpdate returns yes, you are sure the DOM content is actually updated.

So the version here adds a componentDidUpdate and becomes:

var ContentEditable = React.createClass({
    render: function(){
        return <div id="contenteditable"
            onInput={this.emitChange} 
            onBlur={this.emitChange}
            contentEditable
            dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
    },

    shouldComponentUpdate: function(nextProps){
        return nextProps.html !== this.getDOMNode().innerHTML;
    },

    componentDidUpdate: function() {
        if ( this.props.html !== this.getDOMNode().innerHTML ) {
           this.getDOMNode().innerHTML = this.props.html;
        }
    },

    emitChange: function(){
        var html = this.getDOMNode().innerHTML;
        if (this.props.onChange && html !== this.lastHtml) {
            this.props.onChange({
                target: {
                    value: html
                }
            });
        }
        this.lastHtml = html;
    }
});

The Virtual dom stays outdated, and it may not be the most efficient code, but at least it does work :) My bug is resolved


Details:

1) If you put shouldComponentUpdate to avoid caret jumps, then the contenteditable never rerenders (at least on keystrokes)

2) If the component never rerenders on key stroke, then React keeps an outdated virtual dom for this contenteditable.

3) If React keeps an outdated version of the contenteditable in its virtual dom tree, then if you try to reset the contenteditable to the value outdated in the virtual dom, then during the virtual dom diff, React will compute that there are no changes to apply to the DOM!

This happens mostly when:

  • you have an empty contenteditable initially (shouldComponentUpdate=true,prop="",previous vdom=N/A),
  • the user types some text and you prevent renderings (shouldComponentUpdate=false,prop=text,previous vdom="")
  • after user clicks a validation button, you want to empty that field (shouldComponentUpdate=false,prop="",previous vdom="")
  • as both the newly produced and old vdom are "", React does not touch the dom.

AFNetworking Post Request

[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];

NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter

NSString *URLString =@"your url string";

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
//         [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

     NSLog(@"Response DICT:%@",response);

     if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {

         for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
         {
             [yourNsmutableArray addObject:[dicAll mutableCopy]];
         }
         //yourNsmutableArray Nsmutablearray  alloction in view didload

         NSLog(@"yourNsmutableArray  %@",yourNsmutableArray);
     }
     else
     {
         NSLog(@"False");
     }

     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     NSLog(@"RESPONSE STRING:%@",task.response);
     NSLog(@"error userInfo:%@",error.userInfo);

     NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
     NSLog(@"URLString :--->>   %@ Error********* %@",URLString,errResponse);

     [SVProgressHUD dismiss];

 }];

Split long commands in multiple lines through Windows batch file

It seems however that splitting in the middle of the values of a for loop doesn't need a caret(and actually trying to use one will be considered a syntax error). For example,

for %n in (hello
bye) do echo %n

Note that no space is even needed after hello or before bye.

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

Follow this:

  1. Create a bin folder in any directory(to be used in step 3).

  2. Download winutils.exe and place it in the bin directory.

  3. Now add System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR"); in your code.

What methods of ‘clearfix’ can I use?

I'd float #content too, that way both columns contain floats. Also because it will allow you to clear elements inside #content without clearing the side bar.

Same thing with the wrapper, you'd need to make it a block formatting context to wrap the two columns.

This article mentions a few triggers you can use: block formatting contexts.

How to reset form body in bootstrap modal box?

This is a variance of need to reset body to original content. It doesn't deal with a form but I feel it might be of some use. If the original content was a ton of html, it is very difficult to string out the html and store it to a variable. Javascript does not take kindly to the line breaks that VS 2015/whatever allows. So I store original ton of html in default modal like this on page load:

var stylesString = $('#DefaultModal .modal-body').html();

Which allows me to to reuse this content when original default button for modal is pressed (there are other buttons that show other content in same modal).

$("#btnStyles").click(function () {
    //pass the data in the modal body adding html elements
    $('#DefaultModal .modal-body').html(stylesString);
 $('#DefaultModal').modal('show');
})

If I put an alert for the styleString variable it would have an endless string of all the html with no breaks but does it for me and keeps it out of VS editor.

Here is how it looks in Visual Studio inside default modal. Saved in the string variable whether automatic (.html) or by hand in VS, it would be one big line:

<div class="modal-body" id="modalbody">


    <div class="whatdays"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">All Styles</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/ballroom.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Ballroom</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/blues.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Blues</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/contra.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Contra</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/countrywestern.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/english-country.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">English Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/israeli.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Israeli</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/lindyhop.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Lindy Hop/Swing</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/miscvariety.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Misch/Variety</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/neo-square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Neo-Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/polka.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Polka</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/salsa.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Salsa</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/scottish.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Scottish</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/tango.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Tango</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/waltz.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Waltz</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/wcswing.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">WCS</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/zyedeco-gator.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Zydeco/Cajun</span></div>

CRON job to run on the last day of the month

What about this?

edit user's .bashprofile adding:

export LAST_DAY_OF_MONTH=$(cal | awk '!/^$/{ print $NF }' | tail -1)

Then add this entry to crontab:

mm hh * * 1-7 [[ $(date +'%d') -eq $LAST_DAY_OF_MONTH ]] && /absolutepath/myscript.sh

How can I deploy an iPhone application from Xcode to a real iPhone device?

No, its easy to do this. In Xcode, set the Active Configuration to Release. Change the device from Simulator to Device - whatever SDK. If you want to directly export to your iPhone, connect it to your computer. Press Build and Go. If your iPhone is not connected to your computer, a message will come up saying that your iPhone is not connected.

If this applies to you: (iPhone was not connected)

Go to your projects folder and then to the build folder inside. Go to the Release-iphoneos folder and take the app inside, drag and drop on iTunes icon. When you sync your iTouch device, it will copy it to your device. It will also show up in iTunes as a application for the iPhone.

Hope this helps!

P.S.: If it says something about a certificate not being valid, just click on the project in Xcode, the little project icon in the file stack to the left, and press Apple+I, or do Get Info from the menu bar. Click on Build at the top. Under Code Signing, change Code Signing Identity - Any iPhone OS Device to be Don't Sign.

Difference between DOM parentNode and parentElement

there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.

How to open generated pdf using jspdf in new window

Javascript code: Add in end line

$("#pdf_preview").attr("src", pdf.output('datauristring'));

HTML Code: Insert in body

<head>
</head>
<body>
<H1>Testing</h1>
<iframe id="pdf_preview" type="application/pdf" src="" width="800" height="400"></iframe>
</body>
</html>

preview within same window inside iframe along with with other contents.

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

How do you use the Immediate Window in Visual Studio?

The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.

To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I

enter image description here

Here is an example with Immediate Window:

int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}

add breakpoint

enter image description here

call commands

enter image description here

https://msdn.microsoft.com/en-us/library/f177hahy.aspx

How does HTTP file upload work?

Send file as binary content (upload without form or FormData)

In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition header. You can upload like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.

How to check if NSString begins with a certain character

Another approach to do it..

May it help someone...

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

Should I use <i> tag for icons instead of <span>?

I'm jumping in here a little late, but came across this page when pondering it myself. Of course I don't know how Facebook or Twitter justified it, but here is my own thought process for what it's worth.

In the end, I concluded that this practice is not that unsemantic (is that a word?). In fact, besides shortness and the nice association of "i is for icon," I think it's actually the most semantic choice for an icon when a straightforward <img> tag is not practical.

1. The usage is consistent with the spec.

While it may not be what the W3 mainly had in mind, it seems to me the official spec for <i> could accommodate an icon pretty easily. After all, the reply-arrow symbol is saying "reply" in another way. It expresses a technical term that may be unfamiliar to the reader and would be typically italicized. ("Here at Twitter, this is what we call a reply arrow.") And it is a term from another language: a symbolic language.

If, instead of the arrow symbol, Twitter used <i>shout out</i> or <i>[Japanese character for reply]</i> (on an English page), that would be consistent with the spec. Then why not <i>[reply arrow]</i>? (I'm talking strictly HTML semantics here, not accessibility, which I'll get to.)

As far as I can see, the only part of the spec explicitly violated by icon usage is the "span of text" phrase (when the tag doesn't contain text also). It is clear that the <i> tag is mainly meant for text, but that's a pretty small detail compared with the overall intent of the tag. The important question for this tag is not what format of content it contains, but what the meaning of that content is.

This is especially true when you consider that the line between "text" and "icon" can be almost nonexistent on websites. Text may look like more like an icon (as in the Japanese example) or an icon may look like text (as in a jpg button that says "Submit" or a cat photo with an overlaid caption) or text may be replaced or enhanced with an image via CSS. Text, image - who cares? It's all content. As long as everyone - humans with impairments, browsers with impairments, search engine spiders, and other machines of various kinds can understand that meaning, we've done our job.

So the fact that the writers of the spec didn't think (or choose) to clarify this shouldn't tie our hands from doing what makes sense and is consistent with the spirit of the tag. The <a> tag was originally intended to take the user somewhere else, but now it might pop up a lightbox. Big whoop, right? If someone had figured out how to pop up a lightbox on click before the spec caught up, they still should have used the <a> tag, not a <span>, even if it wasn't entirely consistent with the current definition - because it came the closest and was still consistent with the spirit of the tag ("something will happen when you click here"). Same deal with <i> - whatever type of thing you put inside it, or however creatively you use it, it expresses the general idea of an alternate or set-apart term.

2. The <i> tag adds semantic meaning to an icon element.

The alternative option to carry an icon class by itself is <span>, which of course has no semantic meaning whatsoever. When a machine asks the <span> what it contains, it says, "I don't know. Could be anything." But the <i> tag says, "I contain a different way of saying something than the usual way, or maybe an unfamiliar term." That's not the same as "I contain an icon," but it's a lot closer to it than <span> got!

3. Eventually, common usage makes right.

In addition to the above, it's worth considering that machine readers (whether search engine, screen reader, or whatever) may at any time begin to take into account that Facebook, Twitter, and other websites use the <i> tag for icons. They don't care about the spec as much as they care about extracting meaning from code by whatever means necessary. So they might use this knowledge of common usage to simply record that "there may be an icon here" or do something more advanced like triggering a look into the CSS for a hint to meaning, or who knows what. So if you choose to use the <i> for icons on your website, you may be providing more meaning than the spec does.

Moreover, if this usage becomes widespread, it will likely be included in the spec in the future. Then you'll be going through your code, replacing <span>s with <i>'s! So it may make sense to get on board with what seems to be the direction of the spec, especially when it doesn't clearly conflict with the current spec. Common usage tends to dictate language rules more than the other way around. If you're old enough, do you remember that "Web site" was the official spelling when the word was new? Dictionaries insisted there must be a space and Web must be capitalized. There were semantic reasons for that. But common usage said, "Whatever, that's stupid. I'm using 'website' because it's more concise and looks better." And before long, dictionaries officially acknowledged that spelling as correct.

4. So I'm going ahead and using it.

So, <i> provides more meaning to machines because of the spec, it provides more meaning to humans because we easily associate "i" with "icon", and it's only one letter long. Win! And if you make sure to include equivalent text either inside the <i> tag or right next to it (as Twitter does), then screen readers understand where to click to reply, the link is usable if CSS doesn't load, and human readers with good eyesight and a decent browser see a pretty icon. With all this in mind, I don't see the downside.

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

I get the same exception for .xls file, but after I open the file and save it as xlsx file , the below code works:

 try(InputStream is =file.getInputStream()){
      XSSFWorkbook workbook = new XSSFWorkbook(is);
      ...
 }

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

add this to your stylesheet. line-height should match the height of your logo

.navbar-nav li a {
 line-height: 50px;
}

Check out the fiddle at: http://jsfiddle.net/nD4tW/

PHP Check for NULL

Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero):

if (!$result['column']>0){

}

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

What is the optimal algorithm for the game 2048?

I wrote a 2048 solver in Haskell, mainly because I'm learning this language right now.

My implementation of the game slightly differs from the actual game, in that a new tile is always a '2' (rather than 90% 2 and 10% 4). And that the new tile is not random, but always the first available one from the top left. This variant is also known as Det 2048.

As a consequence, this solver is deterministic.

I used an exhaustive algorithm that favours empty tiles. It performs pretty quickly for depth 1-4, but on depth 5 it gets rather slow at a around 1 second per move.

Below is the code implementing the solving algorithm. The grid is represented as a 16-length array of Integers. And scoring is done simply by counting the number of empty squares.

bestMove :: Int -> [Int] -> Int
bestMove depth grid = maxTuple [ (gridValue depth (takeTurn x grid), x) | x <- [0..3], takeTurn x grid /= [] ]

gridValue :: Int -> [Int] -> Int
gridValue _ [] = -1
gridValue 0 grid = length $ filter (==0) grid  -- <= SCORING
gridValue depth grid = maxInList [ gridValue (depth-1) (takeTurn x grid) | x <- [0..3] ]

I thinks it's quite successful for its simplicity. The result it reaches when starting with an empty grid and solving at depth 5 is:

Move 4006
[2,64,16,4]
[16,4096,128,512]
[2048,64,1024,16]
[2,4,16,2]

Game Over

Source code can be found here: https://github.com/popovitsj/2048-haskell

How do I concatenate or merge arrays in Swift?

Similarly, with dictionaries of arrays one can:

var dict1 = [String:[Int]]()
var dict2 = [String:[Int]]()
dict1["key"] = [1,2,3]
dict2["key"] = [4,5,6]
dict1["key"] = dict1["key"]! + dict2["key"]!
print(dict1["key"]!)

and you can iterate over dict1 and add dict2 if the "key" matches

Registering for Push Notifications in Xcode 8/Swift 3.0?

Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate.swift

Request user permission

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
        application.registerForRemoteNotifications()
        return true
}

Getting device token

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print(deviceTokenString)
}

In case of error

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        print("i am not available in simulator \(error)")
}

In case if you need to know the permissions granted

UNUserNotificationCenter.current().getNotificationSettings(){ (settings) in

            switch settings.soundSetting{
            case .enabled:

                print("enabled sound setting")

            case .disabled:

                print("setting has been disabled")

            case .notSupported:
                print("something vital went wrong here")
            }
        }

Twitter - share button, but with image

Look into twitter cards.

The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook sharing.

Example:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">

Check if element is in the list (contains)

A one-liner solution, similar to python, would be (std::set<int> {1, 2, 3, 4}).count(my_var) > 0.

Minimal working example

int my_var = 3;
bool myVarIn = (std::set<int> {1, 2, 3, 4}).count(my_var) > 0;
std::cout << std::boolalpha << myVarIn << std::endl;

prints true or false dependent of the value of my_var.

Replace last occurrence of character in string

_x000D_
_x000D_
var someString = "(/n{})+++(/n{})---(/n{})$$$";_x000D_
var toRemove = "(/n{})"; // should find & remove last occurrence _x000D_
_x000D_
function removeLast(s, r){_x000D_
  s = s.split(r)_x000D_
  return s.slice(0,-1).join(r) + s.pop()_x000D_
}_x000D_
_x000D_
console.log(_x000D_
  removeLast(someString, toRemove)_x000D_
)
_x000D_
_x000D_
_x000D_

Breakdown:

s = s.split(toRemove)         // ["", "+++", "---", "$$$"]
s.slice(0,-1)                 //  ["", "+++", "---"]   
s.slice(0,-1).join(toRemove)  // "})()+++})()---"
s.pop()                       //  "$$$"   

Download multiple files with a single action

I agree that a zip file is a neater solution... But if you have to push multiple file, here's the solution I came up with. It works in IE 9 and up (possibly lower version too - I haven't tested it), Firefox, Safari and Chrome. Chrome will display a message to user to obtain his agreement to download multiple files the first time your site use it.

function deleteIframe (iframe) {
    iframe.remove(); 
}
function createIFrame (fileURL) {
    var iframe = $('<iframe style="display:none"></iframe>');
    iframe[0].src= fileURL;
    $('body').append(iframe);
    timeout(deleteIframe, 60000, iframe);             
 }
 // This function allows to pass parameters to the function in a timeout that are 
 // frozen and that works in IE9
 function timeout(func, time) {
      var args = [];
      if (arguments.length >2) {
           args = Array.prototype.slice.call(arguments, 2);
      }
      return setTimeout(function(){ return func.apply(null, args); }, time);
 }
 // IE will process only the first one if we put no delay
 var wait = (isIE ? 1000 : 0);
 for (var i = 0; i < files.length; i++) {  
      timeout(createIFrame, wait*i, files[i]);
 }

The only side effect of this technique, is that user will see a delay between submit and the download dialog showing. To minimize this effect, I suggest you use the technique describe here and on this question Detect when browser receives file download that consist of setting a cookie with your file to know it has started download. You will have to check for this cookie on client side and to send it on server side. Don't forget to set the proper path for your cookie or you might not see it. You will also have to adapt the solution for multiple file download.

How to convert R Markdown to PDF?

I think you really need pandoc, which great software was designed and built just for this task :) Besides pdf, you could convert your md file to e.g. docx or odt among others.

Well, installing an up-to-date version of Pandoc might be challanging on Linux (as you would need the entire haskell-platform?to build from the sources), but really easy on Windows/Mac with only a few megabytes of download.

If you have the brewed/knitted markdown file you can just call pandoc in e.g bash or with the system function within R. A POC demo of that latter is implemented in the ?andoc.convert function of my little package (which you must be terribly bored of as I try to point your attention there at every opportunity).

Populating a database in a Laravel migration file

Another clean way to do it is to define a private method which create instance et persist concerned Model.

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('label', 256);
        $table->timestamps();
        $table->softDeletes();
    });

    $this->postCreate('admin', 'user');
}

private function postCreate(string ...$roles)  {
    foreach ($roles as $role) {
        $model = new Role();
        $model->setAttribute('label', $role);
        $model->save();
    }
}

With this solution, timestamps fields will be generated by Eloquent.

EDIT: it's better to use seeder system to disctinct database structure generation and database population.

Ruby: kind_of? vs. instance_of? vs. is_a?

kind_of? and is_a? are synonymous.

instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass.

Example:

  • "hello".is_a? Object and "hello".kind_of? Object return true because "hello" is a String and String is a subclass of Object.
  • However "hello".instance_of? Object returns false.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

If you really want to match only the dot, then StringComparison.Ordinal would be fastest, as there is no case-difference.

"Ordinal" doesn't use culture and/or casing rules that are not applicable anyway on a symbol like a ..

What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

Checking if a string can be converted to float in Python

Simplified version of the function is_digit(str), which suffices in most cases (doesn't consider exponential notation and "NaN" value):

def is_digit(str):
    return str.lstrip('-').replace('.', '').isdigit()

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

Simulate a click on 'a' element using javascript/jquery

The code you've already tried:

document.getElementById("gift-close").click();

...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

  1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
  2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
  3. Put the code in a script block that is after the element in the source html.

So:

$(document).ready(function() {
    document.getElementById("gift-close").click();
    // OR
    $("#gift-close")[0].click();
});

Python string.join(list) on object array rather than string array

another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you'll find my answer useful.

Tomcat is not deploying my web project from Eclipse

Depsite the year old topic, this one seems to have the most of the answers for this problem. Just ren into it. Tried everything, starting from "cleans", ending with total ".metadata" and another server setup, and nothing worked.

Than i remembered that a while ago i'w decided to clean up some of the "pom" warnings, and there were some suggestions on "apply to the project data". Then i started to browse the folder project, where i found the source of my headache - a file called ".tomcatplugin". After deleting it(it was the third hour of my attempts of resolving the problem) everything worked like a charm.

Using filesystem in node.js with async / await

Node v14.0.0 and above

you can just do:

import { readdir } from "fs/promises";

just like you would import from "fs"

see this PR for more details: https://github.com/nodejs/node/pull/31553

How do SO_REUSEADDR and SO_REUSEPORT differ?

Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.

There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:

{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}

Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.

The protocol of a socket is set when a socket is created with the socket() function. The source address and port are set with the bind() function. The destination address and port are set with the connect() function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.

If you explicitly bind a socket, it is possible to bind it to port 0, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0 in case of IPv4 and :: in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.

By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA to ipA:portA and socketB to ipB:portB is always possible if ipA != ipB holds true, even when portA == portB. E.g. socketA belongs to a FTP server program and is bound to 192.168.0.1:21 and socketB belongs to another FTP server program and is bound to 10.0.0.1:21, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21, regardless which specific IP address it tries to bind to, as 0.0.0.0 conflicts with all existing local IP addresses.

Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.

BSD

SO_REUSEADDR

If SO_REUSEADDR is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.

Without SO_REUSEADDR, binding socketA to 0.0.0.0:21 and then binding socketB to 192.168.0.1:21 will fail (with error EADDRINUSE), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1, too. With SO_REUSEADDR it will succeed, since 0.0.0.0 and 192.168.0.1 are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA and socketB are bound; without SO_REUSEADDR it will always fail, with SO_REUSEADDR it will always succeed.

To give you a better overview, let's make a table here and list all possible combinations:

SO_REUSEADDR       socketA        socketB       Result
---------------------------------------------------------------------
  ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
  ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
  ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
   OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
   OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
   ON              0.0.0.0:21   192.168.1.0:21    OK
   ON          192.168.1.0:21       0.0.0.0:21    OK
  ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)

The table above assumes that socketA has already been successfully bound to the address given for socketA, then socketB is created, either gets SO_REUSEADDR set or not, and finally is bound to the address given for socketB. Result is the result of the bind operation for socketB. If the first column says ON/OFF, the value of SO_REUSEADDR is irrelevant to the result.

Okay, SO_REUSEADDR has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.

A socket has a send buffer and if a call to the send() function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send() call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.

At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit() (pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.

The question is, how does the system treat a socket in state TIME_WAIT? If SO_REUSEADDR is not set, a socket in state TIME_WAIT is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.

There is one final thing you should know about SO_REUSEADDR. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR flag of the socket fed into the bind() call, for all other sockets inspected, this flag is not even looked at.

SO_REUSEPORT

SO_REUSEPORT is what most people would expect SO_REUSEADDR to be. Basically, SO_REUSEPORT allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR the code handling SO_REUSEPORT will not only verify that the currently bound socket has SO_REUSEPORT set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT set when it was bound.

SO_REUSEPORT does not imply SO_REUSEADDR. This means if a socket did not have SO_REUSEPORT set when it was bound and another socket has SO_REUSEPORT set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT state requires either SO_REUSEADDR to be set on that socket or SO_REUSEPORT must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT and SO_REUSEADDR, on a socket.

There is not much more to say about SO_REUSEPORT other than that it was added later than SO_REUSEADDR, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.

Connect() Returning EADDRINUSE?

Most people know that bind() may fail with the error EADDRINUSE, however, when you start playing around with address reuse, you may run into the strange situation that connect() fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?

As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.

So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect() will actually fail with the error EADDRINUSE for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.

Multicast Addresses

Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.

The meaning of SO_REUSEADDR changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR behaves exactly as SO_REUSEPORT for unicast addresses. Actually, the code treats SO_REUSEADDR and SO_REUSEPORT identically for multicast addresses, that means you could say that SO_REUSEADDR implies SO_REUSEPORT for all multicast addresses and the other way round.


FreeBSD/OpenBSD/NetBSD

All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.


macOS (MacOS X)

At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.

iOS / watchOS / tvOS

iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.


Linux

Linux < 3.9

Prior to Linux 3.9, only the option SO_REUSEADDR existed. This option behaves generally the same as in BSD with two important exceptions:

  1. As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.

  2. The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT prior to 3.9, the behavior of SO_REUSEADDR was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.

Linux >= 3.9

Linux 3.9 added the option SO_REUSEPORT to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.

Yet, there are still two differences to SO_REUSEPORT on other systems:

  1. To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND/SO_EXCLUSIVEADDRUSE flags.

  2. Additionally the kernel performs some "special magic" for SO_REUSEPORT sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT to get a very inexpensive load balancing.


Android

Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.


Windows

Windows only knows the SO_REUSEADDR option, there is no SO_REUSEPORT. Setting SO_REUSEADDR on a socket in Windows behaves like setting SO_REUSEPORT and SO_REUSEADDR on a socket in BSD, with one exception:

Prior to Windows 2003, a socket with SO_REUSEADDR could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!

Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE. Setting SO_EXCLUSIVEADDRUSE on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR set.

This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind() calls are made by the same user, and the third one when the bind() calls are made by different users.


Solaris

Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR, there is no SO_REUSEPORT. The SO_REUSEADDR behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.

Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND. If this option is set on a socket prior to binding it, setting SO_REUSEADDR on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA is bound to a wildcard address and socketB has SO_REUSEADDR enabled and is bound to a non-wildcard address and the same port as socketA, this bind will normally succeed, unless socketA had SO_EXCLBIND enabled, in which case it will fail regardless the SO_REUSEADDR flag of socketB.


Other Systems

In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.

All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h and stdbool.h; e.g. gcc supported both long before offering full C99 support).

All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".

It tests all possible combinations you can think of:

  • TCP and UDP protocol
  • Normal sockets, listen (server) sockets, multicast sockets
  • SO_REUSEADDR set on socket1, socket2, or both sockets
  • SO_REUSEPORT set on socket1, socket2, or both sockets
  • All address combinations you can make out of 0.0.0.0 (wildcard), 127.0.0.1 (specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3 in all tests)

and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT, in which case this option is simply not tested.

What the program cannot easily test is how SO_REUSEADDR acts on sockets in TIME_WAIT state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.

Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

python numpy ValueError: operands could not be broadcast together with shapes

You are looking for np.matmul(X, y). In Python 3.5+ you can use X @ y.

Run a .bat file using python code

So I do in Windows 10 and Python 3.7.1 (tested):

import subprocess
Quellpfad = r"C:\Users\MeMySelfAndI\Desktop"
Quelldatei = r"\a.bat"
Quelle = Quellpfad + Quelldatei
print(Quelle)
subprocess.call(Quelle)

Check if a Bash array contains a value

This could be worth investigating if you don't want to iterate:

#!/bin/bash
myarray=("one" "two" "three");
wanted="two"
if `echo ${myarray[@]/"$wanted"/"WAS_FOUND"} | grep -q "WAS_FOUND" ` ; then
 echo "Value was found"
fi
exit

Snippet adapted from: http://www.thegeekstuff.com/2010/06/bash-array-tutorial/ I think it is pretty clever.

EDIT: You could probably just do:

if `echo ${myarray[@]} | grep -q "$wanted"` ; then
echo "Value was found"
fi

But the latter only works if the array contains unique values. Looking for 1 in "143" will give false positive, methinks.

Compiling and Running Java Code in Sublime Text 2

This is code to compile and run java in sublime text 3

"shell_cmd": "javac -d . $file && java ${file_base_name}.${file_base_name}", "shell": true

nodejs vs node on ubuntu 12.04

https://nodejs.org/en/download/

Download .pkg file on your mac and install it. it directly works.

?  ~ which node
/usr/local/bin/node
?  ~ node --version
v10.11.0
?  ~ which npm
/usr/local/bin/npm
?  ~ npm --version
6.4.1

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

As an alternative to the other answers, you can try symbolic links.

Create the symbolic link first and install the application based on the link. (Depending on the case, this may be way easier to do, for instance when the application has n mentions of the target folder throughout its code)

A symbolic link will create something similar to a shortcut to a folder, but seen as an actual folder by other applications.

This is how you do it:

  • Run cmd as administrator
  • User this command: mklink /D "C:\LinkToProgramFiles" "C:\Program Files"

And then, you start using "C:\LinkToProgramFiles" in the applications that can't handle spaces. (This link can be seen in Windows Explorer as a folder with the symbol of a shortcut)


Be very careful not to create circular links if you start playing too much with this.

Distinct() with lambda?

If Distinct() doesn't produce unique results, try this one:

var filteredWC = tblWorkCenter.GroupBy(cc => cc.WCID_I).Select(grp => grp.First()).Select(cc => new Model.WorkCenter { WCID = cc.WCID_I }).OrderBy(cc => cc.WCID); 

ObservableCollection<Model.WorkCenter> WorkCenter = new ObservableCollection<Model.WorkCenter>(filteredWC);

Inner join of DataTables in C#

I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:

private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
    DataTable result = new DataTable();
    foreach (DataColumn col in t1.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataColumn col in t2.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataRow row1 in t1.Rows)
    {
        var joinRows = t2.AsEnumerable().Where(row2 =>
            {
                foreach (var parameter in joinOn)
                {
                    if (!parameter(row1, row2)) return false;
                }
                return true;
            });
        foreach (DataRow fromRow in joinRows)
        {
            DataRow insertRow = result.NewRow();
            foreach (DataColumn col1 in t1.Columns)
            {
                insertRow[col1.ColumnName] = row1[col1.ColumnName];
            }
            foreach (DataColumn col2 in t2.Columns)
            {
                insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
            }
            result.Rows.Add(insertRow);
        }
    }
    return result;
}

An example of how you might use this:

var test = JoinDataTables(transactionInfo, transactionItems,
               (row1, row2) =>
               row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));

One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.

How to get query parameters from URL in Angular 5?

When you have an empty route object, it's mainly due to the fact that you are not using a router-outlet in your app.component.html.

Without this, you won't be able to get a meaningful route object with non empty subObjects, particularly params & queryParams.

Try to add <router-outlet><router-outlet>just before calling your <app-main-component></app-main-component>

Before that, make sure you have your query param ready in app-routing > which export the class Route used by App component :

param: '/param/:dynamicParam', path: MyMainComponent

Last thing of course, to get your param, I personnaly use this.route.snapshot.params.dynamicParam where dynamicParam is the name used in your app-routing component :)

How to delete duplicate rows in SQL Server?

Please see the below way of deletion too.

Declare @table table
(col1 varchar(10),col2 int,col3 int, col4 int, col5 int, col6 int, col7 int)
Insert into @table values 
('john',1,1,1,1,1,1),
('john',1,1,1,1,1,1),
('sally',2,2,2,2,2,2),
('sally',2,2,2,2,2,2)

Created a sample table named @table and loaded it with given data.

enter image description here

Delete  aliasName from (
Select  *,
        ROW_NUMBER() over (Partition by col1,col2,col3,col4,col5,col6,col7 order by col1) as rowNumber
From    @table) aliasName 
Where   rowNumber > 1

Select * from @table

enter image description here

Note: If you are giving all columns in the Partition by part, then order by do not have much significance.

I know, the question is asked three years ago, and my answer is another version of what Tim has posted, But posting just incase it is helpful for anyone.

What is the difference between screenX/Y, clientX/Y and pageX/Y?

Here's a picture explaining the difference between pageY and clientY.

pageY vs clientY

Same for pageX and clientX, respectively.


pageX/Y coordinates are relative to the top left corner of the whole rendered page (including parts hidden by scrolling),

while clientX/Y coordinates are relative to the top left corner of the visible part of the page, "seen" through browser window.

See Demo

You'll probably never need screenX/Y

Run bash script as daemon

You can go to /etc/init.d/ - you will see a daemon template called skeleton.

You can duplicate it and then enter your script under the start function.

What is the equivalent to getLastInsertId() in Cakephp?

In CakePHP you can get it by: Model::getInsertID() //Returns the ID of the last record this model inserted. Model::getLastInsertID() //Alias to getInsertID().

how to destroy an object in java?

Here is the code:

public static void main(String argso[]) {
int big_array[] = new int[100000];

// Do some computations with big_array and get a result. 
int result = compute(big_array);

// We no longer need big_array. It will get garbage collected when there
// are no more references to it. Since big_array is a local variable,
// it refers to the array until this method returns. But this method
// doesn't return. So we've got to explicitly get rid of the reference
// ourselves, so the garbage collector knows it can reclaim the array. 
big_array = null;

// Loop forever, handling the user's input
for(;;) handle_input(result);
}

Datetime in where clause

select * from tblErrorLog
where errorDate BETWEEN '12/20/2008' AND DATEADD(DAY, 1, '12/20/2008')

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])
    }


    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])
    }
}

Tests:

func testArraySubscriptRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1..<arr.count] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

func testArraySubscriptClosedRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1...arr.count - 1] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

Kendo grid date column not formatting

The option I use is as follows:

columns.Bound(p => p.OrderDate).Format("{0:d}").ClientTemplate("#=formatDate(OrderDate)#");

function formatDate(OrderDate) {
    var formatedOrderDate = kendo.format("{0:d}", OrderDate);

    return formatedOrderDate;
}

Split a string by another string in C#

I generally like to use my own extension for that:

string data = "THExxQUICKxxBROWNxxFOX";
var dataspt = data.Split("xx");
//>THE  QUICK  BROWN  FOX 


//the extension class must be declared as static
public static class StringExtension
{   
    public static string[] Split(this string str, string splitter)
    {
        return str.Split(new[] { splitter }, StringSplitOptions.None);
    }
}

This will however lead to an Exception, if Microsoft decides to include this method-overload in later versions. It is also the likely reason why Microsoft has not included this method in the meantime: At least one company I worked for, used such an extension in all their C# projects.

It may also be possible to conditionally define the method at runtime if it doesn't exist.

Opacity of div's background without affecting contained element in IE 8?

opacity on parent element sets it for the whole sub DOM tree

You can't really set opacity for certain element that wouldn't cascade to descendants as well. That's not how CSS opacity works I'm afraid.

What you can do is to have two sibling elements in one container and set transparent one's positioning:

<div id="container">
    <div id="transparent"></div>
    <div id="content"></div>
</div>

then you have to set transparent position: absolute/relative so its content sibling will be rendered over it.

rgba can do background transparency of coloured backgrounds

rgba colour setting on element's background-color will of course work, but it will limit you to only use colour as background. No images I'm afraid. You can of course use CSS3 gradients though if you provide gradient stop colours in rgba. That works as well.

But be advised that rgba may not be supported by your required browsers.

Alert-free modal dialog functionality

But if you're after some kind of masking the whole page, this is usually done by adding a separate div with this set of styles:

position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /* some high enough value so it will render on top */
opacity: .5;
filter: alpha(opacity=50);

Then when you display the content it should have a higher z-index. But these two elements are not related in terms of siblings or anything. They're just displayed as they should be. One over the other.

Return JSON for ResponseEntity<String>

This is a String, not a json structure(key, value), try:

return new ResponseEntity("{"vale" : "This is a String"}", HttpStatus.OK);

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

Well, In my applications I just need to Add a reference to "DocumentFormat.OpenXml" under .Net tab and both references (DocumentFormat.OpenXml and WindowsBase) are always added automatically. But They are not included within the Bin folder. So when the Application is published to an external server I always place DocumentFormat.OpenXml.dll under the Bin folder manually. Or set the reference "Copy Local" property to true.

Access Control Request Headers, is added to header in AJAX request with jQuery

Try to use the rack-cors gem. And add the header field in your Ajax call.

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Ok after a whole productive day down the drain I got it to work.

First I uninstalled all traces of Genymotion and Virtualbox. I then proceeded to install Genymotion and then Virtual Box again, but the previous version (4.2.18)

I ran Genymotion, Downloaded an Image, I got an error message about the network trying to run it. So I ran it Directly inside Virtual Box, It started up 100% with network and everything. I shut it down, went to Image's settings and changed the first adapter to "Host-only".

I opened the Genymotion Launcher again and "Played" my device and it started up with no problems.

Using the Web.Config to set up my SQL database connection string?

If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS

Here is the connectionString in the web config file which you can add:

<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>

Place is just above the system.web tag.

Then you can call it by:

connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;

Switch focus between editor and integrated terminal in Visual Studio Code

While there are a lot of modal toggles and navigation shortcuts for VS Code, there isn't one specifically for "move from editor to terminal, and back again". However you can compose the two steps by overloading the key and using the when clause.

Open the keybindings.json from the editor: CMD-SHIFT-P -> Preferences: Open Keyboard Shortcuts File and add these entries:

// Toggle between terminal and editor focus
{ "key": "ctrl+`", "command": "workbench.action.terminal.focus"},
{ "key": "ctrl+`", "command": "workbench.action.focusActiveEditorGroup", "when": "terminalFocus"}

With these shortcuts I will focus between the editor and the Integrated Terminal using the same keystroke.

jQuery UI Dialog OnBeforeUnload

this works for me

$(window).bind('beforeunload', function() {
      return 'Do you really want to leave?' ;
});

Using If else in SQL Select statement

Here, using CASE Statement and find result:

select (case when condition1 then result1
             when condition2 then result2
             else result3
             end) as columnname from tablenmae:

For example:

select (CASE WHEN IDParent< 1 then ID 
             else IDParent END) as columnname
from tablenmae

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

How do I add all new files to SVN

This add all unversioned files even if it contains spaces

svn status | awk '{$1=""; print $0}' | xargs -i svn add "{}"

What is the OR operator in an IF statement

Or is ||

And is &&

Update for changed question:

You need to specify what you are comparing against in each logical section of the if statement.

if (title == "User greeting" || title == "User name") 
{
    // do stuff
}

Mongodb: failed to connect to server on first connect

I was getting same error while I tried to connect mlab db that is because my organization network has some restriction, I switched to mobile hotspot and it worked.

How to keep onItemSelected from firing off on a newly instantiated Spinner?

I have done with simplest way:

private AdapterView.OnItemSelectedListener listener;
private Spinner spinner;

onCreate();

spinner = (Spinner) findViewById(R.id.spinner);

listener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {

            Log.i("H - Spinner selected position", position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    };

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            spinner.setOnItemSelectedListener(listener);
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

Done

Java: Static Class?

comment on the "private constructor" arguments: come on, developers are not that stupid; but they ARE lazy. creating an object then call static methods? not gonna happen.

don't spend too much time to make sure your class cannot be misused. have some faith for your colleagues. and there is always a way to misuse your class no matter how you protect it. the only thing that cannot be misused is a thing that is completely useless.

jquery - is not a function error

change

});


$(document).ready(function () {
    $('.smallTabsHeader a').pluginbutton();
});

to

})(jQuery); //<-- ADD THIS


$(document).ready(function () {
    $('.smallTabsHeader a').pluginbutton();
});

This is needed because, you need to call the anonymous function that you created with

(function($){

and notice that it expects an argument that it will use internally as $, so you need to pass a reference to the jQuery object.

Additionally, you will need to change all the this. to $(this)., except the first one, in which you do return this.each

In the first one (where you do not need the $()) it is because in the plugin body, this holds a reference to the jQuery object matching your selector, but anywhere deeper than that, this refers to the specific DOM element, so you need to wrap it in $().

Full code at http://jsfiddle.net/gaby/NXESk/

Declaring variables in Excel Cells

You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:

= myvar*25

jQuery remove selected option from this

 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

Using the find method.

Comparing Dates in Oracle SQL

You can use trunc and to_date as follows:

select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.* 
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56 
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

Passing arguments to AsyncTask, and returning results

You can receive returning results like that: AsyncTask class

@Override
protected Boolean doInBackground(Void... params) {
    if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
        try {
            throw new SQLException("Database credentials missing");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return true;
}

receiving class:

_store.execute();
boolean result =_store.get();

Hoping it will help.

What exactly is nullptr?

According to cppreference, nullptr is a keyword that:

denotes the pointer literal. It is a prvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL.

So nullptr is a value of a distinct type std::nullptr_t, not int. It implicitly converts to the null pointer value of any pointer type. This magic happens under the hood for you and you don't have to worry about its implementation. NULL, however, is a macro and it is an implementation-defined null pointer constant. It's often defined like this:

#define NULL 0

i.e. an integer.

This is a subtle but important difference, which can avoid ambiguity.

For example:

int i = NULL;     //OK
int i = nullptr;  //error
int* p = NULL;    //OK
int* p = nullptr; //OK

and when you have two function overloads like this:

void func(int x);   //1)
void func(int* x);  //2)

func(NULL) calls 1) because NULL is an integer. func(nullptr) calls 2) because nullptr converts implicitly to a pointer of type int*.

Also if you see a statement like this:

auto result = findRecord( /* arguments */ );

if (result == nullptr)
{
 ...
}

and you can't easily find out what findRecord returns, you can be sure that result must be a pointer type; nullptr makes this more readable.

In a deduced context, things work a little differently. If you have a template function like this:

template<typename T>
void func(T *ptr)
{
    ...
}

and you try to call it with nullptr:

func(nullptr);

you will get a compiler error because nullptr is of type nullptr_t. You would have to either explicitly cast nullptr to a specific pointer type or provide an overload/specialization for func with nullptr_t.


Advantages of using nulptr:
  • avoid ambiguity between function overloads
  • enables you to do template specialization
  • more secure, intuitive and expressive code, e.g. if (ptr == nullptr) instead of if (ptr == 0)

How to remove numbers from string using Regex.Replace?

var result = Regex.Replace("123- abcd33", @"[0-9\-]", string.Empty);

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

Convert row names into first column

Or you can use dplyr's add_rownames which does the same thing as David's answer:

library(dplyr)
df <- tibble::rownames_to_column(df, "VALUE")

UPDATE (mid-2016): (incorporated to the above)

old function called add_rownames() has been deprecated and is being replaced by tibble::rownames_to_column() (same functions, but Hadley refactored dplyr a bit).

Converting a char to ASCII?

You can use chars as is as single byte integers.

Where is NuGet.Config file located in Visual Studio project?

In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.

Detect if Android device has Internet connection

A nice solution to check if the active network have internet connection:

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        Network network = connectivityManager.getActiveNetwork();
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
        return networkCapabilities != null && networkCapabilities
                .hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    }
    return false;
}

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

How to position absolute inside a div?

One of #a or #b needs to be not position:absolute, so that #box will grow to accommodate it.

So you can stop #a from being position:absolute, and still position #b over the top of it, like this:

_x000D_
_x000D_
 #box {_x000D_
        background-color: #000;_x000D_
        position: relative;     _x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }_x000D_
    _x000D_
    .a {_x000D_
        width: 210px;_x000D_
        background-color: #fff;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    .b {_x000D_
        width: 100px; /* So you can see the other one */_x000D_
        position: absolute;_x000D_
        top: 10px; left: 10px;_x000D_
        background-color: red;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    #after {_x000D_
        background-color: yellow;_x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }
_x000D_
    <div id="box">_x000D_
        <div class="a">Lorem</div>_x000D_
        <div class="b">Lorem</div>_x000D_
    </div>_x000D_
    <div id="after">Hello world</div>
_x000D_
_x000D_
_x000D_

(Note that I've made the widths different, so you can see one behind the other.)

Edit after Justine's comment: Then your only option is to specify the height of #box. This:

#box {
    /* ... */
    height: 30px;
}

works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
          "http://www.w3.org/TR/html4/strict.dtd">

before that works properly.

What could cause java.lang.reflect.InvocationTargetException?

The error vanished after I did Clean->Run xDoclet->Run xPackaging.

In my workspace, in ecllipse.

Hard reset of a single file

you can use the below command for reset of single file

git checkout HEAD -- path_to_file/file_name

List all changed files to get path_to_file/filename with below command

git status

How do I enable/disable log levels in Android?

We can use class Log in our local component and define the methods as v/i/e/d. Based on the need of we can make call further.
example is shown below.

    public class Log{
        private static boolean TAG = false;
        public static void d(String enable_tag, String message,Object...args){
            if(TAG)
            android.util.Log.d(enable_tag, message+args);
        }
        public static void e(String enable_tag, String message,Object...args){
            if(TAG)
            android.util.Log.e(enable_tag, message+args);
        }
        public static void v(String enable_tag, String message,Object...args){
            if(TAG)
            android.util.Log.v(enable_tag, message+args);
        }
    }
    if we do not need any print(s), at-all make TAG as false for all else 
    remove the check for type of Log (say Log.d).
    as 
    public static void i(String enable_tag, String message,Object...args){
    //      if(TAG)
            android.util.Log.i(enable_tag, message+args);
    }

here message is for string and and args is the value you want to print.

Is it possible to declare a variable in Gradle usable in Java?

https://stackoverflow.com/a/17201265/12021422 Answer by @rciovati works

But make sure you rebuild the project to be able to remove the error from Android Studio IDE

I spent 30 minutes trying to figure out why the new property variables aren't accessible.

If the "Make Project" as marked with red color doesn't work then try the "Rebuild Project" Button as marked with green color.

enter image description here

Return multiple values to a method caller

Future version of C# is going to include named tuples. Have a look at this channel9 session for the demo https://channel9.msdn.com/Events/Build/2016/B889

Skip to 13:00 for the tuple stuff. This will allow stuff like:

(int sum, int count) Tally(IEnumerable<int> list)
{
// calculate stuff here
return (0,0)
}

int resultsum = Tally(numbers).sum

(incomplete example from video)

Missing visible-** and hidden-** in Bootstrap v4

For bootstrap 4, here's a matrix image explaining the classes used to show / hide elements depends on the screen size: enter image description here

Source : Meduim : Bootstrap 4 Hidden & Visible

extract part of a string using bash/cut/split

Define a function like this:

getUserName() {
    echo $1 | cut -d : -f 1 | xargs basename
}

And pass the string as a parameter:

userName=$(getUserName "/var/cpanel/users/joebloggs:DNS9=domain.com")
echo $userName

The view or its master was not found or no view engine supports the searched locations

Check whether the View (.ASPX File) that you have created is having the same name as mentioned in the Controller. For e.g:

 public ActionResult GetView()
 {
    return View("MyView");
 }

In this case, the aspx file should be having the name MyView.aspx instead of GetView.aspx

Padding characters in printf

There's no way to pad with anything but spaces using printf. You can use sed:

printf "%-50s@%s\n" $PROC_NAME [UP] | sed -e 's/ /-/g' -e 's/@/ /' -e 's/-/ /'

Is there a JavaScript strcmp()?

localeCompare() is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:

str1 < str2 ? -1 : +(str1 > str2)

This is an order of magnitude faster than localeCompare() on my machine.

The + ensures that the answer is always numeric rather than boolean.

SHA-256 or MD5 for file integrity

Both SHA256 and MDA5 are hashing algorithms. They take your input data, in this case your file, and output a 256/128-bit number. This number is a checksum. There is no encryption taking place because an infinite number of inputs can result in the same hash value, although in reality collisions are rare.

SHA256 takes somewhat more time to calculate than MD5, according to this answer.

Offhand, I'd say that MD5 would be probably be suitable for what you need.

Sorting an array in C?

In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
     int int_a = * ( (int*) a );
     int int_b = * ( (int*) b );

     if ( int_a == int_b ) return 0;
     else if ( int_a < int_b ) return -1;
     else return 1;
}

qsort( a, 6, sizeof(int), compare )

see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.

As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort

Open mvc view in new window from controller

@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})

   script below will open the action view url in a new window

<script type="text/javascript">
    $(function (){
        $('a.edit').click(function () {
            var url = $(this).attr('href');
            window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
            });
            return false;
        });   
</script>

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

I will put a small comparison table here (just to have it somewhere):

Servlet is mapped as /test%3F/* and the application is deployed under /app.

http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a

Method              URL-Decoded Result           
----------------------------------------------------
getContextPath()        no      /app
getLocalAddr()                  127.0.0.1
getLocalName()                  30thh.loc
getLocalPort()                  8480
getMethod()                     GET
getPathInfo()           yes     /a?+b
getProtocol()                   HTTP/1.1
getQueryString()        no      p+1=c+d&p+2=e+f
getRequestedSessionId() no      S%3F+ID
getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme()                     http
getServerName()                 30thh.loc
getServerPort()                 8480
getServletPath()        yes     /test?
getParameterNames()     yes     [p 2, p 1]
getParameter("p 1")     yes     c d

In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.

Comments

  • "+" is handled as space only in the query string

  • Anchor "#a" is not transferred to the server. Only the browser can work with it.

  • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

If Spring MVC is used

  • Method getPathInfo() returns null.

  • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

  • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

Print JSON parsed object?

Just use

console.info("CONSOLE LOG : ")
console.log(response);
console.info("CONSOLE DIR : ")
console.dir(response);

and you will get this in chrome console :

CONSOLE LOG : 
facebookSDK_JS.html:56 Object {name: "Diego Matos", id: "10155988777540434"}
facebookSDK_JS.html:57 CONSOLE DIR : 
facebookSDK_JS.html:58 Objectid: "10155988777540434"name: "Diego Matos"__proto__: Object

How to get date, month, year in jQuery UI datepicker?

what about that simple way)

$(document).ready ->
 $('#datepicker').datepicker( dateFormat: 'yy-mm-dd',  onSelect: (dateStr) ->
    alert dateStr # yy-mm-dd
    #OR
    alert $("#datepicker").val(); # yy-mm-dd

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Please see my working sample application on Github and compare with your set up.

How to create a .NET DateTime from ISO 8601 format

Here is one that works better for me (LINQPad version):

DateTime d;
DateTime.TryParseExact(
    "2010-08-20T15:00:00Z",
    @"yyyy-MM-dd\THH:mm:ss\Z",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal, 
    out d);
d.ToString()

produces

true
8/20/2010 8:00:00 AM

How to delete and update a record in Hive

The CLI told you where is your mistake : delete WHAT? from student ...

Delete : How to delete/truncate tables from Hadoop-Hive?

Update : Update , SET option in Hive

How to create a Restful web service with input parameters?

Be careful. For this you need @GET (not @PUT).

How to watch and compile all TypeScript sources?

TypeScript 1.5 beta has introduced support for a configuration file called tsconfig.json. In that file you can configure the compiler, define code formatting rules and more importantly for you, provide it with information about the TS files in your project.

Once correctly configured, you can simply run the tsc command and have it compile all the TypeScript code in your project.

If you want to have it watch the files for changes then you can simply add --watch to the tsc command.

Here's an example tsconfig.json file

{
"compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false
},
"include": [
    "**/*"
],
"exclude": [
    "node_modules",
    "**/*.spec.ts"
]}

In the example above, I include all .ts files in my project (recursively). Note that you can also exclude files using an "exclude" property with an array.

For more information, refer to the documentation: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

SQL Server String Concatenation with Null

You can use ISNULL(....)

SET @Concatenated = ISNULL(@Column1, '') + ISNULL(@Column2, '')

If the value of the column/expression is indeed NULL, then the second value specified (here: empty string) will be used instead.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

Stylesheet not updating

I ran into this problem too, a lot of people seem to recommend force reloading your page, which won't fix the issue in cases such as if you're running it on a server. I believe the optimal solution in this scenario is to timestamp your css.

  1. This is how I do it in my Django template:

<link rel="stylesheet" href="{% static 'home/radioStyles.css' %}?{% now 'U' %}" type="text/css"/>

Where adding ?{% now 'U' %} to the end of your css file would fix this issue.

  1. How you would do it with just CSS (hopefully someone edits this to a cleaner version, this looks a little janky but it does work, tested it):

<link rel="stylesheet" type="text/css" href="style.css?Wednesday 2nd February 2020 12PM" />

Where ?Wednesday 2nd February 2020 12PM (current date) seems to fix the issue, I also noticed just putting the time fixes it too.

ValueError: all the input arrays must have same number of dimensions

You can also cast (n,) to (n,1) by enclosing within brackets [ ].

e.g. Instead of np.append(b,a,axis=0) use np.append(b,[a],axis=0)

a=[1,2]
b=[[5,6],[7,8]]
np.append(b,[a],axis=0)

returns

array([[5, 6],
       [7, 8],
       [1, 2]])

Calculate difference between two dates (number of days)?

DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

We recently ran into a similar issue and was unable to find anything obvious as the cause. There turned out to be a control character in our string but when we outputted that string to the browser that character was not visible unless we copied the text into an IDE.

We managed to solve our problem thanks to this post and this:

preg_replace('/[\x00-\x1F\x7F]/', '', $input);

TSQL DATETIME ISO 8601

For ISO 8601 format for Datetime & Datetime2, below is the recommendation from SQL Server. It does not support basic ISO 8601 format for datetime(yyyyMMddThhmmss).

DateTime

YYYY-MM-DDThh:mm:ss[.mmm]

YYYYMMDD[ hh:mm:ss[.mmm]]

Examples:

  1. 2004-05-23T14:25:10

  2. 2004-05-23T14:25:10.487

Datetime2

YYYY-MM-DDThh:mm:ss[.nnnnnnn]

YYYY-MM-DDThh:mm:ss[.nnnnnnn] Examples:

  1. 2004-05-23T14:25:10

  2. 2004-05-23T14:25:10.8849926

You can convert them using 126 option

--Datetime

DECLARE @table Table(ExtendedDate DATETIME, BasicDate Datetime)

DECLARE @ExtendedDate VARCHAR(30) = '2020-07-01T08:39:17' , @BasicDate VARCHAR(30) = '2009-01-23T10:53:21.000'

INSERT INTO @table(ExtendedDate, BasicDate)
SELECT convert(datetime,@ExtendedDate,126) ,convert(datetime,@BasicDate,126)

SELECT * FROM @table
go

-- Datetime2

DECLARE @table Table(ExtendedDate DATETIME2, BasicDate Datetime2)

DECLARE @ExtendedDate VARCHAR(30) = '2000-01-14T13:42:00.0000000' , @BasicDate VARCHAR(30) = '2009-01-23T10:53:21.0000000'

INSERT INTO @table(ExtendedDate, BasicDate)
SELECT convert(datetime2,@ExtendedDate,126) ,convert(datetime2,@BasicDate,126)

SELECT * FROM @table
go

Datetime

+-------------------------+-------------------------+
|      ExtendedDate       |        BasicDate        |
+-------------------------+-------------------------+
| 2020-07-01 08:39:17.000 | 2009-01-23 10:53:21.000 |
+-------------------------+-------------------------+

Datetime2


+-----------------------------+-----------------------------+
|        ExtendedDate         |          BasicDate          |
+-----------------------------+-----------------------------+
| 2000-01-14 13:42:00.0000000 | 2009-01-23 10:53:21.0000000 |
+-----------------------------+-----------------------------+

How can I "disable" zoom on a mobile web page?

The solution using a meta-tag did not work for me (tested on Chrome win10 and safari IOS 14.3), and I also believe that the concerns regarding accessibility, as mentioned by Jack and others, should be honored.

My solution is to disable zooming only on elements that are damaged by the default zoom.

I did this by registering event listeners for zoom-gestures and using event.preventDefault() to suppress the browsers default zoom-behavior.

This needs to be done with several events (touch gestures, mouse wheel and keys). The following snippet is an example for the mouse wheel and pinch gestures on touchpads:

noteSheetCanvas.addEventListener("wheel", e => {
        // suppress browsers default zoom-behavior:
        e.preventDefault();

        // execution my own custom zooming-behavior:
        if (e.deltaY > 0) {
            this._zoom(1);
        } else {
            this._zoom(-1);
        }
    });

How to detect touch gestures is described here: https://stackoverflow.com/a/11183333/1134856

I used this to keep the standard zooming behavior for most parts of my application and to define custom zooming-behavior on a canvas-element.

Init array of structs in Go

Adding this just as an addition to @jimt's excellent answer:

one common way to define it all at initialization time is using an anonymous struct:

var opts = []struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}{
    {'a', "multiple", "Usage for a", false},
    {
        shortnm: 'b',
        longnm:  "b-option",
        needArg: false,
        help:    "Usage for b",
    },
}

This is commonly used for testing as well to define few test cases and loop through them.

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

Converting between datetime, Timestamp and datetime64

If you want to convert an entire pandas series of datetimes to regular python datetimes, you can also use .to_pydatetime().

pd.date_range('20110101','20110102',freq='H').to_pydatetime()

> [datetime.datetime(2011, 1, 1, 0, 0) datetime.datetime(2011, 1, 1, 1, 0)
   datetime.datetime(2011, 1, 1, 2, 0) datetime.datetime(2011, 1, 1, 3, 0)
   ....

It also supports timezones:

pd.date_range('20110101','20110102',freq='H').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()

[ datetime.datetime(2011, 1, 1, 11, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
 datetime.datetime(2011, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
....

NOTE: If you are operating on a Pandas Series you cannot call to_pydatetime() on the entire series. You will need to call .to_pydatetime() on each individual datetime64 using a list comprehension or something similar:

datetimes = [val.to_pydatetime() for val in df.problem_datetime_column]

How to execute a Ruby script in Terminal?

Assuming ruby interpreter is in your PATH (it should be), you simply run

ruby your_file.rb

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Read file As String

The code finally used is the following from:

http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm

public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line).append("\n");
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;
}

error C2065: 'cout' : undeclared identifier

I ran across this error after just having installed vs 2010 and just trying to get a nearly identical program to work.

I've done vanilla C coding on unix-style boxes before, decided I'd play with this a bit myself.

The first program I tried was:

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World!";
    return 0;
}

The big thing to notice here... if you've EVER done any C coding,

int _tmain(int argc, _TCHAR* argv[])

Looks weird. it should be:

int main( int argc, char ** argv )

In my case I just changed the program to:

#include <iostream>
using namespace std;

int main()
{
     cout << "Hello world from  VS 2010!\n";
     return 0;
}

And it worked fine.

Note: Use CTRL + F5 so that the console window sticks around so you can see the results.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.

Personally, I wouldn't bother; I'd just rename the column.

PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.

How to use Selenium with Python?

There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples

You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.

Redirect all output to file in Bash

Use >> to append:

command >> file

How do I get console input in javascript?

Good old readline();.

See MDN (archive).

What does the Excel range.Rows property really do?

I've found this works:

Rows(CStr(iVar1) & ":" & CStr(iVar2)).Select

What is the LDF file in SQL Server?

ldf saves the log of the db, certainly doesn't saves any real data, but is very important for the proper function of the database.

You can however change the log model to the database to simple so this log does not grow too fast.

Check this for example.

Check here for reference.

XOR operation with two strings in java

This is the code I'm using:

private static byte[] xor(final byte[] input, final byte[] secret) {
    final byte[] output = new byte[input.length];
    if (secret.length == 0) {
        throw new IllegalArgumentException("empty security key");
    }
    int spos = 0;
    for (int pos = 0; pos < input.length; ++pos) {
        output[pos] = (byte) (input[pos] ^ secret[spos]);
        ++spos;
        if (spos >= secret.length) {
            spos = 0;
        }
    }
    return output;
}

How to edit incorrect commit message in Mercurial?

Update: Mercurial has added --amend which should be the preferred option now.


You can rollback the last commit (but only the last one) with hg rollback and then reapply it.

Important: this permanently removes the latest commit (or pull). So if you've done a hg update that commit is no longer in your working directory then it's gone forever. So make a copy first.

Other than that, you cannot change the repository's history (including commit messages), because everything in there is check-summed. The only thing you could do is prune the history after a given changeset, and then recreate it accordingly.

None of this will work if you have already published your changes (unless you can get hold of all copies), and you also cannot "rewrite history" that include GPG-signed commits (by other people).

UnicodeEncodeError: 'charmap' codec can't encode characters

In Python 3.7, and running Windows 10 this worked (I am not sure whether it will work on other platforms and/or other versions of Python)

Replacing this line:

with open('filename', 'w') as f:

With this:

with open('filename', 'w', encoding='utf-8') as f:

The reason why it is working is because the encoding is changed to UTF-8 when using the file, so characters in UTF-8 are able to be converted to text, instead of returning an error when it encounters a UTF-8 character that is not suppord by the current encoding.

Making view resize to its parent when added with addSubview

that's all you need

childView.frame = parentView.bounds

LINQ: "contains" and a Lambda query

I'm not sure precisely what you're looking for, but this program:

    public class Building
    {
        public enum StatusType
        {
            open,
            closed,
            weird,
        };

        public string Name { get; set; }
        public StatusType Status { get; set; }
    }

    public static List <Building> buildingList = new List<Building> ()
    {
        new Building () { Name = "one", Status = Building.StatusType.open },
        new Building () { Name = "two", Status = Building.StatusType.closed },
        new Building () { Name = "three", Status = Building.StatusType.weird },

        new Building () { Name = "four", Status = Building.StatusType.open },
        new Building () { Name = "five", Status = Building.StatusType.closed },
        new Building () { Name = "six", Status = Building.StatusType.weird },
    };

    static void Main (string [] args)
    {
        var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };

        var q = from building in buildingList
                where statusList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);
    }

produces the expected output:

one: open
two: closed
four: open
five: closed

This program compares a string representation of the enum and produces the same output:

    public class Building
    {
        public enum StatusType
        {
            open,
            closed,
            weird,
        };

        public string Name { get; set; }
        public string Status { get; set; }
    }

    public static List <Building> buildingList = new List<Building> ()
    {
        new Building () { Name = "one", Status = "open" },
        new Building () { Name = "two", Status = "closed" },
        new Building () { Name = "three", Status = "weird" },

        new Building () { Name = "four", Status = "open" },
        new Building () { Name = "five", Status = "closed" },
        new Building () { Name = "six", Status = "weird" },
    };

    static void Main (string [] args)
    {
        var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
        var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());

        var q = from building in buildingList
                where statusStringList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);

        Console.ReadKey ();
    }

I created this extension method to convert one IEnumerable to another, but I'm not sure how efficient it is; it may just create a list behind the scenes.

public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
    foreach ( TSource source in sources )
        yield return convert (source);
}

Then you can change the where clause to:

where statusList.ConvertEach <string> (status => status.GetCharValue()).
    Contains (v.Status)

and skip creating the List<string> with ConvertAll () at the beginning.

How to add minutes to my Date

Just for anybody who is interested. I was working on an iOS project that required similar functionality so I ended porting the answer by @jeznag to swift

private func addMinutesToDate(minutes: Int, beforeDate: NSDate) -> NSDate {
    var SIXTY_SECONDS = 60

    var m = (Double) (minutes * SIXTY_SECONDS)
    var c =  beforeDate.timeIntervalSince1970  + m
    var newDate = NSDate(timeIntervalSince1970: c)

    return newDate
}

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

If you do Code-First and already have a Database:

public override void Up()
{
    AlterColumn("dbo.MyTable","Id", c =>  c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"));
}

jQuery UI: Datepicker set year range dropdown to 100 years

This is a bit late in the day for suggesting this, given how long ago the original question was posted, but this is what I did.

I needed a range of 70 years, which, while not as much as 100, is still too many years for the visitor to scroll through. (jQuery does step through year in groups, but that's a pain in the patootie for most people.)

The first step was to modify the JavaScript for the datepicker widget: Find this code in jquery-ui.js or jquery-ui-min.js (where it will be minimized):

for (a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+
a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)
 a.yearshtml+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
a.yearshtml+="</select>";

And replace it with this:

a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+
 ".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');
 \" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');
 \">";
for(opg=-1;b<=g;b++) {
    a.yearshtml+=((b%10)==0 || opg==-1 ?
        (opg==1 ? (opg=0, '</optgroup>') : '')+
        (b<(g-10) ? (opg=1, '<optgroup label="'+b+' >">') : '') : '')+
        '<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
}
a.yearshtml+="</select>";

This surrounds the decades (except for the current) with OPTGROUP tags.

Next, add this to your CSS file:

.ui-datepicker OPTGROUP { font-weight:normal; }
.ui-datepicker OPTGROUP OPTION { display:none; text-align:right; }
.ui-datepicker OPTGROUP:hover OPTION { display:block; }

This hides the decades until the visitor mouses over the base year. Your visitor can scroll through any number of years quickly.

Feel free to use this; just please give proper attribution in your code.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

POST JSON to API using Rails and HTTParty

The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)

query_string_normalizer: ->(query){query.to_json}

How to delete the contents of a folder?

I'm surprised nobody has mentioned the awesome pathlib to do this job.

If you only want to remove files in a directory it can be a oneliner

from pathlib import Path

[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()] 

To also recursively remove directories you can write something like this:

from pathlib import Path
from shutil import rmtree

for path in Path("/path/to/folder").glob("**/*"):
    if path.is_file():
        path.unlink()
    elif path.is_dir():
        rmtree(path)

Is mathematics necessary for programming?

No, you don't need to know any math (except maybe binary/oct/hex/dec representations) for system programming and stuff like that.

How to support placeholder attribute in IE8 and 9

the $.Browser.msie is not on the latest JQuery anymore... you have to use the $.support

like below:

 <script>

     (function ($) {
         $.support.placeholder = ('placeholder' in document.createElement('input'));
     })(jQuery);


     //fix for IE7 and IE8
     $(function () {
         if (!$.support.placeholder) {
             $("[placeholder]").focus(function () {
                 if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
             }).blur(function () {
                 if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
             }).blur();

             $("[placeholder]").parents("form").submit(function () {
                 $(this).find('[placeholder]').each(function() {
                     if ($(this).val() == $(this).attr("placeholder")) {
                         $(this).val("");
                     }
                 });
             });
         }
     });
 </script>