Programs & Examples On #User defined fields

Django - Did you forget to register or load this tag?

For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword

{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

For other versions use static

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

Also you have to check that you defined STATIC_URL in setting.py

At last, make sure the static files exist in the defined folder

How to make HTML Text unselectable

No one here posted an answer with all of the correct CSS variations, so here it is:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

How do I get the current date in Cocoa

You need to do something along the lines of the following:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSLog(@"%d", [components hour]);

And so on.

&& (AND) and || (OR) in IF statements

Java has 5 different boolean compare operators: &, &&, |, ||, ^

& and && are "and" operators, | and || "or" operators, ^ is "xor"

The single ones will check every parameter, regardless of the values, before checking the values of the parameters. The double ones will first check the left parameter and its value and if true (||) or false (&&) leave the second one untouched. Sound compilcated? An easy example should make it clear:

Given for all examples:

 String aString = null;

AND:

 if (aString != null & aString.equals("lala"))

Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.

 if (aString != null && aString.equals("lala"))

The first parameter is checked and it returns false, so the second paramter won't be checked, because the result is false anyway.

The same for OR:

 if (aString == null | !aString.equals("lala"))

Will raise NullPointerException, too.

 if (aString == null || !aString.equals("lala"))

The first parameter is checked and it returns true, so the second paramter won't be checked, because the result is true anyway.

XOR can't be optimized, because it depends on both parameters.

How to set zoom level in google map

Your code below is zooming the map to fit the specified bounds:

addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);

If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  bounds.extend(pt);
}

If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.

If you will only ever have one marker, don't use fitBounds. Call setCenter, setZoom with the marker position and your desired zoom level.

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  map.setCenter(pt);
  map.setZoom(your desired zoom);
}

_x000D_
_x000D_
html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
_x000D_
<html>

<head>
  <script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
  <script type="text/javascript">
    var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
    var center = null;
    var map = null;
    var currentPopup;
    var bounds = new google.maps.LatLngBounds();

    function addMarker(lat, lng, info) {
      var pt = new google.maps.LatLng(lat, lng);
      map.setCenter(pt);
      map.setZoom(5);
      var marker = new google.maps.Marker({
        position: pt,
        icon: icon,
        map: map
      });
      var popup = new google.maps.InfoWindow({
        content: info,
        maxWidth: 300
      });
      google.maps.event.addListener(marker, "click", function() {
        if (currentPopup != null) {
          currentPopup.close();
          currentPopup = null;
        }
        popup.open(map, marker);
        currentPopup = popup;
      });
      google.maps.event.addListener(popup, "closeclick", function() {
        map.panTo(center);
        currentPopup = null;
      });
    }

    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
        },
        navigationControl: true,
        navigationControlOptions: {
          style: google.maps.NavigationControlStyle.SMALL
        }
      });
      addMarker(27.703402, 85.311668, 'New Road');
      // center = bounds.getCenter();
      // map.fitBounds(bounds);

    }
  </script>
</head>

<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
  <div id="map"></div>
</body>

</html>
_x000D_
_x000D_
_x000D_

How to change theme for AlertDialog

I guess it cannot be done. At least not with the Builder. I'm working with 1.6 and the Implementation in Builder.create() is:

public AlertDialog create() {
    final AlertDialog dialog = new AlertDialog(P.mContext);
    P.apply(dialog.mAlert);
    [...]
}

which calls the "not-theme-aware" constructor of AlertDialog, which looks like this:

protected AlertDialog(Context context) {
    this(context, com.android.internal.R.style.Theme_Dialog_Alert);
}

There is a second constructor in AlertDialog for changing themes:

protected AlertDialog(Context context, int theme) {
    super(context, theme);
    [...]
}

that the Builder just doesn't call.

If the Dialog is pretty generic anyway, I'd try writing a subclass of AlertDialog, calling the second constructor and use that class instead of the Builder-mechanism.

Most efficient way to prepend a value to an array

If you are prepending an array to the front of another array, it is more efficient to just use concat. So:

var newArray = values.concat(oldArray);

But this will still be O(N) in the size of oldArray. Still, it is more efficient than manually iterating over oldArray. Also, depending on the details, it may help you, because if you are going to prepend many values, it's better to put them into an array first and then concat oldArray on the end, rather than prepending each one individually.

There's no way to do better than O(N) in the size of oldArray, because arrays are stored in contiguous memory with the first element in a fixed position. If you want to insert before the first element, you need to move all the other elements. If you need a way around this, do what @GWW said and use a linked list, or a different data structure.

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

This worked for me.

You need to run it twice once for globals followed by locals

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

Automatically start a Windows Service on install

How about following commands?

net start "<service name>"
net stop "<service name>"

Develop Android app using C#

There are indeed C# compilers for Android available. Even though I prefer developing Android Apps in Java, I can recommend MonoForAndroid. You find more information on http://xamarin.com/monoforandroid

How can I mark a foreign key constraint using Hibernate annotations?

@JoinColumn(name="reference_column_name") annotation can be used above that property or field of class that is being referenced from some other entity.

C# SQL Server - Passing a list to a stored procedure

If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

What's the difference between a word and byte?

Whatever the terminology present in datasheets and compilers, a 'Byte' is eight bits. Let's not try to confuse enquirers and generalities with the more obscure exceptions, particularly as the word 'Byte' comes from the expression "By Eight". I've worked in the semiconductor/electronics industry for over thirty years and not once known 'Byte' used to express anything more than eight bits.

How can I limit the visible options in an HTML <select> dropdown?

You can try this

_x000D_
_x000D_
<select name="select1" onmousedown="if(this.options.length>8){this.size=8;}"  onchange='this.size=0;' onblur="this.size=0;">_x000D_
             <option value="1">This is select number 1</option>_x000D_
             <option value="2">This is select number 2</option>_x000D_
             <option value="3">This is select number 3</option>_x000D_
             <option value="4">This is select number 4</option>_x000D_
             <option value="5">This is select number 5</option>_x000D_
             <option value="6">This is select number 6</option>_x000D_
             <option value="7">This is select number 7</option>_x000D_
             <option value="8">This is select number 8</option>_x000D_
             <option value="9">This is select number 9</option>_x000D_
             <option value="10">This is select number 10</option>_x000D_
             <option value="11">This is select number 11</option>_x000D_
             <option value="12">This is select number 12</option>_x000D_
           </select>
_x000D_
_x000D_
_x000D_

It worked for me

Adding external library in Android studio

Adding library in Android studio 2.1

Just Go to project -> then it has some android,package ,test ,project view

Just change it to Project View

under the app->lib folder you can directly copy paste the lib and do android synchronize it. That's it

How can I pass a list as a command-line argument with argparse?

Additionally to nargs, you might want to use choices if you know the list in advance:

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

How to randomize Excel rows

I usually do as you describe:
Add a separate column with a random value (=RAND()) and then perform a sort on that column.

Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.

Spring Boot - Loading Initial Data

You're almost there!

@Component
public class DataLoader implements CommandLineRunner {

    private UserRepository userRepository;

    public DataLoader(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public void run(String... args) throws Exception {
         LoadUsers()
    }

    private void LoadUsers() {
        userRepository.save(new User("lala", "lala", "lala"));
    }
}

Convert PDF to PNG using ImageMagick

when you set the density to 96, doesn't it look good?

when i tried it i saw that saving as jpg resulted with better quality, but larger file size

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

If you want to ignore the certificate all together then take a look at the answer here: Ignore self-signed ssl cert using Jersey Client

Although this will make your app vulnerable to man-in-the-middle attacks.

Or, try adding the cert to your java store as a trusted cert. This site may be helpful. http://blog.icodejava.com/tag/get-public-key-of-ssl-certificate-in-java/

Here's another thread showing how to add a cert to your store. Java SSL connect, add server cert to keystore programmatically

The key is:

KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(someCert);
ks.setEntry("someAlias", newEntry, null);

How to set timeout for a line of c# code

You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan):

using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");

Dropping connected users in Oracle database

Issue has been fixed using below procedure :

DECLARE
  v_user_exists NUMBER;
  user_name CONSTANT varchar2(20) := 'SCOTT';
BEGIN
  LOOP
    FOR c IN (SELECT s.sid, s.serial# FROM v$session s WHERE upper(s.username) = user_name)
    LOOP
      EXECUTE IMMEDIATE
        'alter system kill session ''' || c.sid || ',' || c.serial# || ''' IMMEDIATE';
    END LOOP;
    BEGIN
      EXECUTE IMMEDIATE 'drop user ' || user_name || ' cascade';
      EXCEPTION WHEN OTHERS THEN
      IF (SQLCODE = -1940) THEN
        NULL;
      ELSE
        RAISE;
      END IF;
    END;
    BEGIN
      SELECT COUNT(*) INTO v_user_exists FROM dba_users WHERE username = user_name;
      EXIT WHEN v_user_exists = 0;
    END;
  END LOOP;
END;
/

using stored procedure in entity framework

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

Hadoop cluster setup - java.net.ConnectException: Connection refused

Your issue is a very interesting one. Hadoop setup could be frustrating some time due to the complexity of the system and many moving parts involved. I think the issue you faced is definitely a firewall one. My hadoop cluster has similar setup. With a firewall rule added with command:

 sudo iptables -A INPUT -p tcp --dport 9000 -j REJECT

I'm able to see the exact issue:

15/03/02 23:46:10 INFO client.RMProxy: Connecting to ResourceManager at  /0.0.0.0:8032
java.net.ConnectException: Call From mybox/127.0.1.1 to localhost:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

You can verify your firewall settings with command:

/usr/local/hadoop/etc$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
REJECT     tcp  --  anywhere             anywhere             tcp dpt:9000 reject-with icmp-port-unreachable

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination   

Once the suspicious rule is identified, it could be deleted with a command like:

 sudo iptables -D INPUT -p tcp --dport 9000 -j REJECT 

Now, the connection should go through.

Visual Studio : short cut Key : Duplicate Line

I use application link:AutoHotkey with below code saved in CommentDuplikateSaveClipboard.ahk file. You can edit/remove shortcuts it is easy.
I have link to this file "Shortcut to CommentDuplikateSaveClipboard.ahk" in Autostart in windows.
This script protect your clipboard.
If you are more curious you would add shortcuts to thisable/enable script.
I sometimes use very impressive Multi Clipboard script to easy handle with many clips saved on disk and use with CTRL+C,X,V to copy,paste,cut,next,previous,delete this,delete all.

;CommentDuplikateSaveClipboard.ahk

!c:: ; Alt+C === Duplicate Line
^d:: ; Ctrl+D
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{CTRLDOWN}c{CTRLUP}{END}{ENTER}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return

!x:: ; Alt+X === Comment Duplicate Line
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{CTRLDOWN}c{CTRLUP}{LEFT}//{END}{ENTER}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return

!z:: ; Alt+Z === Del uncomment  Line
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{DEL}{HOME}{DEL}{DEL}
Clipboard := ClipSaved
ClipSaved =
return

!d:: ; Alt+D === Delete line
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{DEL}
return

!s:: ; Alt+S === Swap lines
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{CTRLDOWN}x{CTRLUP}{UP}{END}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return

!a:: ; Alt+A === Comment this line, uncomment above
Send, {END}{HOME}//{UP}{HOME}{DEL}{DEL}
return

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

JSP : JSTL's <c:out> tag

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

How to prevent robots from automatically filling up a form?

There is a tutorial about this on the JQuery site. Although it's JQuery the idea is framework independent.

If JavaScript isn't available then you may need to fall back to CAPTCHA type approach.

Remove ListView items in Android

Try this code, it works for me.

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.remove(position);
     adapter.notifyDataSetChanged();
  }
}

How to compare two dates?

For calculating days in two dates difference, can be done like below:

import datetime
import math

issuedate = datetime(2019,5,9)   #calculate the issue datetime
current_date = datetime.datetime.now() #calculate the current datetime
diff_date = current_date - issuedate #//calculate the date difference with time also
amount = fine  #you want change

if diff_date.total_seconds() > 0.0:   #its matching your condition
    days = math.ceil(diff_date.total_seconds()/86400)  #calculate days (in 
    one day 86400 seconds)
    deductable_amount = round(amount,2)*days #calclulated fine for all days

Becuase if one second is more with the due date then we have to charge

How to send POST request in JSON using HTTPClient in Android?

There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.

/**
 * This method is used to process GET requests to the server.
 * 
 * @param url 
 * @return String
 * @throws IOException
 */
public static String connect(String url) throws IOException {

    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    try {

        response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            //instream.close();
        }
    } 
    catch (ClientProtocolException e) {
        Utilities.showDLog("connect","ClientProtocolException:-"+e);
    } catch (IOException e) {
        Utilities.showDLog("connect","IOException:-"+e); 
    }
    return result;
}


 /**
 * This method is used to send POST requests to the server.
 * 
 * @param URL
 * @param paramenter
 * @return result of server response
 */
static public String postHTPPRequest(String URL, String paramenter) {       

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 60*1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 60*1000;

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(URL);
    httppost.setHeader("Content-Type", "application/json");
    try {
        if (paramenter != null) {
            StringEntity tmp = null;
            tmp = new StringEntity(paramenter, "UTF-8");
            httppost.setEntity(tmp);
        }
        HttpResponse httpResponse = null;
        httpResponse = httpclient.execute(httppost);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            InputStream input = null;
            input = entity.getContent();
            String res = convertStreamToString(input);
            return res;
        }
    } 
     catch (Exception e) {
        System.out.print(e.toString());
    }
    return null;
}

How to make HTML code inactive with comments

Reason of comments:

  1. Comment out elements temporarily rather than removing them, especially if they've been left unfinished.
  2. Write notes or reminders to yourself inside your actual HTML documents.
  3. Create notes for other scripting languages like JavaScript which requires them

HTML Comments

<!-- Everything is invisible  -->

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

How to print a float with 2 decimal places in Java?

OK - str to float.

package test;

import java.text.DecimalFormat;

public class TestPtz {
  public static void main(String[] args) {
    String preset0 = "0.09,0.20,0.09,0.07";
    String[] thisto = preset0.split(",");    
    float a = (Float.valueOf(thisto[0])).floatValue();
    System.out.println("[Original]: " + a);   
    a = (float) (a + 0.01);

    // Part 1 - for display / debug
    System.out.printf("[Local]: %.2f \n", a);
    // Part 2 - when value requires to be send as it is
    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println("[Remote]: " + df.format(a));

  }
}

Output:

run:
[Original]: 0.09
[Local]: 0.10 
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)

Adding the "Clear" Button to an iPhone UITextField

Swift 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

or even shorter:

textField.clearButtonMode = .whileEditing

How to detect tableView cell touched or clicked in swift

This worked good for me:

_x000D_
_x000D_
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {_x000D_
        print("section: \(indexPath.section)")_x000D_
        print("row: \(indexPath.row)")_x000D_
    }
_x000D_
_x000D_
_x000D_

The output should be:

section: 0
row: 0

How to read GET data from a URL using JavaScript?

Try like this.. Eg : www.example.com?id=1

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.search);
    return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('id'));

Hope it helps. :)

How to insert pandas dataframe via mysqldb into database?

Python 2 + 3

Prerequesites

  • Pandas
  • MySQL server
  • sqlalchemy
  • pymysql: pure python mysql client

Code

from pandas.io import sql
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
                       .format(user="root",
                               pw="your_password",
                               db="pandas"))
df.to_sql(con=engine, name='table_name', if_exists='replace')

How to reference static assets within vue javascript

It works for me by using require syntax like this:

$('.eventSlick').slick({
    dots: true,
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: false,
    autoplaySpeed: 2000,
    arrows: true,
    draggable: false,
    prevArrow: '<button type="button" data-role="none" class="slick-prev"><img src="' + require("@/assets/img/icon/Arrow_Left.svg")+'"></button>',

Hibernate table not mapped error in HQL query

I had same problem , instead @Entity I used following code for getting records

    List<Map<String, Object>> list = null;
            list = incidentHibernateTemplate.execute(new HibernateCallback<List<Map<String, Object>>>() {

            @Override
            public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery("SELECT * from table where appcode = :app");
                    query.setParameter("app", apptype);
                query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                return query.list();

                }
            });

I used following code for update

private @Autowired HibernateTemplate incidentHibernateTemplate;
Integer updateCount = 0;

    updateCount = incidentHibernateTemplate.execute((Session session) -> {
        Query<?> query = session
                    .createSQLQuery("UPDATE  tablename SET key = :apiurl, data_mode = :mode WHERE apiname= :api ");
          query.setParameter("apiurl", url);
          query.setParameter("api", api);
          query.setParameter("mode", mode);
            return query.executeUpdate();
        }
    );

How to find the socket buffer size of linux

Whilst, as has been pointed out, it is possible to see the current default socket buffer sizes in /proc, it is also possible to check them using sysctl (Note: Whilst the name includes ipv4 these sizes also apply to ipv6 sockets - the ipv6 tcp_v6_init_sock() code just calls the ipv4 tcp_init_sock() function):

 sysctl net.ipv4.tcp_rmem
 sysctl net.ipv4.tcp_wmem

However, the default socket buffers are just set when the sock is initialised but the kernel then dynamically sizes them (unless set using setsockopt() with SO_SNDBUF). The actual size of the buffers for currently open sockets may be inspected using the ss command (part of the iproute package), which can also provide a bunch more info on sockets like congestion control parameter etc. E.g. To list the currently open TCP (t option) sockets and associated memory (m) information:

ss -tm

Here's some example output:

State       Recv-Q Send-Q        Local Address:Port        Peer Address:Port
ESTAB       0      0             192.168.56.102:ssh        192.168.56.1:56328
skmem:(r0,rb369280,t0,tb87040,f0,w0,o0,bl0,d0)

Here's a brief explanation of skmem (socket memory) - for more info you'll need to look at the kernel sources (e.g. sock.h):

r:sk_rmem_alloc
rb:sk_rcvbuf          # current receive buffer size
t:sk_wmem_alloc
tb:sk_sndbuf          # current transmit buffer size
f:sk_forward_alloc
w:sk_wmem_queued      # persistent transmit queue size
o:sk_omem_alloc
bl:sk_backlog
d:sk_drops

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Windows Explorer "Command Prompt Here"

If that's so bothering, you could try to switch to windows explorer alternative like freecommander which has a toolbar button for that purpose.

How to get the last day of the month?

In Python 3.7 there is the undocumented calendar.monthlen(year, month) function:

>>> calendar.monthlen(2002, 1)
31
>>> calendar.monthlen(2008, 2)
29
>>> calendar.monthlen(2100, 2)
28

It is equivalent to the documented calendar.monthrange(year, month)[1] call.

IE6/IE7 css border on select element

As far as I know, it's not possible in IE because it uses the OS component.

Here is a link where the control is replaced, but I don't know if thats what you want to do.

Edit: The link is broken I'm dumping the content

<select> Something New, Part 1

By Aaron Gustafson

So you've built a beautiful, standards-compliant site utilizing the latest and greatest CSS techniques. You've mastered control of styling every element, but in the back of your mind, a little voice is nagging you about how ugly your <select>s are. Well, today we're going to explore a way to silence that little voice and truly complete our designs. With a little DOM scripting and some creative CSS, you too can make your <select>s beautiful… and you won't have to sacrifice accessibility, usability or graceful degradation.

The Problem

We all know the <select> is just plain ugly. In fact, many try to limit its use to avoid its classic web circa 1994 inset borders. We should not avoid using the <select> though--it is an important part of the current form toolset; we should embrace it. That said, some creative thinking can improve it.

The <select>

We'll use a simple for our example:

<select id="something" name="something">
  <option value="1">This is option 1</option>
  <option value="2">This is option 2</option>
  <option value="3">This is option 3</option>
  <option value="4">This is option 4</option>
  <option value="5">This is option 5</option>
</select>

[Note: It is implied that this <select> is in the context of a complete form.]

So we have five <option>s within a <select>. This <select> has a uniquely assigned id of "something." Depending on the browser/platform you're viewing it on, your <select> likely looks roughly like this:

A <select> as rendered in Windows XP/Firefox 1.0.2.
(source: easy-designs.net)

or this

A <select> as rendered in Mac OSX/Safari 1.2.
(source: easy-designs.net)

Let's say we want to make it look a little more modern, perhaps like this:

Our concept of a nicely-styled <select>.
(source: easy-designs.net)

So how do we do it? Keeping the basic <select> is not an option. Apart from basic background color, font and color adjustments, you don't really have a lot of control over the .

However, we can mimic the superb functionality of a <select> in a new form control without sacrificing semantics, usability or accessibility. In order to do that, we need to examine the nature of a <select>.

A <select> is, essentially, an unordered list of choices in which you can choose a single value to submit along with the rest of a form. So, in essence, it's a <ul> on steroids. Continuing with that line of thinking, we can replace the <select> with an unordered list, as long as we give it some enhanced functionality. As <ul>s can be styled in a myriad of different ways, we're almost home free. Now the questions becomes "how to ensure that we maintain the functionality of the <select> when using a <ul>?" In other words, how do we submit the correct value along with the form, if we are no longer using a form control?

The solution

Enter the DOM. The final step in the process is making the <ul> function/feel like a <select>, and we can accomplish that with JavaScript/ECMA Script and a little clever CSS. Here is the basic list of requirements we need to have a functional faux <select>:

  • click the list to open it,
  • click on list items to change the value assigned & close the list,
  • show the default value when nothing is selected, and
  • show the chosen list item when something is selected.

With this plan, we can begin to tackle each part in succession.

Building the list

So first we need to collect all of the attributes and s out of the and rebuild it as a . We accomplish this by running the following JS:

function selectReplacement(obj) {
  var ul = document.createElement('ul');
  ul.className = 'selectReplacement';
  // collect our object's options
  var opts = obj.options;
  // iterate through them, creating <li>s
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    ul.appendChild(li);
  }
  // add the ul to the form
  obj.parentNode.appendChild(ul);
}

You might be thinking "now what happens if there is a selected <option> already?" We can account for this by adding another loop before we create the <li>s to look for the selected <option>, and then store that value in order to class our selected <li> as "selected":

…
  var opts = obj.options;
  // check for the selected option (default to the first option)
  for (var i=0; i<opts.length; i++) {
    var selectedOpt;
    if (opts[i].selected) {
      selectedOpt = i;
      break; // we found the selected option, leave the loop
    } else {
      selectedOpt = 0;
    }
  }
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    if (i == selectedOpt) {
      li.className = 'selected';
    }
    ul.appendChild(li);
…

[Note: From here on out, option 5 will be selected, to demonstrate this functionality.]

Now, we can run this function on every <select> on the page (in our case, one) with the following:

function setForm() {
  var s = document.getElementsByTagName('select');
  for (var i=0; i<s.length; i++) {
    selectReplacement(s[i]);
  }
}
window.onload = function() {
  setForm();
}

We are nearly there; let's add some style.

Some clever CSS

I don't know about you, but I am a huge fan of CSS dropdowns (especially the Suckerfish variety). I've been working with them for some time now and it finally dawned on me that a <select> is pretty much like a dropdown menu, albeit with a little more going on under the hood. Why not apply the same stylistic theory to our faux-<select>? The basic style goes something like this:

ul.selectReplacement {
  margin: 0;
  padding: 0;
  height: 1.65em;
  width: 300px;
}
ul.selectReplacement li {
  background: #cf5a5a;
  color: #fff;
  cursor: pointer;
  display: none;
  font-size: 11px;
  line-height: 1.7em;
  list-style: none;
  margin: 0;
  padding: 1px 12px;
  width: 276px;
}
ul.selectOpen li {
  display: block;
}
ul.selectOpen li:hover {
  background: #9e0000;
  color: #fff;
}

Now, to handle the "selected" list item, we need to get a little craftier:

ul.selectOpen li {
  display: block;
}
ul.selectReplacement li.selected {
  color: #fff;
  display: block;
}
ul.selectOpen li.selected {
  background: #9e0000;
  display: block;
}
ul.selectOpen li:hover,
ul.selectOpen li.selected:hover {
  background: #9e0000;
  color: #fff;
}

Notice that we are not using the :hover pseudo-class for the <ul> to make it open, instead we are class-ing it as "selectOpen". The reason for this is two-fold:

  1. CSS is for presentation, not behavior; and
  2. we want our faux-<select> behave like a real <select>, we need the list to open in an onclick event and not on a simple mouse-over.

To implement this, we can take what we learned from Suckerfish and apply it to our own JavaScript by dynamically assigning and removing this class in ``onclickevents for the list items. To do this right, we will need the ability to change theonclick` events for each list item on the fly to switch between the following two actions:

  1. show the complete faux-<select> when clicking the selected/default option when the list is collapsed; and
  2. "select" a list item when it is clicked & collapse the faux-<select>.

We will create a function called selectMe() to handle the reassignment of the "selected" class, reassignment of the onclick events for the list items, and the collapsing of the faux-<select>:

As the original Suckerfish taught us, IE will not recognize a hover state on anything apart from an <a>, so we need to account for that by augmenting some of our code with what we learned from them. We can attach onmouseover and onmouseout events to the "selectReplacement" class-ed <ul> and its <li>s:

function selectReplacement(obj) {
  …
  // create list for styling
  var ul = document.createElement('ul');
  ul.className = 'selectReplacement';
  if (window.attachEvent) {
    ul.onmouseover = function() {
      ul.className += ' selHover';
    }
    ul.onmouseout = function() {
      ul.className = 
        ul.className.replace(new RegExp(" selHover\\b"), '');
    }
  }
  …
  for (var i=0; i<opts.length; i++) {
    …
    if (i == selectedOpt) {
      li.className = 'selected';
    }
    if (window.attachEvent) {
      li.onmouseover = function() {
        this.className += ' selHover';
      }
      li.onmouseout = function() {
        this.className = 
          this.className.replace(new RegExp(" selHover\\b"), '');
      }
    }
  ul.appendChild(li);
}

Then, we can modify a few selectors in the CSS, to handle the hover for IE:

ul.selectReplacement:hover li,
ul.selectOpen li {
  display: block;
}
ul.selectReplacement li.selected {
  color: #fff;
  display: block;
}
ul.selectReplacement:hover li.selected**,
ul.selectOpen li.selected** {
  background: #9e0000;
  display: block;
}
ul.selectReplacement li:hover,
ul.selectReplacement li.selectOpen,
ul.selectReplacement li.selected:hover {
  background: #9e0000;
  color: #fff;
  cursor: pointer;
}

Now we have a list behaving like a <select>; but we still need a means of changing the selected list item and updating the value of the associated form element.

JavaScript fu

We already have a "selected" class we can apply to our selected list item, but we need a way to go about applying it to a <li> when it is clicked on and removing it from any of its previously "selected" siblings. Here's the JS to accomplish this:

function selectMe(obj) {
  // get the <li>'s siblings
  var lis = obj.parentNode.getElementsByTagName('li');
  // loop through
  for (var i=0; i<lis.length; i++) {
    // not the selected <li>, remove selected class
    if (lis[i] != obj) {
      lis[i].className='';
    } else { // our selected <li>, add selected class
      lis[i].className='selected';
    }
  }
}

[Note: we can use simple className assignment and emptying because we are in complete control of the <li>s. If you (for some reason) needed to assign additional classes to your list items, I recommend modifying the code to append and remove the "selected" class to your className property.]

Finally, we add a little function to set the value of the original <select> (which will be submitted along with the form) when an <li> is clicked:

function setVal(objID, selIndex) {
  var obj = document.getElementById(objID);
  obj.selectedIndex = selIndex;
}

We can then add these functions to the onclick event of our <li>s:

…
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    li.selIndex = opts[i].index;
    li.selectID = obj.id;
    li.onclick = function() {
      setVal(this.selectID, this.selIndex);
      selectMe(this);
    }
    if (i == selectedOpt) {
      li.className = 'selected';
    }
    ul.appendChild(li);
  }
…

There you have it. We have created our functional faux-. As we have not hidden the originalyet, we can [watch how it behaves](files/4.html) as we choose different options from our faux-. Of course, in the final version, we don't want the original to show, so we can hide it byclass`-ing it as "replaced," adding that to the JS here:

function selectReplacement(obj) {
  // append a class to the select
  obj.className += ' replaced';
  // create list for styling
  var ul = document.createElement('ul');
…

Then, add a new CSS rule to hide the

select.replaced {
  display: none;
}

With the application of a few images to finalize the design (link not available) , we are good to go!


And here is another link to someone that says it can't be done.

Switching between GCC and Clang/LLVM using CMake

System wide C++ change on Ubuntu:

sudo apt-get install clang
sudo update-alternatives --config c++

Will print something like this:

  Selection    Path              Priority   Status
------------------------------------------------------------
* 0            /usr/bin/g++       20        auto mode
  1            /usr/bin/clang++   10        manual mode
  2            /usr/bin/g++       20        manual mode

Then just select clang++.

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

This is not the best solve, but if you really don't care it is an easy solution. I simply renamed my class. So I had class Card and I changed it to MyCard.

Bootstrap 4 dropdown with search

As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.

Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).

How to make Sonar ignore some classes for codeCoverage metric?

I am able to achieve the necessary code coverage exclusions by updating jacoco-maven-plugin configuration in pom.xml

<plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.6</version>
                <executions>
                    <execution>
                        <id>pre-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <propertyName>jacocoArgLine</propertyName>
                            <destFile>${project.test.result.directory}/jacoco/jacoco.exec</destFile>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${project.test.result.directory}/jacoco/jacoco.exec</dataFile>
                            <outputDirectory>${project.test.result.directory}/jacoco</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <excludes>
                        <exclude>**/GlobalExceptionHandler*.*</exclude>
                        <exclude>**/ErrorResponse*.*</exclude>
                    </excludes>
                </configuration>
            </plugin>

this configuration excludes the GlobalExceptionHandler.java and ErrorResponse.java in the jacoco coverage.

And the following two lines does the same for sonar coverage .

    <sonar.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.</sonar.exclusions>
        <sonar.coverage.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.* </sonar.coverage.exclusions>

Excel - Shading entire row based on change of value

I had to do something similar for my users, with a small variant that they want to have a running number grouping the similar items. Thought I'd share it here.

  • Make a new column A
  • Assuming the first row of data is in row 2 (row 1 being header), put 1 in A2
  • Assuming your File No is in column B, in the second row (in this case A3) make the formula =IF(B3=B2,A2,A2+1)
  • Fill/copy-paste cell A3 down the column to the last row (be careful not to copy A2 by accident; that will populate all cells with 1)
  • Select the data range
  • In the Home ribbon select Conditional Formatting -> New Rule
  • Choose Use a formula to determine which cells to format
  • In the formula cell, put =MOD($A1, 2)=1 as the formula
  • Click Format, select the Fill tab
  • Select the Background Color you want, then click OK
  • Click OK

enter image description here

Testing whether a value is odd or even

Different way:

var isEven = function(number) {
  // Your code goes here!
  if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};

isEven(69)

How to define a List bean in Spring?

Import the spring util namespace. Then you can define a list bean as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/util
                    http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class.

How do I set ANDROID_SDK_HOME environment variable?

Just set the path to the Android SDK directory

flutter config --android-sdk c:\android\sdk

Only read selected columns

Say the data are in file data.txt, you can use the colClasses argument of read.table() to skip columns. Here the data in the first 7 columns are "integer" and we set the remaining 6 columns to "NULL" indicating they should be skipped

> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)), 
+            header = TRUE)
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

Change "integer" to one of the accepted types as detailed in ?read.table depending on the real type of data.

data.txt looks like this:

$ cat data.txt 
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29

and was created by using

write.table(dat, file = "data.txt", row.names = FALSE)

where dat is

dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L, 
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L, 
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L, 
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr", 
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))

If the number of columns is not known beforehand, the utility function count.fields will read through the file and count the number of fields in each line.

## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))

How to measure elapsed time in Python?

Using time.time to measure execution gives you the overall execution time of your commands including running time spent by other processes on your computer. It is the time the user notices, but is not good if you want to compare different code snippets / algorithms / functions / ...

More information on timeit:

If you want a deeper insight into profiling:

Update: I used http://pythonhosted.org/line_profiler/ a lot during the last year and find it very helpfull and recommend to use it instead of Pythons profile module.

Is there a way to make npm install (the command) to work behind proxy?

On Windows system

Try removing the proxy and registry settings (if already set) and set environment variables on command line via

SET HTTP_PROXY=http://username:password@domain:port
SET HTTPS_PROXY=http://username:password@domain:port

then try to run npm install. By this, you'll not set the proxy in .npmrc but for that session it will work.

Find the unique values in a column and then sort them

Another way is using set data type.

Some characteristic of Sets: Sets are unordered, can include mixed data types, elements in a set cannot be repeated, are mutable.

Solving your question:

df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
sorted(set(df.A))

The answer in List type:

[1, 2, 3, 6, 8]

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How do I get a background location update every n minutes in my iOS application?

On iOS 8/9/10 to make background location update every 5 minutes do the following:

  1. Go to Project -> Capabilities -> Background Modes -> select Location updates

  2. Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)

  3. To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.

I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.

@interface LocationManager () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSDate *lastTimestamp;

@end

@implementation LocationManager

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        LocationManager *instance = sharedInstance;
        instance.locationManager = [CLLocationManager new];
        instance.locationManager.delegate = instance;
        instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // you can use kCLLocationAccuracyHundredMeters to get better battery life
        instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
    });

    return sharedInstance;
}

- (void)startUpdatingLocation
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (status == kCLAuthorizationStatusDenied)
    {
        NSLog(@"Location services are disabled in settings.");
    }
    else
    {
        // for iOS 8
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.locationManager requestAlwaysAuthorization];
        }
        // for iOS 9
        if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
        {
            [self.locationManager setAllowsBackgroundLocationUpdates:YES];
        }

        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *mostRecentLocation = locations.lastObject;
    NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));

    NSDate *now = [NSDate date];
    NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;

    if (!self.lastTimestamp || interval >= 5 * 60)
    {
        self.lastTimestamp = now;
        NSLog(@"Sending current location to web service.");
    }
}

@end

Print multiple arguments in Python

There are many ways to print that.

Let's have a look with another example.

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

The data-toggle attributes in Twitter Bootstrap

Any attribute that starts with data- is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel and other attributes for purposes other than their original intended purposes (rel was often used to hold data for things like advanced tooltips).

In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).

html5doctor has a good article on the data- attribute.

Cycle 2 is another example of extensive use of the data- attribute.

How to retrieve data from a SQL Server database in C#?

To retrieve data from database:

private SqlConnection Conn;
 private void CreateConnection()
 {
    string ConnStr =
    ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
 CreateConnection();
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}

Are PHP short tags acceptable to use?

Because the confusion it can generate with XML declarations. Many people agree with you, though.

An additional concern is the pain it'd generate to code everything with short tags only to find out at the end that the final hosting server has them turned off...

Why is the minidlna database not being refreshed?

In summary, the most reliable way to have MiniDLNA rescan all media files is by issuing the following set of commands:

$ sudo minidlnad -R
$ sudo service minidlna restart

Client-side script to rescan server

However, every so often MiniDLNA will be running on a server. Here is a client-side script to request a rescan on such a server:

#!/usr/bin/env bash
ssh -t server.on.lan 'sudo minidlnad -R && sudo service minidlna restart'

Most efficient way to create a zero filled JavaScript array?

You can check if index exist or not exist, in order to append +1 to it.

this way you don't need a zeros filled array.

EXAMPLE:

var current_year = new Date().getFullYear();
var ages_array = new Array();

for (var i in data) {
    if(data[i]['BirthDate'] != null && data[i]['BirthDate'] != '0000-00-00'){

        var birth = new Date(data[i]['BirthDate']);
        var birth_year = birth.getFullYear();
        var age = current_year - birth_year;

        if(ages_array[age] == null){
            ages_array[age] = 1;
        }else{
            ages_array[age] += 1;
        }

    }
}

console.log(ages_array);

Failed to build gem native extension — Rails install

sudo apt-get install ruby-dev

worked for me

fitting data with numpy

Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

from numpy.polynomial import Polynomial

p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())

p uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

pnormal = p.convert(domain=(-1, 1))

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

Print very long string completely in pandas dataframe

Another easier way to print the whole string is to call values on the dataframe.

df = pd.DataFrame({'one' : ['one', 'two', 
      'This is very long string very long string very long string veryvery long string']})

print(df.values)

The Output will be

[['one']
 ['two']
 ['This is very long string very long string very long string veryvery long string']]

How to find third or n?? maximum salary from salary table?

For n-th highest value

select min(salary) 
from (select salary from(select salary from employee order by salary desc)where rownum<=n);

Global npm install location on windows?

According to: https://docs.npmjs.com/files/folders

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.

prefix Configuration

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary.

The docs might be a little outdated, but they explain why global installs can end up in different directories:

(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"

Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.

This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):

mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm

open a new cmd.exe window and reinstall all global packages.

Explanation (by lineno.):

  1. Create a folder in a sensible location to hold the globals (Microsoft is adamant that you shouldn't write to ProgramFiles, so %PROGRAMDATA% seems like the next logical place.
  2. The directory needs to be on the path, so use setx .. /M to set the system path (under HKEY_LOCAL_MACHINE). This is what requires you to run this in a shell with administrator permissions.
  3. Tell npm to use this new path. (Note: folder isn't visible in %PATH% in this shell, so you must open a new window).

How do I install command line MySQL client on mac?

If you installed from the DMG on a mac, it created a mysql client but did not put it in your user path.

Add this to your .bash_profile:

export PATH="/usr/local/mysql/bin:$PATH

This will let you run mysql from anywhere as you.

Custom Drawable for ProgressBar/ProgressDialog

I'm not sure but in this case you can still go with a complete customized AlertDialog by having a seperate layout file set in the alert dialog and set the animation for your imageview using part of your above code that should also do it!

Int to Char in C#

Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use

string s = Char.ConvertFromUtf32(56);

which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.

Mongoose's find method with $or condition does not work properly

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

Bypass invalid SSL certificate errors when calling web services in .Net

I was having same error using DownloadString; and was able to make it works as below with suggestions on this page

System.Net.WebClient client = new System.Net.WebClient();            
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string sHttpResonse = client.DownloadString(sUrl);

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Asked and answered before...

Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )"

"1" is a non-null expression so it's the same as COUNT(*). The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK) = COUNT(*)

This is a similar myth to EXISTS (SELECT * ... or EXISTS (SELECT 1 ...

And see the ANSI 92 spec, section 6.5, General Rules, case 1

        a) If COUNT(*) is specified, then the result is the cardinality
          of T.

        b) Otherwise, let TX be the single-column table that is the
          result of applying the <value expression> to each row of T
          and eliminating null values. If one or more null values are
          eliminated, then a completion condition is raised: warning-
          null value eliminated in set function.

What's the proper way to "go get" a private repository?

I had a problem with go get using private repository on gitlab from our company. I lost a few minutes trying to find a solution. And I did find this one:

  1. You need to get a private token at:
    https://gitlab.mycompany.com/profile/account

  2. Configure you git to add extra header with your private token:

    $ git config --global http.extraheader "PRIVATE-TOKEN: YOUR_PRIVATE_TOKEN
    
  3. Configure your git to convert requests from http to ssh:

    $ git config --global url."[email protected]:".insteadOf "https://gitlab.mycompany.com/"
    
  4. Finally you can use your go get normally:

    $ go get gitlab.com/company/private_repo
    

How to read a file from jar in Java?

A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.

public static void main(String args[]) {
    String relativeFilePath = "style/someCSSFile.css";
    String zipFilePath = "/someDirectory/someWarFile.war";
    String contents = readZipFile(zipFilePath,relativeFilePath);
    System.out.println(contents);
}

public static String readZipFile(String zipFilePath, String relativeFilePath) {
    try {
        ZipFile zipFile = new ZipFile(zipFilePath);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            // if the entry is not directory and matches relative file then extract it
            if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
                BufferedInputStream bis = new BufferedInputStream(
                        zipFile.getInputStream(entry));
                // Read the file
                    // With Apache Commons I/O
                 String fileContentsStr = IOUtils.toString(bis, "UTF-8");

                    // With Guava
                //String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
                // close the input stream.
                bis.close();
                return fileContentsStr;
            } else {
                continue;
            }
        }
    } catch (IOException e) {
        logger.error("IOError :" + e);
        e.printStackTrace();
    }
    return null;
}

In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

TypeError: module.__init__() takes at most 2 arguments (3 given)

You may also do the following in Python 3.6.1

from Object import Object as Parent

and your class definition to:

class Visitor(Parent):

SQLite select where empty?

You can do this with the following:

int counter = 0;
String sql = "SELECT projectName,Owner " + "FROM Project WHERE Owner= ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, "");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
    counter++;
}
System.out.println(counter);

This will give you the no of rows where the column value is null or blank.

Node.js/Express.js App Only Works on Port 3000

If you are using Nodemon my guess is the PORT 3000 is set in the nodemonConfig. Check if that is the case.

How to trigger HTML button when you press Enter in textbox?

  1. Replace the button with a submit
  2. Be progressive, make sure you have a server side version
  3. Bind your JavaScript to the submit handler of the form, not the click handler of the button

Pressing enter in the field will trigger form submission, and the submit handler will fire.

How can I remove time from date with Moment.js?

The correct way would be to specify the input as per your requirement which will give you more flexibility.

The present definition includes the following

LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A'

You can use any of these or change the input passed into moment().format(). For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY').

Mock a constructor with parameter

With mockito you can use withSettings(), for example if the CounterService required 2 dependencies, you can pass them as a mock:

UserService userService = Mockito.mock(UserService.class); SearchService searchService = Mockito.mock(SearchService.class); CounterService counterService = Mockito.mock(CounterService.class, withSettings().useConstructor(userService, searchService));

DOUBLE vs DECIMAL in MySQL

"are there any issue we should expect from only storing and retreiving a money amount in a DOUBLE column ?"

It sounds like no rounding errors can be produced in your scenario and if there were, they would be truncated by the conversion to BigDecimal.

So I would say no.

However, there is no guarantee that some change in the future will not introduce a problem.

CSS Selector "(A or B) and C"?

Not yet, but there is the experimental :matches() pseudo-class function that does just that:

:matches(.a .b) .c {
  /* stuff goes here */
}

You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :matches(). We just have to wait a little more before using this everywhere (I surely will).

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

use -n parameter to install like for cocoapods:

sudo gem install cocoapods -n /usr/local/bin

Bootstrap 3 Navbar Collapse

Easiest way is to customize bootstrap

find variable:

 @grid-float-breakpoint

which is set to @screen-sm, you can change it according to your needs. Hope it helps!

Why split the <script> tag when writing it with document.write()?

</script> has to be broken up because otherwise it would end the enclosing <script></script> block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

However in practice browsers only end parsing a CDATA script block on an actual </script> close-tag.

In XHTML there is no such special handling for script blocks, so any < (or &) character inside them must be &escaped; like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:

<script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>

Apache Spark: The number of cores vs. the number of executors

Short answer: I think tgbaggio is right. You hit HDFS throughput limits on your executors.

I think the answer here may be a little simpler than some of the recommendations here.

The clue for me is in the cluster network graph. For run 1 the utilization is steady at ~50 M bytes/s. For run 3 the steady utilization is doubled, around 100 M bytes/s.

From the cloudera blog post shared by DzOrd, you can see this important quote:

I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.

So, let's do a few calculations see what performance we expect if that is true.


Run 1: 19 GB, 7 cores, 3 executors

  • 3 executors x 7 threads = 21 threads
  • with 7 cores per executor, we expect limited IO to HDFS (maxes out at ~5 cores)
  • effective throughput ~= 3 executors x 5 threads = 15 threads

Run 3: 4 GB, 2 cores, 12 executors

  • 2 executors x 12 threads = 24 threads
  • 2 cores per executor, so hdfs throughput is ok
  • effective throughput ~= 12 executors x 2 threads = 24 threads

If the job is 100% limited by concurrency (the number of threads). We would expect runtime to be perfectly inversely correlated with the number of threads.

ratio_num_threads = nthread_job1 / nthread_job3 = 15/24 = 0.625
inv_ratio_runtime = 1/(duration_job1 / duration_job3) = 1/(50/31) = 31/50 = 0.62

So ratio_num_threads ~= inv_ratio_runtime, and it looks like we are network limited.

This same effect explains the difference between Run 1 and Run 2.


Run 2: 19 GB, 4 cores, 3 executors

  • 3 executors x 4 threads = 12 threads
  • with 4 cores per executor, ok IO to HDFS
  • effective throughput ~= 3 executors x 4 threads = 12 threads

Comparing the number of effective threads and the runtime:

ratio_num_threads = nthread_job2 / nthread_job1 = 12/15 = 0.8
inv_ratio_runtime = 1/(duration_job2 / duration_job1) = 1/(55/50) = 50/55 = 0.91

It's not as perfect as the last comparison, but we still see a similar drop in performance when we lose threads.

Now for the last bit: why is it the case that we get better performance with more threads, esp. more threads than the number of CPUs?

A good explanation of the difference between parallelism (what we get by dividing up data onto multiple CPUs) and concurrency (what we get when we use multiple threads to do work on a single CPU) is provided in this great post by Rob Pike: Concurrency is not parallelism.

The short explanation is that if a Spark job is interacting with a file system or network the CPU spends a lot of time waiting on communication with those interfaces and not spending a lot of time actually "doing work". By giving those CPUs more than 1 task to work on at a time, they are spending less time waiting and more time working, and you see better performance.

Format date as dd/MM/yyyy using pipes

I am using this Temporary Solution:

import {Pipe, PipeTransform} from "angular2/core";
import {DateFormatter} from 'angular2/src/facade/intl';

@Pipe({
    name: 'dateFormat'
})
export class DateFormat implements PipeTransform {
    transform(value: any, args: string[]): any {
        if (value) {
            var date = value instanceof Date ? value : new Date(value);
            return DateFormatter.format(date, 'pt', 'dd/MM/yyyy');
        }
    }
}

How do I trim leading/trailing whitespace in a standard way?

Here is how I do it. It trims the string in place, so no worry about deallocating a returned string or losing the pointer to an allocated string. It may not be the shortest answer possible, but it should be clear to most readers.

#include <ctype.h>
#include <string.h>
void trim_str(char *s)
{
    const size_t s_len = strlen(s);

    int i;
    for (i = 0; i < s_len; i++)
    {
        if (!isspace( (unsigned char) s[i] )) break;
    }

    if (i == s_len)
    {
        // s is an empty string or contains only space characters

        s[0] = '\0';
    }
    else
    {
        // s contains non-space characters

        const char *non_space_beginning = s + i;

        char *non_space_ending = s + s_len - 1;
        while ( isspace( (unsigned char) *non_space_ending ) ) non_space_ending--;

        size_t trimmed_s_len = non_space_ending - non_space_beginning + 1;

        if (s != non_space_beginning)
        {
            // Non-space characters exist in the beginning of s

            memmove(s, non_space_beginning, trimmed_s_len);
        }

        s[trimmed_s_len] = '\0';
    }
}

What is a Java String's default initial value?

That depends. Is it just a variable (in a method)? Or a class-member?

If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value.

If it's a class-member it will be initialized to null by the VM.

What is this date format? 2011-08-12T20:17:46.384Z

You can use the following example.

    String date = "2011-08-12T20:17:46.384Z";

    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    String outputPattern = "yyyy-MM-dd HH:mm:ss";

    LocalDateTime inputDate = null;
    String outputDate = null;


    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);

    inputDate = LocalDateTime.parse(date, inputFormatter);
    outputDate = outputFormatter.format(inputDate);

    System.out.println("inputDate: " + inputDate);
    System.out.println("outputDate: " + outputDate);

How to execute cmd commands via Java

I found this in forums.oracle.com

Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

You need something like

   String[] command =
    {
        "cmd",
    };
    Process p = Runtime.getRuntime().exec(command);
    new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
    new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
    PrintWriter stdin = new PrintWriter(p.getOutputStream());
    stdin.println("dir c:\\ /A /Q");
    // write any other commands you want here
    stdin.close();
    int returnCode = p.waitFor();
    System.out.println("Return code = " + returnCode);

SyncPipe Class:

class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
      istrm_ = istrm;
      ostrm_ = ostrm;
  }
  public void run() {
      try
      {
          final byte[] buffer = new byte[1024];
          for (int length = 0; (length = istrm_.read(buffer)) != -1; )
          {
              ostrm_.write(buffer, 0, length);
          }
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
  }
  private final OutputStream ostrm_;
  private final InputStream istrm_;
}

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

I ran into this today and got it to work with:

EXECUTE sp_rename N'dbo.table_name.original_field_name', N'new_field_name', 'COLUMN' 

To get this syntax, I followed Martin Smith's advice above - open up the table in design view, rename the column and then click table designer | generate change script. This produced the script below which does the renaming in two steps:

/* To prevent any potential data loss issues, you should review this script in
   detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
EXECUTE sp_rename N'dbo.table_name.original_field_name', N'Tmp_new_field_name_1', COLUMN' 
GO
EXECUTE sp_rename N'dbo.table_name.Tmp_new_field_name_1', N'new_field_name', 'COLUMN' 
GO
ALTER TABLE dbo.table_name SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

How do AX, AH, AL map onto EAX?

| 0000 0001 0010 0011 0100 0101 0110 0111 | ------> EAX

|                     0100 0101 0110 0111 | ------> AX

|                               0110 0111 | ------> AL

|                     0100 0101           | ------> AH

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

Convert Unix timestamp into human readable date using MySQL

Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.

I have an automatically updated last_modified field, defined as:

`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC

SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`

In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.

Run this twice, first without setting the time_zone.

CSS3 selector to find the 2nd div of the same class

Is there a reason that you can't do this via Javascript? My advice would be to target the selectors with a universal rule (.foo) and then parse back over to get the last foo with Javascript and set any additional styling you'll need.

Or as suggested by Stein, just add two classes if you can:

<div class="foo"></div>
<div class="foo last"></div>

.foo {}
.foo.last {}

Maven dependency update on commandline

Simple run your project online i.e mvn clean install . It fetches all the latest dependencies that you mention in your pom.xml and built the project

Why can't I duplicate a slice with `copy()`?

If your slices were of the same size, it would work:

arr := []int{1, 2, 3}
tmp := []int{0, 0, 0}
i := copy(tmp, arr)
fmt.Println(i)
fmt.Println(tmp)
fmt.Println(arr)

Would give:

3
[1 2 3]
[1 2 3]

From "Go Slices: usage and internals":

The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements)

The usual example is:

t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)
s = t

jQuery UI Alert Dialog as a replacement for alert()

There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.

function jAlert2(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": onCloseCallback,
            "Cancel": function() {
          $( this ).dialog( "destroy" );
            }

        },
    });

How to Set AllowOverride all

Plus those upvoted correct answers sometimes same error could be seen because of mismatched and different settings on SSL part of webserver configurations. (Obviously when not using .htaccess file).

How to get a MemoryStream from a Stream in .NET?

I use this combination of extension methods:

    public static Stream Copy(this Stream source)
    {
        if (source == null)
            return null;

        long originalPosition = -1;

        if (source.CanSeek)
            originalPosition = source.Position;

        MemoryStream ms = new MemoryStream();

        try
        {
            Copy(source, ms);

            if (originalPosition > -1)
                ms.Seek(originalPosition, SeekOrigin.Begin);
            else
                ms.Seek(0, SeekOrigin.Begin);

            return ms;
        }
        catch
        {
            ms.Dispose();
            throw;
        }
    }

    public static void Copy(this Stream source, Stream target)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (target == null)
            throw new ArgumentNullException("target");

        long originalSourcePosition = -1;
        int count = 0;
        byte[] buffer = new byte[0x1000];

        if (source.CanSeek)
        {
            originalSourcePosition = source.Position;
            source.Seek(0, SeekOrigin.Begin);
        }

        while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
            target.Write(buffer, 0, count);

        if (originalSourcePosition > -1)
        {
            source.Seek(originalSourcePosition, SeekOrigin.Begin);
        }
    }

Insert data into table with result from another select query

Below is an example of such a query:

INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I know this question is already been answered but for new comers those two solutions may help:

  1. Make sure your gmail is allowing low secure apps to sign in, you can turn it on here: https://www.google.com/settings/security/lesssecureapps.
  2. Change your password.

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

"All I want to do is join the tables and then group all the employees in a particular location together."

It sounds like what you want is for the output of the SQL statement to list every employee in the company, but first all the people in the Anaheim office, then the people in the Buffalo office, then the people in the Cleveland office (A, B, C, get it, obviously I don't know what locations you have).

In that case, lose the GROUP BY statement. All you need is ORDER BY loc.LocationID

Re-render React component when prop changes

A friendly method to use is the following, once prop updates it will automatically rerender component:

render {

let textWhenComponentUpdate = this.props.text 

return (
<View>
  <Text>{textWhenComponentUpdate}</Text>
</View>
)

}

sqlite copy data from one table to another

If you're copying data like that, that probably means your datamodel isn't fully normalized, right? Is it possible to make one list of countries and do a JOIN more?

Instead of a JOIN you could also use virtual tables so you don't have to change the queries in your system.

How to get the innerHTML of selectable jquery element?

The parameter ui has a property called selected which is a reference to the selected dom element, you can call innerHTML on that element.

Your code $('.ui-selected').innerHTML tries to return the innerHTML property of a jQuery wrapper element for a dom element with class ui-selected

$(function () {
    $("#select-image").selectable({
        selected: function (event, ui) {
            var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
            console.log($variable);
        }
    });
});

Demo: Fiddle

How to Parse JSON Array with Gson

To conver in Object Array

Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);

To convert as post type

Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);

To read it as List of objects TypeToken can be used

List<Post> posts=(List<Post>)gson.fromJson(jsonString, 
                     new TypeToken<List<Post>>(){}.getType());

Adb install failure: INSTALL_CANCELED_BY_USER

Faced the same Issue in MI devices and figured out the problem by following these Steps :

1) Go to Setting

2) Click on Additional Settings

3) Click on Developer Options

4) Click toggle of Install via USB to enable it

and the issue will be resolved.

enter image description here

Polynomial time and exponential time

Below are some common Big-O functions while analyzing algorithms.

  • O(1) - constant time
  • O(log(n)) - logarithmic time
  • O((log(n))c) - polylogarithmic time
  • O(n) - linear time
  • O(n2) - quadratic time
  • O(nc) - polynomial time
  • O(cn) - exponential time
  • O(n!) - factorial time

(n = size of input, c = some constant)

Here is the model graph representing Big-O complexity of some functions

graph model

cheers :-)

graph credits http://bigocheatsheet.com/

How can I view array structure in JavaScript with alert()?

pass your js array to the function below and it will do the same as php print_r() function

 alert(print_r(your array));  //call it like this

function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
        var value = arr[item];

        if(typeof(value) == 'object') { //If it is an array,
            dumped_text += level_padding + "'" + item + "' ...\n";
            dumped_text += print_r(value,level+1);
        } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    }
} else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

'IF' in 'SELECT' statement - choose output value based on column values

You can try this also

 SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table

Is the LIKE operator case-sensitive with MSSQL Server?

The like operator takes two strings. These strings have to have compatible collations, which is explained here.

In my opinion, things then get complicated. The following query returns an error saying that the collations are incompatible:

select *
from INFORMATION_SCHEMA.TABLES
where 'abc' COLLATE SQL_Latin1_General_CP1_CI_AS like 'ABC' COLLATE SQL_Latin1_General_CP1_CS_AS

On a random machine here, the default collation is SQL_Latin1_General_CP1_CI_AS. The following query is successful, but returns no rows:

select *
from INFORMATION_SCHEMA.TABLES
where 'abc' like 'ABC' COLLATE SQL_Latin1_General_CP1_CS_AS

The values "abc" and "ABC" do not match in a case-sensitve world.

In other words, there is a difference between having no collation and using the default collation. When one side has no collation, then it is "assigned" an explicit collation from the other side.

(The results are the same when the explicit collation is on the left.)

CSS override rules and specificity

The important needs to be inside the ;

td.rule2 div {     background-color: #ffff00 !important; } 

in fact i believe this should override it

td.rule2 { background-color: #ffff00 !important; } 

Simplest way to do grouped barplot

with ggplot2:

library(ggplot2)
Animals <- read.table(
  header=TRUE, text='Category        Reason Species
1   Decline       Genuine      24
2  Improved       Genuine      16
3  Improved Misclassified      85
4   Decline Misclassified      41
5   Decline     Taxonomic       2
6  Improved     Taxonomic       7
7   Decline       Unclear      41
8  Improved       Unclear     117')

ggplot(Animals, aes(factor(Reason), Species, fill = Category)) + 
  geom_bar(stat="identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1")

Bar Chart

Responsively change div size keeping aspect ratio

That's my solution

<div class="main" style="width: 100%;">
    <div class="container">
        <div class="sizing"></div>
        <div class="content"></div>
    </div>
</div>

.main {
    width: 100%;
}
.container {
    width: 30%;
    float: right;
    position: relative;
}
.sizing {
    width: 100%;
    padding-bottom: 50%;
    visibility: hidden;
}
.content {
    width: 100%;
    height: 100%;
    background-color: red;
    position: absolute;
    margin-top: -50%;
}

http://jsfiddle.net/aG4Fs/3/

Open Popup window using javascript

First point is- showing multiple popups is not desirable in terms of usability.

But you can achieve it by using multiple popup names

var newwindow;
function createPop(url, name)
{    
   newwindow=window.open(url,name,'width=560,height=340,toolbar=0,menubar=0,location=0');  
   if (window.focus) {newwindow.focus()}
}

Better approach will be showing both in a single page in two different iFrames or Divs.

Update:

So I will suggest to create a new tab in the test.aspx page to show the report, instead of replacing the image content and placing the pdf.

What do &lt; and &gt; stand for?

Others have noted the correct answer, but have not clearly explained the all-important reason:

  • why do we need this?

What do < and > stand for?

  • &lt; stands for the < sign. Just remember: lt == less than
  • &gt; stands for the > Just remember: gt == greater than

Why can’t we simply use the < and > characters in HTML?

  • This is because the > and < characters are ‘reserved’ characters in HTML.
  • HTML is a mark up language: The < and > are used to denote the starting and ending of different elements: e.g. <h1> and not for the displaying of the greater than or less than symbols. But what if you wanted to actually display those symbols? You would simply use &lt; and &gt; and the browser will know exactly how to display it.

How do I convert a numpy array to (and display) an image?

Shortest path is to use scipy, like this:

from scipy.misc import toimage
toimage(data).show()

This requires PIL or Pillow to be installed as well.

A similar approach also requiring PIL or Pillow but which may invoke a different viewer is:

from scipy.misc import imshow
imshow(data)

TypeScript and field initializers

Below is a solution that combines a shorter application of Object.assign to more closely model the original C# pattern.

But first, lets review the techniques offered so far, which include:

  1. Copy constructors that accept an object and apply that to Object.assign
  2. A clever Partial<T> trick within the copy constructor
  3. Use of "casting" against a POJO
  4. Leveraging Object.create instead of Object.assign

Of course, each have their pros/cons. Modifying a target class to create a copy constructor may not always be an option. And "casting" loses any functions associated with the target type. Object.create seems less appealing since it requires a rather verbose property descriptor map.

Shortest, General-Purpose Answer

So, here's yet another approach that is somewhat simpler, maintains the type definition and associated function prototypes, and more closely models the intended C# pattern:

const john = Object.assign( new Person(), {
    name: "John",
    age: 29,
    address: "Earth"
});

That's it. The only addition over the C# pattern is Object.assign along with 2 parenthesis and a comma. Check out the working example below to confirm it maintains the type's function prototypes. No constructors required, and no clever tricks.

Working Example

This example shows how to initialize an object using an approximation of a C# field initializer:

_x000D_
_x000D_
class Person {_x000D_
    name: string = '';_x000D_
    address: string = '';_x000D_
    age: number = 0;_x000D_
_x000D_
    aboutMe() {_x000D_
        return `Hi, I'm ${this.name}, aged ${this.age} and from ${this.address}`;_x000D_
    }_x000D_
}_x000D_
_x000D_
// typescript field initializer (maintains "type" definition)_x000D_
const john = Object.assign( new Person(), {_x000D_
    name: "John",_x000D_
    age: 29,_x000D_
    address: "Earth"_x000D_
});_x000D_
_x000D_
// initialized object maintains aboutMe() function prototype_x000D_
console.log( john.aboutMe() );
_x000D_
_x000D_
_x000D_

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Chrome driver already support:

Java:

webDriver = new ChromeDriver();
webDriver.manage().window().maximize();

How does a Linux/Unix Bash script know its own PID?

use $BASHPID or $$

See the [manual][1] for more information, including differences between the two.

TL;DRTFM

  • $$ Expands to the process ID of the shell.
    • In a () subshell, it expands to the process ID of the invoking shell, not the subshell.
  • $BASHPID Expands to the process ID of the current Bash process (new to bash 4).

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

I make it simple, if the layout is same i just put the intent it.

My code like this:

public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {


    private Button btnCertificate, btnSeminarKit;

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

        initClick();
    }

    private void initClick() {
        btnCertificate = (Button) findViewById(R.id.btn_Certificate);
        btnCertificate.setOnClickListener(this);

        btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
        btnSeminarKit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_Certificate:
                break;
            case R.id.btn_SeminarKit:
                break;
        }
        Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
        startActivity(intent);
    }
}

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

How to get dictionary values as a generic list

Off course, myDico.Values is List<List<MyType>>.

Use Linq if you want to flattern your lists

var items = myDico.SelectMany (d => d.Value).ToList();

__FILE__, __LINE__, and __FUNCTION__ usage in C++

FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.

PS:

static string  getScopedClassMethod( string thePrettyFunction )
{
  size_t index = thePrettyFunction . find( "(" );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( index );

  index = thePrettyFunction . rfind( " " );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( 0, index + 1 );

  return thePrettyFunction;   /* The scoped class name. */
}

stdcall and cdecl

Raymond Chen gives a nice overview of what __stdcall and __cdecl does.

(1) The caller "knows" to clean up the stack after calling a function because the compiler knows the calling convention of that function and generates the necessary code.

void __stdcall StdcallFunc() {}

void __cdecl CdeclFunc()
{
    // The compiler knows that StdcallFunc() uses the __stdcall
    // convention at this point, so it generates the proper binary
    // for stack cleanup.
    StdcallFunc();
}

It is possible to mismatch the calling convention, like this:

LRESULT MyWndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam);
// ...
// Compiler usually complains but there's this cast here...
windowClass.lpfnWndProc = reinterpret_cast<WNDPROC>(&MyWndProc);

So many code samples get this wrong it's not even funny. It's supposed to be like this:

// CALLBACK is #define'd as __stdcall
LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg
    WPARAM wParam, LPARAM lParam);
// ...
windowClass.lpfnWndProc = &MyWndProc;

However, assuming the programmer doesn't ignore compiler errors, the compiler will generate the code needed to clean up the stack properly since it'll know the calling conventions of the functions involved.

(2) Both ways should work. In fact, this happens quite frequently at least in code that interacts with the Windows API, because __cdecl is the default for C and C++ programs according to the Visual C++ compiler and the WinAPI functions use the __stdcall convention.

(3) There should be no real performance difference between the two.

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

To debug optimized code, learn assembly/machine language.

Use the GDB TUI mode. My copy of GDB enables it when I type the minus and Enter. Then type C-x 2 (that is hold down Control and press X, release both and then press 2). That will put it into split source and disassembly display. Then use stepi and nexti to move one machine instruction at a time. Use C-x o to switch between the TUI windows.

Download a PDF about your CPU's machine language and the function calling conventions. You will quickly learn to recognize what is being done with function arguments and return values.

You can display the value of a register by using a GDB command like p $eax

Compare two List<T> objects for equality, ignoring order

If you want them to be really equal (i.e. the same items and the same number of each item), I think that the simplest solution is to sort before comparing:

Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))

Edit:

Here is a solution that performs a bit better (about ten times faster), and only requires IEquatable, not IComparable:

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
  var cnt = new Dictionary<T, int>();
  foreach (T s in list1) {
    if (cnt.ContainsKey(s)) {
      cnt[s]++;
    } else {
      cnt.Add(s, 1);
    }
  }
  foreach (T s in list2) {
    if (cnt.ContainsKey(s)) {
      cnt[s]--;
    } else {
      return false;
    }
  }
  return cnt.Values.All(c => c == 0);
}

Edit 2:

To handle any data type as key (for example nullable types as Frank Tzanabetis pointed out), you can make a version that takes a comparer for the dictionary:

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
  var cnt = new Dictionary<T, int>(comparer);
  ...

How to escape comma and double quote at same time for CSV file?

Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:

if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
    cell_value = cell_value.replaceAll("\"", "\"\"");
    row.append("\"");
    row.append(cell_value);
    row.append("\"");
} else {
    row.append(cell_value);
}

in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\"") by adding additional double quote (like "\"\""), then put the whole thing into a double quote (like "\""+theWholeThing+"\"" )

Cannot load properties file from resources directory

I use something like this to load properties file.

        final ResourceBundle bundle = ResourceBundle
                .getBundle("properties/errormessages");

        for (final Enumeration<String> keys = bundle.getKeys(); keys
                .hasMoreElements();) {
            final String key = keys.nextElement();
            final String value = bundle.getString(key);
            prop.put(key, value);
        }

How to calculate an age based on a birthday?

I do it like this:

(Shortened the code a bit)

public struct Age
{
    public readonly int Years;
    public readonly int Months;
    public readonly int Days;

}

public Age( int y, int m, int d ) : this()
{
    Years = y;
    Months = m;
    Days = d;
}

public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
    if( startDate.Date > endDate.Date )
        {
            throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
        }

        int years = endDate.Year - startDate.Year;
        int months = 0;
        int days = 0;

        // Check if the last year, was a full year.
        if( endDate < startDate.AddYears (years) && years != 0 )
        {
            years--;
        }

        // Calculate the number of months.
        startDate = startDate.AddYears (years);

        if( startDate.Year == endDate.Year )
        {
            months = endDate.Month - startDate.Month;
        }
        else
        {
            months = ( 12 - startDate.Month ) + endDate.Month;
        }

        // Check if last month was a complete month.
        if( endDate < startDate.AddMonths (months) && months != 0 )
        {
            months--;
        }

        // Calculate the number of days.
        startDate = startDate.AddMonths (months);

        days = ( endDate - startDate ).Days;

        return new Age (years, months, days);
}

// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...

}

Make: how to continue after a command fails?

Return successfully by blocking rm's returncode behind a pipe with the true command, which always returns 0 (success)

rm file | true

Undefined index with $_POST

Use:

if (isset($_POST['user'])) {
   //do something
}

But you probably should be using some more proper validation. Try a simple regex or a rock-solid implementation from Zend Framework or Symfony.

http://framework.zend.com/manual/en/zend.validate.introduction.html

http://symfony.com/doc/current/book/validation.html

Or even the built-in filter extension:

http://php.net/manual/en/function.filter-var.php

Never trust user input, be smart. Don't trust anything. Always make sure what you receive is really what you expect. If it should be a number, make SURE it's a number.

Much improved code:

$user = filter_var($_POST['user'], FILTER_SANITIZE_STRING);
$isValid = filter_var($user, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^[a-zA-Z0-9]+$/")));

if ($isValid) {
    // do something
}

Sanitization and validation.

how to set JAVA_OPTS for Tomcat in Windows?

Apparently the correct form is without the ""

As in

set JAVA_OPTS=-Xms512M -Xmx1024M

Determine what attributes were changed in Rails after_save callback?

For those who want to know the changes just made in an after_save callback:

Rails 5.1 and greater

model.saved_changes

Rails < 5.1

model.previous_changes

Also see: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-previous_changes

How do you check for permissions to write to a directory or file?

When your code does the following:

  1. Checks the current user has permission to do something.
  2. Carries out the action that needs the entitlements checked in 1.

You run the risk that the permissions change between 1 and 2 because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an UnauthorisedAccessException is thrown even if you have previously checked permissions.

Note that the SecurityManager class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, IsGranted will always return true for locally running applications.

Example (derived from Josh's example):

//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

//2. Attempt the action but handle permission changes.
try
{
    using (FileStream fstream = new FileStream(filename, FileMode.Create))
    using (TextWriter writer = new StreamWriter(fstream))
    {
        writer.WriteLine("sometext");
    }
}
catch (UnauthorizedAccessException ex)
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

It's tricky and not recommended to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the System.Security.AccessControl classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. This post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.

How to set DialogFragment's width and height?

Working on Android 6.0, ran into the same issue. AlertDialog would default to predefined width set in the theme regardless of the actual width set in the custom view's root Layout. I was able to get it to set properly adjusting the width of the loading_message TextView. Without investigating further, it seems that sizing the actual elements and having the root Layout wrap around them makes it work as expected. Below is an XML layout of a loading dialog which sets width of the the dialog correctly. Using the this library for the animation.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/custom_color"
    android:padding="@dimen/custom_dimen">
    <com.github.rahatarmanahmed.cpv.CircularProgressView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/progress_view"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_centerHorizontal="true"
        app:cpv_color="@color/white"
        app:cpv_animAutostart="true"
        app:cpv_indeterminate="true" />
    <TextView
        android:id="@+id/loading_message"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progress_view"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:textSize="18dp"
        android:layout_marginTop="@dimen/custom_dimen"
        android:textColor="@color/white"
        android:text="@string/custom_string"/>
</RelativeLayout>

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

Android: show soft keyboard automatically when focus is on an EditText

This is bit tricky. I did in this way and it worked.

1.At first call to hide the soft Input from the window. This will hide the soft input if the soft keyboard is visible or do nothing if it is not.

2.Show your dialog

3.Then simply call to toggle soft input.

code:

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWind??owToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

How to find out line-endings in a text file?

You can use vim -b filename to edit a file in binary mode, which will show ^M characters for carriage return and a new line is indicative of LF being present, indicating Windows CRLF line endings. By LF I mean \n and by CR I mean \r. Note that when you use the -b option the file will always be edited in UNIX mode by default as indicated by [unix] in the status line, meaning that if you add new lines they will end with LF, not CRLF. If you use normal vim without -b on a file with CRLF line endings, you should see [dos] shown in the status line and inserted lines will have CRLF as end of line. The vim documentation for fileformats setting explains the complexities.

Also, I don't have enough points to comment on the Notepad++ answer, but if you use Notepad++ on Windows, use the View / Show Symbol / Show End of Line menu to display CR and LF. In this case LF is shown whereas for vim the LF is indicated by a new line.

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

How to create PDF files in Python

It depends on what format your image files are in, but for a project here at work I used the tiff2pdf tool in LibTIFF from RemoteSensing.org. Basically just used subprocess to call tiff2pdf.exe with the appropriate argument to read the kind of tiff I had and output the kind of pdf I wanted. If they aren't tiffs you could probably convert them to tiffs using PIL, or maybe find a tool more specific to your image type (or more generic if the images will be diverse) like ReportLab mentioned above.

What is the difference between Html.Hidden and Html.HiddenFor

Every method in HtmlHelper class has a twin with For suffix. Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this

o=>o.SomeProperty 

instead of "SomeProperty" in the case of using Html.Hidden method.

How to convert from Hex to ASCII in JavaScript?

function hex2a(hexx) {
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}
hex2a('32343630'); // returns '2460'

SQL: sum 3 columns when one column has a null value?

You can use ISNULL:

ISNULL(field, VALUEINCASEOFNULL)

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Reading input files by line using read command in shell scripting skips last line

Use while loop like this:

while IFS= read -r line || [ -n "$line" ]; do
  echo "$line"
done <file

Or using grep with while loop:

while IFS= read -r line; do
  echo "$line"
done < <(grep "" file)

Using grep . instead of grep "" will skip the empty lines.

Note:

  1. Using IFS= keeps any line indentation intact.

  2. You should almost always use the -r option with read.

  3. Don't read lines with for

  4. File without a newline at the end isn't a standard unix text file.

How to generate different random numbers in a loop in C++?

Try moving the seed srand outside the loop like so:

srand ( time(NULL) );
for (int t=0;t<10;t++)
{
    int random_x;
    random_x = rand() % 100;
    cout<< "\nRandom X = "<<random_x;
} 

As Mark Ransom says in the comment, moving the seed outside the loop will only help if the loop is not residing in a function you are calling several times.

How to Convert a Text File into a List in Python

Going with what you've started:

row = [[]] 
crimefile = open(fileName, 'r') 
for line in crimefile.readlines(): 
    tmp = []
    for element in line[0:-1].split(','):
        tmp.append(element)
row.append(tmp)

Visual Studio "Could not copy" .... during build

I experienced the error-messages when attempting to build the primary WinForms (XAF) project. I could only execute the application one time then needed to shutdown the VS2015 IDE and restart before a rebuild could be performed. After some digging in the project's property pages - in the "debug" property page, a check box was selected - Enable the Visual Studio Hosting Process. I unchecked and restarted the IDE, the application is now building without - "unable to copy the {project}.exe" messages.

What is the purpose of the Visual Studio Hosting Process?

Gaussian filter in MATLAB

@Jacob already showed you how to use the Gaussian filter in Matlab, so I won't repeat that.

I would choose filter size to be about 3*sigma in each direction (round to odd integer). Thus, the filter decays to nearly zero at the edges, and you won't get discontinuities in the filtered image.

The choice of sigma depends a lot on what you want to do. Gaussian smoothing is low-pass filtering, which means that it suppresses high-frequency detail (noise, but also edges), while preserving the low-frequency parts of the image (i.e. those that don't vary so much). In other words, the filter blurs everything that is smaller than the filter.

If you're looking to suppress noise in an image in order to enhance the detection of small features, for example, I suggest to choose a sigma that makes the Gaussian just slightly smaller than the feature.

How to correct TypeError: Unicode-objects must be encoded before hashing?

If it's a single line string. wrapt it with b or B. e.g:

variable = b"This is a variable"

or

variable2 = B"This is also a variable"

How do you display a Toast from a background thread on Android?

Like this or this, with a Runnable that shows the Toast. Namely,

Activity activity = // reference to an Activity
// or
View view = // reference to a View

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        showToast(activity);
    }
});
// or
view.post(new Runnable() {
    @Override
    public void run() {
        showToast(view.getContext());
    }
});

private void showToast(Context ctx) {
    Toast.makeText(ctx, "Hi!", Toast.LENGTH_SHORT).show();
}

Converting HTML to plain text in PHP for e-mail

I didn't find any of the existing solutions fitting - simple HTML emails to simple plain text files.

I've opened up this repository, hope it helps someone. MIT license, by the way :)

https://github.com/RobQuistNL/SimpleHtmlToText

Example:

$myHtml = '<b>This is HTML</b><h1>Header</h1><br/><br/>Newlines';
echo (new Parser())->parseString($myHtml);

returns:

**This is HTML**
### Header ###


Newlines

Checking Maven Version

Step 1: Start button -> Computer menu item -> Properties on right click menu item -> Advanced System Settings button on left panel -> Advanced tab in System Properties dialog -> Environment Variables button -> System variables table

Step 2: Add MAVEN_HOME variable

enter image description here

Step 3: Update PATH variable enter image description here

Step 4: Make sure you have JAVA_HOME variable correctly enter image description here

step 5: open console and check below command

mvn -v

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

How to align content of a div to the bottom

You don't need absolute+relative for this. It is very much possible using relative position for both container and data. This is how you do it.

Assume height of your data is going to be x. Your container is relative and footer is also relative. All you have to do is add to your data

bottom: -webkit-calc(-100% + x);

Your data will always be at the bottom of your container. Works even if you have container with dynamic height.

HTML will be like this

<div class="container">
  <div class="data"></div>
</div>

CSS will be like this

.container{
  height:400px;
  width:600px;
  border:1px solid red;
  margin-top:50px;
  margin-left:50px;
  display:block;
}
.data{
  width:100%;
  height:40px;
  position:relative;
   float:left;
  border:1px solid blue;
  bottom: -webkit-calc(-100% + 40px);
   bottom:calc(-100% + 40px);
}

Live example here

Hope this helps.

Google Maps API v3: How to remove all markers?

You can do it this way too:

function clearMarkers(category){ 
  var i;       

  for (i = 0; i < markers.length; i++) {                          
    markers[i].setVisible(false);        
  }    
}

Check if a number is a perfect square

This is my method:

def is_square(n) -> bool:
    return int(n**0.5)**2 == int(n)

Take square root of number. Convert to integer. Take the square. If the numbers are equal, then it is a perfect square otherwise not.

It is incorrect for a large square such as 152415789666209426002111556165263283035677489.

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

Daniel's comment as an answer:

"escaping only occurs in Django during template rendering. Therefore, there's no need for an unescape - you just tell the templating engine not to escape. either {{ context_var|safe }} or {% autoescape off %}{{ context_var }}{% endautoescape %}"

How can I tell when a MySQL table was last updated?

Although there is an accepted answer I don't feel that it is the right one. It is the simplest way to achieve what is needed, but even if already enabled in InnoDB (actually docs tell you that you still should get NULL ...), if you read MySQL docs, even in current version (8.0) using UPDATE_TIME is not the right option, because:

Timestamps are not persisted when the server is restarted or when the table is evicted from the InnoDB data dictionary cache.

If I understand correctly (can't verify it on a server right now), timestamp gets reset after server restart.

As for real (and, well, costly) solutions, you have Bill Karwin's solution with CURRENT_TIMESTAMP and I'd like to propose a different one, that is based on triggers (I'm using that one).

You start by creating a separate table (or maybe you have some other table that can be used for this purpose) which will work like a storage for global variables (here timestamps). You need to store two fields - table name (or whatever value you'd like to keep here as table id) and timestamp. After you have it, you should initialize it with this table id + starting date (NOW() is a good choice :) ).

Now, you move to tables you want to observe and add triggers AFTER INSERT/UPDATE/DELETE with this or similar procedure:

CREATE PROCEDURE `timestamp_update` ()
BEGIN
    UPDATE `SCHEMA_NAME`.`TIMESTAMPS_TABLE_NAME`
    SET `timestamp_column`=DATE_FORMAT(NOW(), '%Y-%m-%d %T')
    WHERE `table_name_column`='TABLE_NAME';
END

MSIE and addEventListener Problem in Javascript?

In case you are using JQuery 2.x then please add the following in the

<html>
   <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge;" />
   </head>
   <body>
    ...
   </body>
</html>

This worked for me.

MySQL: Insert datetime into other datetime field

Try

    UPDATE products SET former_date=20111218131717 WHERE id=1

Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.

How to execute .sql file using powershell?

if(Test-Path "C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS") { #Sql Server 2012
    Import-Module SqlPs -DisableNameChecking
    C: # Switch back from SqlServer
} else { #Sql Server 2008
    Add-PSSnapin SqlServerCmdletSnapin100 # here live Invoke-SqlCmd
}

Invoke-Sqlcmd -InputFile "MySqlScript.sql" -ServerInstance "Database name" -ErrorAction 'Stop' -Verbose -QueryTimeout 1800 # 30min

Bulk Insert to Oracle using .NET

SQL Server's SQLBulkCopy is blindingly fast. Unfortunately, I found that OracleBulkCopy is far slower. Also it has problems:

  • You must be very sure that your input data is clean if you plan to use OracleBulkCopy. If a primary key violation occurs, an ORA-26026 is raised and it appears to be unrecoverable. Trying to rebuild the index does not help and any subsequent insert on the table fails, also normal inserts.
  • Even if the data is clean, I found that OracleBulkCopy sometimes gets stuck inside WriteToServer. The problem seems to depend on the batch size. In my test data, the problem would happen at the exact same point in my test when I repeat is. Use a larger or smaller batch size, and the problem does not happen. I see that the speed is more irregular on larger batch sizes, this points to problems related to memory management.

Actually System.Data.OracleClient.OracleDataAdapter is faster than OracleBulkCopy if you want to fill a table with small records but many rows. You need to tune the batch size though, the optimum BatchSize for OracleDataAdapter is smaller than for OracleBulkCopy.

I ran my test on a Windows 7 machine with an x86 executable and the 32 bits ODP.Net client 2.112.1.0. . The OracleDataAdapter is part of System.Data.OracleClient 2.0.0.0. My test set is about 600,000 rows with a record size of max. 102 bytes (average size 43 chars). Data source is a 25 MB text file, read in line by line as a stream.

In my test I built up the input data table to a fixed table size and then used either OracleBulkCopy or OracleDataAdapter to copy the data block to the server. I left BatchSize as 0 in OracleBulkCopy (so that the current table contents is copied as one batch) and set it to the table size in OracleDataAdapter (again that should create a single batch internally). Best results:

  • OracleBulkCopy: table size = 500, total duration 4'22"
  • OracleDataAdapter: table size = 100, total duration 3'03"

For comparison:

  • SqlBulkCopy: table size = 1000, total duration 0'15"
  • SqlDataAdapter: table size = 1000, total duration 8'05"

Same client machine, test server is SQL Server 2008 R2. For SQL Server, bulk copy is clearly the best way to go. Not only is it overall fastest, but server load is also lower than when using data adapter. It is a pity that OracleBulkCopy does not offer quite the same experience - the BulkCopy API is much easier to use than DataAdapter.

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

Library functions like "pow" are usually carefully crafted to yield the minimum possible error (in generic case). This is usually achieved approximating functions with splines (according to Pascal's comment the most common implementation seems to be using Remez algorithm)

fundamentally the following operation:

pow(x,y);

has a inherent error of approximately the same magnitude as the error in any single multiplication or division.

While the following operation:

float a=someValue;
float b=a*a*a*a*a*a;

has a inherent error that is greater more than 5 times the error of a single multiplication or division (because you are combining 5 multiplications).

The compiler should be really carefull to the kind of optimization it is doing:

  1. if optimizing pow(a,6) to a*a*a*a*a*a it may improve performance, but drastically reduce the accuracy for floating point numbers.
  2. if optimizing a*a*a*a*a*a to pow(a,6) it may actually reduce the accuracy because "a" was some special value that allows multiplication without error (a power of 2 or some small integer number)
  3. if optimizing pow(a,6) to (a*a*a)*(a*a*a) or (a*a)*(a*a)*(a*a) there still can be a loss of accuracy compared to pow function.

In general you know that for arbitrary floating point values "pow" has better accuracy than any function you could eventually write, but in some special cases multiple multiplications may have better accuracy and performance, it is up to the developer choosing what is more appropriate, eventually commenting the code so that noone else would "optimize" that code.

The only thing that make sense (personal opinion, and apparently a choice in GCC wichout any particular optimization or compiler flag) to optimize should be replacing "pow(a,2)" with "a*a". That would be the only sane thing a compiler vendor should do.

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

What is the difference between map and flatMap and a good use case for each?

Difference in output of map and flatMap:

1.flatMap

val a = sc.parallelize(1 to 10, 5)

a.flatMap(1 to _).collect()

Output:

 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

2.map:

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)

val b = a.map(_.length).collect()

Output:

3 6 6 3 8

How to get exact browser name and version?

this JavaScript give you the browser name and the version,

var browser = '';
var browserVersion = 0;

if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
    browser = 'Opera';
} else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
    browser = 'MSIE';
} else if (/Navigator[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
    browser = 'Netscape';
} else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
    browser = 'Chrome';
} else if (/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
    browser = 'Safari';
    /Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
    browserVersion = new Number(RegExp.$1);
} else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
    browser = 'Firefox';
}
if(browserVersion === 0){
    browserVersion = parseFloat(new Number(RegExp.$1));
}
alert(browser + "*" + browserVersion);

Implicit type conversion rules in C++ operators

If you exclude the unsigned types, there is an ordered hierarchy: signed char, short, int, long, long long, float, double, long double. First, anything coming before int in the above will be converted to int. Then, in a binary operation, the lower ranked type will be converted to the higher, and the results will be the type of the higher. (You'll note that, from the hierarchy, anytime a floating point and an integral type are involved, the integral type will be converted to the floating point type.)

Unsigned complicates things a bit: it perturbs the ranking, and parts of the ranking become implementation defined. Because of this, it's best to not mix signed and unsigned in the same expression. (Most C++ experts seem to avoid unsigned unless bitwise operations are involved. That is, at least, what Stroustrup recommends.)

String.Replace ignoring case

You can use the Microsoft.VisualBasic namespace to find this helper function:

Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)

Creating a random string with A-Z and 0-9 in Java

Here you can use my method for generating Random String

protected String getSaltString() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;

    }

The above method from my bag using to generate a salt string for login purpose.

How can I refresh a page with jQuery?

You can write it in two ways. 1st is the standard way of reloading the page also called as simple refresh

location.reload(); //simple refresh

And another is called the hard refresh. Here you pass the boolean expression and set it to true. This will reload the page destroying the older cache and displaying the contents from scratch.

location.reload(true);//hard refresh

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

How to edit an Android app?

You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.

You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.

If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.

In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.

Max size of an iOS application

Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.

enter image description here

Emulator in Android Studio doesn't start

I was having this same problem. I decided to create (see the button at the lower-left). I defined the image to match my device and that seems to work.

I am thinking with Android Studio at version 1.0.1, there are still plenty of bugs.

How to convert PDF files to images

Regarding PDFiumSharp: After elaboration I was able to create PNG files from a PDF solution.

This is my code:

using PDFiumSharp;
using System.Collections.Generic;
using System.Drawing;
using System.IO;

public class Program
{
    static public void Main(String[] args)
    {
        var renderfoo = new Renderfoo()
        renderfoo.RenderPDFAsImages(@"C:\Temp\example.pdf", @"C:\temp");
    }
}



public class Renderfoo
{

    public void RenderPDFAsImages(string Inputfile, string OutputFolder)
    {
        string fileName = Path.GetFileNameWithoutExtension(Inputfile);

        using (PDFiumSharp.PdfDocument doc = new PDFiumSharp.PdfDocument(Inputfile))
        {
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                var page = doc.Pages[i];
                using (var bitmap = new System.Drawing.Bitmap((int)page.Width, (int)page.Height))
                {
                    var grahpics = Graphics.FromImage(bitmap);
                    grahpics.Clear(Color.White);
                    page.Render(bitmap);
                    var targetFile = Path.Combine(OutputFolder, fileName + "_" + i + ".png");
                    bitmap.Save(targetFile);
                }
            }
        }
    }

}

For starters, you need to take the following steps to get the PDFium wrapper up and running:

  • Run the Custom Code tool for both tt files via right click in Visual Studio
  • Compile the GDIPlus Project
  • Copy the compiled assemblies (from the GDIPlus project) to your project
  • Reference both PDFiumSharp and PDFiumsharp.GdiPlus assemblies in your project

  • Make sure that pdfium_x64.dll and/or pdfium_x86.dll are both found in your project output directory.

jQuery multiselect drop down menu

<select id="mycontrolId" multiple="multiple">
   <option value="1" >one</option>
   <option value="2" >two</option>
   <option value="3">three</option>
   <option value="4">four</option>
</select>

var data = "1,3,4"; var dataarray = data.split(",");

$("#mycontrolId").val(dataarray);

Creating a byte array from a stream

It really depends on whether or not you can trust s.Length. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

With .NET 4 and above, I'd use Stream.CopyTo, which is basically equivalent to the loop in my code - create the MemoryStream, call stream.CopyTo(ms) and then return ms.ToArray(). Job done.

I should perhaps explain why my answer is longer than the others. Stream.Read doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. BinaryReader.Read will keep going until the end of the stream or your specified size, but you still have to know the size to start with.

The above method will keep reading (and copying into a MemoryStream) until it runs out of data. It then asks the MemoryStream to return a copy of the data in an array. If you know the size to start with - or think you know the size, without being sure - you can construct the MemoryStream to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by MemoryStream.GetBuffer) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.

See this article for more info (and an alternative implementation).

What are C++ functors and their uses?

Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.

Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies its argument by a specified amount:

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) {
    }

    int operator () (int other) const {
        return factor * other;
    }
};

Then you could pass a MultiplyBy object to an algorithm like std::transform:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

How to highlight a selected row in ngRepeat?

You probably want to have LI rather than the UL have the background-color:

.selected li {
  background-color: red;
}

Then you want to have a dynamic class for the UL:

<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">

Now you need to update the $scope.selected when clicking the row:

$scope.setSelected = function() {
   console.log("show", arguments, this);
   this.selected = 'selected';
}

and then un-select the previously highlighted row:

$scope.setSelected = function() {
   // console.log("show", arguments, this);
   if ($scope.lastSelected) {
     $scope.lastSelected.selected = '';
   }
   this.selected = 'selected';
   $scope.lastSelected = this;
}

Working solution:

http://plnkr.co/edit/wq6nxc?p=preview

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

Whenever I'm testing something with PHP/Curl, I try it from the command line first, figure out what works, and then port my options to PHP.

SQL query for today's date minus two months

SELECT COUNT(1)
FROM FB
WHERE
    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

Android view pager with page indicator

Just an improvement to the nice answer given by @vuhung3990. I implemented the solution and works great but if I touch one radio button it will be selected and nothing happens.

I suggest to also change page when a radio button is tapped. To do this, simply add a listener to the radioGroup:

mPager = (ViewPager) findViewById(R.id.pager);
final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radiogroup);    
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioButton :
                        mPager.setCurrentItem(0, true);
                        break;
                    case R.id.radioButton2 :
                        mPager.setCurrentItem(1, true);
                        break;
                    case R.id.radioButton3 :
                        mPager.setCurrentItem(2, true);
                        break;
                }
            }
        });

How do I get the directory that a program is running from?

#include <windows.h>
using namespace std;

// The directory path returned by native GetCurrentDirectory() no end backslash
string getCurrentDirectoryOnWindows()
{
    const unsigned long maxDir = 260;
    char currentDir[maxDir];
    GetCurrentDirectory(maxDir, currentDir);
    return string(currentDir);
}

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.