Programs & Examples On #Pdfsharp

PDFsharp - A .NET library for processing PDF (create, merge, split, or modify PDF files). For questions related to using the PDFsharp library on any platform and with any programming language.

Difference between abstract class and interface in Python

Abstract classes are classes that contain one or more abstract methods. Along with abstract methods, Abstract classes can have static, class and instance methods. But in case of interface, it will only have abstract methods not other. Hence it is not compulsory to inherit abstract class but it is compulsory to inherit interface.

Converting from longitude\latitude to Cartesian coordinates

Theory for convert GPS(WGS84) to Cartesian coordinates https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates

The following is what I am using:

  • Longitude in GPS(WGS84) and Cartesian coordinates are the same.
  • Latitude need be converted by WGS 84 ellipsoid parameters semi-major axis is 6378137 m, and
  • Reciprocal of flattening is 298.257223563.

I attached a VB code I wrote:

Imports System.Math

'Input GPSLatitude is WGS84 Latitude,h is altitude above the WGS 84 ellipsoid

Public Function GetSphericalLatitude(ByVal GPSLatitude As Double, ByVal h As Double) As Double

        Dim A As Double = 6378137 'semi-major axis 
        Dim f As Double = 1 / 298.257223563  '1/f Reciprocal of flattening
        Dim e2 As Double = f * (2 - f)
        Dim Rc As Double = A / (Sqrt(1 - e2 * (Sin(GPSLatitude * PI / 180) ^ 2)))
        Dim p As Double = (Rc + h) * Cos(GPSLatitude * PI / 180)
        Dim z As Double = (Rc * (1 - e2) + h) * Sin(GPSLatitude * PI / 180)
        Dim r As Double = Sqrt(p ^ 2 + z ^ 2)
        Dim SphericalLatitude As Double =  Asin(z / r) * 180 / PI
        Return SphericalLatitude
End Function

Please notice that the h is altitude above the WGS 84 ellipsoid.

Usually GPS will give us H of above MSL height. The MSL height has to be converted to height h above the WGS 84 ellipsoid by using the geopotential model EGM96 (Lemoine et al, 1998).
This is done by interpolating a grid of the geoid height file with a spatial resolution of 15 arc-minutes.

Or if you have some level professional GPS has Altitude H (msl,heigh above mean sea level) and UNDULATION,the relationship between the geoid and the ellipsoid (m) of the chosen datum output from internal table. you can get h = H(msl) + undulation

To XYZ by Cartesian coordinates:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

MongoDB: How to update multiple documents with a single command?

You can use.`

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  `

'this' vs $scope in AngularJS controllers

In this course(https://www.codeschool.com/courses/shaping-up-with-angular-js) they explain how to use "this" and many other stuff.

If you add method to the controller through "this" method, you have to call it in the view with controller's name "dot" your property or method.

For example using your controller in the view you may have code like this:

    <div data-ng-controller="YourController as aliasOfYourController">

       Your first pane is {{aliasOfYourController.panes[0]}}

    </div>

How do you develop Java Servlets using Eclipse?

Alternatively you can use Jetty which is (now) part of the Eclipe Platform (the Help system is running Jetty). Besides Jetty is used by Android, Windows Mobile..

To get started check the Eclipse Wiki or if you prefer a Video And check out this related Post!

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

I run it like this -

created > startOfDay(-0d)

It gives me all issues created today. When you change -0d to -1d, it will give you all issues created yesterday and today.

What to do about Eclipse's "No repository found containing: ..." error messages?

In my case, the only solution was a manual installation (the plugin's page explained how to install it from the Eclipse's Help menu and, as an alternative, were to unpack the zip manually).

gradlew: Permission Denied

I got the same error trying to execute flutter run on a mac. Apparently, in your flutter project, there is a file android/gradlew that is expected to be executable (and it wasn't). So in my case,

chmod a+rx android/gradlew

i used this command and execute the project

Append an object to a list in R in amortized constant time, O(1)?

If it's a list of string, just use the c() function :

R> LL <- list(a="tom", b="dick")
R> c(LL, c="harry")
$a
[1] "tom"

$b
[1] "dick"

$c
[1] "harry"

R> class(LL)
[1] "list"
R> 

That works on vectors too, so do I get the bonus points?

Edit (2015-Feb-01): This post is coming up on its fifth birthday. Some kind readers keep repeating any shortcomings with it, so by all means also see some of the comments below. One suggestion for list types:

newlist <- list(oldlist, list(someobj))

In general, R types can make it hard to have one and just one idiom for all types and uses.

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

It's all based on your requirement. if you are developing a small scale app and covers only specific region (target audience), you can choose BIGINT to store only numbers since VARCHAR consumes more byte than BIGINT ( having optimal memory usage design matters ). but if you are developing a large scale app and targets global users and you have enough database capabilities to store data, you can definitely choose VARCHAR.

C++ equivalent of Java's toString?

You can also do it this way, allowing polymorphism:

class Base {
public:
   virtual std::ostream& dump(std::ostream& o) const {
      return o << "Base: " << b << "; ";
   }
private:
  int b;
};

class Derived : public Base {
public:
   virtual std::ostream& dump(std::ostream& o) const {
      return o << "Derived: " << d << "; ";
   }
private:
   int d;
}

std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); }

Javascript/Jquery to change class onclick?

Your getElementById is looking for an element with id "myclass", but in your html the id of the DIV is showhide. Change to:

<script>
function changeclass() {

var NAME = document.getElementById("showhide")

NAME.className="mynewclass"

} 
</script>

Unless you are trying to target a different element with the id "myclass", then you need to make sure such an element exists.

How do I prevent an Android device from going to sleep programmatically?

what @eldarerathis said is correct in all aspects, the wake lock is the right way of keeping the device from going to sleep.

I don't know waht you app needs to do but it is really important that you think on how architect your app so that you don't force the phone to stay awake for more that you need, or the battery life will suffer enormously.

I would point you to this really good example on how to use AlarmManager to fire events and wake up the phone and (your app) to perform what you need to do and then go to sleep again: Alarm Manager (source: commonsware.com)

How to get character for a given ascii value

Sorry I dont know Java, but I was faced with the same problem tonight, so I wrote this (it's in c#)

public string IncrementString(string inboundString)    {
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(inboundString.ToArray);
bool incrementNext = false;

for (l = -(bytes.Count - 1); l <= 0; l++) {
    incrementNext = false;

    int bIndex = Math.Abs(l);
    int asciiVal = Conversion.Val(bytes(bIndex).ToString);

    asciiVal += 1;

    if (asciiVal > 57 & asciiVal < 65)
        asciiVal = 65;
    if (asciiVal > 90) {
        asciiVal = 48;
        incrementNext = true;
    }

    bytes(bIndex) = System.Text.Encoding.ASCII.GetBytes({ Strings.Chr(asciiVal) })(0);

    if (incrementNext == false)
        break; // TODO: might not be correct. Was : Exit For
}

inboundString = System.Text.Encoding.ASCII.GetString(bytes);

return inboundString;
}

How to modify memory contents using GDB?

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

How to convert a 3D point into 2D perspective projection?

Thanks to @Mads Elvenheim for a proper example code. I have fixed the minor syntax errors in the code (just a few const problems and obvious missing operators). Also, near and far have vastly different meanings in vs.

For your pleasure, here is the compileable (MSVC2013) version. Have fun. Mind that I have made NEAR_Z and FAR_Z constant. You probably dont want it like that.

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

#define M_PI 3.14159

#define NEAR_Z 0.5
#define FAR_Z 2.5

struct Vector
{
    float x;
    float y;
    float z;
    float w;

    Vector() : x( 0 ), y( 0 ), z( 0 ), w( 1 ) {}
    Vector( float a, float b, float c ) : x( a ), y( b ), z( c ), w( 1 ) {}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt( x*x + y*y + z*z );
    }
    Vector& operator*=(float fac) noexcept
    {
        x *= fac;
        y *= fac;
        z *= fac;
        return *this;
    }
    Vector  operator*(float fac) const noexcept
    {
        return Vector(*this)*=fac;
    }
    Vector& operator/=(float div) noexcept
    {
        return operator*=(1/div);   // avoid divisions: they are much
                                    // more costly than multiplications
    }

    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if (mag < epsilon) {
            std::out_of_range e( "" );
            throw e;
        }
        return Vector(*this)/=mag;
    }
};

inline float Dot( const Vector& v1, const Vector& v2 )
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
public:
    Matrix() : data( 16 )
    {
        Identity();
    }
    void Identity()
    {
        std::fill( data.begin(), data.end(), float( 0 ) );
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[]( size_t index )
    {
        if (index >= 16) {
            std::out_of_range e( "" );
            throw e;
        }
        return data[index];
    }
    const float& operator[]( size_t index ) const
    {
        if (index >= 16) {
            std::out_of_range e( "" );
            throw e;
        }
        return data[index];
    }
    Matrix operator*( const Matrix& m ) const
    {
        Matrix dst;
        int col;
        for (int y = 0; y<4; ++y) {
            col = y * 4;
            for (int x = 0; x<4; ++x) {
                for (int i = 0; i<4; ++i) {
                    dst[x + col] += m[i + col] * data[x + i * 4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=( const Matrix& m )
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix( float fov, float aspectRatio )
    {
        Identity();
        float f = 1.0f / std::tan( fov * 0.5f );
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (FAR_Z + NEAR_Z) / (FAR_Z- NEAR_Z);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*NEAR_Z*FAR_Z) / (NEAR_Z - FAR_Z);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};


inline Vector operator*( const Vector& v, Matrix& m )
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip( int width, int height, const VecArr& vertex )
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix( 60.0f * (M_PI / 180.0f), aspect);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping
    by checking if the x, y and z components are inside the range of [-w, w].
    One checks each vector component seperately against each plane. Per-vertex
    data like colours, normals and texture coordinates need to be linearly
    interpolated for clipped edges to reflect the change. If the edge (v0,v1)
    is tested against the positive x plane, and v1 is outside, the interpolant
    becomes: (v1.x - w) / (v1.x - v0.x)
    I skip this stage all together to be brief.
    */
    for (VecArr::const_iterator i = vertex.begin(); i != vertex.end(); ++i) {
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back( v );
    }

    /* TODO: Clipping here */

    for (VecArr::iterator i = dst.begin(); i != dst.end(); ++i) {
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}
#pragma once

How exactly does the python any() function work?

(x > 0 for x in list) in that function call creates a generator expression eg.

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

Which any uses, and shortcircuits on encountering the first object that evaluates True

ReSharper "Cannot resolve symbol" even when project builds

For me, inspecting the solution gave me hundreds of errors, including many "cannot find file in search paths". I tried every suggestion out there to fix it and none of them worked. I ended up finding out inspecting the project, instead of the solution, worked perfectly.

How to clear or stop timeInterval in angularjs?

You can store the promise returned by the interval and use $interval.cancel() to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start() and stop() functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click) and in the controller.

_x000D_
_x000D_
angular.module('app', [])_x000D_
_x000D_
  .controller('ItemController', function($scope, $interval) {_x000D_
  _x000D_
    // store the interval promise in this variable_x000D_
    var promise;_x000D_
  _x000D_
    // simulated items array_x000D_
    $scope.items = [];_x000D_
    _x000D_
    // starts the interval_x000D_
    $scope.start = function() {_x000D_
      // stops any running interval to avoid two intervals running at the same time_x000D_
      $scope.stop(); _x000D_
      _x000D_
      // store the interval promise_x000D_
      promise = $interval(setRandomizedCollection, 1000);_x000D_
    };_x000D_
  _x000D_
    // stops the interval_x000D_
    $scope.stop = function() {_x000D_
      $interval.cancel(promise);_x000D_
    };_x000D_
  _x000D_
    // starting the interval by default_x000D_
    $scope.start();_x000D_
 _x000D_
    // stops the interval when the scope is destroyed,_x000D_
    // this usually happens when a route is changed and _x000D_
    // the ItemsController $scope gets destroyed. The_x000D_
    // destruction of the ItemsController scope does not_x000D_
    // guarantee the stopping of any intervals, you must_x000D_
    // be responsible for stopping it when the scope is_x000D_
    // is destroyed._x000D_
    $scope.$on('$destroy', function() {_x000D_
      $scope.stop();_x000D_
    });_x000D_
            _x000D_
    function setRandomizedCollection() {_x000D_
      // items to randomize 1 - 11_x000D_
      var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
        _x000D_
      // empties the items array_x000D_
      $scope.items.length = 0; _x000D_
      _x000D_
      // loop through random N times_x000D_
      while(randomItems--) {_x000D_
        _x000D_
        // push random number from 1 - 10000 to $scope.items_x000D_
        $scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
      }_x000D_
    }_x000D_
  _x000D_
  });
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
  _x000D_
  <!-- Event trigger to start the interval -->_x000D_
  <button type="button" ng-click="start()">Start Interval</button>_x000D_
  _x000D_
  <!-- Event trigger to stop the interval -->_x000D_
  <button type="button" ng-click="stop()">Stop Interval</button>_x000D_
  _x000D_
  <!-- display all the random items -->_x000D_
  <ul>_x000D_
    <li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
  </ul>_x000D_
  <!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Here is Kotlin version.
Thanks you :)

         fun unSafeOkHttpClient() :OkHttpClient.Builder {
            val okHttpClient = OkHttpClient.Builder()
            try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts:  Array<TrustManager> = arrayOf(object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                    override fun getAcceptedIssuers(): Array<X509Certificate>  = arrayOf()
                })

                // Install the all-trusting trust manager
                val  sslContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, SecureRandom())

                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory = sslContext.socketFactory
                if (trustAllCerts.isNotEmpty() &&  trustAllCerts.first() is X509TrustManager) {
                    okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
                    okHttpClient.hostnameVerifier { _, _ -> true }
                }

                return okHttpClient
            } catch (e: Exception) {
                return okHttpClient
            }
        }

Convert javascript array to string

jQuery.each is just looping over the array, it doesn't do anything with the return value?. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):

var blkstr = $.map(value, function(val,index) {                    
     var str = index + ":" + val;
     return str;
}).join(", ");  

DEMO


But why use jQuery at all in this case? map only introduces an unnecessary function call per element.

var values = [];

for(var i = 0, l = value.length; i < l; i++) {
    values.push(i + ':' + value[i]);
}

// or if you actually have an object:

for(var id in value) {
    if(value.hasOwnProperty(id)) {
        values.push(id + ':' + value[id]);
    }
}

var blkstr = values.join(', ');

?: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.

update to python 3.7 using anaconda

The September 4th release for 3.7 recommends the following:

conda install python=3.7 anaconda=custom

If you want to create a new environment, they recommend:

conda create -n example_env numpy scipy pandas scikit-learn notebook
anaconda-navigator
conda activate example_env

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

Creating .exe distributions isn't typical for Java. While such wrappers do exist, the normal mode of operation is to create a .jar file.

To create a .jar file from a Java project in Eclipse, use file->export->java->Jar file. This will create an archive with all your classes.

On the command prompt, use invocation like the following:

java -cp myapp.jar foo.bar.MyMainClass

How to obfuscate Python code effectively?

Try pasting your hello world python code to the following site:

http://enscryption.com/encrypt-and-obfuscate-scripts.html

It will produce a complex encrypted and obfuscated, but fully functional script for you. See if you can crack the script and reveal the actual code. Or see if the level of complexity it provides satisfies your need for peace of mind.

The encrypted script that is produced for you through this site should work on any Unix system that has python installed.

If you would like to encrypt another way, I strongly suggest you write your own encryption/obfuscation algorithm (if security is that important to you). That way, no one can figure out how it works but you. But, for this to really work, you have to spend a tremendous amount of time on it to ensure there aren't any loopholes that someone who has a lot of time on their hands can exploit. And make sure you use tools that are already natural to the Unix system... i.e. openssl or base64. That way, your encrypted script is more portable.

Alternative to a goto statement in Java

There isn't any direct equivalent to the goto concept in Java. There are a few constructs that allow you to do some of the things you can do with a classic goto.

  • The break and continue statements allow you to jump out of a block in a loop or switch statement.
  • A labeled statement and break <label> allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block).
  • If you label a loop statement, you can continue <label> to continue with the next iteration of an outer loop from an inner loop.
  • Throwing and catching exceptions allows you to (effectively) jump out of many levels of a method call. (However, exceptions are relatively expensive and are considered to be a bad way to do "ordinary" control flow1.)
  • And of course, there is return.

None of these Java constructs allow you to branch backwards or to a point in the code at the same level of nesting as the current statement. They all jump out one or more nesting (scope) levels and they all (apart from continue) jump downwards. This restriction helps to avoid the goto "spaghetti code" syndrome inherent in old BASIC, FORTRAN and COBOL code2.


1- The most expensive part of exceptions is the actual creation of the exception object and its stacktrace. If you really, really need to use exception handling for "normal" flow control, you can either preallocate / reuse the exception object, or create a custom exception class that overrides the fillInStackTrace() method. The downside is that the exception's printStackTrace() methods won't give you useful information ... should you ever need to call them.

2 - The spaghetti code syndrome spawned the structured programming approach, where you limited in your use of the available language constructs. This could be applied to BASIC, Fortran and COBOL, but it required care and discipline. Getting rid of goto entirely was a pragmatically better solution. If you keep it in a language, there is always some clown who will abuse it.

How to Exit a Method without Exiting the Program?

In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;

will always return at that point. However:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    return;
}

will only return if it goes into that if statement.

Uncaught ReferenceError: jQuery is not defined

set this jquery min js

script src="http://code.jquery.com/jquery-1.10.1.min.js"

in wp-admin/admin-header.php

How to get all columns' names for all the tables in MySQL?

The question was :

Is there a fast way of getting all COLUMN NAMES from all tables in MySQL, without having to list all the tables?

SQL to get all information for each column

select * from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position

SQL to get all COLUMN NAMES

select COLUMN_NAME from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

just to add another example of what a lambda can do without using map:

a = 10
b = 2

var mixed = (a,b) => a * b; 
// OR
var mixed = (a,b) => { (any logic); return a * b };

console.log(mixed(a,b)) 
// 20

Swift - How to convert String to Double

Extension with optional locale

Swift 2.2

extension String {
    func toDouble(locale: NSLocale? = nil) -> Double? {
        let formatter = NSNumberFormatter()
        if let locale = locale {
            formatter.locale = locale
        }
        return formatter.numberFromString(self)?.doubleValue
    }
}

Swift 3.1

extension String {
    func toDouble(_ locale: Locale) -> Double {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.locale = locale
        formatter.usesGroupingSeparator = true
        if let result = formatter.number(from: self)?.doubleValue {
            return result
        } else {
            return 0
        }
    }
}

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

Shortcut to Apply a Formula to an Entire Column in Excel

Select a range of cells (the entire column in this case), type in your formula, and hold down Ctrl while you press Enter. This places the formula in all selected cells.

"Find next" in Vim

The most useful shortcut in Vim, IMHO, is the * key.

Put the cursor on a word and hit the * key and you will jump to the next instance of that word.

The # key does the same, but it jumps to the previous instance of the word.

It is truly a time saver.

jQuery detect if textarea is empty

Here is my working code

function emptyTextAreaCheck(textarea, submitButtonClass) {
        if(!submitButtonClass)
            submitButtonClass = ".transSubmit";

            if($(textarea).val() == '') {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            }

        $(textarea).live('focus keydown keyup', function(){
            if($(this).val().length == 0) {
                $(submitButtonClass).addClass('disabled_button');
                $(submitButtonClass).removeClass('transSubmit');
            } else {
                $('.disabled_button').addClass('transSubmit').css({
                    'cursor':'pointer'
                }).removeClass('disabled_button');
            }
        });
    }

Java8: sum values from specific field of the objects in a list

You can also collect with an appropriate summing collector like Collectors#summingInt(ToIntFunction)

Returns a Collector that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.

For example

Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));

RecyclerView: Inconsistency detected. Invalid item position

extends LinearLayoutManager and catch this error

public class NoCrashLinearLayoutManager extends LinearLayoutManager {

    public NoCrashLinearLayoutManager(Context context) {
        super(context);
    }

    public NoCrashLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public NoCrashLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
        } catch (IndexOutOfBoundsException e){
            e.printStackTrace();
        }
    }
}

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

TypeError: tuple indices must be integers, not str

TL;DR: add the parameter cursorclass=MySQLdb.cursors.DictCursor at the end of your MySQLdb.connect.


I had a working code and the DB moved, I had to change the host/user/pass. After this change, my code stopped working and I started getting this error. Upon closer inspection, I copy-pasted the connection string on a place that had an extra directive. The old code read like:

 conn = MySQLdb.connect(host="oldhost",
                        user="olduser",
                        passwd="oldpass",
                        db="olddb", 
                        cursorclass=MySQLdb.cursors.DictCursor)

Which was replaced by:

 conn = MySQLdb.connect(host="newhost",
                        user="newuser",
                        passwd="newpass",
                        db="newdb")

The parameter cursorclass=MySQLdb.cursors.DictCursor at the end was making python allow me to access the rows using the column names as index. But the poor copy-paste eliminated that, yielding the error.

So, as an alternative to the solutions already presented, you can also add this parameter and access the rows in the way you originally wanted. ^_^ I hope this helps others.

How to find the mysql data directory from command line in windows

Check if the Data directory is in "C:\ProgramData\MySQL\MySQL Server 5.7\Data". This is where it is on my computer. Someone might find this helpful.

Why is my CSS style not being applied?

Have you tried forcing the selectors to be in the front of the class?

p span label.fancify {

    font-size: 1.5em;
    font-weight: 800;
    font-family: Consolas, "Segoe UI", Calibri, sans-serif;
    font-style: italic;
}

Usually it will add more weight to your CSS declaration. My mistake ... There should be no space between the selector and the class. The same goes for the ID. If you have for example:

<div id="first">
    <p id="myParagraph">Hello <span class="bolder">World</span></p>
</div>

You would style it like this:

div#first p#myParagraph {
     color : #ff0000;
}

Just to make a complete example using a class:

div#first p#myParagraph span.bolder{
    font-weight:900;
}

For more information about pseudo-selectors and child selectors : http://www.w3.org/TR/CSS2/selector.html

CSS is a whole science :) Beware that some browsers can have incompatibilities and will not show you the proper results. For more information check this site: http://www.caniuse.com/

Looping over a list in Python

Try this,

x in mylist is better and more readable than x in mylist[:] and your len(x) should be equal to 3.

>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
...      if len(x)==3:
...        print x
...
[1, 2, 3]
[8, 9, 10]

or if you need more pythonic use list-comprehensions

>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>

Launching an application (.EXE) from C#?

Use Process.Start to start a process.

using System.Diagnostics;
class Program
{
    static void Main()
    {
    //
    // your code
    //
    Process.Start("C:\\process.exe");
    }
} 

background-image: url("images/plaid.jpg") no-repeat; wont show up

Try this:

body
{ 
    background:url("images/plaid.jpg") no-repeat fixed center;
}

jsfiddle example: http://jsfiddle.net/Q9Zfa/

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

java -version
java -showversion

Both commands work In Linux 16.04 LTS

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

How to use cURL to send Cookies?

You can refer to https://curl.haxx.se/docs/http-cookies.html for a complete tutorial of how to work with cookies. You can use

curl -c /path/to/cookiefile http://yourhost/

to write to a cookie file and start engine and to use cookie you can use

curl -b /path/to/cookiefile  http://yourhost/

to read cookies from and start the cookie engine, or if it isn't a file it will pass on the given string.

Tesseract running error

I had this error too on the Windows machine.

My solution.

1) Download your language files from https://github.com/tesseract-ocr/tessdata/tree/3.04.00

For example, for eng, I downloaded all files with eng prefix.

2) Put them into tessdata directory inside of some folder. Add this folder into System Path variables as TESSDATA_PREFIX.

Result will be System env var: TESSDATA_PREFIX=D:/Java/OCR And OCR folder has tessdata with languages files.

This is a screenshot of the directory:

enter image description here

How to git reset --hard a subdirectory?

What about

subdir=thesubdir
for fn in $(find $subdir); do
  git ls-files --error-unmatch $fn 2>/dev/null >/dev/null;
  if [ "$?" = "1" ]; then
    continue;
  fi
  echo "Restoring $fn";
  git show HEAD:$fn > $fn;
done 

How to search in a List of Java object

If you always search based on value3, you could store the objects in a Map:

Map<String, List<Sample>> map = new HashMap <>();

You can then populate the map with key = value3 and value = list of Sample objects with that same value3 property.

You can then query the map:

List<Sample> allSamplesWhereValue3IsDog = map.get("Dog");

Note: if no 2 Sample instances can have the same value3, you can simply use a Map<String, Sample>.

SQL Query - how do filter by null or not null

Wherever you are trying to check NULL value of a column, you should use

IS NULL and IS NOT NULL

You should not use =NULL or ==NULL


Example(NULL)

select * from user_registration where registered_time IS NULL 

will return the rows with registered_time value is NULL


Example(NOT NULL)

select * from user_registration where registered_time IS NOT NULL 

will return the rows with registered_time value is NOT NULL

Note: The keyword null, not null and is are not case sensitive.

Java Error opening registry key

I have Windows 7. I got the same problem after installing: PyCharm. I wasn't satisfied with PyCharm, so I decided to use Eclipse instead. This is when I discovered that things went wrong with my JDK. I used to have Java.9.x. So I decided to uninstall it and get the newer version (at my time it was Java.11.x. The same problem persisted. I followed most of the steps mentioned above in the post like: - Removing all java*.exe files, - removing Java related entries from the registry. - Cleaning-up all unnecessary Java folders. However nothing helped. I still had something in the system referring to a broken Java pathname.

What really brought remedy is the following: - Uninstalled what ever version of JDK I had at the moment. - Re-Installed the last JDK version I had before the problem took place - Properly uninstall that version. - Install whatever latest version of SDK. ..

That's it .. at this point everything returned to normal ... Except that Java.11.xx did not fix the system path automatically, I had to do it manually.

Difference between dates in JavaScript

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

_x000D_
_x000D_
function date_units_diff(a, b, unit_amounts) {_x000D_
    var split_to_whole_units = function (milliseconds, unit_amounts) {_x000D_
        // unit_amounts = list/array of amounts of milliseconds in a_x000D_
        // second, seconds in a minute, etc., for example "[1000, 60]"._x000D_
        time_data = [milliseconds];_x000D_
        for (i = 0; i < unit_amounts.length; i++) {_x000D_
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));_x000D_
            time_data[i] = time_data[i] % unit_amounts[i];_x000D_
        }; return time_data.reverse();_x000D_
    }; if (unit_amounts == undefined) {_x000D_
        unit_amounts = [1000, 60, 60, 24];_x000D_
    };_x000D_
    var utc_a = new Date(a.toUTCString());_x000D_
    var utc_b = new Date(b.toUTCString());_x000D_
    var diff = (utc_b - utc_a);_x000D_
    return split_to_whole_units(diff, unit_amounts);_x000D_
}_x000D_
_x000D_
// Example of use:_x000D_
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);_x000D_
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(_x000D_
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));
_x000D_
_x000D_
_x000D_

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index 

Generating a unique machine id

There is a library available for getting hardware specific informations: Hardware serial number extractor (CPU, RAM, HDD, BIOS)

Twitter Bootstrap carousel different height images cause bouncing arrows

The solution given earlier leads to a situation where images may be too small for the carousel box. A proper solution to the problem of bumping controls is to override Bootstraps CSS.

Original code:

.carousel-control {
top: 40%;
}

Override the variable with a fixed value inside your own stylesheet (300px worked in my design):

.carousel-control {
top: 300px;
}

Hopefully this will solve your problem.

How to get the caller's method name in the called method?

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)

How to remove leading zeros using C#

This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:

using System.Text.RegularExpressions;

/*
00123 => 123
00000 => 0
00000a => 0a
00001a => 1a
00001a => 1a
0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
*/

Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
var strs = new string[]
{
    "00123",
    "00000",
    "00000a",
    "00001a",
    "00001a",
    "0000132423423424565443546546356546454654633333a",
};
foreach (string str in strs)
{
    Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
}

And this regex will remove leading zeroes anywhere inside string:

new Regex(@"(?<!\d)0+(?=\d)");
//  "0000123432 d=0 p=002 3?0574 m=600"
//     => "123432 d=0 p=2 3?574 m=600"

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

assign multiple variables to the same value in Javascript

The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment.

let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:

/data/data/APP_PACKAGE_NAME

The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

Convert decimal to hexadecimal in UNIX shell script

Tried printf(1)?

printf "%x\n" 34
22

There are probably ways of doing that with builtin functions in all shells but it would be less portable. I've not checked the POSIX sh specs to see whether it has such capabilities.

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

I work on 60-70% zoom vue and my dropdown are unreadable so I made this simple code to overcome the issue

Note that I selected first all my dropdown lsts (CTRL+mouse click), went on formula tab, clicked "define name" and called them "ProduktSelection"

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("ProduktSelection")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

ActiveWindow.Zoom = 100

End If

End Sub

I then have another sub

Private Sub Worksheet_Change(ByVal Target As Range) 

where I come back to 65% when value is changed.

Forbidden You don't have permission to access / on this server

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)

Solution:

Replace all:

<Directory />
     AllowOverride none
    Require all denied

</Directory>

with

<Directory />
     AllowOverride none
#    Require all denied

</Directory>

hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
#   Require local
</Directory>

how to configure hibernate config file for sql server

The connection URL should look like this for SQL Server:

jdbc:sqlserver://serverName[\instanceName][:port][;databaseName=your_db_name]

Examples:

jdbc:sqlserver://localhost
jdbc:sqlserver://127.0.0.1\INGESQL:1433;databaseName=datatest
...

PHP fwrite new line

How about you store it like this? Maybe in username:password format, so

sebastion:password123
anotheruser:password321

Then you can use list($username,$password) = explode(':',file_get_contents('users.txt')); to parse the data on your end.

Is System.nanoTime() completely useless?

nanoTime is extremely insecure for timing. I tried it out on my basic primality testing algorithms and it gave answers which were literally one second apart for the same input. Don't use that ridiculous method. I need something that is more accurate and precise than get time millis, but not as bad as nanoTime.

Handling warning for possible multiple enumeration of IEnumerable

If the aim is really to prevent multiple enumerations than the answer by Marc Gravell is the one to read, but maintaining the same semantics you could simple remove the redundant Any and First calls and go with:

public List<object> Foo(IEnumerable<object> objects)
{
    if (objects == null)
        throw new ArgumentNullException("objects");

    var first = objects.FirstOrDefault();

    if (first == null)
        throw new ArgumentException(
            "Empty enumerable not supported.", 
            "objects");

    var list = DoSomeThing(first);  

    var secondList = DoSomeThingElse(objects);

    list.AddRange(secondList);

    return list;
}

Note, that this assumes that you IEnumerable is not generic or at least is constrained to be a reference type.

Detect application heap size in Android

Here's how you do it:

Getting the max heap size that the app can use:

Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory();

Getting how much of the heap your app currently uses:

long usedMemory=runtime.totalMemory() - runtime.freeMemory();

Getting how much of the heap your app can now use (available memory) :

long availableMemory=maxMemory-usedMemory;

And, to format each of them nicely, you can use:

String formattedMemorySize=Formatter.formatShortFileSize(context,memorySize); 

Wait until page is loaded with Selenium WebDriver for Python

On a side note, instead of scrolling down 100 times, you can check if there are no more modifications to the DOM (we are in the case of the bottom of the page being AJAX lazy-loaded)

def scrollDown(driver, value):
    driver.execute_script("window.scrollBy(0,"+str(value)+")")

# Scroll down the page
def scrollDownAllTheWay(driver):
    old_page = driver.page_source
    while True:
        logging.debug("Scrolling loop")
        for i in range(2):
            scrollDown(driver, 500)
            time.sleep(2)
        new_page = driver.page_source
        if new_page != old_page:
            old_page = new_page
        else:
            break
    return True

HTTP Headers for File Downloads

You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:

<?php

$filename = $_GET['file'];

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
  exit;
};
switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

Add a new line to a text file in MS-DOS

echo "text to echo" > file.txt

Disable/turn off inherited CSS3 transitions

Another way to remove all transitions is with the unset keyword:

a.tags {
    transition: unset;
}

In the case of transition, unset is equivalent to initial, since transition is not an inherited property:

a.tags {
    transition: initial;
}

A reader who knows about unset and initial can tell that these solutions are correct immediately, without having to think about the specific syntax of transition.

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

You need to check which jar is giving problem. It must be corrupted. Delete that jar and run mvn spring-boot:run command again. May be more that one jar has corrupted so every time you need to run that command to delete that jar. In my case mysql, jackson, aspect jars was corrupted mvn spring-boot:run command 3 times and I figure out this and deleted the jars from .m2 folder. Now the issue has resolved.

The provider is not compatible with the version of Oracle client

Here's what I did to solve this problem that persisted for 3 long hours:

  1. Under Oracle home located at C:\oracle\product\11.2.0 I had a folder called client_1 where I had previously installed ODP.NET bits for Windows 64 bits.

  2. Later while trying to debug my ASP.NET Web API app with Visual Studio 2012, I kept getting this error message: The provider is not compatible with the version of Oracle client.

  3. Searching Google I found that this was happening because I was using ODP.NET 64 bits. Then I grabbed ODP.NET for Windows 32 bits and installed it but I kept getting the same error message.

  4. SOLUTION: deleted the folder client_1 and resinstalled ODP.NET 32 bits. Somewhat the installer was mixing bits from the 64 bit version with the 32 bit version. Go figure...

  5. Now I'm happy again and I can open a new OracleConnection. FINALLY! :)

Get user's current location

as PHP relies on server, the real-time location cant be provided only static location can be provided it is better to avoid to rely on the JS for location rather than using php. But there is a need to post the js data to php so that it can be easily be accesible to program on server

How to save a pandas DataFrame table as a png

Pandas allows you to plot tables using matplotlib (details here). Usually this plots the table directly onto a plot (with axes and everything) which is not what you want. However, these can be removed first:

import matplotlib.pyplot as plt
import pandas as pd
from pandas.table.plotting import table # EDIT: see deprecation warnings below

ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis

table(ax, df)  # where df is your data frame

plt.savefig('mytable.png')

The output might not be the prettiest but you can find additional arguments for the table() function here. Also thanks to this post for info on how to remove axes in matplotlib.


EDIT:

Here is a (admittedly quite hacky) way of simulating multi-indexes when plotting using the method above. If you have a multi-index data frame called df that looks like:

first  second
bar    one       1.991802
       two       0.403415
baz    one      -1.024986
       two      -0.522366
foo    one       0.350297
       two      -0.444106
qux    one      -0.472536
       two       0.999393
dtype: float64

First reset the indexes so they become normal columns

df = df.reset_index() 
df
    first second       0
0   bar    one  1.991802
1   bar    two  0.403415
2   baz    one -1.024986
3   baz    two -0.522366
4   foo    one  0.350297
5   foo    two -0.444106
6   qux    one -0.472536
7   qux    two  0.999393

Remove all duplicates from the higher order multi-index columns by setting them to an empty string (in my example I only have duplicate indexes in "first"):

df.ix[df.duplicated('first') , 'first'] = '' # see deprecation warnings below
df
  first second         0
0   bar    one  1.991802
1          two  0.403415
2   baz    one -1.024986
3          two -0.522366
4   foo    one  0.350297
5          two -0.444106
6   qux    one -0.472536
7          two  0.999393

Change the column names over your "indexes" to the empty string

new_cols = df.columns.values
new_cols[:2] = '',''  # since my index columns are the two left-most on the table
df.columns = new_cols 

Now call the table function but set all the row labels in the table to the empty string (this makes sure the actual indexes of your plot are not displayed):

table(ax, df, rowLabels=['']*df.shape[0], loc='center')

et voila:

enter image description here

Your not-so-pretty but totally functional multi-indexed table.

EDIT: DEPRECATION WARNINGS

As pointed out in the comments, the import statement for table:

from pandas.tools.plotting import table

is now deprecated in newer versions of pandas in favour of:

from pandas.plotting import table 

EDIT: DEPRECATION WARNINGS 2

The ix indexer has now been fully deprecated so we should use the loc indexer instead. Replace:

df.ix[df.duplicated('first') , 'first'] = ''

with

df.loc[df.duplicated('first') , 'first'] = ''

JavaScript/jQuery - "$ is not defined- $function()" error

if you are trying to use jquery in your electron app before adding jquery you should add it to your modules:

<script>
    if (typeof module === 'object') {
        window.module = module;
        module = undefined;
    }
</script>
<script src="js/jquery-3.5.1.min.js"></script>

fatal: could not read Username for 'https://github.com': No such file or directory

This error can also happen when trying to clone an invalid HTTP URL. For example, this is the error I got when trying to clone a GitHub URL that was a few characters off:

$ git clone -v http://github.com/username/repo-name.git
Cloning into 'repo-name'...
Username for 'https://github.com': 
Password for 'https://github.com': 
remote: Repository not found.
fatal: Authentication failed for 'https://github.com/username/repo-name.git/'

It actually happened inside Emacs, though, so the error in Emacs looked like this:

fatal: could not read Username for ’https://github.com’: No such device or address

So instead of a helpful error saying that there was no such repo at that URL, it gave me that, sending me on a wild goose chase until I finally realized that the URL was incorrect.

This is with git version 2.7.4.

I'm posting this here because it happened to me a month ago and again just now, sending me on the same wild goose chase again. >:(

Adding git branch on the Bash command prompt

Here is a simple clean version that I use: link

enter image description here

C++ program converts fahrenheit to celsius

In C++, 5/9 computes the result as an integer as both the operands are integers. You need to give an hint to the compiler that you want the result as a float/double. You can do it by explictly casting one of the operands like ((double)5)/9;

EDIT Since it is tagged C++, you can do the casting bit more elegantly using the static_cast. For example: static_cast<double>(5)/9. Although in this particular case you can directly use 5.0/9 to get the desired result, the casting will be helpful when you have variables instead of constant values such as 5.

Export to csv/excel from kibana

I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.

Best way to check for null values in Java?

You also can use StringUtils.isNoneEmpty("") for check is null or empty.

How do you import an Eclipse project into Android Studio now?

Android Studio has been improved since this question was posted, and the latest versions of Android Studio (as of this writing, we are at 2.1.1) have fairly good Eclipse importing capabilities, so importing Eclipse projects directly into Android Studio is now the best approach for migrating projects from Eclipse into Android Studio.

I will describe how to do this below, including a few of the pitfalls that one might encounter. I will deal in particular with importing an Eclipse workspace that contains multiple apps sharing one or more project libraries (the approaches posted thus far seem limited to importing just one Eclipse app project and its project libraries). While I don't deal with every possible issue, I do go into a lot of detail regarding some of them, which I hope will be helpful to those going through this process for the first time themselves.

I recently imported the projects from an Eclipse workspace. This workspace included four library projects that were shared between up to nine projects each.

Some background:

An Eclipse workspace contains multiple projects, which may be library projects or apps.

An Android Studio project is analogous to an Eclipse workspace, in that it can contain both library projects and apps. However, a library project or an app is represented by a "module" in Android Studio, whereas it is represented by a "project" in Eclipse.

So, to summarize: Eclipse workspaces will end up as Android Studio projects, and Eclipse projects inside a workspace will end up as Android Studio modules inside a project.

You should start the import process by creating an Android Studio project (File / New / New Project). You might give this project the same (or similar) name as you gave your Eclipse workspace. This project will eventually hold all of your modules, one each for each Eclipse project (including project libraries) that you will import.

The import process does not change your original Eclipse files, so long as you place the imported files in a different folder hierarchy, so you should choose a folder for this project that is not in your original Eclipse hierarchy. For example, if your Eclipse projects are all in a folder called Android, you might create a sibling folder called AStudio.

Your Android Studio project can then be created as a sub-folder of this new folder. The New Project wizard will prompt you to enter this top-level project folder, into which it will create your project.

Android Studio's new project wizard will then ask you to configure a single module at the time you create the project. This can be a little confusing at first, because they never actually tell you that you are creating a module, but you are; you are creating a project with a single module in it. Apparently, every project is required to have at least one module, so, since you are relying on Eclipse to provide your modules, your initial module will be a placeholder to vacuously satisfy that formal requirement.

Thus, you probably will want to create an initial module for your project that does as little as possible. Therefore, select Phone and Tablet as the type of your module, accept the default minimum SDK (API level 8), and select Add No Activity for your module.

Next, select one of the Eclipse app projects in your workspace that requires the largest number of libraries as your first project to import. The advantage of doing this is that when you import that project, all the library projects that it uses (directly, or indirectly, if some of your library projects themselves require other library projects) will get imported along with it as part of the importing process.

Each of these imported projects will get its own module within your Android Studio project. All of these modules will be siblings of one another (both in your project hierarchy, and in the folder hierarchy where their files are placed), just as if you had imported the modules separately. However, the dependencies between the modules will be created for you (in your app's build.gradle files) as part of the importing process.

Note that after you finish importing, testing and debugging this "most dependent" Eclipse project and its supporting library projects, you will go on to import a second Eclipse app project (if you have a second one in your workspace) and its library project modules (with those imported earlier getting found by the import wizard as existing modules and re-used for this new module, rather than being duplicated).

So, you should never have to import even a single library project from Eclipse directly; they will all be brought in indirectly, based on their dependencies upon app projects that you import. This is assuming that all of your library projects in the workspace are created to serve the needs of one or more app projects in that same workspace.

To perform the import of this first app project, back in Android Studio, while you are in the project that you just created, select File / New / New Module. You might think that you should be using File / New / Import Module, but no, you should not, because if you do that, Android Studio will create a new project to hold your imported module, and it will import your module to that project. You actually could create your first module that way, but then the second through Nth modules would still require that you use this other method (for importing a module into an existing project), and so I think that just starting with an "empty" project (or rather, one with its own vacuous, do-nothing placeholder module), and then importing each of your Eclipse projects as a new module into that project (i.e., the approach we are taking here), may be less confusing.

So, you are going to take your practically-empty new project, and perform a File / New / New Module in it. The wizard that this invokes will give you a choice of what kind of module you want to create. You must select "Import Eclipse ADT Project." That is what accesses the wizard that knows how to convert an Eclipse project into an Android Studio module (along with the library modules on which it depends) within your current Android Studio project.

When prompted for a source folder, you should enter the folder for your Eclipse project (this is the folder that contains that project's AndroidManifest.xml file).

The import wizard will then display the module name that it intends to create (similar to your original Eclipse project's name, but with a lower-case first letter because that is a convention that distinguishes module names from project names (which start with an upper-case letter). It usually works pretty well to accept this default.

Below the module name is a section titled "Additional required modules." This will list every library required by the module you are importing (or by any of its libraries, etc.). Since this is the first module you are importing, none of these will already be in your project, so each of them will have its Import box checked by default. You should leave these checked because you need these modules. (Note that when you import later Eclipse app projects, if a library that they need has already been imported, those libraries will still appear here, but there will be a note that "Project already contains module with this name," and the Import box will be un-checked by default. In that case, you should leave the box unchecked, so that the importer will hook up your newly-imported module(s) to the libraries that have already been imported. It may be that accepting the default names that Android Studio creates for your modules will be important for allowing the IDE to find and re-use these library modules.

Next, the importer will offer to replace any jars and library sources with Gradle dependencies, and to create camelCase module names for any dependent modules, checking all those options by default. You should generally leave these options checked and continue. Read the warning, though, about possible problems. Remember that you can always delete an imported module or modules (via the Project Structure dialog) and start the import process over again.

The next display that I got (YMMV) claims that the Android Support Repository is not installed in my SDK installation. It provides a button to open the Android SDK Manager for purposes of installing it. However, that button did not work for me. I manually opened the SDK manager as a separate app, and found that the Android Support Repository was already installed. There was an update, however. I installed that, and tapped the Refresh button in the import dialog, but that did nothing. So, I proceeded, and the perceived lack of this Repository did not seem to hurt the importing process (although I did get messages regarding it being missing from time to time later on, while working with the imported code, which I was able to appease by clicking a supplied link that corrected the problem - at least temporarily). Eventually this problem went away when I installed an update to the repository, so you may not experience it at all.

At this point, you will click Finish, and after a bit it should create your modules and build them. If all goes well, you should get a BUILD SUCCESSFUL message in your Gradle Console.

One quirk is that if the build fails, you may not see your imported modules in the Project hierarchy. It seems that you need to get to the first valid build before the new modules will appear there (my experience, anyway). You may still be able to see the new modules in the File / Project Structure dialog (e.g., if you want to delete them and start your import over).

Remember that since you are not changing your original Eclipse projects, you can always delete the modules that you have just imported (if importing goes badly), and start all over again. You can even make changes to the Eclipse side after deleting your Android Studio modules, if that will make importing go better the second time (so long as you preserve your fallback ability to build your existing source under Eclipse). As you'll see when we discuss version control below, it may be necessary for you to retain your ability to build under Eclipse, because the project structure is changed under Android Studio, so if you need to go back to a commit that precedes your move to Android Studio (e.g., to make a bug fix), you will want to have the ability to build that earlier commit in Eclipse.

To delete a module, you must select File / Project Structure, then select the module from the left side of the dialog, and then hit the delete key. For some reason, I was not able to delete a module directly in the Project hierarchy; it had to be done using this Project Structure dialog.

The import wizard generates an import-summary.txt file containing a detailed list of any issues it may have encountered, along with actions taken to resolve them. You should read it carefully, as it may provide clues as to what is happening if you have trouble building or running the imported code. It will also help you to find things that the importer moves around to accommodate the different structure of Android Studio projects.

If all does not go well, then have at look at these possible problems that you may encounter, along with solutions for those problems:

Generally speaking, there are two main kinds of problems that I encountered:

  1. Proguard problems
  2. Manifest problems

When Proguard is messed up, the (obfuscated) names of methods in your libraries may not match the names being used to invoke them from your app, and you will get compiler errors like "error: cannot find symbol class ..."

In Eclipse, Proguard stuff is pretty much ignored for library projects, with the Proguard stuff for any app project that you are building determining the obfuscation, etc. for not just itself, but for processing all of the libraries on which it depends. And that is generally what you want.

In Android Studio, however, you need to make some changes to attain this same effect. Basically, in the build.gradle files for each of your library project modules, you will want something like this:

buildTypes {
    release {
        minifyEnabled false
        consumerProguardFiles 'proguard.cfg'
    }
}

Where proguard.cfg is your library module's own proguard configuration file.

The term "consumer" in "consumerProguardFiles" apparently refers to the app module that is using this library module. So the proguard commands from that app are used in preference to those of the library module itself, and apparently this results in obfuscations that are coordinated and compatible, so that all calls from the app module to its library modules are made with matching symbols.

These "consumerProguardFiles" entries are not created automatically during the import process (at least that was my own experience) so you will want to make sure to edit that into your library modules' build.gradle files if they are not created for you during importing.

If you wanted to distribute your library projects separately, with obfuscation, then you would need an individual proguard file for them; I have not done this myself, and so that is beyond the scope of this answer.

In the app module, you will want something like this:

buildTypes {
    release {
        minifyEnabled true
        proguardFiles 'proguard.cfg'
    }
}

(BTW, as of this writing, while my apps are running just fine, I have not yet directly confirmed that things are actually getting obfuscated using this approach, so do check this yourself - e.g., by using a decompiler like apktool. I will be checking this later on, and will edit this answer when I get that info).

The second kind of problem is due to the fact that Eclipse pretty much ignores the manifest files for library projects when compiling an app project that uses those library projects, while in Android Studio, there is an interleaving of the two that apparently does not consistently prioritize the app's manifest over those of its libraries.

I encountered this because I had a library manifest that listed (just for documentation purposes) an abstract Activity class as the main activity. There was a class derived from this abstract class in my app that was declared in the manifest of each app that used the library.

In Eclipse, this never caused any problems, because the library manifests were ignored. But in Android Studio, I ended up with that abstract class as my activity class for the app, which caused a run-time error when the code made an attempt to instantiate that abstract class.

You have two choices in this case:

  1. Use tools syntax to override specific library manifest stuff in your app manifest - for example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.goalstate.WordGames.FullBoard.trialsuite"
       xmlns:tools="http://schemas.android.com/tools"
       .
       .
        <application
           tools:replace="android:name"

or,

  1. Strip out practically everything from your library modules' manifests, and rely upon the app module's manifest to provide every value. Note that you do need to have a manifest for each library module, but not much more is required than the header and a bare manifest element with just a package attribute in it.

I tried both and ended up with approach 2., above, as the simpler method. However, if you wanted to distribute your library modules separately, you would need to create a more meaningful manifest file that reflects each library module's own individual requirements.

There is probably a more "correct" way to do this which puts requirements (e.g., permissions) for each library in the library manifest itself, and allows the automatic interleaving process to combine these with those declared for the app. However, given that Eclipse ignores the manifests for libraries, it seems safer at least initially to rely entirely on the app manifests and just strip the library manifests down to the bare bones.

Be aware that some of the project properties, and also the manifest attributes, from your Eclipse project will have been used to construct portions of your build.gradle files. Specifically, your compileSdkVersion in build.gradle is set to the project build version from the Eclipse project properties, applicationId is the package name from your app's manifest, and minSdkVersion and targetSdkVersion are also copied from the app's manifest file. The dependencies section of build.gradle comes from the library project dependencies in your project's properties.

Note that this may make some of your AndroidManifest.xml values redundant and quite possibly residual (i.e., unused). This could create confusion. My understanding is that the build.gradle values are the ones that actually have an effect, and that the manifest values like targetSdkVersion are not used any more for purposes of building. However, they may still be used by app stores such as Google Play; I don't know for certain one way or the other, so at this point I am just maintaining them in tandem.

Besides the above two kinds of issue, there are more routine things like importing a project that has a project build level of 22 when you have only installed SDK level 23 in Android Studio. In that situation, it is probably better to edit your app module's build.gradle file to move compileSdkVersion from 22 (the imported value) to 23, than it would be to install the SDK for level 22, but either approach should work.

Throughout this entire process, when something does not build properly and you make a change to try to address it, you might want to try Build / Rebuild Project and/or Tools / Android / Sync Project with Gradle Files, and/or File / Invalidate Caches/Restart, to make sure that your changes have been fully incorporated. I don't know exactly when these are truly necessary, because I don't know how much is done incrementally when you haven't yet had a successful build, but I performed them all fairly regularly as a kind of superstitious ritual, and I'm fairly certain that it helped. For example, when I got a Resources$NotFound runtime error that appeared to be from an inability to find the launch icon resource, I tried all three, and the problem was fixed.

When you have performed the above for your first Eclipse project and have attained a successful build, then with luck, you can select your app module from the dropdown at the top of the Android Studio display to the left of the play button, then click the play button itself, then select a device or Android Virtual Device, and the app should be loaded for running.

Likewise, you should be able to create a signed copy of your app using the Build / Generate Signed APK feature. Note that some import-related errors may appear when running your signed copy that do not appear when using the play button, so you need to confirm that both are working before deciding that your import is complete.

Following this, you will probably want to turn on version control. I am using git myself, but there are a number of other options available.

Version control is mostly beyond the scope of this answer, but there are a few things that are affected by the importing process. First, in Eclipse you might have your various projects in various folders stuck all over the place, but when you import into Android Studio, all modules will be created as direct child folders of your main project folder. So if you had a separate git folder for each project in Eclipse, or for related groups of projects organized under a parent folder for each group (as I did), that is not going to translate very well to Android Studio.

My knowledge of this is limited as I have not worked with version control yet in Android Studio, so maybe there is a way around this, but it appears that all version control in Android Studio is unified at the project level, and so all of your modules will be under a single git archive.

This means that you may need to abandon your old git archive and start fresh with a new archive for your imported source code. And that means that you will want to keep your old git archive around, so that it can be used with Eclipse to perform any needed bug fixes, etc., at least for a while. And you also will want it to preserve a history of your project.

If you are fortunate enough to have had all of your projects organized under a single Eclipse workspace, and if you were using a single git archive for those projects, then it is possible that you might just copy your old git archive from in and under your Eclipse workspace folder to in and under your Android Studio project folder. Then, you could edit any still-relevant .gitignore items from you Eclipse project into the auto-generated .gitignore file for your Android Studio project, and let git figure out what has been changed during the importing process (and some things will have been moved around - for example, the manifest file is no longer at the top level of your module). Others have reported that git is pretty good at figuring out what has changed; I have not tried this myself.

But even if you did this, going back to a commit that precedes your move from Eclipse to Android Studio would be going back to a set of files that would only make sense from inside Eclipse. So it sounds, well, "difficult" to work with. Especially since Eclipse will still be pointing to its original set of project folders.

I personally had multiple git archives for my various sets of related projects, and so I decided to just make a clean break and start git over again in Android Studio. If you had to do this, it could affect your planning, because you would want to be at a very stable point in your code development before making the move in that case, since you will lose some accessibility to that older code within your version control system (e.g., ability to merge with post-import code) once you have made the move to Android Studio.

The part of this answer that pertains to git is partly speculative, since I have not actually worked with version control yet on my imported project files, but I wanted to include it to give some idea of the challenges, and I plan to update my answer after I have worked more with version control inside Android Studio.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I use java.net.URI#getRawPath(), e.g.

String s = "a+b c.html";
String fixed = new URI(null, null, s, null).getRawPath();

The value of fixed will be a+b%20c.html, which is what you want.

Post-processing the output of URLEncoder.encode() will obliterate any pluses that are supposed to be in the URI. For example

URLEncoder.encode("a+b c.html").replaceAll("\\+", "%20");

will give you a%20b%20c.html, which will be interpreted as a b c.html.

Javascript AES encryption

Judging from my own experience, asmcrypto.js provides the fastest AES implementation in JavaScript (especially in Firefox since it can fully leverage asm.js there).

From the readme:

Chrome/31.0
SHA256: 51 MiB/s (9 times faster than SJCL and CryptoJS)
AES-CBC: 47 MiB/s (13 times faster than CryptoJS and 20 times faster than SJCL)

Firefox/26.0
SHA256: 144 MiB/s (5 times faster than CryptoJS and 20 times faster than SJCL)
AES-CBC: 81 MiB/s (3 times faster than CryptoJS and 8 times faster than SJCL)

Edit: The Web Cryptography API is now implemented in most browsers and should be used as the primary solution if you care about performance. Be aware that IE11 implemented an earlier draft version of the standard which did not use promises.

Some examples can be found here:

Python style - line continuation with strings?

Another possibility is to use the textwrap module. This also avoids the problem of "string just sitting in the middle of nowhere" as mentioned in the question.

import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))

querySelector, wildcard element match?

I just wrote this short script; seems to work.

/**
 * Find all the elements with a tagName that matches.
 * @param {RegExp} regEx  regular expression to match against tagName
 * @returns {Array}       elements in the DOM that match
 */
function getAllTagMatches(regEx) {
  return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) { 
    return el.tagName.match(regEx);
  });
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

Easiest way to compare arrays in C#

Also for arrays (and tuples) you can use new interfaces from .NET 4.0: IStructuralComparable and IStructuralEquatable. Using them you can not only check equality of arrays but also compare them.

static class StructuralExtensions
{
    public static bool StructuralEquals<T>(this T a, T b)
        where T : IStructuralEquatable
    {
        return a.Equals(b, StructuralComparisons.StructuralEqualityComparer);
    }

    public static int StructuralCompare<T>(this T a, T b)
        where T : IStructuralComparable
    {
        return a.CompareTo(b, StructuralComparisons.StructuralComparer);
    }
}

{
    var a = new[] { 1, 2, 3 };
    var b = new[] { 1, 2, 3 };
    Console.WriteLine(a.Equals(b)); // False
    Console.WriteLine(a.StructuralEquals(b)); // True
}
{
    var a = new[] { 1, 3, 3 };
    var b = new[] { 1, 2, 3 };
    Console.WriteLine(a.StructuralCompare(b)); // 1
}

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

round a single column in pandas

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

x.astype('float')

before round(...).

How can I handle the warning of file_get_contents() function in PHP?

You can prepend an @: $content = @file_get_contents($site);

This will supress any warning - use sparingly!. See Error Control Operators

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."

How to cast int to enum in C++?

int i = 1;
Test val = static_cast<Test>(i);

What is the simplest way to get indented XML with line breaks from XmlDocument?

If the above Beautify method is being called for an XmlDocument that already contains an XmlProcessingInstruction child node the following exception is thrown:

Cannot write XML declaration. WriteStartDocument method has already written it.

This is my modified version of the original one to get rid of the exception:

private static string beautify(
    XmlDocument doc)
{
    var sb = new StringBuilder();
    var settings =
        new XmlWriterSettings
            {
                Indent = true,
                IndentChars = @"    ",
                NewLineChars = Environment.NewLine,
                NewLineHandling = NewLineHandling.Replace,
            };

    using (var writer = XmlWriter.Create(sb, settings))
    {
        if (doc.ChildNodes[0] is XmlProcessingInstruction)
        {
            doc.RemoveChild(doc.ChildNodes[0]);
        }

        doc.Save(writer);
        return sb.ToString();
    }
}

It works for me now, probably you would need to scan all child nodes for the XmlProcessingInstruction node, not just the first one?


Update April 2015:

Since I had another case where the encoding was wrong, I searched for how to enforce UTF-8 without BOM. I found this blog post and created a function based on it:

private static string beautify(string xml)
{
    var doc = new XmlDocument();
    doc.LoadXml(xml);

    var settings = new XmlWriterSettings
    {
        Indent = true,
        IndentChars = "\t",
        NewLineChars = Environment.NewLine,
        NewLineHandling = NewLineHandling.Replace,
        Encoding = new UTF8Encoding(false)
    };

    using (var ms = new MemoryStream())
    using (var writer = XmlWriter.Create(ms, settings))
    {
        doc.Save(writer);
        var xmlString = Encoding.UTF8.GetString(ms.ToArray());
        return xmlString;
    }
}

Toggle visibility property of div

It's better if you check visibility like this: if($('#video-over').is(':visible'))

Bootstrap 3 - Responsive mp4-video

It is to my understanding that you want to embed a video on your site that:

  • Is responsive
  • Allows both autoplay and loop
  • Uses Bootstrap

This Demo Here does just that. You have to place another embed class outside of the object/embed/iframe tag as per the the instructions here - but you're also able to use a video tag instead of the object tag even though it's not specified.

<div align="center" class="embed-responsive embed-responsive-16by9">
    <video autoplay loop class="embed-responsive-item">
        <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
    </video>
</div>

How to pass argument to Makefile from command line?

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".

CSS: Position loading indicator in the center of the screen

You can use this OnLoad or during fetch infos from DB

In HTML Add following code:

<div id="divLoading">
<p id="loading">
    <img src="~/images/spinner.gif">
</p>

In CSS add following Code:

#divLoading {
  margin: 0px;
  display: none;
  padding: 0px;
  position: absolute;
  right: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  background-color: rgb(255, 255, 255);
  z-index: 30001;
  opacity: 0.8;}

#loading {
   position: absolute;
   color: White;
  top: 50%;
  left: 45%;}

if you want to show and hide from JS:

  document.getElementById('divLoading').style.display = 'none'; //Not Visible
  document.getElementById('divLoading').style.display = 'block';//Visible

How to create an array for JSON using PHP?

I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.

<?php

// define a JSON Object class
class jsonOBJ {
    private $_arr;
    private $_arrName;

    function __construct($arrName){
        $this->_arrName = $arrName;
        $this->_arr[$this->_arrName] = array();

    }

    function toArray(){return $this->_arr;}
    function toString(){return json_encode($this->_arr);}

    function push($newObjectElement){
        $this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
    }

    function add($key,$val){
        $this->_arr[$this->_arrName][] = array($key=>$val);
    }
}

// create an instance of the object
$jsonObj = new jsonOBJ("locations");

// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));

$jsonObj->add("location","TestLoc3"); // from key:val pairs

echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>

Will output:

Array
(
    [locations] => Array
        (
            [0] => Array
                (
                    [location] => TestLoc1
                )

            [1] => Array
                (
                    [location] => TestLoc2
                )

            [2] => Array
                (
                    [location] => TestLoc3
                )

        )

)


{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}

To iterate, convert to a normal object:

$myObj = $jsonObj->toArray();

Then:

foreach($myObj["locations"] as $locationObj){
    echo $locationObj["location"] ."<br />";
}

Outputs:

TestLoc1
TestLoc2
TestLoc3

Access direct:

$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];

A practical example:

// return a JSON Object (jsonOBJ) from the rows
    function ParseRowsAsJSONObject($arrName, $rowRS){
        $jsonArr = new jsonOBJ($arrName); // name of the json array

        $rows = mysqli_num_rows($rowRS);
        if($rows > 0){
            while($rows > 0){
                $rd = mysqli_fetch_assoc($rowRS);
                $jsonArr->push($rd);
                $rows--;
            }
            mysqli_free_result($rowRS);
        }
        return $jsonArr->toArray();
    }

How to get multiple counts with one SQL query?

For MySQL, this can be shortened to:

SELECT distributor_id,
    COUNT(*) total,
    SUM(level = 'exec') ExecCount,
    SUM(level = 'personal') PersonalCount
FROM yourtable
GROUP BY distributor_id

How to Convert UTC Date To Local time Zone in MySql Select Query

In my case, where the timezones are not available on the server, this works great:

SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`

Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!

How to stop an animation (cancel() does not work)

Use the method setAnimation(null) to stop an animation, it exposed as public method in View.java, it is the base class for all widgets, which are used to create interactive UI components (buttons, text fields, etc.). /** * Sets the next animation to play for this view. * If you want the animation to play immediately, use * {@link #startAnimation(android.view.animation.Animation)} instead. * This method provides allows fine-grained * control over the start time and invalidation, but you * must make sure that 1) the animation has a start time set, and * 2) the view's parent (which controls animations on its children) * will be invalidated when the animation is supposed to * start. * * @param animation The next animation, or null. */ public void setAnimation(Animation animation)

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

Why doesn't [01-12] range work as expected?

You seem to have misunderstood how character classes definition works in regex.

To match any of the strings 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, or 12, something like this works:

0[1-9]|1[0-2]

References


Explanation

A character class, by itself, attempts to match one and exactly one character from the input string. [01-12] actually defines [012], a character class that matches one character from the input against any of the 3 characters 0, 1, or 2.

The - range definition goes from 1 to 1, which includes just 1. On the other hand, something like [1-9] includes 1, 2, 3, 4, 5, 6, 7, 8, 9.

Beginners often make the mistakes of defining things like [this|that]. This doesn't "work". This character definition defines [this|a], i.e. it matches one character from the input against any of 6 characters in t, h, i, s, | or a. More than likely (this|that) is what is intended.

References


How ranges are defined

So it's obvious now that a pattern like between [24-48] hours doesn't "work". The character class in this case is equivalent to [248].

That is, - in a character class definition doesn't define numeric range in the pattern. Regex engines doesn't really "understand" numbers in the pattern, with the exception of finite repetition syntax (e.g. a{3,5} matches between 3 and 5 a).

Range definition instead uses ASCII/Unicode encoding of the characters to define ranges. The character 0 is encoded in ASCII as decimal 48; 9 is 57. Thus, the character definition [0-9] includes all character whose values are between decimal 48 and 57 in the encoding. Rather sensibly, by design these are the characters 0, 1, ..., 9.

See also


Another example: A to Z

Let's take a look at another common character class definition [a-zA-Z]

In ASCII:

  • A = 65, Z = 90
  • a = 97, z = 122

This means that:

  • [a-zA-Z] and [A-Za-z] are equivalent
  • In most flavors, [a-Z] is likely to be an illegal character range
    • because a (97) is "greater than" than Z (90)
  • [A-z] is legal, but also includes these six characters:
    • [ (91), \ (92), ] (93), ^ (94), _ (95), ` (96)

Related questions

How to write specific CSS for mozilla, chrome and IE

Paul Irish's approach to IE specific CSS is the most elegant I've seen. It uses conditional statements to add classes to the HTML element, which can then be used to apply appropriate IE version specific CSS without resorting to hacks. The CSS validates, and it will continue to work down the line for future browser versions.

The full details of the approach can be seen on his site.

This doesn't cover browser specific hacks for Mozilla and Chrome... but I don't really find I need those anyway.

How to return a custom object from a Spring Data JPA GROUP BY query

    //in Service      
      `
                public List<DevicesPerCustomer> findDevicesPerCustomer() {
                    LOGGER.info(TAG_NAME + " :: inside findDevicesPerCustomer : ");
                    List<Object[]> list = iDeviceRegistrationRepo.findDevicesPerCustomer();
                    List<DevicesPerCustomer> out = new ArrayList<>();
                    if (list != null && !list.isEmpty()) {
                        DevicesPerCustomer mDevicesPerCustomer = null;
                        for (Object[] object : list) {
                            mDevicesPerCustomer = new DevicesPerCustomer();
mDevicesPerCustomer.setCustomerId(object[0].toString());
                            mDevicesPerCustomer.setCount(Integer.parseInt(object[1].toString()));
                            
                            out.add(mDevicesPerCustomer);
                        }
                    }
            
                    return out;
                }`
        
    //In Repo
        `   @Query(value = "SELECT d.customerId,count(*) FROM senseer.DEVICE_REGISTRATION d  where d.customerId is not null group by d.customerId", nativeQuery=true)
            List<Object[]> findDevicesPerCustomer();`

POSTing JSON to URL via WebClient in C#

You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:

var baseAddress = "http://www.example.com/1.0/service/action";

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

hope it helps,

jQuery hide and show toggle div with plus and minus icon

Toggle the text Show and Hide and move your backgroundPosition Y axis

LIVE DEMO

$(function(){ // DOM READY shorthand

    $(".slidingDiv").hide();

    $('.show_hide').click(function( e ){
        // e.preventDefault(); // If you use anchors
        var SH = this.SH^=1; // "Simple toggler"
        $(this).text(SH?'Hide':'Show')
               .css({backgroundPosition:'0 '+ (SH?-18:0) +'px'})
               .next(".slidingDiv").slideToggle();
    });

});

CSS:

.show_hide{
  background:url(plusminus.png) no-repeat;
  padding-left:20px;  
}

How can I read numeric strings in Excel cells as string (not numbers)?

I would much rather go the route of the wil's answer or Vinayak Dornala, unfortunately they effected my performance far to much. I went for a HACKY solution of implicit casting:

for (Row row : sheet){
String strValue = (row.getCell(numericColumn)+""); // hack
...

I don't suggest you do this, for my situation it worked because of the nature of how the system worked and I had a reliable file source.

Footnote: numericColumn Is an int which is generated from reading the header of the file processed.

How can I generate UUID in C#

Here is a client side "sequential guid" solution.

http://www.pinvoke.net/default.aspx/rpcrt4.uuidcreate

using System;
using System.Runtime.InteropServices;


namespace MyCompany.MyTechnology.Framework.CrossDomain.GuidExtend
{
    public static class Guid
    {

        /*

        Original Reference for Code:
        http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html

        */


        [DllImport("rpcrt4.dll", SetLastError = true)]
        static extern int UuidCreateSequential(out System.Guid guid);

        public static System.Guid NewGuid()
        {
            return CreateSequentialUuid();
        }


        public static System.Guid CreateSequentialUuid()
        {
            const int RPC_S_OK = 0;
            System.Guid g;
            int hr = UuidCreateSequential(out g);
            if (hr != RPC_S_OK)
                throw new ApplicationException("UuidCreateSequential failed: " + hr);
            return g;
        }


        /*

        Text From URL above:

        UuidCreateSequential (rpcrt4)

        Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
        To create a page in a module other than rpcrt4, prefix the name with the module name and a period.
        . Summary
        Creates a new UUID 
        C# Signature:
        [DllImport("rpcrt4.dll", SetLastError=true)]
        static extern int UuidCreateSequential(out Guid guid);


        VB Signature:
        Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer


        User-Defined Types:
        None.

        Notes:
        Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.

        CoCreateGuid generates random-looking GUIDs like these:

        92E60A8A-2A99-4F53-9A71-AC69BD7E4D75
        BB88FD63-DAC2-4B15-8ADF-1D502E64B92F
        28F8800C-C804-4F0F-B6F1-24BFC4D4EE80
        EBD133A6-6CF3-4ADA-B723-A8177B70D268
        B10A35C0-F012-4EC1-9D24-3CC91D2B7122



        UuidCreateSequential generates sequential GUIDs like these:

        19F287B4-8830-11D9-8BFC-000CF1ADC5B7
        19F287B5-8830-11D9-8BFC-000CF1ADC5B7
        19F287B6-8830-11D9-8BFC-000CF1ADC5B7
        19F287B7-8830-11D9-8BFC-000CF1ADC5B7
        19F287B8-8830-11D9-8BFC-000CF1ADC5B7



        Here is a summary of the differences in the output of UuidCreateSequential:

        The last six bytes reveal your MAC address 
        Several GUIDs generated in a row are sequential 
        Tips & Tricks:
        Please add some!

        Sample Code in C#:
        static Guid UuidCreateSequential()
        {
           const int RPC_S_OK = 0;
           Guid g;
           int hr = UuidCreateSequential(out g);
           if (hr != RPC_S_OK)
             throw new ApplicationException
               ("UuidCreateSequential failed: " + hr);
           return g;
        }



        Sample Code in VB:
        Sub Main()
           Dim myId As Guid
           Dim code As Integer
           code = UuidCreateSequential(myId)
           If code <> 0 Then
             Console.WriteLine("UuidCreateSequential failed: {0}", code)
           Else
             Console.WriteLine(myId)
           End If
        End Sub




        */








    }
}

Keywords: CreateSequentialUUID SequentialUUID

Google OAuth 2 authorization - Error: redirect_uri_mismatch

If you're using Google+ javascript button, then you have to use postmessage instead of the actual URI. It took me almost the whole day to figure this out since Google's docs do not clearly state it for some reason.

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

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

how to convert long date value to mm/dd/yyyy format

Try this example

 String[] formats = new String[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
 }

and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html

How to change color of SVG image using CSS (jQuery SVG image replacement)?

If we have a greater number of such svg images we can also take the help of font-files.
Sites like https://glyphter.com/ can get us a font file from our svgs.


E.g.

@font-face {
    font-family: 'iconFont';
    src: url('iconFont.eot');
}
#target{
    color: white;
    font-size:96px;
    font-family:iconFont;
}

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

What are the different types of indexes, what are the benefits of each?

Different database systems have different names for the same type of index, so be careful with this. For example, what SQL Server and Sybase call "clustered index" is called in Oracle an "index-organised table".

How to get two or more commands together into a batch file

Try this: edited

@echo off
set "comd=dir /b /s *.zip"
set "pathName="
set /p "pathName=Enter The Value: "
cd /d "%pathName%"
%comd%
pause

Sending a mail from a linux shell script

Admitting you want to use some smtp server, you can do:

export SUBJECT=some_subject
export smtp=somehost:someport
export EMAIL=someaccount@somedomain
echo "some message" | mailx -s "$SUBJECT" "$EMAIL"

Change somehost, someport, and someaccount@somedomain to actual values that you would use. No encryption and no authentication is performed in this example.

How to pretty print nested dictionaries?

I'm a relative python newbie myself but I've been working with nested dictionaries for the past couple weeks and this is what I had came up with.

You should try using a stack. Make the keys from the root dictionary into a list of a list:

stack = [ root.keys() ]     # Result: [ [root keys] ]

Going in reverse order from last to first, lookup each key in the dictionary to see if its value is (also) a dictionary. If not, print the key then delete it. However if the value for the key is a dictionary, print the key then append the keys for that value to the end of the stack, and start processing that list in the same way, repeating recursively for each new list of keys.

If the value for the second key in each list were a dictionary you would have something like this after several rounds:

[['key 1','key 2'],['key 2.1','key 2.2'],['key 2.2.1','key 2.2.2'],[`etc.`]]

The upside to this approach is that the indent is just \t times the length of the stack:

indent = "\t" * len(stack)

The downside is that in order to check each key you need to hash through to the relevant sub-dictionary, though this can be handled easily with a list comprehension and a simple for loop:

path = [li[-1] for li in stack]
# The last key of every list of keys in the stack

sub = root
for p in path:
    sub = sub[p]


if type(sub) == dict:
    stack.append(sub.keys()) # And so on

Be aware that this approach will require you to cleanup trailing empty lists, and to delete the last key in any list followed by an empty list (which of course may create another empty list, and so on).

There are other ways to implement this approach but hopefully this gives you a basic idea of how to do it.

EDIT: If you don't want to go through all that, the pprint module prints nested dictionaries in a nice format.

How to install Cmake C compiler and CXX compiler

The approach I use is to start the "Visual Studio Command Prompt" which can be found in the Start menu. E.g. my visual studio 2010 Express install has a shortcute Visual Studio Command Prompt (2010) at Start Menu\Programs\Microsoft Visual Studio 2010\Visual Studio Tools.

This shortcut prepares an environment by calling a script vcvarsall.bat where the compiler, linker, etc. are setup from the right Visual Studio installation.

Alternatively, if you already have a prompt open, you can prepare the environment by calling a similar script:

:: For x86 (using the VS100COMNTOOLS env-var)
call "%VS100COMNTOOLS%"\..\..\VC\bin\vcvars32.bat

or

:: For amd64 (using the full path)
call C:\Program Files\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat

However:

Your output (with the '$' prompt) suggests that you are attempting to run CMake from a MSys shell. In that case it might be better to run CMake for MSys or MinGW, by explicitly specifying a makefile generator:

cmake -G"MSYS Makefiles"
cmake -G"MinGW Makefiles"

Run cmake --help to get a list of all possible generators.

Javascript code for showing yesterday's date and todays date

One liner:

var yesterday = new Date(Date.now() - 864e5); // 864e5 == 86400000 == 24*60*60*1000

What are forward declarations in C++?

one quick addendum regarding: usually you put those forward references into a header file belonging to the .c(pp) file where the function/variable etc. is implemented. in your example it would look like this: add.h:

extern int add(int a, int b);

the keyword extern states that the function is actually declared in an external file (could also be a library etc.). your main.c would look like this:

#include 
#include "add.h"

int main()
{
.
.
.

Get current batchfile directory

Very simple:

setlocal
cd /d %~dp0
File.exe

Finding diff between current and last version

Assuming "current version" is the working directory (uncommitted modifications) and "last version" is HEAD (last committed modifications for the current branch), simply do

git diff HEAD

Credit for the following goes to user Cerran.

And if you always skip the staging area with -a when you commit, then you can simply use git diff.

Summary

  1. git diff shows unstaged changes.
  2. git diff --cached shows staged changes.
  3. git diff HEAD shows all changes (both staged and unstaged).

Source: git-diff(1) Manual Page – Cerran

How to Edit a row in the datatable

First you need to find a row with id == 2 then change the name so:

foreach(DataRow dr in table.Rows) // search whole table
{
    if(dr["Product_id"] == 2) // if id==2
    {
        dr["Product_name"] = "cde"; //change the name
        //break; break or not depending on you
    }
}

You could also try these solutions:

table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2

Or:

DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any
if(dr != null)
{
    dr["Product_name"] = "cde"; //changes the Product_name
}

Generate a sequence of numbers in Python

This works by exploiting the % properties of the list rather than the increments.

for num in range(1,100):
    if num % 4 == 1 or num % 4 ==2:
        n.append(num)
        continue
    pass

HTML table headers always visible at top of window when viewing a large table

That proof of concept you made was great! However I also found this jQuery plugin which seems to be working very well. Hope it helps!

How do I retrieve the number of columns in a Pandas data frame?

df.info() function will give you result something like as below. If you are using read_csv method of Pandas without sep parameter or sep with ",".

raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Java count occurrence of each item in an array

I wrote a solution for this to practice myself. It doesn't seem nearly as awesome as the other answers posted, but I'm going to post it anyway, and then learn how to do this using the other methods as well. Enjoy:

public static Integer[] countItems(String[] arr)
{
    List<Integer> itemCount = new ArrayList<Integer>();
    Integer counter = 0;
    String lastItem = arr[0];

    for(int i = 0; i < arr.length; i++)
    {
        if(arr[i].equals(lastItem))
        {
            counter++;
        }
        else
        {
            itemCount.add(counter);
            counter = 1;
        }
        lastItem = arr[i];
    }
    itemCount.add(counter);

    return itemCount.toArray(new Integer[itemCount.size()]);
}

public static void main(String[] args)
{
    String[] array = {"name1","name1","name2","name2", "name2", "name3",
            "name1","name1","name2","name2", "name2", "name3"};
    Arrays.sort(array);
    Integer[] cArr = countItems(array);
    int num = 0;
    for(int i = 0; i < cArr.length; i++)
    {
        num += cArr[i]-1;
        System.out.println(array[num] + ": " + cArr[i].toString());
    }
}

How to call a function after a div is ready?

Thus far, the only way to "listen" on DOM events, like inserting or modifying Elements, was to use the such called Mutation Events. For instance

document.body.addEventListener('DOMNodeInserted', function( event ) {
    console.log('whoot! a new Element was inserted, see my event object for details!');
}, false);

Further reading on that: MDN

The Problem with Mutation Events was (is) they never really made their way into any official spec because of inconcistencies and stuff. After a while, this events were implemented in all modern browser, but they were declared as deprecated, in other words you don't want to use them.


The official replacement for the Mutation Events is the MutationObserver() object.

Further reading on that: MDN

The syntax at present looks like

var observer = new MutationObserver(function( mutations ) {
    mutations.forEach(function( mutation ) {
         console.log( mutation.type );
    }); 
});

var config = { childList: true };

observer.observe( document.body, config );

At this time, the API has been implemented in newer Firefox, Chrome and Safari versions. I'm not sure about IE and Opera. So the tradeoff here is definitely that you can only target for topnotch browsers.

Extracting just Month and Year separately from Pandas Datetime column

You can first convert your date strings with pandas.to_datetime, which gives you access to all of the numpy datetime and timedelta facilities. For example:

df['ArrivalDate'] = pandas.to_datetime(df['ArrivalDate'])
df['Month'] = df['ArrivalDate'].values.astype('datetime64[M]')

C/C++ switch case with string

Just use a if() { } else if () { } chain. Using a hash value is going to be a maintenance nightmare. switch is intended to be a low-level statement which would not be appropriate for string comparisons.

Docker is in volume in use, but there aren't any Docker containers

A one liner to give you just the needed details:

docker inspect `docker ps -aq` | jq '.[] | {Name: .Name, Mounts: .Mounts}' | less

search for the volume of complaint, you have the container name as well.

How do I export a project in the Android studio?

Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.

You don't need to harcode android:debuggable="false" in your application tag. Infact for me studio complaints -

Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)

It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.

The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.

Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.

enter image description here

Now you should see a prompt to select release build or debug build.

For production always select release build!

enter image description here

And you are done. Signed APK exported.

enter image description here

PS : Don't forget to increment your versionCode in manifest file before uploading to playstore :)

Android Recyclerview vs ListView with Viewholder

If you use RecycleView, first you need more efford to setup. You need to give more time to setup simple Item onclick, border, touch event and other simple thing. But end product will be perfect.

So decision is yours. I suggest, if you design simple app like phonebook loading, where simple click of item is enough, you can implement listview. But if you design like social media home page with unlimited scrolling. Several different decoration between item, much control of individual item than use recycle view.

Creating C formatted strings (not printing them)

If you have the code to log_out(), rewrite it. Most likely, you can do:

static FILE *logfp = ...;

void log_out(const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    vfprintf(logfp, fmt, args);
    va_end(args);
}

If there is extra logging information needed, that can be printed before or after the message shown. This saves memory allocation and dubious buffer sizes and so on and so forth. You probably need to initialize logfp to zero (null pointer) and check whether it is null and open the log file as appropriate - but the code in the existing log_out() should be dealing with that anyway.

The advantage to this solution is that you can simply call it as if it was a variant of printf(); indeed, it is a minor variant on printf().

If you don't have the code to log_out(), consider whether you can replace it with a variant such as the one outlined above. Whether you can use the same name will depend on your application framework and the ultimate source of the current log_out() function. If it is in the same object file as another indispensable function, you would have to use a new name. If you cannot work out how to replicate it exactly, you will have to use some variant like those given in other answers that allocates an appropriate amount of memory.

void log_out_wrapper(const char *fmt, ...)
{
    va_list args;
    size_t  len;
    char   *space;

    va_start(args, fmt);
    len = vsnprintf(0, 0, fmt, args);
    va_end(args);
    if ((space = malloc(len + 1)) != 0)
    {
         va_start(args, fmt);
         vsnprintf(space, len+1, fmt, args);
         va_end(args);
         log_out(space);
         free(space);
    }
    /* else - what to do if memory allocation fails? */
}

Obviously, you now call the log_out_wrapper() instead of log_out() - but the memory allocation and so on is done once. I reserve the right to be over-allocating space by one unnecessary byte - I've not double-checked whether the length returned by vsnprintf() includes the terminating null or not.

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

base64 encoded images in email signatures

Important

My answer below shows how to embed images using data URIs. This is useful for the web, but will not work reliably for most email clients. For email purposes be sure to read Shadow2531's answer.


Base-64 data is legal in an img tag and I believe your question is how to properly insert such an image tag.

You can use an online tool or a few lines of code to generate the base 64 string.

The syntax to source the image from inline data is:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

http://en.wikipedia.org/wiki/Data_URI_scheme

Syntax for creating a two-dimensional array in Java

Try this way:

int a[][] = {{1,2}, {3,4}};

int b[] = {1, 2, 3, 4};

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

How can I add a variable to console.log?

You can pass multiple args to log:

console.log("story", name, "story");

Calculate mean and standard deviation from a vector of samples in C++ using Boost

My answer is similar as Josh Greifer but generalised to sample covariance. Sample variance is just sample covariance but with the two inputs identical. This includes Bessel's correlation.

    template <class Iter> typename Iter::value_type cov(const Iter &x, const Iter &y)
    {
        double sum_x = std::accumulate(std::begin(x), std::end(x), 0.0);
        double sum_y = std::accumulate(std::begin(y), std::end(y), 0.0);

        double mx =  sum_x / x.size();
        double my =  sum_y / y.size();

        double accum = 0.0;

        for (auto i = 0; i < x.size(); i++)
        {
            accum += (x.at(i) - mx) * (y.at(i) - my);
        }

        return accum / (x.size() - 1);
    }

Is there an easy way to add a border to the top and bottom of an Android View?

Just to add my solution to the list..

I wanted a semi transparent bottom border that extends past the original shape (So the semi-transparent border was outside the parent rectangle).

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
  <item>
    <shape android:shape="rectangle" >      
      <solid android:color="#33000000" /> <!-- Border colour -->
    </shape>
  </item>
  <item  android:bottom="2dp" >
    <shape android:shape="rectangle" >     
      <solid android:color="#164586" />
    </shape>
  </item>
</layer-list>

Which gives me;

enter image description here

Get AVG ignoring Null or Zero values

worked for me:

AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

How do I replicate a \t tab space in HTML?

You must use

<dd> </dd> in the html code.

<dd>A free, open source, cross-platform,graphical web browser developed by theMozilla Corporation and hundreds of volunteers.</dd>

----------------------------------
Firefox
    A free, open source, cross-platform, graphical web browser developed by the Mozilla 
    Corporation and hundreds of volunteers.

enter image description here

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman's answer for more clarity on what happens while executing the code.

The internal thread pool in nodeJs just has 4 threads by default. and its not like the whole request is attached to a new thread from the thread pool the whole execution of request happens just like any normal request (without any blocking task) , just that whenever a request has any long running or a heavy operation like db call ,a file operation or a http request the task is queued to the internal thread pool which is provided by libuv. And as nodeJs provides 4 threads in internal thread pool by default every 5th or next concurrent request waits until a thread is free and once these operations are over the callback is pushed to the callback queue. and is picked up by event loop and sends back the response.

Now here comes another information that its not once single callback queue, there are many queues.

  1. NextTick queue
  2. Micro task queue
  3. Timers Queue
  4. IO callback queue (Requests, File ops, db ops)
  5. IO Poll queue
  6. Check Phase queue or SetImmediate
  7. close handlers queue

Whenever a request comes the code gets executing in this order of callbacks queued.

It is not like when there is a blocking request it is attached to a new thread. There are only 4 threads by default. So there is another queueing happening there.

Whenever in a code a blocking process like file read occurs , then calls a function which utilises thread from thread pool and then once the operation is done , the callback is passed to the respective queue and then executed in the order.

Everything gets queued based on the the type of callback and processed in the order mentioned above.

Difference between session affinity and sticky session?

I've seen those terms used interchangeably, but there are different ways of implementing it:

  1. Send a cookie on the first response and then look for it on subsequent ones. The cookie says which real server to send to.
    Bad if you have to support cookie-less browsers
  2. Partition based on the requester's IP address.
    Bad if it isn't static or if many come in through the same proxy.
  3. If you authenticate users, partition based on user name (it has to be an HTTP supported authentication mode to do this).
  4. Don't require state.
    Let clients hit any server (send state to the client and have them send it back)
    This is not a sticky session, it's a way to avoid having to do it.

I would suspect that sticky might refer to the cookie way, and that affinity might refer to #2 and #3 in some contexts, but that's not how I have seen it used (or use it myself)

Ansible - Save registered variable to file

---
- hosts: all
  tasks:
  - name: Gather Version
    debug:
     msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
  - name: Write  Version
    local_action: shell echo "This is  {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output

Bootstrap carousel resizing image

I had the same problem. You have to use all the images with same height and width. you can simply change it using paint application from windows using the resize option in the home section and then use CSS to resize the image. Maybe this problem occurs because the the width and height attribute inside the tag is not responding.

How do I output the results of a HiveQL query to CSV?

Similar to Ray's answer above, Hive View 2.0 in Hortonworks Data Platform also allows you to run a Hive query and then save the output as csv.

JavaScript: Collision detection

Mozilla has a good article on this, with the code shown below.

2D collision detection

Rectangle collision

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // Collision detected!
}

Circle collision

if (distance < circle1.radius + circle2.radius) {
    // Collision detected!
}

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

How to make EditText not editable through XML in Android?

This way did the job for me, i can selec and copy to clipboard, but i can't modify or paste.

android:enable="true"
android:textIsSelectable="true"
android:inputType="none"

Increasing (or decreasing) the memory available to R processes

From:

http://gking.harvard.edu/zelig/docs/How_do_I2.html (mirror)

Windows users may get the error that R has run out of memory.

If you have R already installed and subsequently install more RAM, you may have to reinstall R in order to take advantage of the additional capacity.

You may also set the amount of available memory manually. Close R, then right-click on your R program icon (the icon on your desktop or in your programs directory). Select ``Properties'', and then select the ``Shortcut'' tab. Look for the ``Target'' field and after the closing quotes around the location of the R executible, add

--max-mem-size=500M

as shown in the figure below. You may increase this value up to 2GB or the maximum amount of physical RAM you have installed.

If you get the error that R cannot allocate a vector of length x, close out of R and add the following line to the ``Target'' field:

--max-vsize=500M

or as appropriate. You can always check to see how much memory R has available by typing at the R prompt

memory.limit()

which gives you the amount of available memory in MB. In previous versions of R you needed to use: round(memory.limit()/2^20, 2).

How do you run a single query through mysql from the command line?

mysql -uroot -p -hslavedb.mydomain.com mydb_production -e "select * from users;"

From the usage printout:

-e, --execute=name
Execute command and quit. (Disables --force and history file)

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

Ha ha ha Funny it's a simple mistake for me

I got async on my jquery library call. Just remove it and I got solution.

<script async src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

TO

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

Why it did this kind of behave: I got documentation on W3schools LINK

Definition and Usage async

The async attribute is a boolean attribute.

When present, it specifies that the script will be executed asynchronously as soon as it is available.

Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

1. If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)

2. If async is not present and defer is present: The script is executed when the page has finished parsing

3. If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page

How to resolve 'unrecognized selector sent to instance'?

1) Is the synthesize within @implementation block?

2) Should you refer to self.classA = [[ClassA alloc] init]; and self.classA.downloadUrl = @"..." instead of plain classA?

3) In your myApp.m file you need to import ClassA.h, when it's missing it will default to a number, or pointer? (in C variables default to int if not found by compiler):

#import "ClassA.h".

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to

private SSLSocketFactory delegate;

This is my TLSSocketFactory class

public class TLSSocketFactory extends SSLSocketFactory {

private SSLSocketFactory delegate;

public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    delegate = context.getSocketFactory();
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket() throws IOException {
    return enableTLSOnSocket(delegate.createSocket());
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket enableTLSOnSocket(Socket socket) {
    if(socket != null && (socket instanceof SSLSocket)) {
        ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
    }
    return socket;
}
}

and this is how i used it with okhttp and retrofit

 OkHttpClient client=new OkHttpClient();
    try {
        client = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
                .build();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

Difference between MongoDB and Mongoose

If you are planning to use these components along with your proprietary code then please refer below information.

Mongodb:

  1. It's a database.
  2. This component is governed by the Affero General Public License (AGPL) license.
  3. If you link this component along with your proprietary code then you have to release your entire source code in the public domain, because of it's viral effect like (GPL, LGPL etc)
  4. If you are hosting your application over the cloud, the (2) will apply and also you have to release your installation information to the end users.

Mongoose:

  1. It's an object modeling tool.
  2. This component is governed by the MIT license.
  3. Allowed to use this component along with the proprietary code, without any restrictions.
  4. Shipping your application using any media or host is allowed.

How do you check "if not null" with Eloquent?

If you want to search deleted record (Soft Deleted Record), do't user Eloquent Model Query. Instead use Db::table query e.g Instead of using Below:

$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();

Use:

$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();

Fastest JavaScript summation

I tried using performance.now() to analyze the performance of the different types of loops. I took a very large array and found the sum of all elements of the array. I ran the code three times every time and found forEach and reduce to be a clear winner.

// For loop

let arr = [...Array(100000).keys()]
function addUsingForLoop(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
    sum += ar[i];
  }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingForLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 42.17500000959262 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.41999999107793 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 49.845000030472875 milliseconds"

// While loop

let arr = [...Array(100000).keys()]
function addUsingWhileLoop(ar){
let sum = 0;
let index = 0;
while (index < ar.length) {
  sum += ar[index];
  index++;
}
  console.log(`Sum: ${sum}`)
  return sum;
}
let t1 = performance.now();
addUsingWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 44.2499999771826 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.01999997207895 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 41.71000001952052 milliseconds"

// do-while

let arr = [...Array(100000).keys()]
function addUsingDoWhileLoop(ar){
let sum = 0;
let index = 0;
do {
   sum += index;
   index++;
} while (index < ar.length);
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingDoWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 43.79500000504777 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.47500001313165 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 47.535000019706786 milliseconds"

// Reverse loop

let arr = [...Array(100000).keys()]
function addUsingReverseLoop(ar){
   var sum=0;
   for (var i=ar.length; i--;) {
     sum+=arr[i];
   }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingReverseLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.199999982491136 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.96500000823289 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.880000011995435 milliseconds"

// Reverse while loop

let arr = [...Array(100000).keys()]
function addUsingReverseWhileLoop(ar){
    var sum = 0;
    var i = ar.length; 
    while (i--) {
        sum += ar[i];
    }
    console.log(`Sum: ${sum}`);
    return sum;
}
var t1 = performance.now();
addUsingReverseWhileLoop(arr);
var t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.26999999163672 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 42.97000000951812 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.31500000646338 milliseconds"

// reduce

let arr = [...Array(100000).keys()]
let t1 = performance.now();
sum = arr.reduce((pv, cv) => pv + cv, 0);
console.log(`Sum: ${sum}`)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 4.654999997001141 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.040000018198043 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 4.835000028833747 milliseconds"

// forEach

let arr = [...Array(100000).keys()]
function addUsingForEach(ar){
  let sum = 0;
  ar.forEach(item => {
    sum += item;
  })
    console.log(`Sum: ${sum}`);
    return sum
}
let t1 = performance.now();
addUsingForEach(arr)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 5.315000016707927 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.869999993592501 mienter code herelliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.405000003520399 milliseconds"

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

How to add many functions in ONE ng-click?

The standard way to add Multiple functions

<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>

or

<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>

What's the difference between '$(this)' and 'this'?

Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this.

Launch Minecraft from command line - username and password as prefix

Just create this batch command file in your game directory. Bat file takes one argument %1 as the username.

Also, I use a splash screen to make pretty. You will NOT be able to play online, but who cares.

Adjust your memory usage to fit your machine (-Xmx & -Xmns).

NOTE: this is for version of minecraft as of 2016-06-27

@ECHO OFF
SET DIR=%cd%
SET JAVA_HOME=%DIR%\runtime\jre-x64\1.8.0_25
SET JAVA=%JAVA_HOME%\bin\java.exe
SET LOW_MEM=768M
SET MAX_MEM=2G
SET LIBRARIES=versions\1.10.2\1.10.2-natives-59894925878961
SET MAIN_CLASS=net.minecraft.client.main.Main
SET CLASSPATH=libraries\com\mojang\netty\1.6\netty-1.6.jar;libraries\oshi-project\oshi-core\1.1\oshi-core-1.1.jar;libraries\net\java\dev\jna\jna\3.4.0\jna-3.4.0.jar;libraries\net\java\dev\jna\platform\3.4.0\platform-3.4.0.jar;libraries\com\ibm\icu\icu4j-core-mojang\51.2\icu4j-core-mojang-51.2.jar;libraries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;libraries\io\netty\netty-all\4.0.23.Final\netty-all-4.0.23.Final.jar;libraries\com\google\guava\guava\17.0\guava-17.0.jar;libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;libraries\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;libraries\com\google\code\gson\gson\2.2.4\gson-2.2.4.jar;libraries\com\mojang\authlib\1.5.22\authlib-1.5.22.jar;libraries\com\mojang\realms\1.9.3\realms-1.9.3.jar;libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;libraries\it\unimi\dsi\fastutil\7.0.12_mojang\fastutil-7.0.12_mojang.jar;libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta9.jar;libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\log4j-core-2.0-beta9.jar;libraries\org\lwjgl\lwjgl\lwjgl\2.9.4-nightly-20150209\lwjgl-2.9.4-nightly-20150209.jar;libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.4-nightly-20150209\lwjgl_util-2.9.4-nightly-20150209.jar;versions\1.10.2\1.10.2.jar
SET JAVA_OPTIONS=-server -splash:splash.png -d64 -da -dsa -Xrs -Xms%LOW_MEM% -Xmx%MAX_MEM% -XX:NewSize=%LOW_MEM% -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -XX:+DisableExplicitGC -Djava.library.path=%LIBRARIES% -cp %CLASSPATH%  %MAIN_CLASS%

start /D %DIR% /I /HIGH %JAVA% %JAVA_OPTIONS% --username %1 --version 1.10.2 --gameDir %DIR% --assetsDir assets --assetIndex 1.10 --uuid 2536abce90e8476a871679918164abc5 --accessToken 99abe417230342cb8e9e2168ab46297a --userType legacy --versionType release --nativeLauncherVersion 307


Algorithm: efficient way to remove duplicate integers from an array

After review the problem, here is my delphi way, that may help

var
A: Array of Integer;
I,J,C,K, P: Integer;
begin
C:=10;
SetLength(A,10);
A[0]:=1; A[1]:=4; A[2]:=2; A[3]:=6; A[4]:=3; A[5]:=4;
A[6]:=3; A[7]:=4; A[8]:=2; A[9]:=5;

for I := 0 to C-1 do
begin
  for J := I+1 to C-1 do
    if A[I]=A[J] then
    begin
      for K := C-1 Downto J do
        if A[J]<>A[k] then
        begin
          P:=A[K];
          A[K]:=0;
          A[J]:=P;
          C:=K;
          break;
        end
        else
        begin
          A[K]:=0;
          C:=K;
        end;
    end;
end;

//tructate array
setlength(A,C);
end;

How to run test methods in specific order in JUnit4?

You can use one of these piece of codes: @FixMethodOrder(MethodSorters.JVM) OR @FixMethodOrder(MethodSorters.DEFAULT) OR @FixMethodOrder(MethodSorters.NAME_ASCENDING)

Before your test class like this:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BookTest {...}

get name of a variable or parameter

Alternatively,

1) Without touching System.Reflection namespace,

GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}

2) The below one can be faster though (from my tests)

GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

You can also extend this for properties of objects (may be with extension methods):

new { myClass.MyProperty1 }.GETNAME();

You can cache property values to improve performance further as property names don't change during runtime.

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

How to install PHP mbstring on CentOS 6.2

I have experienced the same issue before. In my case, I needed to install php-mbstring extension on GoDaddy VPS server. None of above solutions did work for me.

What I've found is to install PHP extensions using WHM (Web Hosting Manager) of GoDaddy. Anyone who use GoDaddy VPS server can access this page with the following address.

http://{Your_Server_IP_Address}:2087

On this page, you can easily find Easy Apache software that can help you to install/upgrade php components and extensions. You can select currently installed profile and customize and then provision the profile. Everything with Easy Apache is explanatory.

I remember that I did very similar things for HostGator server, but I don't remember how actually I did for profile update.

Edit: When you have got the server which supports Web Hosting Manager, then you can add/update/remove php extensions on WHM. On godaddy servers, it's even recommended to update PHP ini settings on WHM.

Multiprocessing vs Threading Python

Other answers have focused more on the multithreading vs multiprocessing aspect, but in python Global Interpreter Lock (GIL) has to be taken into account. When more number (say k) of threads are created, generally they will not increase the performance by k times, as it will still be running as a single threaded application. GIL is a global lock which locks everything out and allows only single thread execution utilizing only a single core. The performance does increase in places where C extensions like numpy, Network, I/O are being used, where a lot of background work is done and GIL is released.
So when threading is used, there is only a single operating system level thread while python creates pseudo-threads which are completely managed by threading itself but are essentially running as a single process. Preemption takes place between these pseudo threads. If the CPU runs at maximum capacity, you may want to switch to multiprocessing.
Now in case of self-contained instances of execution, you can instead opt for pool. But in case of overlapping data, where you may want processes communicating you should use multiprocessing.Process.

jquery select option click handler

The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.

I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:

let blockChange = false;

$element.keydown(function (e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);

    // prevents select opening when enter is pressed
    if (keycode === 13) {
        e.preventDefault();
    }

    // lets the change event know that these keypresses are to be ignored
    if([38, 40].indexOf(keycode) > -1){
        blockChange = true;
    }

});

$element.keyup(function(e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);
    // handle enter press
    if(keycode === 13) {
        doSomething();
    }

});

$element.change(function(e) {

    // this effective handles the click only as preventDefault was used on enter
    if(!blockChange) {
        doSomething();
    }
    blockChange = false;

});

How to query data out of the box using Spring data JPA by both Sort and Pageable?

Pageable has an option to specify sort as well. From the java doc

PageRequest(int page, int size, Sort.Direction direction, String... properties) 

Creates a new PageRequest with sort parameters applied.

Short description of the scoping rules?

The Python name resolution only knows the following kinds of scope:

  1. builtins scope which provides the Builtin Functions, such as print, int, or zip,
  2. module global scope which is always the top-level of the current module,
  3. three user-defined scopes that can be nested into each other, namely
    1. function closure scope, from any enclosing def block, lambda expression or comprehension.
    2. function local scope, inside a def block, lambda expression or comprehension,
    3. class scope, inside a class block.

Notably, other constructs such as if, for, or with statements do not have their own scope.

The scoping TLDR: The lookup of a name begins at the scope in which the name is used, then any enclosing scopes (excluding class scopes), to the module globals, and finally the builtins – the first match in this search order is used. The assignment to a scope is by default to the current scope – the special forms nonlocal and global must be used to assign to a name from an outer scope.

Finally, comprehensions and generator expressions as well as := asignment expressions have one special rule when combined.


Nested Scopes and Name Resolution

These different scopes build a hierarchy, with builtins then global always forming the base, and closures, locals and class scope being nested as lexically defined. That is, only the nesting in the source code matters, not for example the call stack.

print("builtins are available without definition")

some_global = "1"  # global variables are at module scope

def outer_function():
    some_closure = "3.1"  # locals and closure are defined the same, at function scope
    some_local = "3.2"    # a variable becomes a closure if a nested scope uses it

    class InnerClass:
         some_classvar = "3.3"   # class variables exist *only* at class scope

         def nested_function(self):
             some_local = "3.2"   # locals can replace outer names
             print(some_closure)  # closures are always readable
    return InnerClass

Even though class creates a scope and may have nested classes, functions and comprehensions, the names of the class scope are not visible to enclosed scopes. This creates the following hierarchy:

? builtins           [print, ...]
??? globals            [some_global]
  ??? outer_function     [some_local, some_closure]
    ??? InnerClass         [some_classvar]
    ??? inner_function     [some_local]

Name resolution always starts at the current scope in which a name is accessed, then goes up the hierarchy until a match is found. For example, looking up some_local inside outer_function and inner_function starts at the respective function - and immediately finds the some_local defined in outer_function and inner_function, respectively. When a name is not local, it is fetched from the nearest enclosing scope that defines it – looking up some_closure and print inside inner_function searches until outer_function and builtins, respectively.


Scope Declarations and Name Binding

By default, a name belongs to any scope in which it is bound to a value. Binding the same name again in an inner scope creates a new variable with the same name - for example, some_local exists separately in both outer_function and inner_function. As far as scoping is concerned, binding includes any statement that sets the value of a name – assignment statements, but also the iteration variable of a for loop, or the name of a with context manager. Notably, del also counts as name binding.

When a name must refer to an outer variable and be bound in an inner scope, the name must be declared as not local. Separate declarations exists for the different kinds of enclosing scopes: nonlocal always refers to the nearest closure, and global always refers to a global name. Notably, nonlocal never refers to a global name and global ignores all closures of the same name. There is no declaration to refer to the builtin scope.


some_global = "1"

def outer_function():
    some_closure = "3.2"
    some_global = "this is ignored by a nested global declaration"
    
    def inner_function():
        global some_global     # declare variable from global scope
        nonlocal some_closure  # declare variable from enclosing scope
        message = " bound by an inner scope"
        some_global = some_global + message
        some_closure = some_closure + message
    return inner_function

Of note is that function local and nonlocal are resolved at compile time. A nonlocal name must exist in some outer scope. In contrast, a global name can be defined dynamically and may be added or removed from the global scope at any time.


Comprehensions and Assignment Expressions

The scoping rules of list, set and dict comprehensions and generator expressions are almost the same as for functions. Likewise, the scoping rules for assignment expressions are almost the same as for regular name binding.

The scope of comprehensions and generator expressions is of the same kind as function scope. All names bound in the scope, namely the iteration variables, are locals or closures to the comprehensions/generator and nested scopes. All names, including iterables, are resolved using name resolution as applicable inside functions.

some_global = "global"

def outer_function():
    some_closure = "closure"
    return [            # new function-like scope started by comprehension
        comp_local      # names resolved using regular name resolution
        for comp_local  # iteration targets are local
        in "iterable"
        if comp_local in some_global and comp_local in some_global
    ]

An := assignment expression works on the nearest function, class or global scope. Notably, if the target of an assignment expression has been declared nonlocal or global in the nearest scope, the assignment expression honors this like a regular assignment.

print(some_global := "global")

def outer_function():
    print(some_closure := "closure")

However, an assignment expression inside a comprehension/generator works on the nearest enclosing scope of the comprehension/generator, not the scope of the comprehension/generator itself. When several comprehensions/generators are nested, the nearest function or global scope is used. Since the comprehension/generator scope can read closures and global variables, the assignment variable is readable in the comprehension as well. Assigning from a comprehension to a class scope is not valid.

print(some_global := "global")

def outer_function():
    print(some_closure := "closure")
    steps = [
        # v write to variable in containing scope
        (some_closure := some_closure + comp_local)
        #                 ^ read from variable in containing scope
        for comp_local in some_global
    ]
    return some_closure, steps

While the iteration variable is local to the comprehension in which it is bound, the target of the assignment expression does not create a local variable and is read from the outer scope:

? builtins           [print, ...]
??? globals            [some_global]
  ??? outer_function     [some_closure]
    ??? <listcomp>         [comp_local]

What is the difference between ELF files and bin files?

I just want to correct a point here. ELF file is produced by the Linker, not the compiler.

The Compiler mission ends after producing the object files (*.o) out of the source code files. Linker links all .o files together and produces the ELF.

SQL Server: Invalid Column Name

Intellisense is not auto refreshed and you should not fully rely on that

BackgroundWorker vs background Thread

Also you are tying up a threadpool thread for the lifetime of the background worker, which may be of concern as there are only a finite number of them. I would say that if you are only ever creating the thread once for your app (and not using any of the features of background worker) then use a thread, rather than a backgroundworker/threadpool thread.

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

Facebook Graph API error code list

I have also found some more error subcodes, in case of OAuth exception. Copied from the facebook bugtracker, without any garantee (maybe contain deprecated, wrong and discontinued ones):

/**
  * (Date: 30.01.2013)
  *
  * case 1: - "An error occured while creating the share (publishing to wall)"
  *         - "An unknown error has occurred."
  * case 2:    "An unexpected error has occurred. Please retry your request later."
  * case 3:    App must be on whitelist        
  * case 4:    Application request limit reached
  * case 5:    Unauthorized source IP address        
  * case 200:  Requires extended permissions
  * case 240:  Requires a valid user is specified (either via the session or via the API parameter for specifying the user."
  * case 1500: The url you supplied is invalid
  * case 200:
  * case 210:  - Subject must be a page
  *            - User not visible
  */

 /**
  * Error Code 100 several issus:
  * - "Specifying multiple ids with a post method is not supported" (http status 400)
  * - "Error finding the requested story" but it is available via GET
  * - "Invalid post_id"
  * - "Code was invalid or expired. Session is invalid."
  * 
  * Error Code 2: 
  * - Service temporarily unavailable
  */

cv2.imshow command doesn't work properly in opencv-python

For me waitKey() with number greater than 0 worked

    cv2.waitKey(1)

How to remove item from array by value?

You can achieve this using Lodash _.remove function.

_x000D_
_x000D_
var array = ['three', 'seven', 'eleven'];_x000D_
var evens = _.remove(array, function(e) {_x000D_
  return e !== 'seven';_x000D_
});_x000D_
_x000D_
console.log(evens);
_x000D_
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Reading DataSet

DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.

If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:

SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();

da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];

foreach (DataRow dr in dt.Rows)
{
    MessageBox.Show(dr["Column1"].ToString());
}

To read a specific cell in a row:

int rowNum // row number
string columnName = "DepartureTime";  // database table column name
dt.Rows[rowNum][columnName].ToString();

View the change history of a file using Git versioning

Lately I discovered tig and found it very useful. There are some cases I'd wish it does A or B but most of the time it's rather neat.

For your case, tig <filename> might be what you're looking for.

http://jonas.nitro.dk/tig/

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

Dart: mapping a list (list.map)

you can use

moviesTitles.map((title) => Tab(text: title)).toList()

example:

    bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) => Tab(text: title)).toList()
      ,
    ),

Send private messages to friends

There isn't any graph api for this, you need to use facebook xmpp chat api to send the message, good news is: I have made a php class which is too easy to use,call a function and message will be sent, its open source, check it out: facebook message api php the description says its a closed source but the it was made open source later, see the first comment, you can clone from github. It's a open source now.

What is the difference between char s[] and char *s?

char s[] = "hello";

declares s to be an array of char which is long enough to hold the initializer (5 + 1 chars) and initializes the array by copying the members of the given string literal into the array.

char *s = "hello";

declares s to be a pointer to one or more (in this case more) chars and points it directly at a fixed (read-only) location containing the literal "hello".

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

Remove ALL styling/formatting from hyperlinks

if you state a.redLink{color:red;} then to keep this on hover and such add a.redLink:hover{color:red;} This will make sure no other hover states will change the color of your links

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use &check; for ✓ and &cross; for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.

As mentioned in the comments, &check; and &cross; are not supported in HTML4, so you may be better off using the more cryptic &#x2713; and &#x2717; if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.

How to add label in chart.js for pie chart

It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.

var optionsPie = {
    tooltipTemplate: "<%= label %> - <%= value %>"
}

If you want the tooltip to be always shown you can make some other edits to the options:

 var optionsPie = {
        tooltipEvents: [],
        showTooltips: true,
        onAnimationComplete: function() {
            this.showTooltip(this.segments, true);
        },
        tooltipTemplate: "<%= label %> - <%= value %>"
    }

In your data items, you have to add the desired label property and value and that's all.

data = [
    {
        value: 480000,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Tobacco"
    }
];

Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie) and you are done.

This probably works best for pies which are not very small in size.

Pie chart with labels

Center a popup window on screen?

(this was posted in 2020)

An extension to CrazyTim's answer

You can also set the width to a percentage (or a ratio) for a dynamic size. Absolute size is still accepted.

function popupWindow(url, title, w='75%', h='16:9', opts){
    // sort options
    let options = [];
    if(typeof opts === 'object'){
        Object.keys(opts).forEach(function(value, key){
            if(value === true){value = 'yes';}else if(value === false){value = 'no';}
            options.push(`${key}=${value}`);
        });
        if(options.length){options = ','+options.join(',');}
        else{options = '';}
    }else if(Array.isArray(opts)){
        options = ','+opts.join(',');
    }else if(typeof opts === 'string'){
        options = ','+opts;
    }else{options = '';}

    // add most vars to local object (to shorten names)
    let size = {w: w, h: h};
    let win = {w: {i: window.top.innerWidth, o: window.top.outerWidth}, h: {i: window.top.innerHeight, o: window.top.outerHeight}, x: window.top.screenX || window.top.screenLeft, y: window.top.screenY || window.top.screenTop}

    // set window size if percent
    if(typeof size.w === 'string' && size.w.endsWith('%')){size.w = Number(size.w.replace(/%$/, ''))*win.w.o/100;}
    if(typeof size.h === 'string' && size.h.endsWith('%')){size.h = Number(size.h.replace(/%$/, ''))*win.h.o/100;}

    // set window size if ratio
    if(typeof size.w === 'string' && size.w.includes(':')){
        size.w = size.w.split(':', 2);
        if(win.w.o < win.h.o){
            // if height is bigger than width, reverse ratio
            size.w = Number(size.h)*Number(size.w[1])/Number(size.w[0]);
        }else{size.w = Number(size.h)*Number(size.w[0])/Number(size.w[1]);}
    }
    if(typeof size.h === 'string' && size.h.includes(':')){
        size.h = size.h.split(':', 2);
        if(win.w.o < win.h.o){
            // if height is bigger than width, reverse ratio
            size.h = Number(size.w)*Number(size.h[0])/Number(size.h[1]);
        }else{size.h = Number(size.w)*Number(size.h[1])/Number(size.h[0]);}
    }

    // force window size to type number
    if(typeof size.w === 'string'){size.w = Number(size.w);}
    if(typeof size.h === 'string'){size.h = Number(size.h);}

    // keep popup window within padding of window size
    if(size.w > win.w.i-50){size.w = win.w.i-50;}
    if(size.h > win.h.i-50){size.h = win.h.i-50;}

    // do math
    const x = win.w.o / 2 + win.x - (size.w / 2);
    const y = win.h.o / 2 + win.y - (size.h / 2);
    return window.open(url, title, `width=${size.w},height=${size.h},left=${x},top=${y}${options}`);
}

usage:

// width and height are optional (defaults: width = '75%' height = '16:9')
popupWindow('https://www.google.com', 'Title', '75%', '16:9', {/* options (optional) */});

// options can be an object, array, or string

// example: object (only in object, true/false get replaced with 'yes'/'no')
const options = {scrollbars: false, resizable: true};

// example: array
const options = ['scrollbars=no', 'resizable=yes'];

// example: string (same as window.open() string)
const options = 'scrollbars=no,resizable=yes';

Mipmap drawables for icons

When building separate apks for different densities, drawable folders for other densities get stripped. This will make the icons appear blurry in devices that use launcher icons of higher density. Since, mipmap folders do not get stripped, it’s always best to use them for including the launcher icons.

Adding headers when using httpClient.GetAsync

You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

This doesn't just reference to POST-requests, you can also use it for GET-requests.