Programs & Examples On #Geolocation

Geolocation is the identification of the real-world geographic location of an object, such as a cell phone or an Internet-connected computer terminal. Use [w3c-geolocation] for questions about the W3C Geolocation API.

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I finally found a working version for firefox, chrome & default navigator in android (4.2 tested only):

function getGeoLocation() {
        var options = null;
        if (navigator.geolocation) {
            if (browserChrome) //set this var looking for Chrome un user-agent header
                options={enableHighAccuracy: false, maximumAge: 15000, timeout: 30000};
            else
                options={maximumAge:Infinity, timeout:0};
            navigator.geolocation.getCurrentPosition(getGeoLocationCallback,
                    getGeoLocationErrorCallback,
                   options);
        }
    }

How to emulate GPS location in the Android Emulator?

First go in DDMS section in your eclipse Than open emulator Control .... Go To Manual Section set lat and long and then press Send Button

How to get the exact local time of client?

You can also make your own nodeJS endpoint, publish it with something like heroku, and access it

require("http").createServer(function (q,r) {
    r.setHeader("accees-control-allow-origin","*")
    r.end(Date.now())
}).listen(process.env.PORT || 80)

Then just access it on JS

fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))

This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3 milliseconds to Date.now() to add 3 hours)

For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side

In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..

EDIT just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client

require("http").createServer(function (q,r) {
    var d= new Date()
    r.setHeader("accees-control-allow-origin","*")
    r.setHeader("zman", d.toString())
    r.end(d.getTime())
}).listen(process.env.PORT || 80)

What is meaning of negative dbm in signal strength?

At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.

Thats why it always -ve.

How to calculate distance from Wifi router using Signal Strength?

Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer

All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.

If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.

How to get a time zone from a location using latitude and longitude coordinates?

If you prefer to avoid a web service, you can retrieve that information from the browser like this:

var d = new Date();
var usertime = d.toLocaleString();

//some browsers / OSs provide the timezone name in their local string
var tzsregex = /\b(ACDT|ACST|ACT|ADT|AEDT|AEST|AFT|AKDT|AKST|AMST|AMT|ART|AST|AWDT|AWST|AZOST|AZT|BDT|BIOT|BIT|BOT|BRT|BST|BTT|CAT|CCT|CDT|CEDT|CEST|CET|CHADT|CHAST|CIST|CKT|CLST|CLT|COST|COT|CST|CT|CVT|CXT|CHST|DFT|EAST|EAT|ECT|EDT|EEDT|EEST|EET|EST|FJT|FKST|FKT|GALT|GET|GFT|GILT|GIT|GMT|GST|GYT|HADT|HAEC|HAST|HKT|HMT|HST|ICT|IDT|IRKT|IRST|IST|JST|KRAT|KST|LHST|LINT|MART|MAGT|MDT|MET|MEST|MIT|MSD|MSK|MST|MUT|MYT|NDT|NFT|NPT|NST|NT|NZDT|NZST|OMST|PDT|PETT|PHOT|PKT|PST|RET|SAMT|SAST|SBT|SCT|SGT|SLT|SST|TAHT|THA|UYST|UYT|VET|VLAT|WAT|WEDT|WEST|WET|WST|YAKT|YEKT)\b/gi;

//in other browsers the timezone needs to be estimated based on the offset
var timezonenames = {"UTC+0":"GMT","UTC+1":"CET","UTC+2":"EET","UTC+3":"EEDT","UTC+3.5":"IRST","UTC+4":"MSD","UTC+4.5":"AFT","UTC+5":"PKT","UTC+5.5":"IST","UTC+6":"BST","UTC+6.5":"MST","UTC+7":"THA","UTC+8":"AWST","UTC+9":"AWDT","UTC+9.5":"ACST","UTC+10":"AEST","UTC+10.5":"ACDT","UTC+11":"AEDT","UTC+11.5":"NFT","UTC+12":"NZST","UTC-1":"AZOST","UTC-2":"GST","UTC-3":"BRT","UTC-3.5":"NST","UTC-4":"CLT","UTC-4.5":"VET","UTC-5":"EST","UTC-6":"CST","UTC-7":"MST","UTC-8":"PST","UTC-9":"AKST","UTC-9.5":"MIT","UTC-10":"HST","UTC-11":"SST","UTC-12":"BIT"};

var timezone = usertime.match(tzsregex);
if (timezone) {
    timezone = timezone[timezone.length-1];
} else {
    var offset = -1*d.getTimezoneOffset()/60;
    offset = "UTC" + (offset >= 0 ? "+" + offset : offset);
    timezone = timezonenames[offset];
}

//there are 3 variables can use to see the timezone
// usertime - full date
// offset - UTC offset time
// timezone - country

console.log('Full Date: ' + usertime);
console.log('UTC Offset: ' + offset);
console.log('Country Code Timezone: ' + timezone);

In my current case it is printing:

Full Date: ?27?/?01?/?2014? ?16?:?53?:?37 UTC Offset: UTC-3 Country Code Timezone: BRT

Hope it can be helpful.

Good way of getting the user's location in Android

Currently i am using since this is trustable for getting location and calculating distance for my application...... i am using this for my taxi application.

use the fusion API that google developer have developed with fusion of GPS Sensor,Magnetometer,Accelerometer also using Wifi or cell location to calculate or estimate the location. It is also able to give location updates also inside the building accurately. for detail get to link https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

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

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class MainActivity extends Activity implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final long ONE_MIN = 500;
    private static final long TWO_MIN = 500;
    private static final long FIVE_MIN = 500;
    private static final long POLLING_FREQ = 1000 * 20;
    private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
    private static final float MIN_ACCURACY = 1.0f;
    private static final float MIN_LAST_READ_ACCURACY = 1;

    private LocationRequest mLocationRequest;
    private Location mBestReading;
TextView tv;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!servicesAvailable()) {
            finish();
        }

        setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv1);
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(POLLING_FREQ);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();


        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onPause() {d
        super.onPause();

        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }


        tv.setText(location + "");
        // Determine whether new location is better than current best
        // estimate
        if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
            mBestReading = location;


            if (mBestReading.getAccuracy() < MIN_ACCURACY) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }
        }
    }

    @Override
    public void onConnected(Bundle dataBundle) {
        // Get first reading. Get additional location updates if necessary
        if (servicesAvailable()) {

            // Get best last location measurement meeting criteria
            mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);

            if (null == mBestReading
                    || mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
                    || mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

               //Schedule a runnable to unregister location listeners

                    @Override
                    public void run() {
                        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);

                    }

                }, ONE_MIN, TimeUnit.MILLISECONDS);

            }

        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }


    private Location bestLastKnownLocation(float minAccuracy, long minTime) {
        Location bestResult = null;
        float bestAccuracy = Float.MAX_VALUE;
        long bestTime = Long.MIN_VALUE;

        // Get the best most recent location currently available
        Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        //tv.setText(mCurrentLocation+"");
        if (mCurrentLocation != null) {
            float accuracy = mCurrentLocation.getAccuracy();
            long time = mCurrentLocation.getTime();

            if (accuracy < bestAccuracy) {
                bestResult = mCurrentLocation;
                bestAccuracy = accuracy;
                bestTime = time;
            }
        }

        // Return best reading or null
        if (bestAccuracy > minAccuracy || bestTime < minTime) {
            return null;
        }
        else {
            return bestResult;
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    private boolean servicesAvailable() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

        if (ConnectionResult.SUCCESS == resultCode) {
            return true;
        }
        else {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0).show();
            return false;
        }
    }
}

Does GPS require Internet?

In Android 4

Go to Setting->Location services->

Uncheck Google`s location service.
Check GPS satelites.

For test you can use GPS Test.Please test Outdoor!
Offline maps are available on new version of Google map.

Get GPS location from the web browser

Observable

/*
  function geo_success(position) {
    do_something(position.coords.latitude, position.coords.longitude);
  }

  function geo_error() {
    alert("Sorry, no position available.");
  }

  var geo_options = {
    enableHighAccuracy: true,
    maximumAge        : 30000,
    timeout           : 27000
  };

  var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
  */
  getLocation(): Observable<Position> {
    return Observable.create((observer) => {
      const watchID = navigator.geolocation.watchPosition((position: Position) => {
        observer.next(position);
      });
      return () => {
        navigator.geolocation.clearWatch(watchID);
      };
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

Where am I? - Get country

Here is a complete solution based on the LocationManager and as fallbacks the TelephonyManager and the Network Provider's locations. I used the above answer from @Marco W. for the fallback part(great answer as itself!).

Note: the code contains PreferencesManager, this is a helper class that saves and loads data from SharedPrefrences. I'm using it to save the country to S"P, I'm only getting the country if it is empty. For my product I don't really care for all the edge cases(user travels abroad and so on).

public static String getCountry(Context context) {
    String country = PreferencesManager.getInstance(context).getString(COUNTRY);
    if (country != null) {
        return country;
    }

    LocationManager locationManager = (LocationManager) PiplApp.getInstance().getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location == null) {
            location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (location == null) {
            log.w("Couldn't get location from network and gps providers")
            return
        }
        Geocoder gcd = new Geocoder(context, Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(location.getLatitude(),
                    location.getLongitude(), 1);

            if (addresses != null && !addresses.isEmpty()) {
                country = addresses.get(0).getCountryName();
                if (country != null) {
                    PreferencesManager.getInstance(context).putString(COUNTRY, country);
                    return country;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    country = getCountryBasedOnSimCardOrNetwork(context);
    if (country != null) {
        PreferencesManager.getInstance(context).putString(COUNTRY, country);
        return country;
    }
    return null;
}


/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 *
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
private static String getCountryBasedOnSimCardOrNetwork(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    } catch (Exception e) {
    }
    return null;
}

How to convert latitude or longitude to meters?

Here is a javascript function:

function measure(lat1, lon1, lat2, lon2){  // generally used geo measurement function
    var R = 6378.137; // Radius of earth in KM
    var dLat = lat2 * Math.PI / 180 - lat1 * Math.PI / 180;
    var dLon = lon2 * Math.PI / 180 - lon1 * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    return d * 1000; // meters
}

Explanation: https://en.wikipedia.org/wiki/Haversine_formula

The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes.

Getting visitors country from their IP

Replace 127.0.0.1 with visitors IpAddress.

$country = geoip_country_name_by_name('127.0.0.1');

Installation instructions are here, and read this to know how to obtain City, State, Country, Longitude, Latitude, etc...

Get the distance between two geo points

There are a couple of methods you could use, but to determine which one is best we first need to know if you are aware of the user's altitude, as well as the altitude of the other points?

Depending on the level of accuracy you are after, you could look into either the Haversine or Vincenty formulae...

These pages detail the formulae, and, for the less mathematically inclined also provide an explanation of how to implement them in script!

Haversine Formula: http://www.movable-type.co.uk/scripts/latlong.html

Vincenty Formula: http://www.movable-type.co.uk/scripts/latlong-vincenty.html

If you have any problems with any of the meanings in the formulae, just comment and I'll do my best to answer them :)

Can we locate a user via user's phone number in Android?

Quick answer: No, at least not with native SMS service.

Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.

How to get current location in Android

You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.

If you don't use the onLocationChanged it always will be the old location.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

Get current location of user in Android without using GPS or internet

Have you take a look Google Maps Geolocation Api? Google Map Geolocation

This is simple RestApi, you just need POST a request, the the service will return a location with accuracy in meters.

Simple calculations for working with lat/lon and km distance?

Why not use properly formulated geospatial queries???

Here is the SQL server reference page on the STContains geospatial function:

https://docs.microsoft.com/en-us/sql/t-sql/spatial-geography/stcontains-geography-data-type?view=sql-server-ver15

or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:

DECLARE @CurrentLocation geography; 
SET @CurrentLocation  = geography::Point(12.822222, 80.222222, 4326)

SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km

There should be similar functionality for almost any database out there.

If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using

How do I get the current GPS location programmatically in Android?

Here is additional information for other answers.

Since Android has

GPS_PROVIDER and NETWORK_PROVIDER

you can register to both and start fetch events from onLocationChanged(Location location) from two at the same time. So far so good. Now the question do we need two results or we should take the best. As I know GPS_PROVIDER results have better accuracy than NETWORK_PROVIDER.

Let's define Location field:

private Location currentBestLocation = null;

Before we start listen on Location change we will implement the following method. This method returns the last known location, between the GPS and the network one. For this method newer is best.

/**
 * @return the last know best location
 */
private Location getLastBestLocation() {
    Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    long GPSLocationTime = 0;
    if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }

    long NetLocationTime = 0;

    if (null != locationNet) {
        NetLocationTime = locationNet.getTime();
    }

    if ( 0 < GPSLocationTime - NetLocationTime ) {
        return locationGPS;
    }
    else {
        return locationNet;
    }
}

Each time when we retrieve a new location we will compare it with our previous result.

...
static final int TWO_MINUTES = 1000 * 60 * 2;
...

I add a new method to onLocationChanged:

@Override
public void onLocationChanged(Location location) {

    makeUseOfNewLocation(location);

    if(currentBestLocation == null){
        currentBestLocation = location;
    }

    ....
}


/**
 * This method modify the last know good location according to the arguments.
 *
 * @param location The possible new location.
 */
void makeUseOfNewLocation(Location location) {
    if ( isBetterLocation(location, currentBestLocation) ) {
        currentBestLocation = location;
    }
}

....

/** Determines whether one location reading is better than the current location fix
 * @param location  The new location that you want to evaluate
 * @param currentBestLocation  The current location fix, to which you want to compare the new one.
 */
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location,
    // because the user has likely moved.
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be worse.
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
                                                currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

// Checks whether two providers are the same
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}

....

What is the simplest and most robust way to get the user's current location on Android?

I have written detailed tutorial covering current location here on demonuts.com.You can find more description here and also you can download whole demo source code for better understanding.

There are already many answers there but I want to show latest way to get location using Google API, so new programmers can use new method:

First of all, put this in gradle file

compile 'com.google.android.gms:play-services:8.4.0'

then implement necessary interfaces

public class MainActivity  extends BaseActivitiy implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener

declare instances

  private GoogleApiClient mGoogleApiClient;
  private Location mLocation;
  private LocationManager locationManager;
  private LocationRequest mLocationRequest;

put this in onCreate()

 mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

At last, override necessary methods

 @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLocation == null){
            startLocationUpdates();
        }
        if (mLocation != null) {
            double latitude = mLocation.getLatitude();
            double longitude = mLocation.getLongitude();
        } else {
            // Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
        }
    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL);
        // Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
        Log.d("reque", "--->>>>");
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
    }

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }
    @Override
    public void onLocationChanged(Location location) {

    }

Don't forget to start GPS in your device before running app.

Google Maps: how to get country, state/province/region, city given a lat/long value?

Just try this code this code work with me

var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
 //console.log(lat +"          "+long);
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) {
//console.log( JSON.stringify(output.results[0]));
//console.log( JSON.stringify(output.results[0].address_components[4].short_name));
var results = output.results;
if (results[0]) {
//console.log("results.length= "+results.length);
//console.log("hi "+JSON.stringify(results[0],null,4));
for (var j = 0; j < results.length; j++){
 //console.log("j= "+j);
//console.log(JSON.stringify(results[j],null,4));
for (var i = 0; i < results[j].address_components.length; i++){
 if(results[j].address_components[i].types[0] == "country") {
 //this is the object you are looking for
  country = results[j].address_components[i];
 }
 }
 }
 console.log(country.long_name);
 console.log(country.short_name);
 } else {
 alert("No results found");
 console.log("No results found");
 }
 });
 }, function (err) {
 });

Getting the location from an IP address

I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.

I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".

How to get visitor's location (i.e. country) using geolocation?

A very easy to use service is provided by ws.geonames.org. Here's an example URL:

http://ws.geonames.org/countryCode?lat=43.7534932&lng=28.5743187&type=JSON

And here's some (jQuery) code which I've added to your code:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        $.getJSON('http://ws.geonames.org/countryCode', {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            type: 'JSON'
        }, function(result) {
            alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);
        });
    });
}?

Try it on jsfiddle.net ...

HTML 5 Geo Location Prompt in Chrome

if you're hosting behind a server, and still facing issues: try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/

The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).

For my sanity check I was using Remy Sharp's demo: https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html

and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):

"User denied Geolocation"

I made the following change to get more detailed error message:

function error(msg) {
  var s = document.querySelector('#status');
  msg = msg.message ? msg.message : msg; //add this line
  s.innerHTML = typeof msg == 'string' ? msg : "failed";
  s.className = 'fail';

  // console.log(arguments);
}

failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :

"The current location cannot be determined"

getCurrentPosition() and watchPosition() are deprecated on insecure origins

You can run chrome with the --unsafely-treat-insecure-origin-as-secure="http://example.com" flag (replacing "example.com" with the origin you actually want to test), which will treat that origin as secure for this session. Note that you also need to include the --user-data-dir=/test/only/profile/dir to create a fresh testing profile for the flag to work.

For example if use Windows, Click Start and run.

chrome --unsafely-treat-insecure-origin-as-secure="http://localhost:8100"  --user-data-dir=C:\testprofile

Given the lat/long coordinates, how can we find out the city/country?

The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.

Try this link to see an example of the output (this is in json, output is also available in XML)

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

Calculate distance between 2 GPS coordinates

I. Regarding "Breadcrumbs" method

  1. Earth radius is different on different Lat. This must be taken into consideration in Haversine algorithm.
  2. Consider Bearing change, which turns straight lines to arches (which are longer)
  3. Taking Speed change into account will turn arches to spirals (which are longer or shorter than arches)
  4. Altitude change will turn flat spirals to 3D spirals (which are longer again). This is very important for hilly areas.

Below see the function in C which takes #1 and #2 into account:

double   calcDistanceByHaversine(double rLat1, double rLon1, double rHeading1,
       double rLat2, double rLon2, double rHeading2){
  double rDLatRad = 0.0;
  double rDLonRad = 0.0;
  double rLat1Rad = 0.0;
  double rLat2Rad = 0.0;
  double a = 0.0;
  double c = 0.0;
  double rResult = 0.0;
  double rEarthRadius = 0.0;
  double rDHeading = 0.0;
  double rDHeadingRad = 0.0;

  if ((rLat1 < -90.0) || (rLat1 > 90.0) || (rLat2 < -90.0) || (rLat2 > 90.0)
              || (rLon1 < -180.0) || (rLon1 > 180.0) || (rLon2 < -180.0)
              || (rLon2 > 180.0)) {
        return -1;
  };

  rDLatRad = (rLat2 - rLat1) * DEGREE_TO_RADIANS;
  rDLonRad = (rLon2 - rLon1) * DEGREE_TO_RADIANS;
  rLat1Rad = rLat1 * DEGREE_TO_RADIANS;
  rLat2Rad = rLat2 * DEGREE_TO_RADIANS;

  a = sin(rDLatRad / 2) * sin(rDLatRad / 2) + sin(rDLonRad / 2) * sin(
              rDLonRad / 2) * cos(rLat1Rad) * cos(rLat2Rad);

  if (a == 0.0) {
        return 0.0;
  }

  c = 2 * atan2(sqrt(a), sqrt(1 - a));
  rEarthRadius = 6378.1370 - (21.3847 * 90.0 / ((fabs(rLat1) + fabs(rLat2))
              / 2.0));
  rResult = rEarthRadius * c;

  // Chord to Arc Correction based on Heading changes. Important for routes with many turns and U-turns

  if ((rHeading1 >= 0.0) && (rHeading1 < 360.0) && (rHeading2 >= 0.0)
              && (rHeading2 < 360.0)) {
        rDHeading = fabs(rHeading1 - rHeading2);
        if (rDHeading > 180.0) {
              rDHeading -= 180.0;
        }
        rDHeadingRad = rDHeading * DEGREE_TO_RADIANS;
        if (rDHeading > 5.0) {
              rResult = rResult * (rDHeadingRad / (2.0 * sin(rDHeadingRad / 2)));
        } else {
              rResult = rResult / cos(rDHeadingRad);
        }
  }
  return rResult;
}

II. There is an easier way which gives pretty good results.

By Average Speed.

Trip_distance = Trip_average_speed * Trip_time

Since GPS Speed is detected by Doppler effect and is not directly related to [Lon,Lat] it can be at least considered as secondary (backup or correction) if not as main distance calculation method.

Get city name using geolocation

Here is updated working version for me which will get City/Town, It looks like some fields are modified in the json response. Referring previous answers for this questions. ( Thanks to Michal & one more reference : Link

var geocoder;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
// Get the latitude and the longitude;
function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  codeLatLng(lat, lng);
}

function errorFunction() {
  alert("Geocoder failed");
}

function initialize() {
  geocoder = new google.maps.Geocoder();

}

function codeLatLng(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({latLng: latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        var arrAddress = results;
        console.log(results);
        $.each(arrAddress, function(i, address_component) {
          if (address_component.types[0] == "locality") {
            console.log("City: " + address_component.address_components[0].long_name);
            itemLocality = address_component.address_components[0].long_name;
          }
        });
      } else {
        alert("No results found");
      }
    } else {
      alert("Geocoder failed due to: " + status);
    }
  });
}

How to get Latitude and Longitude of the mobile device in android?

Best way is

Add permission manifest file

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

Then you can get GPS location or if GPS location is not available then this function return NETWORK location

    public static Location getLocationWithCheckNetworkAndGPS(Context mContext) {
    LocationManager lm = (LocationManager)
            mContext.getSystemService(Context.LOCATION_SERVICE);
    assert lm != null;
    isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    Location networkLoacation = null, gpsLocation = null, finalLoc = null;
    if (isGpsEnabled)
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return null;
        }gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (isNetworkLocationEnabled)
        networkLoacation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    if (gpsLocation != null && networkLoacation != null) {

        //smaller the number more accurate result will
        if (gpsLocation.getAccuracy() > networkLoacation.getAccuracy())
            return finalLoc = networkLoacation;
        else
            return finalLoc = gpsLocation;

    } else {

        if (gpsLocation != null) {
            return finalLoc = gpsLocation;
        } else if (networkLoacation != null) {
            return finalLoc = networkLoacation;
        }
    }
    return finalLoc;
}

How to display my location on Google Maps for Android API v2

From android 6.0 you need to check for user permission, if you want to use GoogleMap.setMyLocationEnabled(true) you will get Call requires permission which may be rejected by user error

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
   mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}

if you want to read more, check google map docs

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

Get Country of IP Address with PHP

$country_code = trim(file_get_contents("http://ipinfo.io/{$ip_address}/country"))

will get you the country code.

How to simulate browsing from various locations?

The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.

How does Google calculate my location on a desktop?

They use a combination of IP geolocation, as well as comparing the results of a scan for nearby wireless networks with a database on their side (which is built by collecting GPS coordinates alongside wifi scan data when Android phone users use their GPS)

Address validation using Google Maps API

Google basis (free) does not provide address verification (Geocoding) as there is no UK postcode license.

This means postcode searches are very in-accurate. The proximity search is very poor, even for town searches, often not recognising locations.

This is why Google have a premier and a enterprise solution which still is more expensive and not as good as business mapping specialists like bIng and Via Michelin who also have API's.

As a free lance developer, so serious business would use Google as the system is weak and really provides a watered down solution.

Identifying country by IP address

Yes, you can download the IP address ranges by country from https://lite.ip2location.com/ip-address-ranges-by-country

You can see that each country has multiple ranges and changes frequently.

Increase bootstrap dropdown menu width

Usually the desire is to match the menu width to the width of the dropdown parent. This can be achieved easily like so:

.dropdown-menu {
  width:100%;
}

what is the difference between OLE DB and ODBC data sources?

Both are data providers (API that your code will use to talk to a data source). Oledb which was introduced in 1998 was meant to be a replacement for ODBC (introduced in 1992)

Open another application from your own (intent)

// This works on Android Lollipop 5.0.2

public static boolean launchApp(Context context, String packageName) {

    final PackageManager manager = context.getPackageManager();
    final Intent appLauncherIntent = new Intent(Intent.ACTION_MAIN);
    appLauncherIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = manager.queryIntentActivities(appLauncherIntent, 0);
    if ((null != resolveInfos) && (!resolveInfos.isEmpty())) {
        for (ResolveInfo rInfo : resolveInfos) {
            String className = rInfo.activityInfo.name.trim();
            String targetPackageName = rInfo.activityInfo.packageName.trim();
            Log.d("AppsLauncher", "Class Name = " + className + " Target Package Name = " + targetPackageName + " Package Name = " + packageName);
            if (packageName.trim().equals(targetPackageName)) {
                Intent intent = new Intent();
                intent.setClassName(targetPackageName, className);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                Log.d("AppsLauncher", "Launching Package '" + packageName + "' with Activity '" + className + "'");
                return true;
            }
        }
    }
    return false;
}

Regex pattern for checking if a string starts with a certain substring?

I really recommend using the String.StartsWith method over the Regex.IsMatch if you only plan to check the beginning of a string.

  • Firstly, the regular expression in C# is a language in a language with does not help understanding and code maintenance. Regular expression is a kind of DSL.
  • Secondly, many developers does not understand regular expressions: it is something which is not understandable for many humans.
  • Thirdly, the StartsWith method brings you features to enable culture dependant comparison which regular expressions are not aware of.

In your case you should use regular expressions only if you plan implementing more complex string comparison in the future.

How can I get terminal output in python?

The recommended way in Python 3.5 and above is to use subprocess.run():

from subprocess import run
output = run("pwd", capture_output=True).stdout

Make a link in the Android browser start up my app?

I think you'll want to look at the <intent-filter> element of your Mainfest file. Specifically, take a look at the documentation for the <data> sub-element.

Basically, what you'll need to do is define your own scheme. Something along the lines of:

<intent-filter>
    <data android:scheme="anton" />
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" /> <--Not positive if this one is needed
    ...
</intent-filter>

Then you should be able to launch your app with links that begin with the anton: URI scheme.

Using git commit -a with vim

  1. In vim, you save a file with :wEnter while in the normal mode (you get to the normal mode by pressing Esc).
  2. You close your file with :q while in the normal mode.

You can combine both these actions and do Esc:wqEnter to save the commit and quit vim.

As an alternate to the above, you can also press ZZ while in the normal mode, which will save the file and exit vim. This is also easier for some people as it's the same key pressed twice.

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

If you don't want to install TortoiseSVN, you can simply install 'Subversion for Windows' from here:

http://sourceforge.net/projects/win32svn/

After installing, just open up a command prompt, go the folder you want to download into, then past in the checkout command as indicated on the project's 'source' page. E.g.

svn checkout http://projectname.googlecode.com/svn/trunk/ projectname-read-only

Note the space between the URL and the last string is intentional, the last string is the folder name into which the source will be downloaded.

Bootstrap 3 Slide in Menu / Navbar on Mobile

This was for my own project and I'm sharing it here too.

DEMO: http://jsbin.com/OjOTIGaP/1/edit

This one had trouble after 3.2, so the one below may work better for you:

https://jsbin.com/seqola/2/edit --- BETTER VERSION, slightly


CSS

/* adjust body when menu is open */
body.slide-active {
    overflow-x: hidden
}
/*first child of #page-content so it doesn't shift around*/
.no-margin-top {
    margin-top: 0px!important
}
/*wrap the entire page content but not nav inside this div if not a fixed top, don't add any top padding */
#page-content {
    position: relative;
    padding-top: 70px;
    left: 0;
}
#page-content.slide-active {
    padding-top: 0
}
/* put toggle bars on the left :: not using button */
#slide-nav .navbar-toggle {
    cursor: pointer;
    position: relative;
    line-height: 0;
    float: left;
    margin: 0;
    width: 30px;
    height: 40px;
    padding: 10px 0 0 0;
    border: 0;
    background: transparent;
}
/* icon bar prettyup - optional */
#slide-nav .navbar-toggle > .icon-bar {
    width: 100%;
    display: block;
    height: 3px;
    margin: 5px 0 0 0;
}
#slide-nav .navbar-toggle.slide-active .icon-bar {
    background: orange
}
.navbar-header {
    position: relative
}
/* un fix the navbar when active so that all the menu items are accessible */
.navbar.navbar-fixed-top.slide-active {
    position: relative
}
/* screw writing importants and shit, just stick it in max width since these classes are not shared between sizes */
@media (max-width:767px) { 
    #slide-nav .container {
        margin: 0;
        padding: 0!important;
    }
    #slide-nav .navbar-header {
        margin: 0 auto;
        padding: 0 15px;
    }
    #slide-nav .navbar.slide-active {
        position: absolute;
        width: 80%;
        top: -1px;
        z-index: 1000;
    }
    #slide-nav #slidemenu {
        background: #f7f7f7;
        left: -100%;
        width: 80%;
        min-width: 0;
        position: absolute;
        padding-left: 0;
        z-index: 2;
        top: -8px;
        margin: 0;
    }
    #slide-nav #slidemenu .navbar-nav {
        min-width: 0;
        width: 100%;
        margin: 0;
    }
    #slide-nav #slidemenu .navbar-nav .dropdown-menu li a {
        min-width: 0;
        width: 80%;
        white-space: normal;
    }
    #slide-nav {
        border-top: 0
    }
    #slide-nav.navbar-inverse #slidemenu {
        background: #333
    }
    /* this is behind the navigation but the navigation is not inside it so that the navigation is accessible and scrolls*/
    #slide-nav #navbar-height-col {
        position: fixed;
        top: 0;
        height: 100%;
        width: 80%;
        left: -80%;
        background: #eee;
    }
    #slide-nav.navbar-inverse #navbar-height-col {
        background: #333;
        z-index: 1;
        border: 0;
    }
    #slide-nav .navbar-form {
        width: 100%;
        margin: 8px 0;
        text-align: center;
        overflow: hidden;
        /*fast clearfixer*/
    }
    #slide-nav .navbar-form .form-control {
        text-align: center
    }
    #slide-nav .navbar-form .btn {
        width: 100%
    }
}
@media (min-width:768px) { 
    #page-content {
        left: 0!important
    }
    .navbar.navbar-fixed-top.slide-active {
        position: fixed
    }
    .navbar-header {
        left: 0!important
    }
}

HTML

 <div class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="slide-nav">
  <div class="container">
   <div class="navbar-header">
    <a class="navbar-toggle"> 
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
     </a>
    <a class="navbar-brand" href="#">Project name</a>
   </div>
   <div id="slidemenu">
     
          <form class="navbar-form navbar-right" role="form">
            <div class="form-group">
              <input type="search" placeholder="search" class="form-control">
            </div>
            <button type="submit" class="btn btn-primary">Search</button>
          </form>
     
    <ul class="nav navbar-nav">
     <li class="active"><a href="#">Home</a></li>
     <li><a href="#about">About</a></li>
     <li><a href="#contact">Contact</a></li>
     <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
      <ul class="dropdown-menu">
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link</a></li>
       <li><a href="#">One more separated link</a></li>
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link</a></li>
       <li><a href="#">One more separated link</a></li>
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link test long title goes here</a></li>
       <li><a href="#">One more separated link</a></li>
      </ul>
     </li>
    </ul>
          
   </div>
  </div>
 </div>

jQuery

$(document).ready(function () {


    //stick in the fixed 100% height behind the navbar but don't wrap it
    $('#slide-nav.navbar .container').append($('<div id="navbar-height-col"></div>'));

    // Enter your ids or classes
    var toggler = '.navbar-toggle';
    var pagewrapper = '#page-content';
    var navigationwrapper = '.navbar-header';
    var menuwidth = '100%'; // the menu inside the slide menu itself
    var slidewidth = '80%';
    var menuneg = '-100%';
    var slideneg = '-80%';


    $("#slide-nav").on("click", toggler, function (e) {

        var selected = $(this).hasClass('slide-active');

        $('#slidemenu').stop().animate({
            left: selected ? menuneg : '0px'
        });

        $('#navbar-height-col').stop().animate({
            left: selected ? slideneg : '0px'
        });

        $(pagewrapper).stop().animate({
            left: selected ? '0px' : slidewidth
        });

        $(navigationwrapper).stop().animate({
            left: selected ? '0px' : slidewidth
        });


        $(this).toggleClass('slide-active', !selected);
        $('#slidemenu').toggleClass('slide-active');


        $('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');


    });


    var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';


    $(window).on("resize", function () {

        if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
            $(selected).removeClass('slide-active');
        }


    });

});

Using 'sudo apt-get install build-essentials'

Drop the 's' off of the package name.

You want sudo apt-get install build-essential

You may also need to run sudo apt-get update to make sure that your package index is up to date.

For anyone wondering why this package may be needed as part of another install, it contains the essential tools for building most other packages from source (C/C++ compiler, libc, and make).

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

A simpler way would be to create a link called cudart64_101.dll to point to cudart64_102.dll. This is not very orthodox but since TensorFlow is looking for cudart64_101.dll exported symbols and the nvidia folks are not amateurs, they would most likely not remove symbols from 101 to 102. It works, based on this assumption (mileage may vary).

HTML SELECT - Change selected option by VALUE using JavaScript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

jQuery serialize does not register checkboxes

jQuery serialize closely mimics how a standard form would be serialized by the browser before being appended to the query string or POST body in the request. Unchecked checkboxes aren't included by the browser, which makes sense really because they have a boolean state -- they're either selected by the user (included) or not selected by the user (not included).

If you need it to be in the serialized, you should ask yourself "why? why not just check for its existence in the data?".

Bear in mind that if the way JavaScript serializes form data behaves differently to the way the browser does it then you're eliminating any chance of graceful degradation for your form. If you still absolutely need to do it, just use a <select> box with Yes/No as options. At least then, users with JS disabled aren't alienated from your site and you're not going against the defined behaviour in the HTML specification.

<select id="event_allDay" name="event_allDay">
   <option value="0" selected>No</option>
   <option value="1">Yes</option>
</select>

I've seen this employed on some sites in the past and always thought to myself, "why don't they just use a checkbox"?

How to lose margin/padding in UITextView?

For SwiftUI

If you are making your own TextView using UIViewRepresentable and want to control the padding, in your makeUIView function, simply do:

uiTextView.textContainerInset = UIEdgeInsets(top: 10, left: 18, bottom: 0, right: 18)

or whatever you want.

How do you plot bar charts in gnuplot?

Simple bar graph:

bar graph

set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes

data.dat:

0 label       100
1 label2      450
2 "bar label" 75

If you want to style your bars differently, you can do something like:

multi color bar graph

set style line 1 lc rgb "red"
set style line 2 lc rgb "blue"

set style fill solid
set boxwidth 0.5

plot "data.dat" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \
     "data.dat" every ::1::2 using 1:3:xtic(2) with boxes ls 2

If you want to do multiple bars for each entry:

data.dat:

0     5
0.5   6


1.5   3
2     7


3     8
3.5   1

gnuplot:

set xtics ("label" 0.25, "label2" 1.75, "bar label" 3.25,)

set boxwidth 0.5
set style fill solid

plot 'data.dat' every 2    using 1:2 with boxes ls 1,\
     'data.dat' every 2::1 using 1:2 with boxes ls 2

barchart_multi

If you want to be tricky and use some neat gnuplot tricks:

Gnuplot has psuedo-columns that can be used as the index to color:

plot 'data.dat' using 1:2:0 with boxes lc variable

barchart_multi2

Further you can use a function to pick the colors you want:

mycolor(x) = ((x*11244898) + 2851770)
plot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable

barchart_multi3

Note: you will have to add a couple other basic commands to get the same effect as the sample images.

Rotate an image in image source in html

If your rotation angles are fairly uniform, you can use CSS:

<img id="image_canv" src="/image.png" class="rotate90">

CSS:

.rotate90 {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:

<img id="image_canv" src="/image.png" data-rotate="90">

Sample jQuery:

$('img').each(function() {
    var deg = $(this).data('rotate') || 0;
    var rotate = 'rotate(' + deg + 'deg)';
    $(this).css({ 
        '-webkit-transform': rotate,
        '-moz-transform': rotate,
        '-o-transform': rotate,
        '-ms-transform': rotate,
        'transform': rotate 
    });
});

Demo:

http://jsfiddle.net/verashn/6rRnd/5/

Using R to list all files with a specified extension

I am not very good in using sophisticated regular expressions, so I'd do such task in the following way:

files <- list.files()
dbf.files <- files[-grep(".xml", files, fixed=T)]

First line just lists all files from working dir. Second one drops everything containing ".xml" (grep returns indices of such strings in 'files' vector; subsetting with negative indices removes corresponding entries from vector). "fixed" argument for grep function is just my whim, as I usually want it to peform crude pattern matching without Perl-style fancy regexprs, which may cause surprise for me.

I'm aware that such solution simply reflects drawbacks in my education, but for a novice it may be useful =) at least it's easy.

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

h1 is a block level element. You will need to use something like span instead as it is an inline level element (ie: it does not span the whole row).

In your case, I would suggest the following:

style.css

.highlight 
{
   background-color: green;
}

html

<span class="highlight">only the text will be highlighted</span>

How to get name of calling function/method in PHP?

For me debug_backtrace was hitting my memory limit, and I wanted to use this in production to log and email errors as they happen.

Instead I found this solution which works brilliantly!

// Make a new exception at the point you want to trace, and trace it!
$e = new Exception;
var_dump($e->getTraceAsString());

// Outputs the following 
#2 /usr/share/php/PHPUnit/Framework/TestCase.php(626): SeriesHelperTest->setUp()
#3 /usr/share/php/PHPUnit/Framework/TestResult.php(666): PHPUnit_Framework_TestCase->runBare()
#4 /usr/share/php/PHPUnit/Framework/TestCase.php(576): PHPUnit_Framework_TestResult->run(Object(SeriesHelperTest))
#5 /usr/share/php/PHPUnit/Framework/TestSuite.php(757): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))
#6 /usr/share/php/PHPUnit/Framework/TestSuite.php(733): PHPUnit_Framework_TestSuite->runTest(Object(SeriesHelperTest), Object(PHPUnit_Framework_TestResult))
#7 /usr/share/php/PHPUnit/TextUI/TestRunner.php(305): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult), false, Array, Array, false)
#8 /usr/share/php/PHPUnit/TextUI/Command.php(188): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#9 /usr/share/php/PHPUnit/TextUI/Command.php(129): PHPUnit_TextUI_Command->run(Array, true)
#10 /usr/bin/phpunit(53): PHPUnit_TextUI_Command::main()
#11 {main}"

C compiler for Windows?

GCC is not technically a linux specific compiler. Its a standards compliant c/c++ compiler, and I use it for windows programs on a daily basis. Its probably best that you use it until you become more comfortable with something else.

I recommend that you use the MinGW distribution of GCC. That will compile your programs natively for windows, using a standard library, etc.

If you're looking for an IDE, I have two recommendations. Visual Studio is the Microsoft version, and although it has its issues, it is an excellent IDE for working with the code. However, if you're looking for something a bit more lightweight, CodeBlocks is also rather good, and has the added benefit of being able to use basically any compiler you have installed (including several forms of GCC and the Microsoft Compiler that comes with Visual Studio) and being able to open project files fro other IDEs. Plus, it runs on linux too, so you could make that transition even easier on yourself.

I personally prefer GCC, but that's just me. If you really want the Microsoft Solution, VS is the way to go.

python dictionary sorting in descending order based on values

Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.

In different terms, your d and your e would be exactly equivalent dictionaries.

What you can do here is to use an OrderedDict:

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

The original d has some arbitrary order. d_ascending has the order you thought you had in your original d, but didn't. And d_descending has the order you want for your e.


If you don't really need to use e as a dictionary, but you just want to be able to iterate over the elements of d in a particular order, you can simplify this:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)

If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict that re-sorts itself as necessary, etc.

Disable color change of anchor tag when visited

a {
    color: orange !important;
}

!important has the effect that the property in question cannot be overridden unless another !important is used. It is generally considered bad practice to use !important unless absolutely necessary; however, I can't think of any other way of ‘disabling’ :visited using CSS only.

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

C++ Singleton design pattern

Another non-allocating alternative: create a singleton, say of class C, as you need it:

singleton<C>()

using

template <class X>
X& singleton()
{
    static X x;
    return x;
}

Neither this nor Catalin's answer is automatically thread-safe in current C++, but will be in C++0x.

How to flip background image using CSS?

You can flip both vertical and horizontal at the same time

    -moz-transform: scaleX(-1) scaleY(-1);
    -o-transform: scaleX(-1) scaleY(-1);
    -webkit-transform: scaleX(-1) scaleY(-1);
    transform: scaleX(-1) scaleY(-1);

And with the transition property you can get a cool flip

    -webkit-transition: transform .4s ease-out 0ms;
    -moz-transition: transform .4s ease-out 0ms;
    -o-transition: transform .4s ease-out 0ms;
    transition: transform .4s ease-out 0ms;
    transition-property: transform;
    transition-duration: .4s;
    transition-timing-function: ease-out;
    transition-delay: 0ms;

Actually it flips the whole element, not just the background-image

SNIPPET

_x000D_
_x000D_
function flip(){_x000D_
 var myDiv = document.getElementById('myDiv');_x000D_
 if (myDiv.className == 'myFlipedDiv'){_x000D_
  myDiv.className = '';_x000D_
 }else{_x000D_
  myDiv.className = 'myFlipedDiv';_x000D_
 }_x000D_
}
_x000D_
#myDiv{_x000D_
  display:inline-block;_x000D_
  width:200px;_x000D_
  height:20px;_x000D_
  padding:90px;_x000D_
  background-color:red;_x000D_
  text-align:center;_x000D_
  -webkit-transition:transform .4s ease-out 0ms;_x000D_
  -moz-transition:transform .4s ease-out 0ms;_x000D_
  -o-transition:transform .4s ease-out 0ms;_x000D_
  transition:transform .4s ease-out 0ms;_x000D_
  transition-property:transform;_x000D_
  transition-duration:.4s;_x000D_
  transition-timing-function:ease-out;_x000D_
  transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
  -moz-transform:scaleX(-1) scaleY(-1);_x000D_
  -o-transform:scaleX(-1) scaleY(-1);_x000D_
  -webkit-transform:scaleX(-1) scaleY(-1);_x000D_
  transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
_x000D_
_x000D_

How to calculate the bounding box for a given lat/lng location?

I adapted a PHP script I found to do just this. You can use it to find the corners of a box around a point (say, 20 km out). My specific example is for Google Maps API:

http://www.richardpeacock.com/blog/2011/11/draw-box-around-coordinate-google-maps-based-miles-or-kilometers

How do you get the cursor position in a textarea?

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/

What does a circled plus mean?

I used the logic in the replies by rampion and schnaader. I will summarise how I confirmed the results. I changed the numbers to binary and then used the XOR-operation. Alternatively, you can use the Hexadecimal tables: Click here!

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

throwing an exception in objective-c/cocoa

A word of caution here. In Objective-C, unlike many similar languages, you generally should try to avoid using exceptions for common error situations that may occur in normal operation.

Apple's documentation for Obj-C 2.0 states the following: "Important: Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors (such as a file not being accessible)"

Apple's conceptual Exception handling documentation explains the same, but with more words: "Important: You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime. [.....] Instead of exceptions, error objects (NSError) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications."

The reasons for this is partly to adhere to programming idioms in Objective-C (using return values in simple cases and by-reference parameters (often the NSError class) in more complex cases), partly that throwing and catching exceptions is much more expensive and finally (and perpaps most importantly) that Objective-C exceptions are a thin wrapper around C's setjmp() and longjmp() functions, essentially messing up your careful memory handling, see this explanation.

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

How to Migrate to WKWebView?

Swift 4

    let webView = WKWebView()   // Set Frame as per requirment, I am leaving it for you
    let url = URL(string: "http://www.google.com")!
    webView.load(URLRequest(url: url))
    view.addSubview(webView)

Which version of CodeIgniter am I currently using?

For CodeIgniter 4, use the following:

<?php    
    echo \CodeIgniter\CodeIgniter::CI_VERSION;
?>

What's the difference between deadlock and livelock?

DEADLOCK Deadlock is a condition in which a task waits indefinitely for conditions that can never be satisfied - task claims exclusive control over shared resources - task holds resources while waiting for other resources to be released - tasks cannot be forced to relinguish resources - a circular waiting condition exists

LIVELOCK Livelock conditions can arise when two or more tasks depend on and use the some resource causing a circular dependency condition where those tasks continue running forever, thus blocking all lower priority level tasks from running (these lower priority tasks experience a condition called starvation)

CAML query with nested ANDs and ORs for multiple fields

You can try U2U Query Builder http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll

I didn't use them but I'm sure it will help you achieving your task.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

What is the difference between POST and GET?

A POST, unlike a GET, typically has relevant information in the body of the request. (A GET should not have a body, so aside from cookies, the only place to pass info is in the URL.) Besides keeping the URL relatively cleaner, POST also lets you send much more information (as URLs are limited in length, for all practical purposes), and lets you send just about any type of data (file upload forms, for example, can't use GET -- they have to use POST plus a special content type/encoding).

Aside from that, a POST connotes that the request will change something, and shouldn't be redone willy-nilly. That's why you sometimes see your browser asking you if you want to resubmit form data when you hit the "back" button.

GET, on the other hand, should be idempotent -- meaning you could do it a million times and the server will do the same thing (and show basically the same result) each and every time.

Get the value of input text when enter key pressed

Try this:

<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>  
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>

JS Code

function search(ele) {
    if(event.key === 'Enter') {
        alert(ele.value);        
    }
}

DEMO Link

SQL count rows in a table

Here is the Query

select count(*) from tablename

or

select count(rownum) from studennt

LINQ Contains Case Insensitive

IndexOf works best in this case

return this
   .ObjectContext
   .FACILITY_ITEM
   .Where(fi => fi.DESCRIPTION.IndexOf(description, StringComparison.OrdinalIgnoreCase)>=0);

Create a List of primitive int?

When you use Java for Android development, it is recommended to use SparseIntArray to prevent autoboxing between int and Integer.

You can finde more information to SparseIntArray in the Android Developers documentation and a good explanation for autoboxing on Android enter link description here

Is the sizeof(some pointer) always equal to four?

In addition to the 16/32/64 bit differences even odder things can occur.

There have been machines where sizeof(int *) will be one value, probably 4 but where sizeof(char *) is larger. Machines that naturally address words instead of bytes have to "augment" character pointers to specify what portion of the word you really want in order to properly implement the C/C++ standard.

This is now very unusual as hardware designers have learned the value of byte addressability.

MySQL: When is Flush Privileges in MySQL really needed?

2 points in addition to all other good answers:

1:

what are the Grant Tables?

from dev.mysql.com

The MySQL system database includes several grant tables that contain information about user accounts and the privileges held by them.

clari?cation: in MySQL, there are some inbuilt databases , one of them is "mysql" , all the tables on "mysql" database have been called as grant tables

2:

note that if you perform:

UPDATE a_grant_table SET password=PASSWORD('1234') WHERE test_col = 'test_val';

and refresh phpMyAdmin , you'll realize that your password has been changed on that table but even now if you perform:

mysql -u someuser -p

your access will be denied by your new password until you perform :

FLUSH PRIVILEGES;

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

Can't bind to 'ngIf' since it isn't a known property of 'div'

If you are using RC5 then import this:

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

and be sure to import CommonModule from the module that is providing your component.

 @NgModule({
    imports: [CommonModule],
    declarations: [MyComponent]
  ...
})
class MyComponentModule {}

Center a popup window on screen?

The accepted solution does not work unless the browser takes up the full screen,

This seems to always work

  const popupCenterScreen = (url, title, w, h, focus) => {
    const top = (screen.height - h) / 4, left = (screen.width - w) / 2;
    const popup = window.open(url, title, `scrollbars=yes,width=${w},height=${h},top=${top},left=${left}`);
    if (focus === true && window.focus) popup.focus();
    return popup;
  }

Impl:

some.function.call({data: ''})
    .then(result =>
     popupCenterScreen(
         result.data.url,
         result.data.title, 
         result.data.width, 
         result.data.height, 
         true));

AngularJS $http-post - convert binary to excel file and download

Download the server response as an array buffer. Store it as a Blob using the content type from the server (which should be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet):

var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
    { type: response.headers('Content-Type') }), fileName));

Save the blob to the user's device:

save(blob, fileName) {
    if (window.navigator.msSaveOrOpenBlob) { // For IE:
        navigator.msSaveBlob(blob, fileName);
    } else { // For other browsers:
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
}

Call to undefined method mysqli_stmt::get_result

for those searching for an alternative to $result = $stmt->get_result() I've made this function which allows you to mimic the $result->fetch_assoc() but using directly the stmt object:

function fetchAssocStatement($stmt)
{
    if($stmt->num_rows>0)
    {
        $result = array();
        $md = $stmt->result_metadata();
        $params = array();
        while($field = $md->fetch_field()) {
            $params[] = &$result[$field->name];
        }
        call_user_func_array(array($stmt, 'bind_result'), $params);
        if($stmt->fetch())
            return $result;
    }

    return null;
}

as you can see it creates an array and fetches it with the row data, since it uses $stmt->fetch() internally, you can call it just as you would call mysqli_result::fetch_assoc (just be sure that the $stmt object is open and result is stored):

//mysqliConnection is your mysqli connection object
if($stmt = $mysqli_connection->prepare($query))
{
    $stmt->execute();
    $stmt->store_result();

    while($assoc_array = fetchAssocStatement($stmt))
    {
        //do your magic
    }

    $stmt->close();
}

Filter Java Stream to 1 and only 1 element

We can use RxJava (very powerful reactive extension library)

LinkedList<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));

User userFound =  Observable.from(users)
                  .filter((user) -> user.getId() == 1)
                  .single().toBlocking().first();

The single operator throws an exception if no user or more then one user is found.

Pad left or right with string.format (not padleft or padright) with arbitrary string

There is another solution.

Implement IFormatProvider to return a ICustomFormatter that will be passed to string.Format :

public class StringPadder : ICustomFormatter
{
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
  {
     // do padding for string arguments
     // use default for others
  }
}

public class StringPadderFormatProvider : IFormatProvider
{
  public object GetFormat(Type formatType)
  { 
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  }
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();
}

Then you can use it like this :

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

Hyphen, underscore, or camelCase as word delimiter in URIs?

here's the best of both worlds.

I also "like" underscores, besides all your positive points about them, there is also a certain old-school style to them.

So what I do is use underscores and simply add a small rewrite rule to your Apache's .htaccess file to re-write all underscores to hyphens.

https://yoast.com/apache-rewrite-dash-underscore/

NGinx Default public www location?

If your configuration does not include a root /some/absolute/path; statement, or it includes one that uses a relative path like root some/relative/path;, then the resulting path depends on compile-time options.

Probably the only case that would allow you to make an educated guess as to what this means for you would be, if you downloaded and compiled the source yourself. In that case, the paths would be relative to whatever --prefix was used. If you didn't change it, it defaults to /usr/local/nginx. You can find the parameters nginx was compiled with via nginx -V, it lists --prefix as the first one.

Since the root directive defaults to html, this would, of course, result in /usr/local/nginx/html being the answer to your question.

However, if you installed nginx in any other way, all bets are off. Your distribution might use entirely different default paths. Learning to figure out what kind of defaults your distribution of choice uses for things is another task entirely.

How to "properly" print a list?

Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

" netsh wlan start hostednetwork " command not working no matter what I try

Same issue.

I solved the problem first activating (right click mouse and select activate) from control panel (network connections) and later changing to set mode to allow (by netsh command), to finally starting the hostednetwork with other netsh command, that is:

1.- Activate (Network Connections) by right click

2.- netsh wlan set hostednetwork mode=allow

3.- netsh wlan start hosted network

Good luck mate !!!

How to add percent sign to NSString

uese following code.

 NSString *searchText = @"Bhupi"
 NSString *formatedSearchText = [NSString stringWithFormat:@"%%%@%%",searchText];

will output: %Bhupi%

I want to align the text in a <td> to the top

https://developer.mozilla.org/en/CSS/vertical-align

<table style="height: 275px; width: 188px">
    <tr>
        <td style="width: 259px; vertical-align:top">
            main page
        </td>
    </tr>
</table>

?

ToString() function in Go

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Playground: http://play.golang.org/p/Azql7_pDAA


Output

101010

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

You can also run docker build with -f option

docker build -t ubuntu-test:latest -f Dockerfile.custom .

How can I pass POST parameters in a URL?

You can make a link perform an Ajax post request when it's clicked.

In jQuery:

$('a').click(function(e) {
    var $this = $(this);
    e.preventDefault();
    $.post('url', {'user': 'something', 'foo': 'bar'}, function() {
        window.location = $this.attr('href');
    });
});

You could also make the link submit a POST form with JavaScript:

<form action="url" method="post">
    <input type="hidden" name="user" value="something" />
    <a href="#">CLick</a>
</form>

<script>
    $('a').click(function(e) {
        e.preventDefault();
        $(this).parents('form').submit();
    });
</script>

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

SELECT b FROM foo;
-- (BLOB)

SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

CREATE GLOBAL TEMPORARY TABLE foo (
    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

Gem Command not found

FWIW, the equivalent package for RHEL/Fedora/CentOS/etc and SuSE/OpenSuSE appears to be called 'rubygems'.

NullPointerException in Java with no StackTrace

You are probably using the HotSpot JVM (originally by Sun Microsystems, later bought by Oracle, part of the OpenJDK), which performs a lot of optimization. To get the stack traces back, you need to pass the option -XX:-OmitStackTraceInFastThrow to the JVM.

The optimization is that when an exception (typically a NullPointerException) occurs for the first time, the full stack trace is printed and the JVM remembers the stack trace (or maybe just the location of the code). When that exception occurs often enough, the stack trace is not printed anymore, both to achieve better performance and not to flood the log with identical stack traces.

To see how this is implemented in the HotSpot JVM, grab a copy of it and search for the global variable OmitStackTraceInFastThrow. Last time I looked at the code (in 2019), it was in the file graphKit.cpp.

Android ACTION_IMAGE_CAPTURE Intent

I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.

I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:

String storageState = Environment.getExternalStorageState();
        if(storageState.equals(Environment.MEDIA_MOUNTED)) {

            String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
            _photoFile = new File(path);
            try {
                if(_photoFile.exists() == false) {
                    _photoFile.getParentFile().mkdirs();
                    _photoFile.createNewFile();
                }

            } catch (IOException e) {
                Log.e(TAG, "Could not create file.", e);
            }
            Log.i(TAG, path);

            _fileUri = Uri.fromFile(_photoFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
            intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
            startActivityForResult(intent, TAKE_PICTURE);
        }   else {
            new AlertDialog.Builder(MainActivity.this)
            .setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
            .setCancelable(true).create().show();
        }

I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.

Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg

There is no need to copy the file in the "onActivityResult" as posted above.

How to get Url Hash (#) from server side

We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:

  1. When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.

  2. On the server you can use this value if you need to do something with it. You can even change it if you need to.

  3. On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.

  4. If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.

We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.

Before submit:

$("form").submit(function() {
  $("input", "#urlhash").val(window.location.hash);
});

On page load:

var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
  window.location.hash = hashVal;
}

IsHashValid() can check for "undefined" or other things you don't want to handle.

Also, make sure you use $(document).ready() appropriately, of course.

Call a stored procedure with another in Oracle

Calling one procedure from another procedure:

One for a normal procedure:

CREATE OR REPLACE SP_1() AS 
BEGIN
/*  BODY */
END SP_1;

Calling procedure SP_1 from SP_2:

CREATE OR REPLACE SP_2() AS
BEGIN
/* CALL PROCEDURE SP_1 */
SP_1();
END SP_2;

Call a procedure with REFCURSOR or output cursor:

CREATE OR REPLACE SP_1
(
oCurSp1 OUT SYS_REFCURSOR
) AS
BEGIN
/*BODY */
END SP_1;

Call the procedure SP_1 which will return the REFCURSOR as an output parameter

CREATE OR REPLACE SP_2 
(
oCurSp2 OUT SYS_REFCURSOR
) AS `enter code here`
BEGIN
/* CALL PROCEDURE SP_1 WITH REF CURSOR AS OUTPUT PARAMETER */
SP_1(oCurSp2);
END SP_2;

How to define a variable in a Dockerfile?

To answer your question:

In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.

You can define a variable with:

ARG myvalue=3

Spaces around the equal character are not allowed.

And use it later with:

RUN echo $myvalue > /test

Random alpha-numeric string in JavaScript?

Random character:

String.fromCharCode(i); //where is an int

Random int:

Math.floor(Math.random()*100);

Put it all together:

function randomNum(hi){
    return Math.floor(Math.random()*hi);
} 
function randomChar(){
    return String.fromCharCode(randomNum(100));
}
function randomString(length){
   var str = "";
   for(var i = 0; i < length; ++i){
        str += randomChar();
   }
   return str;
}
var RandomString = randomString(32); //32 length string

Fiddle: http://jsfiddle.net/maniator/QZ9J2/

Hello World in Python

In python 3.x. you use

print("Hello, World")

In Python 2.x. you use

print "Hello, World!"

Create Word Document using PHP in Linux

OpenOffice templates + OOo command line interface.

  1. Create manually an ODT template with placeholders, like [%value-to-replace%]
  2. When instantiating the template with real data in PHP, unzip the template ODT (it's a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.
  3. Zip the ODT back
  4. Run the conversion ODT -> DOC via OpenOffice command line interface.

There are tools and libraries available to ease each of those steps.

May be that helps.

Append integer to beginning of list in Python

New lists can be made by simply adding lists together.

list1 = ['value1','value2','value3']
list2 = ['value0']
newlist=list2+list1
print(newlist)

notifyDataSetChanged example

I recently wrote on this topic, though this post it old, I thought it will be helpful to someone who wants to know how to implement BaseAdapter.notifyDataSetChanged() step by step and in a correct way.

Please follow How to correctly implement BaseAdapter.notifyDataSetChanged() in Android or the newer blog BaseAdapter.notifyDataSetChanged().

How can we run a test method with multiple parameters in MSTest?

This feature is in pre-release now and works with Visual Studio 2015.

For example:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    [DataRow(1, 2, 2)]
    [DataRow(2, 3, 5)]
    [DataRow(3, 5, 8)]
    public void AdditionTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

Delete a closed pull request from GitHub

This is the reply I received from Github when I asked them to delete a pull request:

"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

In order to clear all selection, I am using like this and its working fine for me. here is the script:

 $("#ddlMultiselect").multiselect("clearSelection");

 $("#ddlMultiselect").multiselect( 'refresh' );

How to break out from a ruby block?

next and break seem to do the correct thing in this simplified example!

class Bar
  def self.do_things
      Foo.some_method(1..10) do |x|
            next if x == 2
            break if x == 9
            print "#{x} "
      end
  end
end

class Foo
    def self.some_method(targets, &block)
      targets.each do |target|
        begin
          r = yield(target)
        rescue  => x
          puts "rescue #{x}"
        end
     end
   end
end

Bar.do_things

output: 1 3 4 5 6 7 8

.htaccess file to allow access to images folder to view pictures?

Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:

Options -Indexes

Or try:

Options All -Indexes

Upload artifacts to Nexus, without Maven

Using curl:

curl -v \
    -F "r=releases" \
    -F "g=com.acme.widgets" \
    -F "a=widget" \
    -F "v=0.1-1" \
    -F "p=tar.gz" \
    -F "file=@./widget-0.1-1.tar.gz" \
    -u myuser:mypassword \
    http://localhost:8081/nexus/service/local/artifact/maven/content

You can see what the parameters mean here: https://support.sonatype.com/entries/22189106-How-can-I-programatically-upload-an-artifact-into-Nexus-

To make the permissions for this work, I created a new role in the admin GUI and I added two privileges to that role: Artifact Download and Artifact Upload. The standard "Repo: All Maven Repositories (Full Control)"-role is not enough. You won't find this in the REST API documentation that comes bundled with the Nexus server, so these parameters might change in the future.

On a Sonatype JIRA issue, it was mentioned that they "are going to overhaul the REST API (and the way it's documentation is generated) in an upcoming release, most likely later this year".

How to Execute a Python File in Notepad ++?

@Ramiz Uddin's answer definitely deserves more visibility :

  • Open Notepad++
  • On the menu go to: RunRun.. (F5)
  • Type in: cmd /K python "$(FULL_CURRENT_PATH)"

echo that outputs to stderr

No, that's the standard way to do it. It shouldn't cause errors.

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

how to align all my li on one line?

I think the NOBR tag might be overkill, and as you said, unreliable.

There are 2 options available depending on how you are displaying the text.

If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"

Implementing autocomplete

I've built a fairly simple, reusable and functional Angular2 autocomplete component based on some of the ideas in this answer/other tutorials around on this subject and others. It's by no means comprehensive but may be helpful if you decide to build your own.

The component:

import { Component, Input, Output, OnInit, ContentChild, EventEmitter, HostListener } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { AutoCompleteRefDirective } from "./autocomplete.directive";

@Component({
    selector: 'autocomplete',
    template: `
<ng-content></ng-content>
<div class="autocomplete-wrapper" (click)="clickedInside($event)">
    <div class="list-group autocomplete" *ngIf="results">
        <a [routerLink]="" class="list-group-item" (click)="selectResult(result)" *ngFor="let result of results; let i = index" [innerHTML]="dataMapping(result) | highlight: query" [ngClass]="{'active': i == selectedIndex}"></a>
    </div>
</div>
    `,
    styleUrls: ['./autocomplete.component.css']
})
export class AutoCompleteComponent implements OnInit {

    @ContentChild(AutoCompleteRefDirective)
    public input: AutoCompleteRefDirective;

    @Input() data: (searchTerm: string) => Observable<any[]>;
    @Input() dataMapping: (obj: any) => string;
    @Output() onChange = new EventEmitter<any>();

    @HostListener('document:click', ['$event'])
    clickedOutside($event: any): void {
        this.clearResults();
    }

    public results: any[];
    public query: string;
    public selectedIndex: number = 0;
    private searchCounter: number = 0;

    ngOnInit(): void {
        this.input.change
            .subscribe((query: string) => {
                this.query = query;
                this.onChange.emit();
                this.searchCounter++;
                let counter = this.searchCounter;

                if (query) {
                    this.data(query)
                        .subscribe(data => {
                            if (counter == this.searchCounter) {
                                this.results = data;
                                this.input.hasResults = data.length > 0;
                                this.selectedIndex = 0;
                            }
                        });
                }
                else this.clearResults();
            });

        this.input.cancel
            .subscribe(() => {
                this.clearResults();
            });

        this.input.select
            .subscribe(() => {
                if (this.results && this.results.length > 0)
                {
                    this.selectResult(this.results[this.selectedIndex]);
                }
            });

        this.input.up
            .subscribe(() => {
                if (this.results && this.selectedIndex > 0) this.selectedIndex--;
            });

        this.input.down
            .subscribe(() => {
                if (this.results && this.selectedIndex + 1 < this.results.length) this.selectedIndex++;
            });
    }

    selectResult(result: any): void {
        this.onChange.emit(result);
        this.clearResults();
    }

    clickedInside($event: any): void {
        $event.preventDefault();
        $event.stopPropagation();
    }

    private clearResults(): void {
        this.results = [];
        this.selectedIndex = 0;
        this.searchCounter = 0;
        this.input.hasResults = false;
    }
}

The component CSS:

.autocomplete-wrapper {
    position: relative;
}

.autocomplete {
    position: absolute;
    z-index: 100;
    width: 100%;
}

The directive:

import { Directive, Input, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({
    selector: '[autocompleteRef]'
})
export class AutoCompleteRefDirective {
    @Input() hasResults: boolean = false;
    @Output() change = new EventEmitter<string>();
    @Output() cancel = new EventEmitter();
    @Output() select = new EventEmitter();
    @Output() up = new EventEmitter();
    @Output() down = new EventEmitter();

    @HostListener('input', ['$event'])
    oninput(event: any) {
        this.change.emit(event.target.value);
    }

    @HostListener('keydown', ['$event'])
    onkeydown(event: any)
    {
        switch (event.keyCode) {
            case 27:
                this.cancel.emit();
                return false;
            case 13:
                var hasResults = this.hasResults;
                this.select.emit();
                return !hasResults;
            case 38:
                this.up.emit();
                return false;
            case 40:
                this.down.emit();
                return false;
            default:
        }
    }
}

The highlight pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'highlight'
})

export class HighlightPipe implements PipeTransform {
    transform(value: string, args: any): any {
        var re = new RegExp(args, 'gi');

        return value.replace(re, function (match) {
            return "<strong>" + match + "</strong>";
        })

    }
}

The implementation:

import { Component } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subscriber } from "rxjs/Subscriber";

@Component({
    selector: 'home',
    template: `
<autocomplete [data]="getData" [dataMapping]="dataMapping" (onChange)="change($event)">
    <input type="text" class="form-control" name="AutoComplete" placeholder="Search..." autocomplete="off" autocompleteRef />
</autocomplete>
    `
})
export class HomeComponent {

    getData = (query: string) => this.search(query);

    // The dataMapping property controls the mapping of an object returned via getData.
    // to a string that can be displayed to the use as an option to select.
    dataMapping = (obj: any) => obj;

    // This function is called any time a change is made in the autocomplete.
    // When the text is changed manually, no object is passed.
    // When a selection is made the object is passed.
    change(obj: any): void {
        if (obj) {
            // You can do pretty much anything here as the entire object is passed if it's been selected.
            // Navigate to another page, update a model etc.
            alert(obj);
        }
    }

    private searchData = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];

    // This function mimics an Observable http service call.
    // In reality it's probably calling your API, but today it's looking at mock static data.
    private search(query: string): Observable<any>
    {
        return new Observable<any>((subscriber: Subscriber<any>) => subscriber
            .next())
            .map(o => this.searchData.filter(d => d.indexOf(query) > -1));
    }
}

Print an integer in binary format in Java

Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number. Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int integer ;
        String binary = "";    //   here we count "" or null 
                               //   just String binary = null;
        System.out.print("Enter the binary Number: ");
        integer = sc.nextInt();

        while(integer>0)
        {
            int x = integer % 2;
            binary = x + binary;
            integer = integer / 2;  
        }
        System.out.println("Your binary number is : "+binary);
        System.out.println("your binary length : " + binary.length());
    }
}

Which terminal command to get just IP address and nothing else?

I prefer not to use awk and such in scripts.. ip has the option to output in JSON.

If you leave out $interface then you get all of the ip addresses:

ip -json addr show $interface | \
  jq -r '.[] | .addr_info[] | select(.family == "inet") | .local'

jquery .html() vs .append()

This has happened to me . Jquery version : 3.3. If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html will end up adding only the last object to the parent element, whereas .append will add all the list objects as children of the parent element.

assign multiple variables to the same value in Javascript

Nothing stops you from doing the above, but hold up!

There are some gotchas. Assignment in Javascript is from right to left so when you write:

var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

it effectively translates to:

var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));

which effectively translates to:

var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));

Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.

Note: My above example assumes you are running your code in the browser, hence window. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global which is the global context for that environment).

Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.

var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.


Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.

Switch in Laravel 5 - Blade

To overcome the space in 'switch ()', you can use code :

Blade::extend(function($value, $compiler){
    $value = preg_replace('/(\s*)@switch[ ]*\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
    $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
    $value = preg_replace('/(\s*)@case[ ]*\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
    $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
    $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
    return $value;
  });

How can I configure my makefile for debug and release builds?

you can have a variable

DEBUG = 0

then you can use a conditional statement

  ifeq ($(DEBUG),1)

  else

  endif

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

HTML Upload MAX_FILE_SIZE does not appear to work

Before I start, please let me emphasize that the size of the file must be checked on the server side. If not checked on server side, malicious users can override your client side limits, and upload huge files to your server. DO NOT TRUST THE USERS.

I played a bit with PHP's MAX_FILE_SIZE, it seemed to work only after the file was uploaded, which makes it irrelevant (again, malicious user can override it quite easily).

The javascript code below (tested in Firefox and Chrome), based on Matthew's post, will warn the user (the good, innocent one) a priori to uploading a large file, saving both traffic and the user's time:

<form method="post" enctype="multipart/form-data" 
onsubmit="return checkSize(2097152)">    
<input type="file" id="upload" />
<input type="submit" />

<script type="text/javascript">
function checkSize(max_img_size)
{
    var input = document.getElementById("upload");
    // check for browser support (may need to be modified)
    if(input.files && input.files.length == 1)
    {           
        if (input.files[0].size > max_img_size) 
        {
            alert("The file must be less than " + (max_img_size/1024/1024) + "MB");
            return false;
        }
    }

    return true;
}
</script>

Publish to IIS, setting Environment Variable

I have modified the answer which @Christian Del Bianco is given. I changed the process for .net core 2 and upper as project.json file now absolute.

  1. First, create appsettings.json file in root directory. with the content

      {
         // Possible string values reported below. When empty it use ENV 
            variable value or Visual Studio setting.
         // - Production
         // - Staging
         // - Test
        // - Development
       "ASPNETCORE_ENVIRONMENT": "Development"
     }
    
  2. Then create another two setting file appsettings.Development.json and appsettings.Production.json with the necessary configuration.

  3. Add necessary code to set up the environment to Program.cs file.

    public class Program
    {
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    
      ***var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();***
    
        try
        {
            ***CreateWebHostBuilder(args, enviromentValue).Build().Run();***
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of setup related exception");
            throw;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }
    }
    
    public static IWebHostBuilder CreateWebHostBuilder(string[] args, string enviromentValue) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog()
            ***.UseEnvironment(enviromentValue);***
    

    }

  4. Add the envsettings.json to your .csproj file for copy to published directory.

       <ItemGroup>
            <None Include="envsettings.json" CopyToPublishDirectory="Always" />
        </ItemGroup>
    
  5. Now just change the ASPNETCORE_ENVIRONMENT as you want in envsettings.json file and published.

Eclipse error: 'Failed to create the Java Virtual Machine'

All these solutions failed me. This happened to me out of the blue after using Eclipse for six months. It seems somehow my JDK got corrupted.

My eventual solution was to download a newer JDK and update my JAVA_HOME accordingly, from jdk1.6.0_37 to jdk1.6.0_43 in my case.

Set default heap size in Windows

Setup JAVA_OPTS as a system variable with the following content:

JAVA_OPTS="-Xms256m -Xmx512m"

After that in a command prompt run the following commands:

SET JAVA_OPTS="-Xms256m -Xmx512m"

This can be explained as follows:

  • allocate at minimum 256MBs of heap
  • allocate at maximum 512MBs of heap

These values should be changed according to application requirements.

EDIT:

You can also try adding it through the Environment Properties menu which can be found at:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.
  4. Click New to add a new variable name and value.
  5. For variable name enter JAVA_OPTS for variable value enter -Xms256m -Xmx512m
  6. Click ok and close the System Properties Tab.
  7. Restart any java applications.

EDIT 2:

JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.

To setup a system variable you have to complete the steps listed above from 1 to 4.

How do I break a string across more than one line of code in JavaScript?

I tried a number of the above suggestions but got an ILLEGAL character warning in Chrome code inspector. The following worked for me (only tested in Chrome though!)

alert('stuff on line 1\\nstuff on line 2);

comes out like...

stuff on line 1
stuff on line 2

NOTE the double backslash!!...this seems to be important!

javascript if number greater than number

You should convert them to number before compare.

Try:

if (+x > +y) {
  //...
}

or

if (Number(x) > Number(y)) {
  // ...
}

Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.

How to find specific lines in a table using Selenium?

The following code allows you to specify the row/column number and get the resulting cell value:

WebDriver driver = new ChromeDriver();
WebElement base = driver.findElement(By.className("Table"));
tableRows = base.findElements(By.tagName("tr"));
List<WebElement> tableCols = tableRows.get([ROW_NUM]).findElements(By.tagName("td"));
String cellValue = tableCols.get([COL_NUM]).getText();

The Android emulator is not starting, showing "invalid command-line parameter"

I had this issue as well. The solution is (if you are on Windows as I am) to change the path to C:\PROGRA~1\Android\android-sdk-windows\.

Assuming Program Files is the first directory with the word PROGRAM in it which it should be. This worked.

How to recover corrupted Eclipse workspace?

If the workspace is not that big you could backup to say dropbox as a private locked folder.

How do I use itertools.groupby()?

WARNING:

The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using

for x in list(groupby(range(10))):
    print(list(x[1]))

will produce:

[]
[]
[]
[]
[]
[]
[]
[]
[]
[9]

Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,

def groupbylist(*args, **kwargs):
    return [(k, list(g)) for k, g in groupby(*args, **kwargs)]

and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.

jQuery UI DatePicker - Change Date Format

Try to use the

$( ".selector" ).datepicker({ dateFormat: 'dd/mm/yy' });  

and there is lots of option available For the datepicker you can find it Here

http://api.jqueryui.com/datepicker/

This is the way we call the datepicker with the parameter

$(function() {
      $('.selector').datepicker({
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            numberOfMonths: 1,
            buttonImage: 'contact/calendar/calendar.gif',
            buttonImageOnly: true,
            onSelect: function(selectedDate) {
                 // we can write code here 
             }
      });
});

Bind failed: Address already in use

You have a process that is already using that port. netstat -tulpn will enable one to find the process ID of that is using a particular port.

How should I edit an Entity Framework connection string?

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

SQL Server - INNER JOIN WITH DISTINCT

add "distinct" after "select".

select distinct a.FirstName, a.LastName, v.District , v.LastName
from AddTbl a 
inner join ValTbl v  where a.LastName = v.LastName  order by Firstname

Zooming MKMapView to fit annotation pins?

@jowie's solution works great. One catch, if a map has only one annotation you'll end up with a fully zoomed out map. I added 0.1 to the rect make size to make sure setVisibleMapRect has something to zoom to.

MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);

How to change JFrame icon

Just add the following code:

setIconImage(new ImageIcon(PathOfFile).getImage());

Any way to make plot points in scatterplot more transparent in R?

Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?

addTrans <- function(color,trans)
{
  # This function adds transparancy to a color.
  # Define transparancy with an integer between 0 and 255
  # 0 being fully transparant and 255 being fully visable
  # Works with either color and trans a vector of equal length,
  # or one of the two of length 1.

  if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
  if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
  if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))

  num2hex <- function(x)
  {
    hex <- unlist(strsplit("0123456789ABCDEF",split=""))
    return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
  }
  rgb <- rbind(col2rgb(color),trans)
  res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
  return(res)
}

Some examples:

cols <- sample(c("red","green","pink"),100,TRUE)

# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)

# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)

# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)

How to add buttons dynamically to my form?

I had the same doubt and came up with the following contribution:

 int height = this.Size.Height;
 int width = this.Size.Width;

 int widthOffset = 10;
 int heightOffset = 10;

 int btnWidth = 100;  // Button Widht
 int btnHeight = 40;  // Button Height

 for (int i = 0; i < 50; ++i)
 {
     if ((widthOffset + btnWidth) >= width)
     {                    
         widthOffset = 10;
         heightOffset = heightOffset + btnHeight

         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
     }

     else
     {                        
         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
      }
  }

Expected Behaviour:
This will generate the buttons dinamically and using the current window size, "break a line" when the button exceeds the right margin of your window.

Can't access 127.0.0.1

In windows first check under services if world wide web publishing services is running. If not start it.

If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.

Python Pandas Error tokenizing data

I believe the solutions,

,engine='python'
, error_bad_lines = False

will be good if it is dummy columns and you want to delete it. In my case, the second row really had more columns and I wanted those columns to be integrated and to have the number of columns = MAX(columns).

Please refer to the solution below that I could not read anywhere:

try:
    df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep)
except pd.errors.ParserError as err:
    str_find = 'saw '
    int_position = int(str(err).find(str_find)) + len(str_find)
    str_nbCol = str(err)[int_position:]
    l_col = range(int(str_nbCol))
    df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep, names = l_col)

How to get the size of a JavaScript object?

I know this is absolutely not the right way to do it, yet it've helped me a few times in the past to get the approx object file size:

Write your object/response to the console or a new tab, copy the results to a new notepad file, save it, and check the file size. The notepad file itself is just a few bytes, so you'll get a fairly accurate object file size.

Concatenating two one-dimensional NumPy arrays

There are several possibilities for concatenating 1D arrays, e.g.,

numpy.r_[a, a],
numpy.stack([a, a]).reshape(-1),
numpy.hstack([a, a]),
numpy.concatenate([a, a])

All those options are equally fast for large arrays; for small ones, concatenate has a slight edge:

enter image description here

The plot was created with perfplot:

import numpy
import perfplot

perfplot.show(
    setup=lambda n: numpy.random.rand(n),
    kernels=[
        lambda a: numpy.r_[a, a],
        lambda a: numpy.stack([a, a]).reshape(-1),
        lambda a: numpy.hstack([a, a]),
        lambda a: numpy.concatenate([a, a]),
    ],
    labels=["r_", "stack+reshape", "hstack", "concatenate"],
    n_range=[2 ** k for k in range(19)],
    xlabel="len(a)",
)

Symfony - generate url with parameter in controller

It's pretty simple :

public function myAction()
{
    $url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}

Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :

$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));

How to select an item in a ListView programmatically?

if (listView1.Items.Count > 0)
{
    listView1.Items[0].Selected = true;
    listView1.Select();
}

list items do not appear selected unless the control has the focus (or you set the HideSelection property to false)

Delete directories recursively in Java

Here is a bare bones main method that accepts a command line argument, you may need to append your own error checking or mold it to how you see fit.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DeleteFiles {

/**
 * @param intitial arguments take in a source to read from and a 
 * destination to read to
 */
    public static void main(String[] args)
                     throws FileNotFoundException,IOException {
        File src = new File(args[0]);
        if (!src.exists() ) {
            System.out.println("FAILURE!");
        }else{
            // Gathers files in directory
            File[] a = src.listFiles();
            for (int i = 0; i < a.length; i++) {
                //Sends files to recursive deletion method
                fileDelete(a[i]);
            }
            // Deletes original source folder
            src.delete();
            System.out.println("Success!");
        }
    }

    /**
     * @param srcFile Source file to examine
     * @throws FileNotFoundException if File not found
     * @throws IOException if File not found
     */
    private static void fileDelete(File srcFile)
                     throws FileNotFoundException, IOException {
        // Checks if file is a directory
        if (srcFile.isDirectory()) {
            //Gathers files in directory
            File[] b = srcFile.listFiles();
            for (int i = 0; i < b.length; i++) {
                //Recursively deletes all files and sub-directories
                fileDelete(b[i]);
            }
            // Deletes original sub-directory file
            srcFile.delete();
        } else {
            srcFile.delete();
        }
    }
}

I hope that helps!

How to implement a ViewPager with different Fragments / Layouts

As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.

ViewPager with multiple Fragments and Layout files - How To

The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments.

FirstFragment.java has a orange background layout, SecondFragment.java has a green background layout and ThirdFragment.java has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.

Also be aware that I am using the support-library's Fragment: android.support.v4.app.Fragment

MainActivity.java (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the android.support.v4 package.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

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

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int pos) {
            switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
            case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }

        @Override
        public int getCount() {
            return 5;
        }       
    }
}

activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

The Fragment classes, FirstFragment.java import android.support.v4.app.Fragment;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.first_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
        tv.setText(getArguments().getString("msg"));

        return v;
    }

    public static FirstFragment newInstance(String text) {

        FirstFragment f = new FirstFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }
}

first_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_orange_dark" >

    <TextView
        android:id="@+id/tvFragFirst"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />
</RelativeLayout>

SecondFragment.java

public class SecondFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

second_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_dark" >

    <TextView
        android:id="@+id/tvFragSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

ThirdFragment.java

public class ThirdFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.third_frag, container, false);

    TextView tv = (TextView) v.findViewById(R.id.tvFragThird);      
    tv.setText(getArguments().getString("msg"));

    return v;
}

public static ThirdFragment newInstance(String text) {

    ThirdFragment f = new ThirdFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);

    f.setArguments(b);

    return f;
}
}

third_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_light" >

    <TextView
        android:id="@+id/tvFragThird"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="26dp"
        android:text="TextView" />

</RelativeLayout>

The end result is the following:

The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.

enter image description here

Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.

Last but not least:

I would recommend that you use an empty constructor in each of your Fragment classes.

Instead of handing over potential parameters via constructor, use the newInstance(...) method and the Bundle for handing over parameters.

This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles attached to Intents.

Resize Google Maps marker icon image

MarkerImage has been deprecated for Icon

Until version 3.10 of the Google Maps JavaScript API, complex icons were defined as MarkerImage objects. The Icon object literal was added in 3.10, and replaces MarkerImage from version 3.11 onwards. Icon object literals support the same parameters as MarkerImage, allowing you to easily convert a MarkerImage to an Icon by removing the constructor, wrapping the previous parameters in {}'s, and adding the names of each parameter.

Phillippe's code would now be:

 var icon = {
     url: "../res/sit_marron.png", // url
     scaledSize: new google.maps.Size(width, height), // size
     origin: new google.maps.Point(0,0), // origin
     anchor: new google.maps.Point(anchor_left, anchor_top) // anchor 
 };

 position = new google.maps.LatLng(latitud,longitud)
 marker = new google.maps.Marker({
  position: position,
  map: map,
  icon: icon
 });

Going to a specific line number using Less in Unix

To open at a specific line straight from the command line, use:

less +320123 filename

If you want to see the line numbers too:

less +320123 -N filename

You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:

less +320123 -j 10 filename

How to get script of SQL Server data?

I had a hell of a time finding this option in SQL Management Studio 2012, but I finally found it. The option is hiding in the Advanced button in the screen below.

I always assumed this contained just assumed advanced options for File generation, since that's what it's next to, but it turns out someone at MS is just really bad at UI design in this case. HTH somebody who comes to this thread like I did.

SQL Management Studio 2012

Send data from activity to fragment in Android

I ran into a similar issue while using the latest Navigation architecture component. Tried out all the above-mentioned code with passing a bundle from my calling activity to Fragment.

The best solution, following the latest development trends in Android, is by using View Model (part of Android Jetpack).

Create and Initialize a ViewModel class in the parent Activity, Please note that this ViewModel has to be shared between the activity and fragment.

Now, Inside the onViewCreated() of the fragment, Initialize the Same ViewModel and setup Observers to listen to the ViewModel fields.

Here is a helpful, in-depth tutorial if you need.

https://medium.com/mindorks/how-to-communicate-between-fragments-and-activity-using-viewmodel-ca733233a51c

Swift - Split string over multiple lines

You can using unicode equals for enter or \n and implement them inside you string. For example: \u{0085}.

Adding and removing extensionattribute to AD object

Set-ADUser -Identity anyUser -Replace @{extensionAttribute4="myString"}

This is also usefull

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select CONVERT(NVARCHAR, SYSDATETIME(), 106) AS [DD-MON-YYYY]

or else

select REPLACE(CONVERT(NVARCHAR,GETDATE(), 106), ' ', '-')

both works fine

How to use HTTP_X_FORWARDED_FOR properly?

In the light of the latest httpoxy vulnerabilities, there is really a need for a full example, how to use HTTP_X_FORWARDED_FOR properly.

So here is an example written in PHP, how to detect a client IP address, if you know that client may be behind a proxy and you know this proxy can be trusted. If you don't known any trusted proxies, just use REMOTE_ADDR

<?php

function get_client_ip ()
{
    // Nothing to do without any reliable information
    if (!isset ($_SERVER['REMOTE_ADDR'])) {
        return NULL;
    }

    // Header that is used by the trusted proxy to refer to
    // the original IP
    $proxy_header = "HTTP_X_FORWARDED_FOR";

    // List of all the proxies that are known to handle 'proxy_header'
    // in known, safe manner
    $trusted_proxies = array ("2001:db8::1", "192.168.50.1");

    if (in_array ($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {

        // Get the IP address of the client behind trusted proxy
        if (array_key_exists ($proxy_header, $_SERVER)) {

            // Header can contain multiple IP-s of proxies that are passed through.
            // Only the IP added by the last proxy (last IP in the list) can be trusted.
            $proxy_list = explode (",", $_SERVER[$proxy_header]);
            $client_ip = trim (end ($proxy_list));

            // Validate just in case
            if (filter_var ($client_ip, FILTER_VALIDATE_IP)) {
                return $client_ip;
            } else {
                // Validation failed - beat the guy who configured the proxy or
                // the guy who created the trusted proxy list?
                // TODO: some error handling to notify about the need of punishment
            }
        }
    }

    // In all other cases, REMOTE_ADDR is the ONLY IP we can trust.
    return $_SERVER['REMOTE_ADDR'];
}

print get_client_ip ();

?>

How do I auto-hide placeholder text upon focus using css or jquery?

I like the css approach spiced with transitions. On Focus the placeholder fades out ;) Works also for textareas.

Thanks @Casey Chu for the great idea.

textarea::-webkit-input-placeholder, input::-webkit-input-placeholder { 
    color: #fff;
    opacity: 0.4;
    transition: opacity 0.5s;
    -webkit-transition: opacity 0.5s; 
}

textarea:focus::-webkit-input-placeholder, input:focus::-webkit-input-placeholder  { 
    opacity: 0;
}

Multi-dimensional associative arrays in JavaScript

If it doesn't have to be an array, you can create a "multidimensional" JS object...

<script type="text/javascript">
var myObj = { 
    fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 }, 
    mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 }, 
    sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 } 
}

document.write(myObj['fred']['apples']);
</script>

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

android : Error converting byte to dex

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile fileTree(include: 'Parse-*.jar', dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:cardview-v7:23.2.0'
    compile 'com.android.support:design:24.0.0-alpha1'
    compile "com.google.firebase:firebase-invites:9.2.0"
    compile "com.google.firebase:firebase-ads:9.2.0"
    compile 'com.google.firebase:firebase-database:9.2.0'
    compile 'com.google.firebase:firebase-core:9.2.0'
}

I add the com.google.firebase:firebase-core:9.2.0 line and choose the same version (9.2.0) for all firebase libraries and the issue was solved.

Do Facebook Oauth 2.0 Access Tokens Expire?

After digging around a bit, i found this. It seems to be the answer:

Updated (11/April/2018)

  • The token will expire after about 60 days.
  • The token will be refreshed once per day, for up to 90 days, when the person using your app makes a request to Facebook's servers.
  • All access tokens need to be renewed every 90 days with the consent of the person using your app.

Facebook change announce (10/04/2018)

Facebook updated token expiration page (10/04/2018)

offline_access: Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.

Its a permission value requested.

http://developers.facebook.com/docs/authentication/permissions

UPDATE

offline_access permission has been removed a while ago.

https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/

Comparing Dates in Oracle SQL

Single quote must be there, since date converted to character.

Select employee_id, count(*)
From Employee
Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95';

Formatting Numbers by padding with leading zeros in SQL Server

As clean as it could get and give scope of replacing with variables:

Select RIGHT(REPLICATE('0',6) + EmployeeID, 6) from dbo.RequestItems
WHERE ID=0

How to find the parent element using javascript

Use the change event of the select:

$('#my_select').change(function()
{
   $(this).parents('td').css('background', '#000000');
});

When to use Common Table Expression (CTE)

I use them to break up complex queries, especially complex joins and sub-queries. I find I'm using them more and more as 'pseudo-views' to help me get my head around the intent of the query.

My only complaint about them is they cannot be re-used. For example, I may have a stored proc with two update statements that could use the same CTE. But the 'scope' of the CTE is the first query only.

Trouble is, 'simple examples' probably don't really need CTE's!

Still, very handy.

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

One-line list comprehension: if-else variants

x if y else z is the syntax for the expression you're returning for each element. Thus you need:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.

With a filter, you need:

[ EXP for x in seq if COND ]

Without a filter you need:

[ EXP for x in seq ]

and in your second example, the expression is a "complex" one, which happens to involve an if-else.

Maven2: Best practice for Enterprise Project (EAR file)

NetBeans IDE automatically defines the structure which is almost similar to one suggested by Patrick Garner. For NetBeans users

File->New Project ->In left side select Maven and In right side select Maven Enterprise Application and press Next -> Asks for project names for both war,ejb and settings.

The IDE will automatically create the structure for you.

How to add parameters to HttpURLConnection using POST using NameValuePair

Try this:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user_name", "Name"));
nameValuePairs.add(new BasicNameValuePair("pass","Password" ));
nameValuePairs.add(new BasicNameValuePair("user_email","email" ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

String ret = EntityUtils.toString(response.getEntity());
Log.v("Util response", ret);

You can add as many nameValuePairs as you need. And don't forget to mention the count in the list.

react-native - Fit Image in containing View, not the whole screen size

I think it's because you didn't specify the width and height for the item.

If you only want to have 2 images in a row, you can try something like this instead of using flex:

item: {
    width: '50%',
    height: '100%',
    overflow: 'hidden',
    alignItems: 'center',
    backgroundColor: 'orange',
    position: 'relative',
    margin: 10,
},

This works for me, hope it helps.

PHP - Merging two arrays into one array (also Remove Duplicates)

try to use the array_unique()

this elminates duplicated data inside the list of your arrays..

How to dismiss keyboard for UITextView with return key?

There is another solution while using with uitextview, You can add toolbar as InputAccessoryView in "textViewShouldBeginEditing", and from this toolbar's done button you can dismiss keyboard, the code for this is following:

In viewDidLoad

toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; //toolbar is uitoolbar object
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(btnClickedDone:)];
[toolBar setItems:[NSArray arrayWithObject:btnDone]];

In textviewdelegate method

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
     [textView setInputAccessoryView:toolBar];
     return YES;
}

In action of Button Done which is in toolbar is following:

-(IBAction)btnClickedDone:(id)sender
{
    [self.view endEditing:YES];
}

How do I set the path to a DLL file in Visual Studio?

Another possibility would be to set the Working Directory under the debugging options to be the directory that has that DLL.

Edit: I was going to mention using a batch file to start Visual Studio (and set the PATH variable in the batch file). So then did a bit of searching and see that this exact same question was asked not long ago in this post. The answer suggests the batch file option as well as project settings that apparently may do the job (I did not test it).

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:

var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar:

var name = cmd.ExecuteScalar();

if (name != null)
{
   position = name.ToString();
   Response.Write("User Registration successful");
}
else
{
    Console.WriteLine("No Employee found.");
}

The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of:

string position;

using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
  con.Open();

  using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
  {
    cmd.Parameters.AddWithValue("@id", id.Text);
  
    var name = cmd.ExecuteScalar();
  
    if (name != null)
    {
       position = name.ToString();
       Response.Write("User Registration successful");
    }
    else
    {
        Console.WriteLine("No Employee found.");
    }
  }
}

c++ Read from .csv file

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
 ID=0   Name=Filipe Age=19  Gender=M
 ID=1   Name=Maria  Age=20  Gender=F
 ID=2   Name=Walter Age=60  Gender=M

How to list npm user-installed packages?

I use npm -g outdated --depth=0 to list outdated versions
in the global space.

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Resource from src/main/resources not found after building with maven

Resources from src/main/resources will be put onto the root of the classpath, so you'll need to get the resource as:

new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/config.txt")));

You can verify by looking at the JAR/WAR file produced by maven as you'll find config.txt in the root of your archive.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

There was an error in understanding of return Type Just add Header and it will solve your problem

@Headers("Content-Type: application/json")

How to debug Lock wait timeout exceeded on MySQL?

What gives this away is the word transaction. It is evident by the statement that the query was attempting to change at least one row in one or more InnoDB tables.

Since you know the query, all the tables being accessed are candidates for being the culprit.

From there, you should be able to run SHOW ENGINE INNODB STATUS\G

You should be able to see the affected table(s)

You get all kinds of additional Locking and Mutex Information.

Here is a sample from one of my clients:

mysql> show engine innodb status\G
*************************** 1. row ***************************
  Type: InnoDB
  Name:
Status:
=====================================
110514 19:44:14 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 4 seconds
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 9014315, signal count 7805377
Mutex spin waits 0, rounds 11487096053, OS waits 7756855
RW-shared spins 722142, OS waits 211221; RW-excl spins 787046, OS waits 39353
------------------------
LATEST FOREIGN KEY ERROR
------------------------
110507 21:41:35 Transaction:
TRANSACTION 0 606162814, ACTIVE 0 sec, process no 29956, OS thread id 1223895360 updating or deleting, thread declared inside InnoDB 499
mysql tables in use 1, locked 1
14 lock struct(s), heap size 3024, 8 row lock(s), undo log entries 1
MySQL thread id 3686635, query id 124164167 10.64.89.145 viget updating
DELETE FROM file WHERE file_id in ('6dbafa39-7f00-0001-51f2-412a450be5cc' )
Foreign key constraint fails for table `backoffice`.`attachment`:
,
  CONSTRAINT `attachment_ibfk_2` FOREIGN KEY (`file_id`) REFERENCES `file` (`file_id`)
Trying to delete or update in parent table, in index `PRIMARY` tuple:
DATA TUPLE: 17 fields;
 0: len 36; hex 36646261666133392d376630302d303030312d353166322d343132613435306265356363; asc 6dbafa39-7f00-0001-51f2-412a450be5cc;; 1: len 6; hex 000024214f7e; asc   $!O~;; 2: len 7; hex 000000400217bc; asc    @   ;; 3: len 2; hex 03e9; asc   ;; 4: len 2; hex 03e8; asc   ;; 5: len 36; hex 65666635323863622d376630302d303030312d336632662d353239626433653361333032; asc eff528cb-7f00-0001-3f2f-529bd3e3a302;; 6: len 40; hex 36646234376337652d376630302d303030312d353166322d3431326132346664656366352e6d7033; asc 6db47c7e-7f00-0001-51f2-412a24fdecf5.mp3;; 7: len 21; hex 416e67656c73204e6f7720436f6e666572656e6365; asc Angels Now Conference;; 8: len 34; hex 416e67656c73204e6f7720436f6e666572656e6365204a756c7920392c2032303131; asc Angels Now Conference July 9, 2011;; 9: len 1; hex 80; asc  ;; 10: len 8; hex 8000124a5262bdf4; asc    JRb  ;; 11: len 8; hex 8000124a57669dc3; asc    JWf  ;; 12: SQL NULL; 13: len 5; hex 8000012200; asc    " ;; 14: len 1; hex 80; asc  ;; 15: len 2; hex 83e8; asc   ;; 16: len 4; hex 8000000a; asc     ;;

But in child table `backoffice`.`attachment`, in index `PRIMARY`, there is a record:
PHYSICAL RECORD: n_fields 6; compact format; info bits 0
 0: len 30; hex 36646261666133392d376630302d303030312d353166322d343132613435; asc 6dbafa39-7f00-0001-51f2-412a45;...(truncated); 1: len 30; hex 38666164663561652d376630302d303030312d326436612d636164326361; asc 8fadf5ae-7f00-0001-2d6a-cad2ca;...(truncated); 2: len 6; hex 00002297b3ff; asc   "   ;; 3: len 7; hex 80000040070110; asc    @   ;; 4: len 2; hex 0000; asc   ;; 5: len 30; hex 416e67656c73204e6f7720436f6e666572656e636520446f63756d656e74; asc Angels Now Conference Document;;

------------
TRANSACTIONS
------------
Trx id counter 0 620783814
Purge done for trx's n:o < 0 620783800 undo n:o < 0 0
History list length 35
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 29956, OS thread id 1192212800
MySQL thread id 5341758, query id 189708501 127.0.0.1 lwdba
show innodb status
---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget
---TRANSACTION 0 0, not started, process no 29956, OS thread id 1223895360
MySQL thread id 5341667, query id 189706152 10.64.89.145 viget
---TRANSACTION 0 0, not started, process no 29956, OS thread id 1227888960
MySQL thread id 5341556, query id 189699857 172.16.135.63 lwdba
---TRANSACTION 0 620781112, not started, process no 29956, OS thread id 1222297920
MySQL thread id 5341511, query id 189696265 10.64.89.143 viget
---TRANSACTION 0 620783736, not started, process no 29956, OS thread id 1229752640
MySQL thread id 5339005, query id 189707998 10.64.89.144 viget
---TRANSACTION 0 620783785, not started, process no 29956, OS thread id 1198602560
MySQL thread id 5337583, query id 189708349 10.64.89.145 viget
---TRANSACTION 0 620783469, not started, process no 29956, OS thread id 1224161600
MySQL thread id 5333500, query id 189708478 10.64.89.144 viget
---TRANSACTION 0 620781240, not started, process no 29956, OS thread id 1198336320
MySQL thread id 5324256, query id 189708493 10.64.89.145 viget
---TRANSACTION 0 617458223, not started, process no 29956, OS thread id 1195141440
MySQL thread id 736, query id 175038790 Has read all relay log; waiting for the slave I/O thread to update it
--------
FILE I/O
--------
I/O thread 0 state: waiting for i/o request (insert buffer thread)
I/O thread 1 state: waiting for i/o request (log thread)
I/O thread 2 state: waiting for i/o request (read thread)
I/O thread 3 state: waiting for i/o request (write thread)
Pending normal aio reads: 0, aio writes: 0,
 ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0
Pending flushes (fsync) log: 0; buffer pool: 0
519878 OS file reads, 18962880 OS file writes, 13349046 OS fsyncs
0.00 reads/s, 0 avg bytes/read, 6.25 writes/s, 4.50 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf: size 1, free list len 1190, seg size 1192,
174800 inserts, 174800 merged recs, 54439 merges
Hash table size 35401603, node heap has 35160 buffer(s)
0.50 hash searches/s, 11.75 non-hash searches/s
---
LOG
---
Log sequence number 28 1235093534
Log flushed up to   28 1235093534
Last checkpoint at  28 1235091275
0 pending log writes, 0 pending chkp writes
12262564 log i/o's done, 3.25 log i/o's/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total memory allocated 18909316674; in additional pool allocated 1048576
Dictionary memory allocated 2019632
Buffer pool size   1048576
Free buffers       175763
Database pages     837653
Modified db pages  6
Pending reads 0
Pending writes: LRU 0, flush list 0, single page 0
Pages read 770138, created 108485, written 7795318
0.00 reads/s, 0.00 creates/s, 4.25 writes/s
Buffer pool hit rate 1000 / 1000
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
1 read views open inside InnoDB
Main thread process no. 29956, id 1185823040, state: sleeping
Number of rows inserted 6453767, updated 4602534, deleted 3638793, read 388349505551
0.25 inserts/s, 1.25 updates/s, 0.00 deletes/s, 2.75 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================

1 row in set, 1 warning (0.00 sec)

You should consider increasing the lock wait timeout value for InnoDB by setting the innodb_lock_wait_timeout, default is 50 sec

mysql> show variables like 'innodb_lock_wait_timeout';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| innodb_lock_wait_timeout | 50    |
+--------------------------+-------+
1 row in set (0.01 sec)

You can set it to higher value in /etc/my.cnf permanently with this line

[mysqld]
innodb_lock_wait_timeout=120

and restart mysql. If you cannot restart mysql at this time, run this:

SET GLOBAL innodb_lock_wait_timeout = 120; 

You could also just set it for the duration of your session

SET innodb_lock_wait_timeout = 120; 

followed by your query

How can I wait for 10 second without locking application UI in android

do this on a new thread (seperate it from main thread)

 new Thread(new Runnable() {
     @Override
     public void run() {
        // TODO Auto-generated method stub
     }
}).run();

Python Requests and persistent sessions

the other answers help to understand how to maintain such a session. Additionally, I want to provide a class which keeps the session maintained over different runs of a script (with a cache file). This means a proper "login" is only performed when required (timout or no session exists in cache). Also it supports proxy settings over subsequent calls to 'get' or 'post'.

It is tested with Python3.

Use it as a basis for your own code. The following snippets are release with GPL v3

import pickle
import datetime
import os
from urllib.parse import urlparse
import requests    

class MyLoginSession:
    """
    a class which handles and saves login sessions. It also keeps track of proxy settings.
    It does also maintine a cache-file for restoring session data from earlier
    script executions.
    """
    def __init__(self,
                 loginUrl,
                 loginData,
                 loginTestUrl,
                 loginTestString,
                 sessionFileAppendix = '_session.dat',
                 maxSessionTimeSeconds = 30 * 60,
                 proxies = None,
                 userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
                 debug = True,
                 forceLogin = False,
                 **kwargs):
        """
        save some information needed to login the session

        you'll have to provide 'loginTestString' which will be looked for in the
        responses html to make sure, you've properly been logged in

        'proxies' is of format { 'https' : 'https://user:pass@server:port', 'http' : ...
        'loginData' will be sent as post data (dictionary of id : value).
        'maxSessionTimeSeconds' will be used to determine when to re-login.
        """
        urlData = urlparse(loginUrl)

        self.proxies = proxies
        self.loginData = loginData
        self.loginUrl = loginUrl
        self.loginTestUrl = loginTestUrl
        self.maxSessionTime = maxSessionTimeSeconds
        self.sessionFile = urlData.netloc + sessionFileAppendix
        self.userAgent = userAgent
        self.loginTestString = loginTestString
        self.debug = debug

        self.login(forceLogin, **kwargs)

    def modification_date(self, filename):
        """
        return last file modification date as datetime object
        """
        t = os.path.getmtime(filename)
        return datetime.datetime.fromtimestamp(t)

    def login(self, forceLogin = False, **kwargs):
        """
        login to a session. Try to read last saved session from cache file. If this fails
        do proper login. If the last cache access was too old, also perform a proper login.
        Always updates session cache file.
        """
        wasReadFromCache = False
        if self.debug:
            print('loading or generating session...')
        if os.path.exists(self.sessionFile) and not forceLogin:
            time = self.modification_date(self.sessionFile)         

            # only load if file less than 30 minutes old
            lastModification = (datetime.datetime.now() - time).seconds
            if lastModification < self.maxSessionTime:
                with open(self.sessionFile, "rb") as f:
                    self.session = pickle.load(f)
                    wasReadFromCache = True
                    if self.debug:
                        print("loaded session from cache (last access %ds ago) "
                              % lastModification)
        if not wasReadFromCache:
            self.session = requests.Session()
            self.session.headers.update({'user-agent' : self.userAgent})
            res = self.session.post(self.loginUrl, data = self.loginData, 
                                    proxies = self.proxies, **kwargs)

            if self.debug:
                print('created new session with login' )
            self.saveSessionToCache()

        # test login
        res = self.session.get(self.loginTestUrl)
        if res.text.lower().find(self.loginTestString.lower()) < 0:
            raise Exception("could not log into provided site '%s'"
                            " (did not find successful login string)"
                            % self.loginUrl)

    def saveSessionToCache(self):
        """
        save session to a cache file
        """
        # always save (to update timeout)
        with open(self.sessionFile, "wb") as f:
            pickle.dump(self.session, f)
            if self.debug:
                print('updated session cache-file %s' % self.sessionFile)

    def retrieveContent(self, url, method = "get", postData = None, **kwargs):
        """
        return the content of the url with respect to the session.

        If 'method' is not 'get', the url will be called with 'postData'
        as a post request.
        """
        if method == 'get':
            res = self.session.get(url , proxies = self.proxies, **kwargs)
        else:
            res = self.session.post(url , data = postData, proxies = self.proxies, **kwargs)

        # the session has been updated on the server, so also update in cache
        self.saveSessionToCache()            

        return res

A code snippet for using the above class may look like this:

if __name__ == "__main__":
    # proxies = {'https' : 'https://user:pass@server:port',
    #           'http' : 'http://user:pass@server:port'}

    loginData = {'user' : 'usr',
                 'password' :  'pwd'}

    loginUrl = 'https://...'
    loginTestUrl = 'https://...'
    successStr = 'Hello Tom'
    s = MyLoginSession(loginUrl, loginData, loginTestUrl, successStr, 
                       #proxies = proxies
                       )

    res = s.retrieveContent('https://....')
    print(res.text)

    # if, for instance, login via JSON values required try this:
    s = MyLoginSession(loginUrl, None, loginTestUrl, successStr, 
                       #proxies = proxies,
                       json = loginData)

Update just one gem with bundler

bundle update gem-name [--major|--patch|--minor]

This also works for dependencies.

Setting up PostgreSQL ODBC on Windows

Installing psqlODBC on 64bit Windows

Though you can install 32 bit ODBC drivers on Win X64 as usual, you can't configure 32-bit DSNs via ordinary control panel or ODBC datasource administrator.

How to configure 32 bit ODBC drivers on Win x64

Configure ODBC DSN from %SystemRoot%\syswow64\odbcad32.exe

  1. Start > Run
  2. Enter: %SystemRoot%\syswow64\odbcad32.exe
  3. Hit return.
  4. Open up ODBC and select under the System DSN tab.
  5. Select PostgreSQL Unicode

You may have to play with it and try different scenarios, think outside-the-box, remember this is open source.

How to access iOS simulator camera

It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

How to search images from private 1.0 registry in docker?

Another method in one line (substitute your actual path/ports if needed).

Example: Assume a generic registry:2.0 start up, the running registry container has a log file that holds images and tag names. I extrapolate the data like this:

grep -r -o "vars\.name=.* vars.reference=.*" /var/lib/docker/containers/* | cut -c 167-225 | sed 's/ver.*$//' | sed 's/vars\.name=//' | sed 's/ vars\.reference=/:/' | sort -u

You may need to tweak the cut values to get the output desired.

MySQL and PHP - insert NULL rather than empty string

you can do it for example with

UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

Inserting data to table (mysqli insert)

Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.

    <?php
    mysqli_connect("localhost","root","","web_table");
    mysql_select_db("web_table") or die(mysql_error());

for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use

       $link = mysqli_connect("localhost","root","","web_table");
       mysqli_select_db ($link , "web_table" ) or die.....

or for where i began

     <?php $connection = mysqli_connect("localhost","root","","web_table");       
      global $connection; // global connection to databases - kill it once you're done

or just query with a $connection parameter as the other argument like above. Get rid of that third line.

How to use OpenSSL to encrypt/decrypt files?

Security Warning: AES-256-CBC does not provide authenticated encryption and is vulnerable to padding oracle attacks. You should use something like age instead.

Encrypt:

openssl aes-256-cbc -a -salt -in secrets.txt -out secrets.txt.enc

Decrypt:

openssl aes-256-cbc -d -a -in secrets.txt.enc -out secrets.txt.new

More details on the various flags

How to manage local vs production settings in Django?

Instead of settings.py, use this layout:

.
+-- settings/
    +-- __init__.py  <= not versioned
    +-- common.py
    +-- dev.py
    +-- prod.py

common.py is where most of your configuration lives.

prod.py imports everything from common, and overrides whatever it needs to override:

from __future__ import absolute_import # optional, but I like it
from .common import *

# Production overrides
DEBUG = False
#...

Similarly, dev.py imports everything from common.py and overrides whatever it needs to override.

Finally, __init__.py is where you decide which settings to load, and it's also where you store secrets (therefore this file should not be versioned):

from __future__ import absolute_import
from .prod import *  # or .dev if you want dev

##### DJANGO SECRETS
SECRET_KEY = '(3gd6shenud@&57...'
DATABASES['default']['PASSWORD'] = 'f9kGH...'

##### OTHER SECRETS
AWS_SECRET_ACCESS_KEY = "h50fH..."

What I like about this solution is:

  1. Everything is in your versioning system, except secrets
  2. Most configuration is in one place: common.py.
  3. Prod-specific things go in prod.py, dev-specific things go in dev.py. It's simple.
  4. You can override stuff from common.py in prod.py or dev.py, and you can override anything in __init__.py.
  5. It's straightforward python. No re-import hacks.

Open new Terminal Tab from command line (Mac OS X)

With X installed (e.g. from homebrew, or Quartz), a simple "xterm &" does (nearly) the trick, it opens a new terminal window (not a tab, though).

Getting "cannot find Symbol" in Java project in Intellij

I had to right-click the project, and select "Reimport" under the "Run Maven" submenu.

Line Break in HTML Select Option?

If you just want a line break in the dropdown list use this:

<option label="" value="" disabled=""> </option>

Android: Creating a Circular TextView?

Much of the Answer here seems to be hacks to the shape drawable, while android in itself supports this with the shapes functionality. This is something that worked perfectly for me.You can do this in two ways

Using a fixed height and width, that would stay the same regardless of the text that you put it as shown below

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">

<solid android:color="@color/alpha_white" />

    <size android:width="25dp" android:height="25dp"/>

<stroke android:color="@color/color_primary" android:width="1dp"/>

</shape>

Using Padding which re-adjusts the shape regardless of the text in the textview it as shown below

<solid android:color="@color/alpha_white" />

<padding
    android:bottom="@dimen/semi_standard_margin"
    android:left="@dimen/semi_standard_margin"
    android:right="@dimen/semi_standard_margin"
    android:top="@dimen/semi_standard_margin" />

<stroke android:color="@color/color_primary" android:width="2dp"/>

semi_standard_margin = 4dp

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

This message can also occur when you specify the incorrect decryption password (yeah, lame, but not quite obvious to realize this from the error message, huh?).

I was using the command line to decrypt the recent DataBase backup for my auxiliary tool and suddenly faced this issue.

Finally, after 10 mins of grief and plus reading through this question/answers I have remembered that the password is different and everything worked just fine with the correct password.

Should I learn C before learning C++?

Having observed people, who have learned Java first, struggle with the concepts of pointers and memory management in C++, I'd say that learning C first is a good idea, in order to grasp these two concepts, isolated from the complexities of other C++ features.

Display an image with Python

import IPython.display as display
from PIL import Image
image_path = 'my_image.jpg'
display.display(Image.open(image_path))

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

Structs data type in php?

It seems that the struct datatype is commonly used in SOAP:

var_dump($client->__getTypes());

array(52) {
  [0] =>
  string(43) "struct Bank {\n string Code;\n string Name;\n}"
}

This is not a native PHP datatype!

It seems that the properties of the struct type referred to in SOAP can be accessed as a simple PHP stdClass object:

$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;

Unfortunately Launcher3 has stopped working error in android studio?

I had a similar problem with a physical device. The problem was related with the fact that the google app ( the search bar for google on top ) was disabled. After the first reboot launcher3 began failing. No matter how many cache/data cleaning I did, it kept failing. I reenabled it and launched it, so it appeared again on the screen and from that moment on, launcher3 was back to life.

I guess there mmust be some kind of dependency with this app.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

According to the documentation, you can only display the __unicode__ representation of a ForeignKey:

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display

Seems odd that it doesn't support the 'book__author' style format which is used everywhere else in the DB API.

Turns out there's a ticket for this feature, which is marked as Won't Fix.

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

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

How can I change the user on Git Bash?

Check what git remote -v returns: the account used to push to an http url is usually embedded into the remote url itself.

https://[email protected]/...

If that is the case, put an url which will force Git to ask for the account to use when pushing:

git remote set-url origin https://github.com/<user>/<repo>

Or one to use the Fre1234 account:

git remote set-url origin https://[email protected]/<user>/<repo>

Also check if you installed your Git For Windows with or without a credential helper as in this question.


The OP Fre1234 adds in the comments:

I finally found the solution.
Go to: Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to Github,
Click on them and click "Remove".

That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper output (it should be manager)

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

Change a Git remote HEAD to point to something besides master

Related to the question, I ended up here when searching for:

How do I make a local repo aware of a changed default branch on GitHub

For completeness, adding the answer:

git remote set-head origin -a

What would be the Unicode character for big bullet in the middle of the character?

http://www.unicode.org is the place to look for symbol names.

? BLACK CIRCLE        25CF
? MEDIUM BLACK CIRCLE 26AB
? BLACK LARGE CIRCLE  2B24

or even:

 NEW MOON SYMBOL   1F311

Good luck finding a font that supports them all. Only one shows up in Windows 7 with Chrome.

What is the difference between Set and List?

TOPIC Name: List VS Set

I have just gone through Java's most important topic called Collections Framework. I thought to share my little knowledge about Collections with you. List, Set, Map are the most important topic of it. So let's start with List and Set.

Difference between List and Set:

  1. List is a collection class which extends AbstractList class where as Set is a collection class which extends AbstractSet class but both implements Collection interface.

  2. List interface allows duplicate values (elements) whereas Set interface does not allow duplicate values. In case of duplicate elements in Set, it replaces older values.

  3. List interface allows NULL values where as Set interface does not allow Null values. In case of using Null values in Set it gives NullPointerException.

  4. List interface maintains insertion order. That means the way we add the elements in the List in the same way we obtain it using iterator or for-each style. Whereas Set implementations do not necessarily maintain insertion order. (Although SortedSet does using TreeSet, and LinkedHashSet maintains insertion order).

  5. List interface has its own methods defined whereas Set interface does not have its own method so Set uses Collection interface methods only.

  6. List interface has one legacy class called Vector whereas Set interface does not have any legacy class

  7. Last but not the least... The listIterator() method can only be used to cycle through the elements within List Classes whereas we can use iterator() method to access Set class elements

Anything else can we add? Please let me know.

Thanks.

Converting string "true" / "false" to boolean value

You could simply have: var result = (str == "true").

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Either remove the below code from the pom.xml or correct your java version to make it work.

  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
  </plugin>

Animate text change in UILabel

With Swift 5, you can choose one of the two following Playground code samples in order to animate your UILabel's text changes with some cross dissolve animation.


#1. Using UIView's transition(with:duration:options:animations:completion:) class method

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Car"

        view.backgroundColor = .white
        view.addSubview(label)

        label.translatesAutoresizingMaskIntoConstraints = false
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
        view.addGestureRecognizer(tapGesture)
    }

    @objc func toggle(_ sender: UITapGestureRecognizer) {
        let animation = {
            self.label.text = self.label.text == "Car" ? "Plane" : "Car"
        }
        UIView.transition(with: label, duration: 2, options: .transitionCrossDissolve, animations: animation, completion: nil)
    }

}

let controller = ViewController()
PlaygroundPage.current.liveView = controller

#2. Using CATransition and CALayer's add(_:forKey:) method

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let label = UILabel()
    let animation = CATransition()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Car"

        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        // animation.type = CATransitionType.fade // default is fade
        animation.duration = 2

        view.backgroundColor = .white
        view.addSubview(label)

        label.translatesAutoresizingMaskIntoConstraints = false
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
        view.addGestureRecognizer(tapGesture)
    }

    @objc func toggle(_ sender: UITapGestureRecognizer) {
        label.layer.add(animation, forKey: nil) // The special key kCATransition is automatically used for transition animations
        label.text = label.text == "Car" ? "Plane" : "Car"
    }

}

let controller = ViewController()
PlaygroundPage.current.liveView = controller

How do I test if a variable is a number in Bash?

I found quite a short version:

function isnum()
{
    return `echo "$1" | awk -F"\n" '{print ($0 != $0+0)}'`
}

transparent navigation bar ios

Try this, it works for me if you also need to support ios7, it is based on the transparency of UItoolBar:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.view.backgroundColor = [UIColor clearColor];
    UIToolbar* blurredView = [[UIToolbar alloc] initWithFrame:self.navigationController.navigationBar.bounds];
    [blurredView setBarStyle:UIBarStyleBlack];
    [blurredView setBarTintColor:[UIColor redColor]];
    [self.navigationController.navigationBar insertSubview:blurredView atIndex:0];

How do I format XML in Notepad++?

Plugins -> XML Tools -> Pretty Print (libXML) or Ctrl+Alt+Shift+B

You probably need to install the plugin:

Plugins > Plugins Manager > Show Plugins Manager

If you are behind a proxy, download it from here.

Then copy XMLTools.dll to the plugins directory and external libraries (four dlls) into the root Notepad++ directory.

Calculating how many days are between two dates in DB2?

I faced the same problem in Derby IBM DB2 embedded database in a java desktop application, and after a day of searching I finally found how it's done :

SELECT days (table1.datecolomn) - days (current date) FROM table1 WHERE days (table1.datecolomn) - days (current date) > 5

for more information check this site

java.security.AccessControlException: Access denied (java.io.FilePermission

Just document it here on Windows you need to escape the \ character:

"e:\\directory\\-"

Create a SQL query to retrieve most recent records

Add an auto incrementing Primary Key to each record, for example, UserStatusId.

Then your query could look like this:

select * from UserStatus where UserStatusId in
(
    select max(UserStatusId) from UserStatus group by User
)

Date User Status Notes

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

A small addition to Riley Avron answer to account locale changes:

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        let writingDirection = UIApplication.sharedApplication().userInterfaceLayoutDirection
        let factor: CGFloat = writingDirection == .LeftToRight ? 1 : -1

        self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount*factor, bottom: 0, right: insetAmount*factor)
        self.titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount*factor, bottom: 0, right: -insetAmount*factor)
        self.contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

How to smooth a curve in the right way?

For a project of mine, I needed to create intervals for time-series modeling, and to make the procedure more efficient I created tsmoothie: A python library for time-series smoothing and outlier detection in a vectorized way.

It provides different smoothing algorithms together with the possibility to computes intervals.

Here I use a ConvolutionSmoother but you can also test it others.

import numpy as np
import matplotlib.pyplot as plt
from tsmoothie.smoother import *

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2

# operate smoothing
smoother = ConvolutionSmoother(window_len=5, window_type='ones')
smoother.smooth(y)

# generate intervals
low, up = smoother.get_intervals('sigma_interval', n_sigma=2)

# plot the smoothed timeseries with intervals
plt.figure(figsize=(11,6))
plt.plot(smoother.smooth_data[0], linewidth=3, color='blue')
plt.plot(smoother.data[0], '.k')
plt.fill_between(range(len(smoother.data[0])), low[0], up[0], alpha=0.3)

enter image description here

I point out also that tsmoothie can carry out the smoothing of multiple timeseries in a vectorized way

Assigning the return value of new by reference is deprecated

C:\wamp\www\..\libraries\pattemplate

1.ini_set('display_errors', 0);

$this->_modules[$moduleType][$sig]  =&new $moduleClass;   wrong

$this->_modules[$moduleType][$sig]  =new $moduleClass;   Right

The page cannot be displayed because an internal server error has occurred on server

In my case, setting httpErrors and the like in Web.config did not help to identify the issue.

Instead I did:

  1. Activate "Failed Request Tracing" for the website with the error.
  2. Configured a trace for HTTP errors 350-999 (just in case), although I suspected 500.
  3. Called the erroneous URL again.
  4. Watched in the log folder ("%SystemDrive%\inetpub\logs\FailedReqLogFiles" in my case).
  5. Opened one of the XML files in Internet Explorer.

I then saw an entry with a detailed exception information. In my case it was

\?\C:\Websites\example.com\www\web.config ( 592) :Cannot add duplicate collection entry of type 'mimeMap' with unique key attribute 'fileExtension' set to '.json'

I now was able to resolve it and fix the error. After that I deactivated "Failed Request Tracing" again.

Array Length in Java

It should be:

int a = arr.length;

Parenthesis should be avoided.

How to convert URL parameters to a JavaScript object?

A concise solution:

location.search
  .slice(1)
  .split('&')
  .map(p => p.split('='))
  .reduce((obj, pair) => {
    const [key, value] = pair.map(decodeURIComponent);
    obj[key] = value;
    return obj;
  }, {});

Calculating the sum of two variables in a batch script

here is mine

echo Math+ 
ECHO First num:
 SET /P a= 
ECHO Second num:
 SET /P b=
 set /a s=%a%+%b% 
echo Result: %s%

Extract code country from phone number [libphonenumber]

Here is a solution to get the country based on an international phone number without using the Google library.

Let me explain first why it is so difficult to figure out the country. The country code of few countries is 1 digit, 2, 3 or 4 digits. That would be simple enough. But the country code 1 is not just used for US, but also for Canada and some smaller places:

1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada

Digits 2..4 decide, if it is US or Canada or ... There is no easy way to figure out the country, like the first xxx are Canada, the rest US.

For my code, I defined a class which holds information for ever digit:

public class DigitInfo {
  public char Digit;
  public Country? Country;
  public DigitInfo?[]? Digits;
}

A first array holds the DigitInfos for the first digit in the number. The second digit is used as an index into DigitInfo.Digits. One travels down that Digits chain, until Digits is empty. If Country is defined (i.e. not null) that value gets returned, otherwise any Country defined earlier gets returned:

country code 1: byPhone[1].Country is US  
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada  
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since   
                   byPhone[1].Country is US, also 1235 is US, because no other   
                   country was found in the later digits

Here is the method which returns the country based on the phone number:

/// <summary>
/// Returns the Country based on an international dialing code.
/// </summary>
public static Country? GetCountry(ReadOnlySpan<char> phoneNumber) {
  if (phoneNumber.Length==0) return null;

  var isFirstDigit = true;
  DigitInfo? digitInfo = null;
  Country? country = null;
  foreach (var digitChar in phoneNumber) {
    var digitIndex = digitChar - '0';
    if (isFirstDigit) {
      isFirstDigit = false;
      digitInfo = ByPhone[digitIndex];
    } else {
      if (digitInfo!.Digits is null) return country;

      digitInfo = digitInfo.Digits[digitIndex];
    }
    if (digitInfo is null) return country;

    country = digitInfo.Country??country;
  }
  return country;
}

The rest of the code (digitInfos for every country of the world, test code, ...) is too big to be posted here, but it can be found on Github: https://github.com/PeterHuberSg/WpfWindowsLib/blob/master/WpfWindowsLib/CountryCode.cs

The code is part of a WPF TextBox and the library contains also other controls for email addresses, etc. A more detailed description is on CodeProject: International Phone Number Validation Explained in Detail

Generate random number between two numbers in JavaScript

jsfiddle: https://jsfiddle.net/cyGwf/477/

Random Integer: to get a random integer between min and max, use the following code

function getRandomInteger(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

Random Floating Point Number: to get a random floating point number between min and max, use the following code

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

scp from Linux to Windows

This one worked for me.

scp /home/ubuntu/myfile username@IP_of_windows_machine:/C:/Users/Anshul/Desktop 

Difference between abstract class and interface in Python

What is the difference between abstract class and interface in Python?

An interface, for an object, is a set of methods and attributes on that object.

In Python, we can use an abstract base class to define and enforce an interface.

Using an Abstract Base Class

For example, say we want to use one of the abstract base classes from the collections module:

import collections
class MySet(collections.Set):
    pass

If we try to use it, we get an TypeError because the class we created does not support the expected behavior of sets:

>>> MySet()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MySet with abstract methods
__contains__, __iter__, __len__

So we are required to implement at least __contains__, __iter__, and __len__. Let's use this implementation example from the documentation:

class ListBasedSet(collections.Set):
    """Alternate set implementation favoring space over speed
    and not requiring the set elements to be hashable. 
    """
    def __init__(self, iterable):
        self.elements = lst = []
        for value in iterable:
            if value not in lst:
                lst.append(value)
    def __iter__(self):
        return iter(self.elements)
    def __contains__(self, value):
        return value in self.elements
    def __len__(self):
        return len(self.elements)

s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2

Implementation: Creating an Abstract Base Class

We can create our own Abstract Base Class by setting the metaclass to abc.ABCMeta and using the abc.abstractmethod decorator on relevant methods. The metaclass will be add the decorated functions to the __abstractmethods__ attribute, preventing instantiation until those are defined.

import abc

For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2:

class Effable(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def __str__(self):
        raise NotImplementedError('users must define __str__ to use this base class')

Or in Python 3, with the slight change in metaclass declaration:

class Effable(object, metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def __str__(self):
        raise NotImplementedError('users must define __str__ to use this base class')

Now if we try to create an effable object without implementing the interface:

class MyEffable(Effable): 
    pass

and attempt to instantiate it:

>>> MyEffable()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__

We are told that we haven't finished the job.

Now if we comply by providing the expected interface:

class MyEffable(Effable): 
    def __str__(self):
        return 'expressable!'

we are then able to use the concrete version of the class derived from the abstract one:

>>> me = MyEffable()
>>> print(me)
expressable!

There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the abc module to do so, however.

Conclusion

We have demonstrated that the creation of an Abstract Base Class defines interfaces for custom objects in Python.