Programs & Examples On #Location provider

Android Location Providers - GPS or Network Provider?

There are some great answers mentioned here. Another approach you could take would be to use some free SDKs available online like Atooma, tranql and Neura, that can be integrated with your Android application (it takes less than 20 min to integrate). Along with giving you the accurate location of your user, it can also give you good insights about your user’s activities. Also, some of them consume less than 1% of your battery

Best way to get user GPS location in background in Android

Grant required permission ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION after start service

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.concurrent.TimeUnit;

/**
 * Created by Ketan Ramani on 05/11/18.
 */

public class BackgroundLocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    /* Declare in manifest
    <service android:name=".BackgroundLocationUpdateService"/>
    */

    private final String TAG = "BackgroundLocationUpdateService";
    private final String TAG_LOCATION = "TAG_LOCATION";
    private Context context;
    private boolean stopService = false;

    /* For Google Fused API */
    protected GoogleApiClient mGoogleApiClient;
    protected LocationSettingsRequest mLocationSettingsRequest;
    private String latitude = "0.0", longitude = "0.0";
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationCallback mLocationCallback;
    private LocationRequest mLocationRequest;
    private Location mCurrentLocation;
    /* For Google Fused API */

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        StartForeground();
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    if (!stopService) {
                        //Perform your task here
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (!stopService) {
                        handler.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
                    }
                }
            }
        };
        handler.postDelayed(runnable, 2000);

        buildGoogleApiClient();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "Service Stopped");
        stopService = true;
        if (mFusedLocationClient != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
            Log.e(TAG_LOCATION, "Location Update Callback Removed");
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void StartForeground() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        String CHANNEL_ID = "channel_location";
        String CHANNEL_NAME = "channel_location";

        NotificationCompat.Builder builder = null;
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
            builder.setChannelId(CHANNEL_ID);
            builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
        } else {
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        }

        builder.setContentTitle("Your title");
        builder.setContentText("You are now online");
        Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(notificationSound);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_logo);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();
        startForeground(101, notification);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG_LOCATION, "Location Changed Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());

        latitude = String.valueOf(location.getLatitude());
        longitude = String.valueOf(location.getLongitude());

        if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
            requestLocationUpdate();
        } else {
            Log.e(TAG_LOCATION, "Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10 * 1000);
        mLocationRequest.setFastestInterval(5 * 1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);
        mLocationSettingsRequest = builder.build();

        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                        Log.e(TAG_LOCATION, "GPS Success");
                        requestLocationUpdate();
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                int statusCode = ((ApiException) e).getStatusCode();
                switch (statusCode) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            int REQUEST_CHECK_SETTINGS = 214;
                            ResolvableApiException rae = (ResolvableApiException) e;
                            rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sie) {
                            Log.e(TAG_LOCATION, "Unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.e(TAG_LOCATION, "Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
                }
            }
        }).addOnCanceledListener(new OnCanceledListener() {
            @Override
            public void onCanceled() {
                Log.e(TAG_LOCATION, "checkLocationSettings -> onCanceled");
            }
        });
    }

    @Override
    public void onConnectionSuspended(int i) {
        connectGoogleClient();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
        mSettingsClient = LocationServices.getSettingsClient(context);

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

        connectGoogleClient();

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Log.e(TAG_LOCATION, "Location Received");
                mCurrentLocation = locationResult.getLastLocation();
                onLocationChanged(mCurrentLocation);
            }
        };
    }

    private void connectGoogleClient() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int resultCode = googleAPI.isGooglePlayServicesAvailable(context);
        if (resultCode == ConnectionResult.SUCCESS) {
            mGoogleApiClient.connect();
        }
    }

    @SuppressLint("MissingPermission")
    private void requestLocationUpdate() {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }
}

In Activity

Start Service : startService(new Intent(this, BackgroundLocationUpdateService.class));

Stop Service : stopService(new Intent(this, BackgroundLocationUpdateService.class));

In Fragment

Start Service : getActivity().startService(new Intent(getActivity().getBaseContext(), BackgroundLocationUpdateService.class));

Stop Service : getActivity().stopService(new Intent(getActivity(), BackgroundLocationUpdateService.class));

Struct memory layout in C

In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

From C99 §6.7.2.1:

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

Change output format for MySQL command line results to CSV

I wound up writing my own command-line tool to take care of this. It's similar to cut, except it knows what to do with quoted fields, etc. This tool, paired with @Jimothy's answer, allows me to get a headerless CSV from a remote MySQL server I have no filesystem access to onto my local machine with this command:

$ mysql -N -e "select people, places from things" | csvm -i '\t' -o ','
Bill,"Raleigh, NC"

csvmaster on github

How do I parse a string into a number with Dart?

Convert String to Int

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);

Convert String to Double

var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);

Example in DartPad

screenshot of dartpad

Docker error: invalid reference format: repository name must be lowercase

In my case I had a naked --env switch, i.e. one without an actual variable name or value, e.g.:

docker run \
   --env \       <----- This was the offending item
   --rm \
   --volume "/home/shared:/shared" "$(docker build . -q)"

opening html from google drive

  1. Create a new folder in Drive and share it as "Public on the web."
  2. Upload your HTML, JS & CSS files to this folder.
  3. Open the HTML file & you will see "Preview" button in the toolbar.
  4. Share the URL that looks like www.googledrive.com/host/... from the preview window and anyone can view your web page.

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

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

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

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

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

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

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

                if ((gettingItemName == false) &&
                (justChanged == true))
                {
                    list.Add(itemName);
                    itemName = string.Empty;
                    justChanged = false;
                }

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

    return list;
}

C# - Winforms - Global Variables

public static class MyGlobals
{
  public static string Global1 = "Hello";
  public static string Global2 = "World";
}

public class Foo
{

    private void Method1()
    {
       string example = MyGlobals.Global1;
       //etc
    }
}

Where can I set environment variables that crontab will use?

If you start the scripts you are executing through cron with:

#!/bin/bash -l

They should pick up your ~/.bash_profile environment variables

How do I display the value of a Django form field in a template?

This seems to work.

{{ form.fields.email.initial }}

How to edit data in result grid in SQL Server Management Studio

Just choose "Edit Top 200 rows", press Ctrl + 3 in the edit grid region (or click "Show SQL Pane") and edit the query...

But please note that this will work only for the query that doesn't contain "join"

Set Culture in an ASP.Net MVC app

I'm using this localization method and added a route parameter that sets the culture and language whenever a user visits example.com/xx-xx/

Example:

routes.MapRoute("DefaultLocalized",
            "{language}-{culture}/{controller}/{action}/{id}",
            new
            {
                controller = "Home",
                action = "Index",
                id = "",
                language = "nl",
                culture = "NL"
            });

I have a filter that does the actual culture/language setting:

using System.Globalization;
using System.Threading;
using System.Web.Mvc;

public class InternationalizationAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext) {

        string language = (string)filterContext.RouteData.Values["language"] ?? "nl";
        string culture = (string)filterContext.RouteData.Values["culture"] ?? "NL";

        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));

    }
}

To activate the Internationalization attribute, simply add it to your class:

[Internationalization]
public class HomeController : Controller {
...

Now whenever a visitor goes to http://example.com/de-DE/Home/Index the German site is displayed.

I hope this answers points you in the right direction.

I also made a small MVC 5 example project which you can find here

Just go to http://{yourhost}:{port}/en-us/home/index to see the current date in English (US), or change it to http://{yourhost}:{port}/de-de/home/index for German etcetera.

How do I restart a service on a remote machine in Windows?

You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.

If you wish to use the command line only, you can use

sc \\machine stop <service>

Count character occurrences in a string in C++

Count character occurrences in a string is easy:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s="Sakib Hossain";
    int cou=count(s.begin(),s.end(),'a');
    cout<<cou;
}

.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

How to delete a file via PHP?

$files = [
    './first.jpg',
    './second.jpg',
    './third.jpg'
];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
    } else {
        // File not found.
    }
}

Why I get 411 Length required error?

When you make a POST HttpWebRequest, you must specify the length of the data you are sending, something like:

string data = "something you need to send"
byte[] postBytes = Encoding.ASCII.GetBytes(data);
request.ContentLength = postBytes.Length;

if you are not sending any data, just set it to 0, that means you just have to add to your code this line:

request.ContentLength = 0;

Usually, if you are not sending any data, chosing the GET method instead is wiser, as you can see in the HTTP RFC

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Python __call__ special method practical example

This is too late but I'm giving an example. Imagine you have a Vector class and a Point class. Both take x, y as positional args. Let's imagine you want to create a function that moves the point to be put on the vector.

4 Solutions

  • put_point_on_vec(point, vec)

  • Make it a method on the vector class. e.g my_vec.put_point(point)

  • Make it a method on the Point class. my_point.put_on_vec(vec)
  • Vector implements __call__, So you can use it like my_vec_instance(point)

This is actually part of some examples I'm working on for a guide for dunder methods explained with Maths that I'm gonna release sooner or later.

I left the logic of moving the point itself because this is not what this question is about

Find size and free space of the filesystem containing a given file

For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage() returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.

Simple example from documentation:

>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)

outStr="b"

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

Can I use jQuery with Node.js?

in 2016 things are way easier. install jquery to node.js with your console:

npm install jquery

bind it to the variable $ (for example - i am used to it) in your node.js code:

var $ = require("jquery");

do stuff:

$.ajax({
    url: 'gimme_json.php',
    dataType: 'json',
    method: 'GET',
    data: { "now" : true }
});

also works for gulp as it is based on node.js.

Change input text border color without changing its height

Set a transparent border and then change it:

.default{
border: 2px solid transparent;
}

.new{
border: 2px solid red;
}

How to check a channel is closed or not without reading it?

I know this answer is so late, I have wrote this solution, Hacking Go run-time, It's not safety, It may crashes:

import (
    "unsafe"
    "reflect"
)


func isChanClosed(ch interface{}) bool {
    if reflect.TypeOf(ch).Kind() != reflect.Chan {
        panic("only channels!")
    }
    
    // get interface value pointer, from cgo_export 
    // typedef struct { void *t; void *v; } GoInterface;
    // then get channel real pointer
    cptr := *(*uintptr)(unsafe.Pointer(
        unsafe.Pointer(uintptr(unsafe.Pointer(&ch)) + unsafe.Sizeof(uint(0))),
    ))
    
    // this function will return true if chan.closed > 0
    // see hchan on https://github.com/golang/go/blob/master/src/runtime/chan.go 
    // type hchan struct {
    // qcount   uint           // total data in the queue
    // dataqsiz uint           // size of the circular queue
    // buf      unsafe.Pointer // points to an array of dataqsiz elements
    // elemsize uint16
    // closed   uint32
    // **
    
    cptr += unsafe.Sizeof(uint(0))*2
    cptr += unsafe.Sizeof(unsafe.Pointer(uintptr(0)))
    cptr += unsafe.Sizeof(uint16(0))
    return *(*uint32)(unsafe.Pointer(cptr)) > 0
}

How to increase space between dotted border dots

IF you're only targeting modern browsers, AND you can have your border on a separate element from your content, then you can use the CSS scale transform to get a larger dot or dash:

border: 1px dashed black;
border-radius: 10px;
-webkit-transform: scale(8);
transform: scale(8);

It takes a lot of positional tweaking to get it to line up, but it works. By changing the thickness of the border, the starting size and the scale factor, you can get to just about thickness-length ratio you want. Only thing you can't touch is dash-to-gap ratio.

Responsive Google Map?

Check this for a solution: http://jsfiddle.net/panchroma/5AEEV/

I can't take the credit for the code though, it comes from quick and easy way to make google maps iframe embed responsive.

Good luck!

CSS

#map_canvas{
width:50%;
height:300px !important;
}

HTML

    <!DOCTYPE html>
<html>
  <head>
    <title>Google Maps JavaScript API v3 Example: Map Simple</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8"/>
    <style>
      html, body, #map_canvas {
        margin: 0;
        padding: 0;
        height: 100%;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
      var map;
      function initialize() {
        var mapOptions = {
          zoom: 8,
          center: new google.maps.LatLng(-34.397, 150.644),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
            mapOptions);
      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html> 

JavaScript - cannot set property of undefined

i'd just do a simple check to see if d[a] exists and if not initialize it...

var a = "1",
    b = "hello",
    c = { "100" : "some important data" },
    d = {};

    if (d[a] === undefined) {
        d[a] = {}
    };
    d[a]["greeting"] = b;
    d[a]["data"] = c;

    console.debug (d);

python global name 'self' is not defined

In Python self is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:

class A(object):
  def f(self):
    print self

a = A()
a.f()

Will give you something like

<__main__.A object at 0x02A9ACF0>

What is the equivalent of "!=" in Excel VBA?

Because the inequality operator in VBA is <>

If strTest <> "" Then
    .....

the operator != is used in C#, C++.

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

How to implement "select all" check box in HTML?

to make it in short-hand version by using jQuery

The select all checkbox

<input type="checkbox" id="chkSelectAll">

The children checkbox

<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">

jQuery

$("#chkSelectAll").on('click', function(){
     this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);  
})

Difference between text and varchar (character varying)

As "Character Types" in the documentation points out, varchar(n), char(n), and text are all stored the same way. The only difference is extra cycles are needed to check the length, if one is given, and the extra space and time required if padding is needed for char(n).

However, when you only need to store a single character, there is a slight performance advantage to using the special type "char" (keep the double-quotes — they're part of the type name). You get faster access to the field, and there is no overhead to store the length.

I just made a table of 1,000,000 random "char" chosen from the lower-case alphabet. A query to get a frequency distribution (select count(*), field ... group by field) takes about 650 milliseconds, vs about 760 on the same data using a text field.

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

I had the same error and it occured when changing the mysql/data folder to another folder.
I just copied all folders inside mysql/data folder to a new location except for two files. Those are ib_logfile0 and ib_logfile1; those are automatically created when starting the MySQL server. That worked for me.

File path issues in R using Windows ("Hex digits in character string" error)

Solution

Try this: x <- read.csv("C:/Users/surfcat/Desktop/2006_dissimilarity.csv", header=TRUE)

Explanation

R is not able to understand normal windows paths correctly because the "\" has special meaning - it is used as escape character to give following characters special meaning (\n for newline, \t for tab, \r for carriage return, ..., have a look here ).

Because R does not know the sequence \U it complains. Just replace the "\" with "/" or use an additional "\" to escape the "\" from its special meaning and everything works smooth.

Alternative

On windows, I think the best thing to do to improve your workflow with windows specific paths in R is to use e.g. AutoHotkey which allows for custom hotkeys:

  • define a Hotkey, e.g. Cntr-Shift-V
  • assigns it an procedure that replaces backslashes within your Clipboard with slaches ...
  • when ever you want to copy paste a path into R you can use Cntr-Shift-V instead of Cntr-V
  • Et-voila

AutoHotkey Code Snippet (link to homepage)

^+v::
StringReplace, clipboard, clipboard, \, /, All 
SendInput, %clipboard% 

How can I add JAR files to the web-inf/lib folder in Eclipse?

add the jar to WEB-INF/lib from file structure refresh the project, you should see the jar now visible under the WEB-INF/lib folder.

this is the best solution that worked for me

File to byte[] in Java

Simple way to do it:

File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);

// int byteLength = fff.length(); 

// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content

byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

Walkthrough Steps

Running the following command will update the repo to use HTTP rather than HTTPS:

sudo sed -i "s/mirrorlist=https/mirrorlist=http/" /etc/yum.repos.d/epel.repo

You should then be able to update with this command:

yum -y update

Anaconda Navigator won't launch (windows 10)

You need to run the cmd prompt from the Scripts directory of Anaconda where ever you have the Anaconda parent folder installed. I happen to have in the root directory of the C drive on my Windows machine. If you are not familiar there are two ways to do that:

A) Use the key combination Win-key + R then type cmd and hit return to launch the terminal window and then type: cd C:\Anaconda\Scripts (or whatever directory path yours is).

B) Navigate using windows explorer to that Scripts directory then type cmd in the address bar of that window and hit return (that will launch the terminal already set to that directory).

Next type the follow commands waiting in between for each to complete:

activate root
conda update -n root conda
conda update --all

When complete type the following and Navigator hopefully should launch:

anaconda-navigator

Is module __file__ attribute absolute or relative?

From the documentation:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

From the mailing list thread linked by @kindall in a comment to the question:

I haven't tried to repro this particular example, but the reason is that we don't want to have to call getpwd() on every import nor do we want to have some kind of in-process variable to cache the current directory. (getpwd() is relatively slow and can sometimes fail outright, and trying to cache it has a certain risk of being wrong.)

What we do instead, is code in site.py that walks over the elements of sys.path and turns them into absolute paths. However this code runs before '' is inserted in the front of sys.path, so that the initial value of sys.path is ''.

For the rest of this, consider sys.path not to include ''.

So, if you are outside the part of sys.path that contains the module, you'll get an absolute path. If you are inside the part of sys.path that contains the module, you'll get a relative path.

If you load a module in the current directory, and the current directory isn't in sys.path, you'll get an absolute path.

If you load a module in the current directory, and the current directory is in sys.path, you'll get a relative path.

How to create relationships in MySQL

If the tables are innodb you can create it like this:

CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY ( account_id ), 
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 
) ENGINE=INNODB;

You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.

How could I use requests in asyncio?

Requests does not currently support asyncio and there are no plans to provide such support. It's likely that you could implement a custom "Transport Adapter" (as discussed here) that knows how to use asyncio.

If I find myself with some time it's something I might actually look into, but I can't promise anything.

Split string into array of characters?

You can just assign the string to a byte array (the reverse is also possible). The result is 2 numbers for each character, so Xmas converts to a byte array containing {88,0,109,0,97,0,115,0}
or you can use StrConv

Dim bytes() as Byte
bytes = StrConv("Xmas", vbFromUnicode)

which will give you {88,109,97,115} but in that case you cannot assign the byte array back to a string.
You can convert the numbers in the byte array back to characters using the Chr() function

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

RestSharp simple complete example

Changing

RestResponse response = client.Execute(request);

to

IRestResponse response = client.Execute(request);

worked for me.

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

Does Python have an ordered set?

If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.

Installing from PyPI is easy with pip:

pip install sortedcontainers

Note that if you can't pip install, simply pull down the sortedlist.py and sortedset.py files from the open-source repository.

Once installed you can simply:

from sortedcontainers import SortedSet
help(SortedSet)

The sortedcontainers module also maintains a performance comparison with several alternative implementations.

For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.

Aligning textviews on the left and right edges in Android layout

It can be done with LinearLayout (less overhead and more control than the Relative Layout option). Give the second view the remaining space so gravity can work. Tested back to API 16.

Proof

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Aligned left" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout> 

If you want to limit the size of the first text view, do this:

Adjust weights as required. Relative layout won't allow you to set a percentage weight like this, only a fixed dp of one of the views

Proof 2

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Aligned left but too long and would squash the other view" />

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout>

Get text from pressed button

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();

Later this btnText can be used .

For example:

if(btnText == "Text for comparison")

How to style dt and dd so they are on the same line?

I recently needed to mix inline and non-inline dt/dd pairs, by specifying the class dl-inline on <dt> elements that should be followed by inline <dd> elements.

_x000D_
_x000D_
dt.dl-inline {_x000D_
  display: inline;_x000D_
}_x000D_
dt.dl-inline:before {_x000D_
  content:"";_x000D_
  display:block;_x000D_
}_x000D_
dt.dl-inline + dd {_x000D_
  display: inline;_x000D_
  margin-left: 0.5em;_x000D_
  clear:right;_x000D_
}
_x000D_
<dl>_x000D_
    <dt>The first term.</dt>_x000D_
    <dd>Definition of the first term. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a placerat odio viverra fusce.</dd>_x000D_
    <dt class="dl-inline">The second term.</dt>_x000D_
    <dd>Definition of the second term. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a placerat odio viverra fusce.</dd>_x000D_
    <dt class="dl-inline">The third term.</dt>_x000D_
    <dd>Definition of the third term. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a placerat odio viverra fusce.</dd>_x000D_
    <dt>The fourth term</dt>_x000D_
    <dd>Definition of the fourth term. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a placerat odio viverra fusce.</dd>_x000D_
</dl_x000D_
_x000D_
>
_x000D_
_x000D_
_x000D_

How do emulators work and how are they written?

Emulator are very hard to create since there are many hacks (as in unusual effects), timing issues, etc that you need to simulate.

For an example of this, see http://queue.acm.org/detail.cfm?id=1755886.

That will also show you why you ‘need’ a multi-GHz CPU for emulating a 1MHz one.

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

It's because of lack of privilege for the user you are running the report builder, just give that user or a group a privilege to run report builder. Please visit this article

Or for shortcut:

  1. Start Internet Explorer using "Run as Administrator"
  2. Open http://localhost/reports
  3. Go to properties tab (SSRS 2008)
  4. Security->New Role Assignment
  5. Add DOMAIN/USERNAME or DOMAIN/USERGROUP
  6. Check Report builder

How to figure out the SMTP server host?

To automate the answer of @Jordan S. Jones at WIN/DOS command-line,

Put this in a batch file named: getmns.bat (get mail name server):

@echo off
if @%1==@ goto USAGE
echo set type=MX>mnscmd.txt
echo %1>>mnscmd.txt
echo exit>>mnscmd.txt
nslookup<mnscmd.txt>mnsresult.txt
type mnsresult.txt
del mnsresult.txt
goto END
:USAGE
echo usage:
echo %0 domainname.ext
:END
echo.

For example:

getmns google.com

output:

google.com      MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
google.com      MX preference = 10, mail exchanger = aspmx.l.google.com
google.com      MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
google.com      MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
google.com      MX preference = 30, mail exchanger = alt2.aspmx.l.google.com

alt4.aspmx.l.google.com internet address = 74.125.25.27
alt3.aspmx.l.google.com internet address = 173.194.72.27
aspmx.l.google.com      internet address = 173.194.65.27
alt1.aspmx.l.google.com internet address = 74.125.200.27
alt2.aspmx.l.google.com internet address = 64.233.187.27

For example to pipe the result again into a file do:

getmns google.com > google.mns.txt

:-D

How to create nested directories using Mkdir in Golang?

This way you don't have to use any magic numbers:

os.MkdirAll(newPath, os.ModePerm)

Also, rather than using + to create paths, you can use:

import "path/filepath"
path := filepath.Join(someRootPath, someSubPath)

The above uses the correct separators automatically on each platform for you.

How to push object into an array using AngularJS

_x000D_
_x000D_
  var app = angular.module('myApp', []);_x000D_
        app.controller('myCtrl', function ($scope) {_x000D_
_x000D_
            //Comments object having reply oject_x000D_
            $scope.comments = [{ comment: 'hi', reply: [{ comment: 'hi inside commnet' }, { comment: 'hi inside commnet' }] }];_x000D_
_x000D_
            //push reply_x000D_
            $scope.insertReply = function (index, reply) {_x000D_
                $scope.comments[index].reply.push({ comment: reply });_x000D_
            }_x000D_
_x000D_
            //push commnet_x000D_
            $scope.newComment = function (comment) {_x000D_
                $scope.comments.push({ comment:comment, reply: [] });_x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
        <!--Comment section-->_x000D_
        <ul ng-repeat="comment in comments track by $index" style="background: skyblue; padding: 10px;">_x000D_
            <li>_x000D_
                <b>Comment {{$index}} : </b>_x000D_
                <br>_x000D_
                {{comment.comment}}_x000D_
                <!--Reply section-->_x000D_
                    <ul ng-repeat="reply in comment.reply track by $index">_x000D_
                        <li><i>Reply {{$index}} :</i><br>_x000D_
                            {{reply.comment}}</li>_x000D_
                    </ul>_x000D_
                <!--End reply section-->_x000D_
                <input type="text" ng-model="reply" placeholder=" Write your reply." /><a href="" ng-click="insertReply($index,reply)">Reply</a>_x000D_
            </li>_x000D_
        </ul>_x000D_
        <!--End comment section -->_x000D_
            _x000D_
_x000D_
        <!--Post your comment-->_x000D_
        <b>New comment</b>_x000D_
        <input type="text" placeholder="Your comment" ng-model="comment" />_x000D_
        <a href="" ng-click="newComment(comment)">Post </a>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Node.js getaddrinfo ENOTFOUND

If you need to use https, then use the https library

https = require('https');

// options
var options = {
    host: 'eternagame.wikia.com',
    path: '/wiki/EteRNA_Dictionary'
}

// get
https.get(options, callback);

How do I return the SQL data types from my query?

I use a simple case statement to render results I can use in technical specification documents. This example does not contain every condition you will run into with a database, but it gives you a good template to work with.

SELECT
     TABLE_NAME          AS 'Table Name',
     COLUMN_NAME         AS 'Column Name',
     CASE WHEN DATA_TYPE LIKE '%char'
          THEN DATA_TYPE + '(' + CONVERT(VARCHAR, CHARACTER_MAXIMUM_LENGTH) + ')'
          WHEN DATA_TYPE IN ('bit', 'int', 'smallint', 'date')
          THEN DATA_TYPE
          WHEN DATA_TYPE = 'datetime'
          THEN DATA_TYPE + '(' + CONVERT(VARCHAR, DATETIME_PRECISION) + ')'
          WHEN DATA_TYPE = 'float'
          THEN DATA_TYPE
          WHEN DATA_TYPE IN ('numeric', 'money')
          THEN DATA_TYPE + '(' + CONVERT(VARCHAR, NUMERIC_PRECISION) + ', ' + CONVERT(VARCHAR, NUMERIC_PRECISION_RADIX) + ')'
     END                 AS 'Data Type',
     CASE WHEN IS_NULLABLE = 'NO'
          THEN 'NOT NULL'
          ELSE 'NULL'
     END                 AS 'PK/LK/NOT NULL'
FROM INFORMATION_SCHEMA.COLUMNS 
ORDER BY 
     TABLE_NAME, ORDINAL_POSITION

Radio button validation in javascript

You could do something like this

var option=document.getElementsByName('Gender');

if (!(option[0].checked || option[1].checked)) {
    alert("Please Select Your Gender");
    return false;
}

Convert MFC CString to integer

CString s="143";
int x=atoi(s);

or

CString s=_T("143");
int x=_toti(s);

atoi will work, if you want to convert CString to int.

Send cookies with curl

.example.com TRUE / FALSE 1560211200 MY_VARIABLE MY_VALUE

The cookies file format apparently consists of a line per cookie and each line consists of the following seven tab-delimited fields:

  • domain - The domain that created AND that can read the variable.
  • flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
  • path - The path within the domain that the variable is valid for.
  • secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
  • expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
  • name - The name of the variable.
  • value - The value of the variable.

From http://www.cookiecentral.com/faq/#3.5

MySQL - Trigger for updating same table after insert

DELIMITER $$

DROP TRIGGER IF EXISTS `setEditStatus`$$
CREATE TRIGGER `setEditStatus` **BEFORE** INSERT on ACCOUNTS
FOR EACH ROW BEGIN

    SET NEW.STATUS = 'E';

END$$

DELIMITER ;

Half circle with CSS (border, outline only)

You could use border-top-left-radius and border-top-right-radius properties to round the corners on the box according to the box's height (and added borders).

Then add a border to top/right/left sides of the box to achieve the effect.

Here you go:

.half-circle {
    width: 200px;
    height: 100px; /* as the half of the width */
    background-color: gold;
    border-top-left-radius: 110px;  /* 100px of height + 10px of border */
    border-top-right-radius: 110px; /* 100px of height + 10px of border */
    border: 10px solid gray;
    border-bottom: 0;
}

WORKING DEMO.

Alternatively, you could add box-sizing: border-box to the box in order to calculate the width/height of the box including borders and padding.

.half-circle {
    width: 200px;
    height: 100px; /* as the half of the width */
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border: 10px solid gray;
    border-bottom: 0;

    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

UPDATED DEMO. (Demo without background color)

VBA (Excel) Initialize Entire Array without Looping

For VBA you need to initialise in two lines.

Sub TestArray()

Dim myArray
myArray = Array(1, 2, 4, 8)

End Sub

How do I auto size a UIScrollView to fit its content

Great & best solution from @leviathan. Just translating to swift using FP (functional programming) approach.

self.scrollView.contentSize = self.scrollView.subviews.reduce(CGRect(), { 
  CGRectUnion($0, $1.frame) 
}.size

How do I bind the enter key to a function in tkinter?

Another alternative is to use a lambda:

ent.bind("<Return>", (lambda event: name_of_function()))

Full code:

from tkinter import *
from tkinter.messagebox import showinfo

def reply(name):
    showinfo(title="Reply", message = "Hello %s!" % name)


top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")

Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)

top.mainloop()

As you can see, creating a lambda function with an unused variable "event" solves the problem.

Batch file to split .csv file

Use the cgwin command SPLIT. Samples

To split a file every 500 lines counts:

split -l 500 [filename.ext]

by default, it adds xa,xb,xc... to filename after extension

To generate files with numbers and ending in correct extension, use following

split -l 1000 sourcefilename.ext destinationfilename -d --additional-suffix=.ext

the position of -d or -l does not matter,

  • "-d" is same as --numeric-suffixes
  • "-l" is same as --lines

For more: split --help

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

Reset all the items in a form

You can reset all controls of a certain type. Something like

foreach(TextBox tb in this.Controls.OfType<TextBox>().ToArray())
{
   tb.Clear();
}

But you can't reset all controls at once

how to convert string to numerical values in mongodb

You can easily convert the string data type to numerical data type.

Don't forget to change collectionName & FieldName. for ex : CollectionNmae : Users & FieldName : Contactno.

Try this query..

db.collectionName.find().forEach( function (x) {
x.FieldName = parseInt(x.FieldName);
db.collectionName.save(x);
});

ZIP file content type for HTTP request

The standard MIME type for ZIP files is application/zip. The types for the files inside the ZIP does not matter for the MIME type.

As always, it ultimately depends on your server setup.

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

How to prevent ENTER keypress to submit a web form?

put into javascript external file

   (function ($) {
 $(window).keydown(function (event) {  

    if (event.keyCode == 13) {

        return false;
    }
});

 })(jQuery);

or somewhere inside body tag

<script>


$(document).ready(function() {
    $(window).keydown(function(event) {
        alert(1);

        if(event.keyCode == 13) {

            return false;
        }
    });
});

</script>

tsc is not recognized as internal or external command

For me, by running Visual Studio Code as Administrator, the problem is resolved.

How to use enums as flags in C++?

The C++ standard explicitly talks about this, see section "17.5.2.1.3 Bitmask types":

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf

Given this "template" you get:

enum AnimalFlags : unsigned int
{
    HasClaws = 1,
    CanFly = 2,
    EatsFish = 4,
    Endangered = 8
};

constexpr AnimalFlags operator|(AnimalFlags X, AnimalFlags Y) {
    return static_cast<AnimalFlags>(
        static_cast<unsigned int>(X) | static_cast<unsigned int>(Y));
}

AnimalFlags& operator|=(AnimalFlags& X, AnimalFlags Y) {
    X = X | Y; return X;
}

And similar for the other operators. Also note the "constexpr", it is needed if you want the compiler to be able to execute the operators compile time.

If you are using C++/CLI and want to able assign to enum members of ref classes you need to use tracking references instead:

AnimalFlags% operator|=(AnimalFlags% X, AnimalFlags Y) {
    X = X | Y; return X;
}

NOTE: This sample is not complete, see section "17.5.2.1.3 Bitmask types" for a complete set of operators.

How to reset (clear) form through JavaScript?

Pure JS solution is as follows:

function clearForm(myFormElement) {

  var elements = myFormElement.elements;

  myFormElement.reset();

  for(i=0; i<elements.length; i++) {

  field_type = elements[i].type.toLowerCase();

  switch(field_type) {

    case "text":
    case "password":
    case "textarea":
          case "hidden":

      elements[i].value = "";
      break;

    case "radio":
    case "checkbox":
        if (elements[i].checked) {
          elements[i].checked = false;
      }
      break;

    case "select-one":
    case "select-multi":
                elements[i].selectedIndex = -1;
      break;

    default:
      break;
  }
    }
}

'nuget' is not recognized but other nuget commands working

Retrieve nuget.exe from https://www.nuget.org/downloads. Copy it to a local folder and add that folder to the PATH environment variable.

This is will make nuget available globally, from any project.

how to refresh Select2 dropdown menu after ajax loading different content?

Got the same problem in 11 11 19, so sorry for possible necroposting. The only what helped was next solution:

var drop = $('#product_1');   // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2');  pick krajee attrs of our elem;
var drop_id = drop.attr('id');  // take id 
settings = window[settings];  // take previous settings from window;
drop.select2(settings);  // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;

It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive. Hope, this solution will be usefull or may push you in right decision in problem fixing

canvas.toDataURL() SecurityError

This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.

var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;

How do I show the value of a #define at compile-time?

#define a <::BOOST_VERSION>
#include a
MSVC2015: fatal error C1083: Cannot open include file: '::106200': No such file or directory

Works even if preprocess to file is enabled, even if invalid tokens are present:

#define a <::'*/`#>
#include a
MSVC2015: fatal error C1083: Cannot open include file: '::'*/`#': No such file or directory
GCC4.x: warning: missing terminating ' character [-Winvalid-pp-token]
#define a <::'*/`#>

How to find where javaw.exe is installed?

It worked to me:

    String javaHome = System.getProperty("java.home");
    File f = new File(javaHome);
    f = new File(f, "bin");
    f = new File(f, "javaw.exe"); //or f = new File(f, "javaws.exe"); //work too
    System.out.println(f + "    exists: " + f.exists());

How can I profile C++ code running on Linux?

I would use Valgrind and Callgrind as a base for my profiling tool suite. What is important to know is that Valgrind is basically a Virtual Machine:

(wikipedia) Valgrind is in essence a virtual machine using just-in-time (JIT) compilation techniques, including dynamic recompilation. Nothing from the original program ever gets run directly on the host processor. Instead, Valgrind first translates the program into a temporary, simpler form called Intermediate Representation (IR), which is a processor-neutral, SSA-based form. After the conversion, a tool (see below) is free to do whatever transformations it would like on the IR, before Valgrind translates the IR back into machine code and lets the host processor run it.

Callgrind is a profiler build upon that. Main benefit is that you don't have to run your aplication for hours to get reliable result. Even one second run is sufficient to get rock-solid, reliable results, because Callgrind is a non-probing profiler.

Another tool build upon Valgrind is Massif. I use it to profile heap memory usage. It works great. What it does is that it gives you snapshots of memory usage -- detailed information WHAT holds WHAT percentage of memory, and WHO had put it there. Such information is available at different points of time of application run.

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

I use:

IF OBJECT_ID('[dbo].[myView]') IS NOT NULL
DROP VIEW [dbo].[myView]
GO
CREATE VIEW [dbo].[myView]
AS

...

Recently I added some utility procedures for this kind of stuff:

CREATE PROCEDURE dbo.DropView
@ASchema VARCHAR(100),
@AView VARCHAR(100)
AS
BEGIN
  DECLARE @sql VARCHAR(1000);
  IF OBJECT_ID('[' + @ASchema + '].[' + @AView + ']') IS NOT NULL
  BEGIN
    SET @sql  = 'DROP VIEW ' + '[' + @ASchema + '].[' + @AView + '] ';
    EXEC(@sql);
  END 
END

So now I write

EXEC dbo.DropView 'mySchema', 'myView'
GO
CREATE View myView
...
GO

I think it makes my changescripts a bit more readable

How do I check if a property exists on a dynamic anonymous type in c#?

This works also for DynamicJsonObject:

  public static bool PropertyExists(dynamic settings, string name)
  {
    if (settings is ExpandoObject)
      return ((IDictionary<string, object>)settings).ContainsKey(name);
    else if (settings is DynamicJsonObject)
      return ((DynamicJsonObject)settings).GetDynamicMemberNames().Contains(name);

    return settings.GetType().GetProperty(name) != null;
  }

What is the difference between static func and class func in Swift?

From Swift2.0, Apple says:

"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"

How to check if a variable exists in a FreeMarker template?

Also I think if_exists was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?

How to search a specific value in all tables (PostgreSQL)?

There is a way to achieve this without creating a function or using an external tool. By using Postgres' query_to_xml() function that can dynamically run a query inside another query, it's possible to search a text across many tables. This is based on my answer to retrieve the rowcount for all tables:

To search for the string foo across all tables in a schema, the following can be used:

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
  left join xmltable('//table/row' 
                     passing table_rows
                       columns
                         table_row text path 'table_row') as x on true

Note that the use of xmltable requires Postgres 10 or newer. For older Postgres version, this can be also done using xpath().

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
   cross join unnest(xpath('/table/row/table_row/text()', table_rows)) as r(data)

The common table expression (WITH ...) is only used for convenience. It loops through all tables in the public schema. For each table the following query is run through the query_to_xml() function:

select to_jsonb(t)
from some_table t
where t::text like '%foo%';

The where clause is used to make sure the expensive generation of XML content is only done for rows that contain the search string. This might return something like this:

<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
  <table_row>{"id": 42, "some_column": "foobar"}</table_row>
</row>
</table>

The conversion of the complete row to jsonb is done, so that in the result one could see which value belongs to which column.

The above might return something like this:

table_name   |   table_row
-------------+----------------------------------------
public.foo   |  {"id": 1, "some_column": "foobar"}
public.bar   |  {"id": 42, "another_column": "barfoo"}

Online example for Postgres 10+

Online example for older Postgres versions

JavaScript code to stop form submission

You can use the return value of the function to prevent the form submission

<form name="myForm" onsubmit="return validateMyForm();"> 

and function like

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValue field to false to get it to work.

Thanks Sam for sharing information.

EDIT :

Thanks to Vikram for his workaround for if validateMyForm() returns false:

 <form onsubmit="event.preventDefault(); validateMyForm();">

where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

Python loop counter in a for loop

enumerate is what you are looking for.

You might also be interested in unpacking:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

JTable How to refresh table model after insert delete or update the data.

Would it not be better to use java.util.Observable and java.util.Observer that will cause the table to update?

What is the current choice for doing RPC in Python?

We are developing Versile Python (VPy), an implementation for python 2.6+ and 3.x of a new ORB/RPC framework. Functional AGPL dev releases for review and testing are available. VPy has native python capabilities similar to PyRo and RPyC via a general native objects layer (code example). The product is designed for platform-independent remote object interaction for implementations of Versile Platform.

Full disclosure: I work for the company developing VPy.

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

Resolved similar problem in IBM RAD 7.5 by selecting:

  1. Projects properties
  2. Project Facets
  3. JSTL check-box

How can I access and process nested objects, arrays or JSON?

If you are looking for one or more objects that meets certain criteria you have a few options using query-js

//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1 
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});

There's also a single and a singleOrDefault they work much like firstand firstOrDefaultrespectively. The only difference is that they will throw if more than one match is found.

for further explanation of query-js you can start with this post

Troubleshooting misplaced .git directory (nothing to commit)

Check the location whether it's the right location of the git project.

What is the most accurate way to retrieve a user's correct IP address in PHP?

Here's a modified version if you use CloudFlare caching layer Services

function getIP()
{
    $fields = array('HTTP_X_FORWARDED_FOR',
                    'REMOTE_ADDR',
                    'HTTP_CF_CONNECTING_IP',
                    'HTTP_X_CLUSTER_CLIENT_IP');

    foreach($fields as $f)
    {
        $tries = $_SERVER[$f];
        if (empty($tries))
            continue;
        $tries = explode(',',$tries);
        foreach($tries as $try)
        {
            $r = filter_var($try,
                            FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 |
                            FILTER_FLAG_NO_PRIV_RANGE |
                            FILTER_FLAG_NO_RES_RANGE);

            if ($r !== false)
            {
                return $try;
            }
        }
    }
    return false;
}

Auto-scaling input[type=text] to width of value?

User nrabinowitz' solution is working great, but I use the keypress event instead of keyup. That reduces the latency if the user types slowly.

top nav bar blocking top content of the page

The bootstrap v4 starter template css uses:

body {
  padding-top: 5rem;
}

Inserting string at position x of another string

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_


Optional: As a prototype method of String

The following can be used to splice text within another string at a desired index, with an optional removeCount parameter.

_x000D_
_x000D_
if (String.prototype.splice === undefined) {_x000D_
  /**_x000D_
   * Splices text within a string._x000D_
   * @param {int} offset The position to insert the text at (before)_x000D_
   * @param {string} text The text to insert_x000D_
   * @param {int} [removeCount=0] An optional number of characters to overwrite_x000D_
   * @returns {string} A modified string containing the spliced text._x000D_
   */_x000D_
  String.prototype.splice = function(offset, text, removeCount=0) {_x000D_
    let calculatedOffset = offset < 0 ? this.length + offset : offset;_x000D_
    return this.substring(0, calculatedOffset) +_x000D_
      text + this.substring(calculatedOffset + removeCount);_x000D_
  };_x000D_
}_x000D_
_x000D_
let originalText = "I want apple";_x000D_
_x000D_
// Positive offset_x000D_
console.log(originalText.splice(6, " an"));_x000D_
// Negative index_x000D_
console.log(originalText.splice(-5, "an "));_x000D_
// Chaining_x000D_
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
_x000D_
_x000D_

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Try this:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

zzz is the timezone offset.

Beamer: How to show images as step-by-step images

This is what I did:

\begin{frame}{series of images}
\begin{center}
\begin{overprint}

\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}

\only<2-5>{\mbox{\structure{Figure:} something}}

\end{overprint}
\end{center}
\end{frame}

What are some resources for getting started in operating system development?

My operating systems course in undergrad had us building a number of subsystems for OS/161, a simple, BSD-like kernel that provides some of the basics while leaving the freedom to explore various design space decisions in implementing higher-level services.

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

Interestingly, I kept getting that error. What fixed it for me was creating a config called gacutil.exe.config in the same directory as gacutil.exe. The config content (a text file) were:

<?xml version ="1.0"?> <configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <requiredRuntime safemode="true" imageVersion="v4.0.30319" version="v4.0.30319"/>
    </startup> </configuration>

I'm posting this here for reference and ask if anyone knows what's actually happening under the hood. I'm not claiming this is the "proper" way of doing it

Getting error "The package appears to be corrupt" while installing apk file

When you are releasing signed apk , please make sure you tick both v1 and v2 in signature versions

See below screenshot for more info Signed APK generation

Converting HTML files to PDF

If you look at the side bar of your question, you will see many related questions...

In your context, the simpler method might be to install a PDF print driver like PDFCreator and just print the page to this output.

Temporary tables in stored procedures

Maybe.

Temporary tables prefixed with one # (#example) are kept on a per session basis. So if your code calls the stored procedure again while another call is running (for example background threads) then the create call will fail because it's already there.

If you're really worried use a table variable instead

DECLARE @MyTempTable TABLE 
(
   someField int,
   someFieldMore nvarchar(50)
)

This will be specific to the "instance" of that stored procedure call.

How to generate unique id in MySQL?

You may like the way that we do it. I wanted a reversible unique code that looked "random" -a fairly common problem.

  • We take an input number such as 1,942.
  • Left pad it into a string: "0000001942"
  • Put the last two digits onto the front: "4200000019"
  • Convert that into a number: 4,200,000,019

We now have a number that varies wildly between calls and is guaranteed to be less than 10,000,000,000. Not a bad start.

  • Convert that number to a Base 34 string: "2oevc0b"
  • Replace any zeros with 'y' and any ones with 'z': "2oevcyb"
  • Upshift: "2OEVCYB"

The reason for choosing base 34 is so that we don't worry about 0/O and 1/l collisions. Now you have a short random-looking key that you can use to look up a LONG database identifier.

MySQL - select data from database between two dates

Maybe use in between better. It worked for me to get range then filter it

Getting a better understanding of callback functions in JavaScript

the proper implementation would be:

if( callback ) callback();

this makes the callback parameter optional..

How to delete object from array inside foreach loop?

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array
            unset($array[$elementKey]);
        } 
    }
}

What is the Eclipse shortcut for "public static void main(String args[])"?

Type main and press and hold Ctrl and next press Space Space (double space) and select, it or pressenter to focus on main option.

This is fastest way.

python: sys is not defined

You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

try:
    import datetime
    import foo
    import sys
except ImportError:
    pass

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

Extracting an attribute value with beautifulsoup

you can also use this :

import requests
from bs4 import BeautifulSoup
import csv

url = "http://58.68.130.147/"
r = requests.get(url)
data = r.text

soup = BeautifulSoup(data, "html.parser")
get_details = soup.find_all("input", attrs={"name":"stainfo"})

for val in get_details:
    get_val = val["value"]
    print(get_val)

What's the difference between .NET Core, .NET Framework, and Xamarin?

You should use .NET Core, instead of .NET Framework or Xamarin, in the following 6 typical scenarios according to the documentation here.

1. Cross-Platform needs

Clearly, if your goal is to have an application (web/service) that should be able to run across platforms (Windows, Linux and MacOS), the best choice in the .NET ecosystem is to use .NET Core as its runtime (CoreCLR) and libraries are cross-platform. The other choice is to use the Mono Project.

Both choices are open source, but .NET Core is directly and officially supported by Microsoft and will have a heavy investment moving forward.

When using .NET Core across platforms, the best development experience exists on Windows with the Visual Studio IDE which supports many productivity features including project management, debugging, source control, refactoring, rich editing including Intellisense, testing and much more. But rich development is also supported using Visual Studio Code on Mac, Linux and Windows including intellisense and debugging. Even third party editors like Sublime, Emacs, VI and more work well and can get editor intellisense using the open source Omnisharp project.

2. Microservices

When you are building a microservices oriented system composed of multiple independent, dynamically scalable, stateful or stateless microservices, the great advantage that you have here is that you can use different technologies/frameworks/languages at a microservice level. That allows you to use the best approach and technology per micro areas in your system, so if you want to build very performant and scalable microservices, you should use .NET Core. Eventually, if you need to use any .NET Framework library that is not compatible with .NET Core, there’s no issue, you can build that microservice with the .NET Framework and in the future you might be able to substitute it with the .NET Core.

The infrastructure platform you could use are many. Ideally, for large and complex microservice systems, you should use Azure Service Fabric. But for stateless microservices you can also use other products like Azure App Service or Azure Functions.

Note that as of June 2016, not every technology within Azure supports the .NET Core, but .NET Core support in Azure will be increasing dramatically now that .NET Core is RTM released.

3. Best performant and scalable systems

When your system needs the best possible performance and scalability so you get the best responsiveness no matter how many users you have, then is where .NET Core and ASP.NET Core really shine. The more you can do with the same amount of infrastructure/hardware, the richer the experience you’ll have for your end users – at a lower cost.

The days of Moore’s law performance improvements for single CPUs does not apply anymore; yet you need to do more while your system is growing and need higher scalability and performance for everyday’ s more demanding users which are growing exponentially in numbers. You need to get more efficient, optimize everywhere, and scale better across clusters of machines, VMs and CPU cores, ultimately. It is not just a matter of user’s satisfaction; it can also make a huge difference in cost/TCO. This is why it is important to strive for performance and scalability.

As mentioned, if you can isolate small pieces of your system as microservices or any other loosely-coupled approach, it’ll be better as you’ll be able to not just evolve each small piece/microservice independently and have a better long-term agility and maintenance, but also you’ll be able to use any other technology at a microservice level if what you need to do is not compatible with .NET Core. And eventually you’d be able to refactor it and bring it to .NET Core when possible.

4. Command line style development for Mac, Linux or Windows.

This approach is optional when using .NET Core. You can also use the full Visual Studio IDE, of course. But if you are a developer that wants to develop with lightweight editors and heavy use of command line, .NET Core is designed for CLI. It provides simple command line tools available on all supported platforms, enabling developers to build and test applications with a minimal installation on developer, lab or production machines. Editors like Visual Studio Code use the same command line tools for their development experiences. And IDE’s like Visual Studio use the same CLI tools but hide them behind a rich IDE experience. Developers can now choose the level they want to interact with the tool chain from CLI to editor to IDE.

5. Need side by side of .NET versions per application level.

If you want to be able to install applications with dependencies on different versions of frameworks in .NET, you need to use .NET Core which provides 100% side-by side as explained previously in this document.

6. Windows 10 UWP .NET apps.

In addition, you may also want to read:

  1. When should I NOT use .NET Core?
  2. When should I still use .NET Framework 4.x, instead of .NET Core?
  3. When should I use Xamarin, instead of .NET Core?

"Unable to find remote helper for 'https'" during git clone

I landed here once because I was working with git itself. When I built it the default makefile installed the binary in ~/bin/git. Since my PATH had ~/bin first when I ran 'git pull --rebase' it used the one in ~/bin and consequently could not locate the helpers.

I worked around the issue by running '/usr/bin/git ...' with a full path (alternatively I could have adjusted my PATH).

Head and tail in one line

Python 2, using lambda

>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

Selecting only first-level elements in jquery

Simply you can use this..

$("ul li a").click(function() {
  $(this).parent().find(">ul")...Something;
}

See example : https://codepen.io/gmkhussain/pen/XzjgRE

Is it possible to create a temporary table in a View and drop it after select?

No, a view consists of a single SELECT statement. You cannot create or drop tables in a view.

Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.

Example (taken from here) - you can think of the SalesBySalesPerson CTE as a temporary table:

CREATE VIEW vSalesStaffQuickStats
AS
  WITH SalesBySalesPerson (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
      AS
      (
            SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
            FROM Sales.SalesOrderHeader
            GROUP BY SalesPersonID
      )
  SELECT E.EmployeeID,
         EmployeeOrders = OS.NumberOfOrders,
         EmployeeLastOrderDate = OS.MostRecentOrderDate,
         E.ManagerID,
         ManagerOrders = OM.NumberOfOrders,
         ManagerLastOrderDate = OM.MostRecentOrderDate
  FROM HumanResources.Employee AS E
  INNER JOIN SalesBySalesPerson AS OS ON E.EmployeeID = OS.SalesPersonID
  LEFT JOIN SalesBySalesPerson AS OM ON E.ManagerID = OM.SalesPersonID
GO

Performance considerations

Which are more performant, CTE or temporary tables?

How to Disable GUI Button in Java

You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all.

Then you have the actionPerformed method that does nothing with your button. So, if you don't have any action related, your button status will never be evaluated again.

Convert list of ints to one number?

Using a generator expression:

def magic(numbers):
    digits = ''.join(str(n) for n in numbers)
    return int(digits)

Can an int be null in Java?

No, but int[] can be.

int[] hayhay = null; //: allowed (int[] is reference type)
int   hayno  = null; //: error   (int   is primitive type)
                     //: Message: incompatible types: 
                     //: <null> cannot be converted to int

How to download image from url

Try this it worked for me

Write this in your Controller

public class DemoController: Controller

        public async Task<FileStreamResult> GetLogoImage(string logoimage)
        {
            string str = "" ;
            var filePath = Server.MapPath("~/App_Data/" + SubfolderName);//If subfolder exist otherwise leave.
            // DirectoryInfo dir = new DirectoryInfo(filePath);
            string[] filePaths = Directory.GetFiles(@filePath, "*.*");
            foreach (var fileTemp in filePaths)
            {
                  str= fileTemp.ToString();
            }
                return File(new MemoryStream(System.IO.File.ReadAllBytes(str)), System.Web.MimeMapping.GetMimeMapping(str), Path.GetFileName(str));
        }

Here is my view

<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

How to initialize an array in Java?

You can do:

int[] data = {10,20,30,40,50,60,71,80,90,91};

What does 'corrupted double-linked list' mean

For anyone who is looking for solutions here, I had a similar issue with C++: malloc(): smallbin double linked list corrupted:

This was due to a function not returning a value it was supposed to.

std::vector<Object> generateStuff(std::vector<Object>& target> {
  std::vector<Object> returnValue;
  editStuff(target);
  // RETURN MISSING
}

Don't know why this was able to compile after all. Probably there was a warning about it.

How can I display a messagebox in ASP.NET?

just try this, it works fine in my browser:

your response writing code should be

Response.Write("<script>alert('login successful');</script>");

Hope this works

How to iterate std::set?

How do you iterate std::set?

int main(int argc,char *argv[]) 
{
    std::set<int> mset;
    mset.insert(1); 
    mset.insert(2);
    mset.insert(3);

    for ( auto it = mset.begin(); it != mset.end(); it++ )
        std::cout << *it;
}

How to handle calendar TimeZones using Java?

You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.

If this is the case, you should take a look at the setTimeZone method of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.

A simple example:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

Calendar cal = Calendar.getInstance();
String timestamp = formatter.format(cal.getTime());

Create Windows service from executable

I created the cross-platform Service Manager software a few years back so that I could start PHP and other scripting languages as system services on Windows, Mac, and Linux OSes:

https://github.com/cubiclesoft/service-manager

Service Manager is a set of precompiled binaries that install and manage a system service on the target OS using nearly identical command-line options (source code also available). Each platform does have subtle differences but the core features are mostly normalized.

If the child process dies, Service Manager automatically restarts it.

Processes that are started with Service Manager should periodically watch for two notification files to handle restart and reload requests but they don't necessarily have to do that. Service Manager will force restart the child process if it doesn't respond in a timely fashion to controlled restart/reload requests.

Get values from a listbox on a sheet

The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.

Here is what I suggest instead:

Private Sub CommandButton2_Click()
    Dim lItem As Long

    For lItem = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(lItem) = True Then
            MsgBox(ListBox1.List(lItem))
        End If
    Next
End Sub

Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm

Passing parameter using onclick or a click binding with KnockoutJS

A generic answer on how to handle click events with KnockoutJS...

Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:

_x000D_
_x000D_
function Item(parent, txt) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.doOtherStuff = function(customParam, data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
  };_x000D_
  _x000D_
  self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doParentStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    self.log(self.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.items = ko.observableArray([_x000D_
    new Item(self, "John Doe"),_x000D_
    new Item(self, "Marcus Aurelius")_x000D_
  ]);_x000D_
  self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
  <div class="parent">_x000D_
    <span data-bind="text: txt"></span><br>_x000D_
    <button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
    <button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
    <button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
    <button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }</button><br>_x000D_
    <button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
    <button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
_x000D_
_x000D_


**A note about the actual question...*

The actual question has one interesting bit:

// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"

Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).

Instead, modify the View Model in your handler instead, and have the View respond. For example:

_x000D_
_x000D_
function RootVm() {_x000D_
  var self = this;_x000D_
  self.buttonWasClickedOnce = ko.observable(false);_x000D_
  self.toggle = function(data, event) {_x000D_
    self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
  };_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div  data-bind="visible: !buttonWasClickedOnce()">_x000D_
    <button data-bind="click: toggle">Toggle!</button>_x000D_
  </div>_x000D_
  <div data-bind="visible: buttonWasClickedOnce">_x000D_
    Can be made visible with toggle..._x000D_
    <button data-bind="click: toggle">Untoggle!</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

deleting rows in numpy array

numpy provides a simple function to do the exact same thing: supposing you have a masked array 'a', calling numpy.ma.compress_rows(a) will delete the rows containing a masked value. I guess this is much faster this way...

How to check status of PostgreSQL server Mac OS X

The pg_ctl status command suggested in other answers checks that the postmaster process exists and if so reports that it's running. That doesn't necessarily mean it is ready to accept connections or execute queries.

It is better to use another method like using psql to run a simple query and checking the exit code, e.g. psql -c 'SELECT 1', or use pg_isready to check the connection status.

How to convert date to timestamp?

this refactored code will do it

let toTimestamp = strDate => Date.parse(strDate)

this works on all modern browsers except ie8-

Retrieving Android API version programmatically

Got it. Its using the getApplicationInfo() method of the Context class.

Encoding Javascript Object to Json string

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;

new_tweets.k.data = { };

new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

You can also do it all at once:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}

Adding a dictionary to another

foreach(var newAnimal in NewAnimals)
    Animals.Add(newAnimal.Key,newAnimal.Value)

Note: this throws an exception on a duplicate key.


Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange extension method that works on any ICollection<T>, and not just on Dictionary<TKey,TValue>.

public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
    if(target==null)
      throw new ArgumentNullException(nameof(target));
    if(source==null)
      throw new ArgumentNullException(nameof(source));
    foreach(var element in source)
        target.Add(element);
}

(throws on duplicate keys for dictionaries)

How to set bot's status

setGame has been discontinued. You must use client.user.setActivity.

Don't forget, if you are setting a streaming status, you MUST specify a Twitch URL

An example is here:

client.user.setActivity("with depression", {
  type: "STREAMING",
  url: "https://www.twitch.tv/example-url"
});

ElasticSearch - Return Unique Values

Elasticsearch 1.1+ has the Cardinality Aggregation which will give you a unique count

Note that it is actually an approximation and accuracy may diminish with high-cardinality datasets, but it's generally pretty accurate in my testing.

You can also tune the accuracy with the precision_threshold parameter. The trade-off, or course, is memory usage.

This graph from the docs shows how a higher precision_threshold leads to much more accurate results.


Relative error vs threshold

How to Select Min and Max date values in Linq Query

This should work for you

//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();

//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max(); 

(From here)

How do I perform HTML decoding/encoding using Python/Django?

You can also use django.utils.html.escape

from django.utils.html import escape

something_nice = escape(request.POST['something_naughty'])

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

You can simply use the "Replace" function in SQL Server.

like this ::

select REPLACE('this is a test message','"','')

note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.

Very simple and easy to execute !

How do search engines deal with AngularJS applications?

Use something like PreRender, it makes static pages of your site so search engines can index it.

Here you can find out for what platforms it is available: https://prerender.io/documentation/install-middleware#asp-net

Assign width to half available screen width declaratively

Using constraints layout

  1. Add a Guideline
  2. Set the percentage to 50%
  3. Constrain your view to the Guideline and the parent.

enter image description here

If you are having trouble changing it to a percentage, then see this answer.

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <android.support.constraint.Guideline
        android:id="@+id/guideline8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/guideline8"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    
</android.support.constraint.ConstraintLayout>

What is the difference between printf() and puts() in C?

In my experience, printf() hauls in more code than puts() regardless of the format string.

If I don't need the formatting, I don't use printf. However, fwrite to stdout works a lot faster than puts.

static const char my_text[] = "Using fwrite.\n";
fwrite(my_text, 1, sizeof(my_text) - sizeof('\0'), stdout);

Note: per comments, '\0' is an integer constant. The correct expression should be sizeof(char) as indicated by the comments.

What is a wrapper class?

Just what it sounds like: a class that "wraps" the functionality of another class or API in a simpler or merely different API.

See: Adapter pattern, Facade pattern

'int' object has no attribute '__getitem__'

Some of the problems:

for i in range[6]:
            for j in range[6]:

should be:

range(6)

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Unexpected end of file means that something else was expected before the PHP parser reached the end of the script.

Judging from your HUGE file, it's probably that you're missing a closing brace (}) from an if statement.

Please at least attempt the following things:

  1. Separate your code from your view logic.
  2. Be consistent, you're using an end ; in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?> vs <?php echo $this->layouts->print_includes() ?>. It's not required, so don't use it (or do, just do one or the other).
  3. Repeated because it's important, separate your concerns. There's no need for all of this code.
  4. Use an IDE, it will help you with errors such as this going forward.

Remove ALL styling/formatting from hyperlinks

You can simply define a style for links, which would override a:hover, a:visited etc.:

a {
  color: blue;
  text-decoration: none; /* no underline */
}

You can also use the inherit value if you want to use attributes from parent styles instead:

body {
  color: blue;
}
a {
  color: inherit; /* blue colors for links too */
  text-decoration: inherit; /* no underline */
}

mongoError: Topology was destroyed

"Topology was destroyed" might be caused by mongoose disconnecting before mongo document indexes are created, per this comment

In order to make sure all models have their indexes built before disconnecting, you can:

await Promise.all(mongoose.modelNames().map(model => mongoose.model(model).ensureIndexes()));

await mongoose.disconnect();

How to access Session variables and set them in javascript?

To modify session data from the server after page creation you would need to use AJAX or even JQuery to get the job done. Both of them can make a connection to the server to modify session data and get returned data back from that connection.

<?php
session_start();
$_SESSION['usedData'] = "Some Value"; //setting for now since it doesn't exist
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Modifying PHP Session Data</title>
        <script type='text/javascript'>
            var usedData = '<?php echo $_SESSION['usedData']; ?>';
            var oldDataValue = null;

            /* If function used, sends new data from input field to the
               server, then gets response from server if any. */

            function modifySession () {
                var newValue = document.getElementById("newValueData").value;

                /* You could always check the newValue here before making
                   the request so you know if its set or needs filtered. */

                var xhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        oldDataValue = usedData;
                        usedData = this.responseText; //response from php script
                        document.getElementById("sessionValue").innerHTML = usedData;
                        document.getElementById("sessionOldValue").innerHTML = oldDataValue;
                    }
                };

            xhttp.open("GET", "modifySession.php?newData="+newValue, true);
            xhttp.send(); 
            }
        </script>
    </head>
    <body>
        <h1><p>Modify Session</p></h1>

        Current Value: <div id='sessionValue' style='display:inline'><?php echo $_SESSION['usedData']; ?></div><br/>
        Old Value: <div id='sessionOldValue' style='display:inline'><?php echo $_SESSION['usedData']; ?></div><br/>

        New Value: <input type='text' id='newValueData' /><br/>
        <button onClick='modifySession()'>Change Value</button>
   </body>
</html>

Now we need to make a small php script called modifySession.php to make changes to session data and post data back if necessary.

<?php
session_start();
$_SESSION['usedData'] = $_GET['newData']; //filter if necessary
echo $_SESSION['usedData']; // Post results back if necessary
?>

This should achieve the desired results you are looking for by modifying the session via server side using PHP/AJAX.

PHP: HTML: send HTML select option attribute in POST

<form name="add" method="post">
     <p>Age:</p>
     <select name="age">
        <option value="1_sre">23</option>
        <option value="2_sam">24</option>
        <option value="5_john">25</option>
     </select>
     <input type="submit" name="submit"/>
</form>

You will have the selected value in $_POST['age'], e.g. 1_sre. Then you will be able to split the value and get the 'stud_name'.

$stud = explode("_",$_POST['age']);
$stud_id = $stud[0];
$stud_name = $stud[1];

How do you push just a single Git branch (and no other branches)?

Better answer will be

git config push.default current

upsteam works but when you have no branch on origin then you will need to set the upstream branch. Changing it to current will automatically set the upsteam branch and will push the branch immediately.

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

Python os.path.join() on a list

Assuming join wasn't designed that way (which it is, as ATOzTOA pointed out), and it only took two parameters, you could still use the built-in reduce:

>>> reduce(os.path.join,["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt'

Same output like:

>>> os.path.join(*["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt' 

Just for completeness and educational reasons (and for other situations where * doesn't work).

Hint for Python 3

reduce was moved to the functools module.

How to detect the currently pressed key?

if (Control.ModifierKeys == Keys.Shift)
    //Shift is pressed

The cursor x/y position is a property, and a keypress (like a mouse click/mousemove) is an event. Best practice is usually to let the interface be event driven. About the only time you would need the above is if you're trying to do a shift + mouseclick thing.

Log exception with traceback

Here is a version that uses sys.excepthook

import traceback
import sys

logger = logging.getLogger()

def handle_excepthook(type, message, stack):
     logger.error(f'An unhandled exception occured: {message}. Traceback: {traceback.format_tb(stack)}')

sys.excepthook = handle_excepthook

Change text from "Submit" on input tag

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won't be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

CSS set li indent

padding-left is what controls the indentation of ul not margin-left.

Compare: Here's setting padding-left to 0, notice all the indentation disappears.

_x000D_
_x000D_
ul {
  padding-left: 0;
}
_x000D_
<ul>
  <li>section a
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
<ul>
  <li>section b
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
_x000D_
_x000D_
_x000D_

and here's setting margin-left to 0px. Notice the indentation does NOT change.

_x000D_
_x000D_
ul {
  margin-left: 0;
}
_x000D_
<ul>
  <li>section a
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
<ul>
  <li>section b
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
_x000D_
_x000D_
_x000D_

How to manage local vs production settings in Django?

I am also working with Laravel and I like the implementation there. I tried to mimic it and combining it with the solution proposed by T. Stone (look above):

PRODUCTION_SERVERS = ['*.webfaction.com','*.whatever.com',]

def check_env():
    for item in PRODUCTION_SERVERS:
        match = re.match(r"(^." + item + "$)", socket.gethostname())
        if match:
            return True

if check_env():
    PRODUCTION = True
else:
    PRODUCTION = False

DEBUG = not PRODUCTION

Maybe something like this would help you.

How to filter an array from all elements of another array

_x000D_
_x000D_
var arr1= [1,2,3,4];_x000D_
var arr2=[2,4]_x000D_
_x000D_
function fil(value){_x000D_
return value !=arr2[0] &&  value != arr2[1]_x000D_
}_x000D_
_x000D_
document.getElementById("p").innerHTML= arr1.filter(fil)
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head> _x000D_
</head>_x000D_
<body>_x000D_
<p id="p"></p>
_x000D_
_x000D_
_x000D_

Difference between [routerLink] and routerLink

Router Link

routerLink with brackets and none - simple explanation.

The difference between routerLink= and [routerLink] is mostly like relative and absolute path.

Similar to a href you may want to navigate to ./about.html or https://your-site.com/about.html.

When you use without brackets then you navigate relative and without params;

my-app.com/dashboard/client

"jumping" from my-app.com/dashboard to my-app.com/dashboard/client

<a routerLink="client/{{ client.id }}" .... rest the same

When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link

first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT

<a [routerLink]="['/client', client.id]" ... rest the same

The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts

The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing.

Angular.io Selectors

See whats the routerLink construct

https://angular.io/api/router/RouterLink#selectors

Split column at delimiter in data frame

Hadley has a very elegant solution to do this inside data frames in his reshape package, using the function colsplit.

require(reshape)
> df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
> df
  ID FOO
1 11 a|b
2 12 b|c
3 13 x|y
> df = transform(df, FOO = colsplit(FOO, split = "\\|", names = c('a', 'b')))
> df
  ID FOO.a FOO.b
1 11     a     b
2 12     b     c
3 13     x     y

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

Here's some code with a dummy geom_blank layer,

range_act <- range(range(results$act), range(results$pred))

d <- reshape2::melt(results, id.vars = "pred")

dummy <- data.frame(pred = range_act, value = range_act,
                    variable = "act", stringsAsFactors=FALSE)

ggplot(d, aes(x = pred, y = value)) +
  facet_wrap(~variable, scales = "free") +
  geom_point(size = 2.5) + 
  geom_blank(data=dummy) + 
  theme_bw()

enter image description here

How to rebuild docker container in docker-compose.yml?

As @HarlemSquirrel posted, it is the best and I think the correct solution.

But, to answer the OP specific problem, it should be something like the following command, as he doesn't want to recreate ALL services in the docker-compose.yml file, but only the nginx one:

docker-compose up -d --force-recreate --no-deps --build nginx

Options description:

Options:
  -d                  Detached mode: Run containers in the background,
                      print new container names. Incompatible with
                      --abort-on-container-exit.
  --force-recreate    Recreate containers even if their configuration
                      and image haven't changed.
  --build             Build images before starting containers.
  --no-deps           Don't start linked services.

MySql Error: 1364 Field 'display_name' doesn't have default value

MySQL is most likely in STRICT mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.

Change the column to allow null:

ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL

or, give it a default value as empty string:

ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''

PostgreSQL Autoincrement

Create Sequence.

CREATE SEQUENCE user_role_id_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 3
  CACHE 1;
ALTER TABLE user_role_id_seq
  OWNER TO postgres;

and alter table

ALTER TABLE user_roles ALTER COLUMN user_role_id SET DEFAULT nextval('user_role_id_seq'::regclass);

python ignore certificate validation urllib2

The easiest way:

python 2

import urllib2, ssl

request = urllib2.Request('https://somedomain.co/')
response = urllib2.urlopen(request, context=ssl._create_unverified_context())

python 3

from urllib.request import urlopen
import ssl

response = urlopen('https://somedomain.co', context=ssl._create_unverified_context())

Read Numeric Data from a Text File in C++

It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:

class array2D { 
    std::vector<double> data;
    size_t columns;
public:
    array2D(size_t x, size_t y) : columns(x), data(x*y) {}

    double &operator(size_t x, size_t y) {
       return data[y*columns+x];
    }
};

Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.

In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.

If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:

11 12 13
23 34 56 78

You might want to use a std::vector<std::vector<double> > instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.

std::vector<std::vector<double> > numbers;

std::string temp;

while (std::getline(infile, temp)) {
    std::istringstream buffer(temp);
    std::vector<double> line((std::istream_iterator<double>(buffer)),
                             std::istream_iterator<double>());

    numbers.push_back(line);
}

...or, with a modern (C++11) compiler, you can use brackets for line's initialization:

    std::vector<double> line{std::istream_iterator<double>(buffer),
                             std::istream_iterator<double>()};

When to use single quotes, double quotes, and backticks in MySQL

There are two types of quotes in MySQL:

  1. ' for enclosing string literals
  2. ` for enclosing identifiers such as table and column names

And then there is " which is a special case. It could be used for one of above-mentioned purposes at a time depending on MySQL server's sql_mode:

  1. By default the " character can be used to enclose string literals just like '
  2. In ANSI_QUOTES mode the " character can be used to enclose identifiers just like `

The following query will produce different results (or errors) depending on SQL mode:

SELECT "column" FROM table WHERE foo = "bar"

ANSI_QUOTES disabled

The query will select the string literal "column" where column foo is equal to string "bar"

ANSI_QUOTES enabled

The query will select the column column where column foo is equal to column bar

When to use what

  • I suggest that you avoid using " so that your code becomes independent of SQL modes
  • Always quote identifiers since it is a good practice (quite a few questions on SO discuss this)

Very Simple, Very Smooth, JavaScript Marquee

My text marquee for more text, and position absolute enabled

http://jsfiddle.net/zrW5q/2075/

(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
  position: 'absolute',
  visibility: 'hidden',
  height: 'auto',
  width: 'auto',
  'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};

$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
    offset = that.width(),
    width = offset,
    css = {
        'text-indent': that.css('text-indent'),
        'overflow': that.css('overflow'),
        'white-space': that.css('white-space')
    },
    marqueeCss = {
        'text-indent': width,
        'overflow': 'hidden',
        'white-space': 'nowrap'
    },
    args = $.extend(true, {
        count: -1,
        speed: 1e1,
        leftToRight: false
    }, args),
    i = 0,
    stop = textWidth * -1,
    dfd = $.Deferred();

function go() {
    if (that.css('overflow') != "hidden") {
        that.css('text-indent', width + 'px');
        return false;
    }
    if (!that.length) return dfd.reject();

    if (width <= stop) {
        i++;
        if (i == args.count) {
            that.css(css);
            return dfd.resolve();
        }
        if (args.leftToRight) {
            width = textWidth * -1;
        } else {
            width = offset;
        }
    }
    that.css('text-indent', width + 'px');
    if (args.leftToRight) {
        width++;
    } else {
        width--;
    }
    setTimeout(go, args.speed);
};

if (args.leftToRight) {
    width = textWidth * -1;
    width++;
    stop = offset;
} else {
    width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {     
    $(this).removeAttr("style");
}).mouseout(function () {
    $(this).marquee();
});
})(jQuery);

How to config Tomcat to serve images from an external folder outside webapps?

This is the way I did it and it worked fine for me. (done on Tomcat 7.x)

Add a <context> to the tomcat/conf/server.xml file.

Windows example:

<Context docBase="c:\Documents and Settings\The User\images" path="/project/images" />

Linux example:

<Context docBase="/var/project/images" path="/project/images" />

Like this (in context):

<Server port="8025" shutdown="SHUTDOWN">
 ...
  <Service name="Catalina">
    ...
    <Engine defaultHost="localhost" name="Catalina">
     ...
     <Host appBase="webapps"
      autoDeploy="false" name="localhost" unpackWARs="true"
      xmlNamespaceAware="false" xmlValidation="false">
      ...
      <!--MAGIC LINE GOES HERE-->
       <Context  docBase="/var/project/images" path="/project/images" />

      </Host>
    </Engine>
  </Service>
</Server>

In this way, you should be able to find the files (e.g. /var/project/images/NameOfImage.jpg) under:

http://localhost:8080/project/images/NameOfImage.jpg 

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

I just experienced the same issue after I had to restart my production server. I am running Debian 8.1 (Jessie) on a DigitalOcean droplet.

This is what I did to resolve my issue:

  1. Check if the file /var/run/mysqld/mysqld.sock exists. If it doesn't, manually create it by entering touch /var/run/mysqld/mysqld.sock (which is what I had to do).

  2. So the MySQL process can use this file. Change ownership of said file by entering chown mysql /var/run/mysqld/mysqld.sock.

  3. Once '2' has been done, restart the MySQL service by entering service mysql restart or /etc/init.d/mysql restart.

After going through the above steps, my issue was solved. I rarely have this issue, and there is probably a better way, so by all means provide constructive feedback if need be :).

Filename too long in Git for Windows

You could also try to enable long file paths.

If you run Windows 10 Home Edition you could change your Registry to enable long paths.

Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem in regedit and then set LongPathsEnabled to 1.

If you have Windows 10 Pro or Enterprise you could also use Local Group Policies.

Go to Computer Configuration ? Administrative Templates ? System ? Filesystem in gpedit.msc, open Enable Win32 long paths and set it to Enabled.

Rails: How do I create a default value for attributes in Rails activerecord's model?

As I see it, there are two problems that need addressing when needing a default value.

  1. You need the value present when a new object is initialized. Using after_initialize is not suitable because, as stated, it will be called during calls to #find which will lead to a performance hit.
  2. You need to persist the default value when saved

Here is my solution:

# the reader providers a default if nil
# but this wont work when saved
def status
  read_attribute(:status) || "P"
end

# so, define a before_validation callback
before_validation :set_defaults
protected
def set_defaults
  # if a non-default status has been assigned, it will remain
  # if no value has been assigned, the reader will return the default and assign it
  # this keeps the default logic DRY
  status = status
end

I'd love to know why people think of this approach.

How to delete a localStorage item when the browser window/tab is closed?

You can make use of the beforeunload event in JavaScript.

Using vanilla JavaScript you could do something like:

window.onbeforeunload = function() {
  localStorage.removeItem(key);
  return '';
};

That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action. I hope that solves your problem.

NOTE: The onbeforeunload method should return a string.

Removing character in list of strings

Beside using loop and for comprehension, you could also use map

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst

What is the best way to iterate over a dictionary?

In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt which enables the following:

for (int index = 0; index < dictionary.Count; index++) {
  var item = dictionary.ElementAt(index);
  var itemKey = item.Key;
  var itemValue = item.Value;
}

Styling the arrow on bootstrap tooltips

For styling each directional arrows(left, right,top and bottom), we have to select each arrow using CSS attribute selector and then style them individually.

Trick: Top arrow must have border color only on top side and transparent on other 3 sides. Other directional arrows also need to be styled this way.

click here for Working Jsfiddle Link

Here is the simple CSS,

.tooltip-inner { background-color:#8447cf;}

[data-placement="top"] + .tooltip > .tooltip-arrow { border-top-color: #8447cf;}

[data-placement="right"] + .tooltip > .tooltip-arrow { border-right-color: #8447cf;}

[data-placement="bottom"] + .tooltip > .tooltip-arrow {border-bottom-color: #8447cf;}

[data-placement="left"] + .tooltip > .tooltip-arrow {border-left-color: #8447cf; }

New features in java 7

In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.

Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.

PHP sessions that have already been started

If you want a new one, then do session_destroy() before starting it. To check if its set before starting it, call session_status() :

$status = session_status();
if($status == PHP_SESSION_NONE){
    //There is no active session
    session_start();
}else
if($status == PHP_SESSION_DISABLED){
    //Sessions are not available
}else
if($status == PHP_SESSION_ACTIVE){
    //Destroy current and start new one
    session_destroy();
    session_start();
}

I would avoid checking the global $_SESSION instead of I am calling the session_status() method since PHP implemented this function explicitly to:

Expose session status via new function, session_status This is for (PHP >=5.4.0)

How to get the excel file name / path in VBA

ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.

If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.

Using android.support.v7.widget.CardView in my project (Eclipse)

https://github.com/yongjhih/CardView

A CardView v7 eclipse project. (from sdk/extras/android/m2repository/com/android/support/cardview-v7)

The project was built by steps:

cp {sdk}/extras/android/m2repository/com/android/support/cardview-v7/21.0.0-rc1/cardview-v7-21.0.0-rc1.aar cardview-v7-21.0.0-rc1.zip
unzip cardview-v7-21.0.0-rc1.zip
mkdir libs/
mv classes.jar libs/cardview-v7-21.0.0-rc1.jar

How to pop an alert message box using PHP?

See this example :

<?php
echo "<div id='div1'>text</div>"
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/jquery1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#div1').click(function () {
                alert('I clicked');
            });
        });
</script>
</head>
<body>

</body>
</html>

How to deserialize JS date using Jackson?

This works for me - i am using jackson 2.0.4

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.

stop:

schtasks /end /s <machine name> /tn <task name>

start:

schtasks /run /s <machine name> /tn <task name>


C:\>schtasks /?

SCHTASKS /parameter [arguments]

Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

Examples:
    SCHTASKS
    SCHTASKS /?
    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

ReactJS SyntheticEvent stopPropagation() only works with React events?

React 17 delegates events to root instead of document, which might solve the problem. More details here.

Node.js - SyntaxError: Unexpected token import

Error: SyntaxError: Unexpected token import or SyntaxError: Unexpected token export


Solution: Change all your imports as example

const express               = require('express');
const webpack               = require('webpack');
const path                  = require('path');
const config                = require('../webpack.config.dev');
const open                  = require('open');

And also change your export default = foo; to module.exports = foo;

How to debug external class library projects in visual studio?

I was having a similar issue as my breakpoints in project(B) were not being hit. My solution was to rebuild project(B) then debug project(A) as the dlls needed to be updated.

Visual studio should allow you to debug into an external library.

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

Try adding this:

$mail->SMTPAuth   = true;
$mail->SMTPSecure = "tls";

By looking at your debug logs, you can notice that the failing PhpMailer log shows this:

(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)

While your successful PEAR log shows this:

DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead

My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.

Sort array by value alphabetically php

Note that sort() operates on the array in place, so you only need to call

sort($a);
doSomething($a);

This will not work;

$a = sort($a);
doSomething($a);

How to get item count from DynamoDB?

Replace the table name and use the below query to get the data on your local environment:

aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT" --endpoint-url http://localhost:8000

Replace the table name and remove the endpoint url to get the data on production environment

aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT"

How to create id with AUTO_INCREMENT on Oracle?

FUNCTION UNIQUE2(
 seq IN NUMBER
) RETURN VARCHAR2
AS
 i NUMBER := seq;
 s VARCHAR2(9);
 r NUMBER(2,0);
BEGIN
  WHILE i > 0 LOOP
    r := MOD( i, 36 );
    i := ( i - r ) / 36;
    IF ( r < 10 ) THEN
      s := TO_CHAR(r) || s;
    ELSE
      s := CHR( 55 + r ) || s;
    END IF;
  END LOOP;
  RETURN 'ID'||LPAD( s, 14, '0' );
END;

Spaces in URLs?

The information there is I think partially correct:

That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.

As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the + is defined, though %20 is standard.

grep a file, but show several surrounding lines?

grep astring myfile -A 5 -B 5

That will grep "myfile" for "astring", and show 5 lines before and after each match

How do I implement basic "Long Polling"?

Thanks for the code, dbr. Just a small typo in long_poller.htm around the line

1000 /* ..after 1 seconds */

I think it should be

"1000"); /* ..after 1 seconds */

for it to work.

For those interested, I tried a Django equivalent. Start a new Django project, say lp for long polling:

django-admin.py startproject lp

Call the app msgsrv for message server:

python manage.py startapp msgsrv

Add the following lines to settings.py to have a templates directory:

import os.path
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (
    os.path.join(PROJECT_DIR, 'templates'),
)

Define your URL patterns in urls.py as such:

from django.views.generic.simple import direct_to_template
from lp.msgsrv.views import retmsg

urlpatterns = patterns('',
    (r'^msgsrv\.php$', retmsg),
    (r'^long_poller\.htm$', direct_to_template, {'template': 'long_poller.htm'}),
)

And msgsrv/views.py should look like:

from random import randint
from time import sleep
from django.http import HttpResponse, HttpResponseNotFound

def retmsg(request):
    if randint(1,3) == 1:
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:
        sleep(randint(2,10))
        return HttpResponse('Hi! Have a random number: %s' % str(randint(1,10)))

Lastly, templates/long_poller.htm should be the same as above with typo corrected. Hope this helps.

How to load a model from an HDF5 file in Keras?

See the following sample code on how to Build a basic Keras Neural Net Model, save Model (JSON) & Weights (HDF5) and load them:

# create model
model = Sequential()
model.add(Dense(X.shape[1], input_dim=X.shape[1], activation='relu')) #Input Layer
model.add(Dense(X.shape[1], activation='relu')) #Hidden Layer
model.add(Dense(output_dim, activation='softmax')) #Output Layer

# Compile & Fit model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X,Y,nb_epoch=5,batch_size=100,verbose=1)    

# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))

# serialize weights to HDF5
model.save_weights("Data/model.h5")
print("Saved model to disk")

# load json and create model
json_file = open('Data/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("Data/model.h5")
print("Loaded model from disk")

# evaluate loaded model on test data 
# Define X_test & Y_test data first
loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
score = loaded_model.evaluate(X_test, Y_test, verbose=0)
print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

How to install Selenium WebDriver on Mac OS

Install

If you use homebrew (which I recommend), you can install selenium using:

brew install selenium-server-standalone

Running

updated -port port_number

To run selenium, do: selenium-server -port 4444

For more options: selenium-server -help

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).