Programs & Examples On #Cocoa bindings

Cocoa bindings is Apple’s implementation of the Model-View-Controller design pattern for Mac OS X applications. It provides technologies that automate the synchronisation of domain data and the user interface elements that present them.

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

escaping question mark in regex javascript

You should use double slash:

var regex = new RegExp("\\?", "g");

Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"

And "\\?", becomes "\?"

SQL Server principal "dbo" does not exist,

As the message said, you should set permission as owner to your user. So you can use following:

ALTER AUTHORIZATION 
ON DATABASE::[YourDBName]
TO [UserLogin];

Hope helpful! Leave comment if it's ok for you.

Oracle SQL Query for listing all Schemas in a DB

SELECT username FROM all_users ORDER BY username;

HTML: How to center align a form

<center><form></form></center>    

does work in most cases like The Wobbuffet mentioned above...

How do I check form validity with angularjs?

form

  • directive in module ng Directive that instantiates FormController.

If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

ng-valid is set if the form is valid.

ng-invalid is set if the form is invalid.

ng-pristine is set if the form is pristine.

ng-dirty is set if the form is dirty.

ng-submitted is set if the form was submitted.

Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.

app.js:

angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';
  }]);

Form:

<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}
 </form>

Source: AngularJS: API: form

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

Disabling the alert message is not a way to solve the problem. Despite the PHP core is continue to work it makes a dangerous assumptions and actions.

Never ignore the error where PHP should make an assumptions of something!!!!

If the class organized as a singleton you can always use function getInstance() and then use getData()

Likse:

$classObj = MyClass::getInstance();
$classObj->getData();

If the class is not a singleton, use

 $classObj = new MyClass();
 $classObj->getData();

Better way to check if a Path is a File or a Directory?

Very late to the party here but I've found the Nullable<Boolean> return value to be quite ugly - IsDirectory(string path) returning null doesn't equate to a non-existent path without verbose commenting, so I've come up with the following:

public static class PathHelper
{
    /// <summary>
    /// Determines whether the given path refers to an existing file or directory on disk.
    /// </summary>
    /// <param name="path">The path to test.</param>
    /// <param name="isDirectory">When this method returns, contains true if the path was found to be an existing directory, false in all other scenarios.</param>
    /// <returns>true if the path exists; otherwise, false.</returns>
    /// <exception cref="ArgumentNullException">If <paramref name="path"/> is null.</exception>
    /// <exception cref="ArgumentException">If <paramref name="path"/> equals <see cref="string.Empty"/></exception>
    public static bool PathExists(string path, out bool isDirectory)
    {
        if (path == null) throw new ArgumentNullException(nameof(path));
        if (path == string.Empty) throw new ArgumentException("Value cannot be empty.", nameof(path));

        isDirectory = Directory.Exists(path);

        return isDirectory || File.Exists(path);
    }
}

This helper method is written to be verbose and concise enough to understand the intent the first time you read it.

/// <summary>
/// Example usage of <see cref="PathExists(string, out bool)"/>
/// </summary>
public static void Usage()
{
    const string path = @"C:\dev";

    if (!PathHelper.PathExists(path, out var isDirectory))
        return;

    if (isDirectory)
    {
        // Do something with your directory
    }
    else
    {
        // Do something with your file
    }
}

SQLite DateTime comparison

I have a situation where I want data from up to two days ago and up until the end of today. I arrived at the following.

WHERE dateTimeRecorded between date('now', 'start of day','-2 days') 
                           and date('now', 'start of day', '+1 day') 

Ok, technically I also pull in midnight on tomorrow like the original poster, if there was any data, but my data is all historical.

The key thing to remember, the initial poster excluded all data after 2009-11-15 00:00:00. So, any data that was recorded at midnight on the 15th was included but any data after midnight on the 15th was not. If their query was,

select * 
  from table_1 
  where mydate between Datetime('2009-11-13 00:00:00') 
                   and Datetime('2009-11-15 23:59:59')

Use of the between clause for clarity.

It would have been slightly better. It still does not take into account leap seconds in which an hour can actually have more than 60 seconds, but good enough for discussions here :)

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

I tried opening my Credential Manager but could not find any credentials in there that has any relation to my TFS account.

So what I did instead I logout of my hotmail account in Internet Explorer and then clear all my Internet Explorer cookies and stored password as detailed in this blog: Changing TFS credentials in Visual Studio 2012

enter image description here

After clearing out the cookies and password, restart IE and then relogin to your hotmail (or windows live account).

Then start Visual Studio and try to reconnect to TFS, you should be prompted for a credential now.

Note: A reader said that you do not have to clear out all IE cookies, just these 3 cookies, but I didn't test this.

cookie:@login.live.com/
cookie:@visualstudio.com/
cookie:@tfs.app.visualstudio.com/

Load image from resources area of project in C#

Are you using Windows Forms? If you've added the image using the Properties/Resources UI, you get access to the image from generated code, so you can simply do this:

var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);

Location for session files in Apache/PHP

I believe its in /tmp/. Check your phpinfo function though, it should say session.save_path in there somewhere.

PHPMailer: SMTP Error: Could not connect to SMTP host

Since this is a popular error, check out the PHPMailer Wiki on troubleshooting.

Also this worked for me

$mailer->Port = '587';

Factorial in numpy and scipy

You can save some homemade factorial functions on a separate module, utils.py, and then import them and compare the performance with the predefinite one, in scipy, numpy and math using timeit. In this case I used as external method the last proposed by Stefan Gruenwald:

import numpy as np


def factorial(n):
    return reduce((lambda x,y: x*y),range(1,n+1))

Main code (I used a framework proposed by JoshAdel in another post, look for how-can-i-get-an-array-of-alternating-values-in-python):

from timeit import Timer
from utils import factorial
import scipy

    n = 100

    # test the time for the factorial function obtained in different ways:

    if __name__ == '__main__':

        setupstr="""
    import scipy, numpy, math
    from utils import factorial
    n = 100
    """

        method1="""
    factorial(n)
    """

        method2="""
    scipy.math.factorial(n)  # same algo as numpy.math.factorial, math.factorial
    """

        nl = 1000
        t1 = Timer(method1, setupstr).timeit(nl)
        t2 = Timer(method2, setupstr).timeit(nl)

        print 'method1', t1
        print 'method2', t2

        print factorial(n)
        print scipy.math.factorial(n)

Which provides:

method1 0.0195569992065
method2 0.00638914108276

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000


Process finished with exit code 0

How to loop and render elements in React.js without an array of objects to map?

Array.from() takes an iterable object to convert to an array and an optional map function. You could create an object with a .length property as follows:

return Array.from({length: this.props.level}, (item, index) => 
  <span className="indent" key={index}></span>
);

Using Python's os.path, how do I go up one directory?

From the current file path you could use:

os.path.join(os.path.dirname(__file__),'..','img','banner.png')

Flutter Countdown Timer

You can use this plugin timer_builder

timer_builder widget that rebuilds itself on scheduled, periodic, or dynamically generated time events.

Examples

Periodic rebuild

import 'package:timer_builder/timer_builder.dart';

class ClockWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return TimerBuilder.periodic(Duration(seconds: 1),
      builder: (context) {
        return Text("${DateTime.now()}");
      }
    );
  }
  
}

Rebuild on a schedule

import 'package:timer_builder/timer_builder.dart';

class StatusIndicator extends StatelessWidget {

  final DateTime startTime;
  final DateTime endTime;
  
  StatusIndicator(this.startTime, this.endTime);
  
  @override
  Widget build(BuildContext context) {
    return TimerBuilder.scheduled([startTime, endTime],
      builder: (context) {
        final now = DateTime.now();
        final started = now.compareTo(startTime) >= 0;
        final ended = now.compareTo(endTime) >= 0;
        return Text(started ? ended ? "Ended": "Started": "Not Started");
      }
    );
  }
  
}

enter image description here

Origin is not allowed by Access-Control-Allow-Origin

If you're writing a Chrome Extension and get this error, then be sure you have added the API's base URL to your manifest.json's permissions block, example:

"permissions": [
    "https://itunes.apple.com/"
]

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

This answer if for the people experiencing the same problem trying to accessing the camera.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Using Linux:

if you are trying to access the camera from your computer most likely there is a permission issue, try running the python script with sudo it should fix it.

sudo python python_script.py

To test if the camera is accessible run the following command.

ffmpeg -f v4l2 -framerate 25 -video_size 640x480 -i /dev/video0 output.mkv 

What is path of JDK on Mac ?

Which Mac version are you using? try these paths

 /System/Library/Frameworks/JavaVM.framework/ OR
 /usr/libexec/java_home

This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

Your using statements appear to be correct.

Are you, perhaps, missing the assembly reference to System.configuration.dll?

Right click the "References" folder in your project and click on "Add Reference..."

How to get the primary IP address of the local machine on Linux and OS X?

This works on Linux and OSX

This will get the interface associated to the default route

NET_IF=`netstat -rn | awk '/^0.0.0.0/ {thif=substr($0,74,10); print thif;} /^default.*UG/ {thif=substr($0,65,10); print thif;}'`

Using the interface discovered above, get the ip address.

NET_IP=`ifconfig ${NET_IF} | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'`

OSX

uname -a

Darwin laptop 14.4.0 Darwin Kernel Version 14.4.0: Thu May 28 11:35:04 PDT 2015; root:xnu-2782.30.5~1/RELEASE_X86_64 x86_64

echo $NET_IF

en5

echo $NET_IP

192.168.0.130

CentOS Linux

uname -a

Linux dev-cil.medfx.local 2.6.18-164.el5xen 1 SMP Thu Sep 3 04:03:03 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux

echo $NET_IF

eth0

echo $NET_IP

192.168.46.10

How to query first 10 rows and next time query other 10 rows from table

Just use the LIMIT clause.

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10

And from the next call you can do this way:

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10 OFFSET 10

More information on OFFSET and LIMIT on LIMIT and OFFSET.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

I just got this error again today as I updated my machine (with updates for PHP) running Ubuntu 14.04. The distribution config file /etc/php5/fpm/pool.d/www.conf is fine and doesn't require any changes currently.

I found the following errors:

dmesg | grep php
[...]
[ 4996.801789] traps: php5-fpm[23231] general protection ip:6c60d1 sp:7fff3f8c68f0 error:0 in php5-fpm[400000+800000]
[ 6788.335355] traps: php5-fpm[9069] general protection ip:6c5d81 sp:7fff98dd9a00 error:0 in php5-fpm[400000+7ff000]

The strange thing was that I have 2 sites running that utilize PHP-FPM on this machine one was running fine and the other (a Tiny Tiny RSS installation) gave me a 502, where both have been running fine before.

I compared both configuration files and found that fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; was missing for the affected site.

Both configuration files now contain the following block and are running fine again:

location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include /etc/nginx/snippets/fastcgi-php.conf;
}

Update

It should be noted that Ubuntu ships two fastcgi related parameter files and also a configuration snippet which is available since Vivid and also in the PPA version. The solution was updated accordingly.

Diff of the fastcgi parameter files:

$ diff -up fastcgi_params fastcgi.conf
--- fastcgi_params      2015-07-22 01:42:39.000000000 +0200
+++ fastcgi.conf        2015-07-22 01:42:39.000000000 +0200
@@ -1,4 +1,5 @@

+fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
 fastcgi_param  QUERY_STRING       $query_string;
 fastcgi_param  REQUEST_METHOD     $request_method;
 fastcgi_param  CONTENT_TYPE       $content_type;

Configuration snippet in /etc/nginx/snippets/fastcgi-php.conf

# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

TypeError: sequence item 0: expected string, int found

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)

How can I iterate over files in a given directory?

You can try using glob module:

import glob

for filepath in glob.iglob('my_dir/*.asm'):
    print(filepath)

and since Python 3.5 you can search subdirectories as well:

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']

From the docs:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

How to tell which disk Windows Used to Boot

  1. Go into Control Panel
  2. System and Security
  3. Administrative Tools
  4. Launch the System Configuration tool

If you have multiple copies of Windows installed, the one you are booted with will be named such as:

Windows 7 (F:\Windows)
Windows 7 (C:\Windows) : Current OS, Default OS

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

How do I get the logfile from an Android device?

Logcollector is a good option but you need to install it first.

When I want to get the logfile to send by mail, I usually do the following:

Set div height equal to screen size

Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.

Use vh instead of %;

Best practice to validate null and empty collection in Java

If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.

This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if

  • null might mean something more specific;
  • your API (contract) might force you to return null.

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

Using Python, find anagrams for a list of words

Simple Solution in Python:

def anagram(s1,s2):

    # Remove spaces and lowercase letters
    s1 = s1.replace(' ','').lower()
    s2 = s2.replace(' ','').lower()

    # Return sorted match.
    return sorted(s1) == sorted(s2)

How do I pass variables and data from PHP to JavaScript?

PHP

$fruits = array("apple" => "yellow", "strawberry" => "red", "kiwi" => "green");
<script>
    var color = <?php echo json_encode($fruits) ?>;
</script>
<script src="../yourexternal.js"></script>

JS (yourexternal.js)

alert("The apple color is" + color['apple'] + ", the strawberry color is " + color['strawberry'] + " and the kiwi color is " + color['kiwi'] + ".");

OUTPUT

The apple color is yellow, the strawberry color is red and the kiwi color is green.

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

What is the difference between min SDK version/target SDK version vs. compile SDK version?

compileSdkVersion : The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device.

minSdkVersion : The min sdk version is the minimum version of the Android operating system required to run your application.

targetSdkVersion : The target sdk version is the version your app is targeted to run on.

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

There are two things I learned from this:

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

  2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

I hope this helps someone else!

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

How to clear all inputs, selects and also hidden fields in a form using jQuery?

To clear all inputs, including hidden fields, using JQuery:

// Behold the power of JQuery.
$('input').val('');

Selects are harder, because they have a fixed list. Do you want to clear that list, or just the selection.

Could be something like

$('option').attr('selected', false);

Access a global variable in a PHP function

For many years I have always used this format:

<?php
    $data = "Hello";

    function sayHello(){
        echo $GLOBALS["data"];
    }

    sayHello();
?>

I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

JavaScript: Collision detection

Here's a very simple bounding rectangle routine. It expects both a and b to be objects with x, y, width and height properties:

function isCollide(a, b) {
    return !(
        ((a.y + a.height) < (b.y)) ||
        (a.y > (b.y + b.height)) ||
        ((a.x + a.width) < b.x) ||
        (a.x > (b.x + b.width))
    );
}

To see this function in action, here's a codepen graciously made by @MixerOID.

Forbidden: You don't have permission to access / on this server, WAMP Error

This could be one solution.

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";
    private static final String URL_FOR_REGISTRATION = "http://192.168.10.4/android_login_example/register.php";
    ProgressDialog progressDialog;

    private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
    private Button btnSignUp;
    private Button btnLinkLogin;
    private RadioGroup genderRadioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // Progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        signupInputName = (EditText) findViewById(R.id.signup_input_name);
        signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
        signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
        signupInputAge = (EditText) findViewById(R.id.signup_input_age);

        btnSignUp = (Button) findViewById(R.id.btn_signup);
        btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

        genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });
        btnLinkLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
            }
        });
    }

    private void submitForm() {

        int selectedId = genderRadioGroup.getCheckedRadioButtonId();
        String gender;
        if(selectedId == R.id.female_radio_btn)
            gender = "Female";
        else
            gender = "Male";

        registerUser(signupInputName.getText().toString(),
                signupInputEmail.getText().toString(),
                signupInputPassword.getText().toString(),
                gender,
                signupInputAge.getText().toString());
    }

    private void registerUser(final String name,  final String email, final String password,
                              final String gender, final String dob) {
        // Tag used to cancel the request
        String cancel_req_tag = "register";

        progressDialog.setMessage("Adding you ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_FOR_REGISTRATION, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    if (!error) {
                        String user = jObj.getJSONObject("user").getString("name");
                        Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {



                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);
                params.put("gender", gender);
                params.put("age", dob);
                return params;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    }

angular 4: *ngIf with multiple conditions

<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">

What's the difference between returning value or Promise.resolve from then()

Both of your examples should behave pretty much the same.

A value returned inside a then() handler becomes the resolution value of the promise returned from that then(). If the value returned inside the .then is a promise, the promise returned by then() will "adopt the state" of that promise and resolve/reject just as the returned promise does.

In your first example, you return "bbb" in the first then() handler, so "bbb" is passed into the next then() handler.

In your second example, you return a promise that is immediately resolved with the value "bbb", so "bbb" is passed into the next then() handler. (The Promise.resolve() here is extraneous).

The outcome is the same.

If you can show us an example that actually exhibits different behavior, we can tell you why that is happening.

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

NotificationCompat.Builder deprecated in Android O

Simple Sample

    public void showNotification (String from, String notification, Intent intent) {
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                Notification_ID,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );


        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }


        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
        Notification mNotification = builder
                .setContentTitle(from)
                .setContentText(notification)

//                .setTicker("Hearty365")
//                .setContentInfo("Info")
                //     .setPriority(Notification.PRIORITY_MAX)

                .setContentIntent(pendingIntent)

                .setAutoCancel(true)
//                .setDefaults(Notification.DEFAULT_ALL)
//                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .build();

        notificationManager.notify(/*notification id*/Notification_ID, mNotification);

    }

Detect if a page has a vertical scrollbar?

This one did works for me:

function hasVerticalScroll(node){
    if(node == undefined){
        if(window.innerHeight){
            return document.body.offsetHeight> window.innerHeight;
        }
        else {
            return  document.documentElement.scrollHeight > 
                document.documentElement.offsetHeight ||
                document.body.scrollHeight>document.body.offsetHeight;
        }
    }
    else {
        return node.scrollHeight> node.offsetHeight;
    }
}

For the body, just use hasVerticalScroll().

Linq : select value in a datatable column

var name = from r in MyTable
            where r.ID == 0
            select r.Name;

If the row is unique then you could even just do:

var row = DataContext.MyTable.SingleOrDefault(r => r.ID == 0);
var name = row != null ? row.Name : String.Empty;

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

Select2 open dropdown on focus

This worked for me using Select2 v4.0.3

//Initialize Select2
 jQuery('.js-select').select2();

// Make Select2 respect tab focus
function select2Focus(){
    jQuery(window).keyup(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 9 && jQuery('.select2-search__field:focus').length) {
            jQuery('.js-select').select2('open');
        }
    });
}

select2Focus();

Fork of Irvin Dominin's demo: http://jsfiddle.net/163cwdrw/

CSS - make div's inherit a height

You need to take out a float: left; property... because when you use float the parent div do not grub the height of it's children... If you want the parent dive to get the children height you need to give to the parent div a css property overflow:hidden; But to solve your problem you can use display: table-cell; instead of float... it will automatically scale the div height to its parent height...

Yahoo Finance All Currencies quote API Documentation

As NT3RP told us that:

... we (Yahoo!) don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service...

So I just thought of sharing this site with you:
http://josscrowcroft.github.com/open-exchange-rates/
[update: site has moved to - http://openexchangerates.org]

This site says:

No access fees, no rate limits, no ugly XML - just free, hourly updated exchange rates in JSON format
[update: Free for personal use, a bargain for your business.]

I hope I've helped and this is of some use to you (and others too). : )

How to set text color to a text view programmatically

Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:

textView.setTextColor(getResources().getColor(R.color.some_color));

Please note that from API 23, getResources().getColor() is deprecated. Use instead:

textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));

where the required color is defined in an xml as:

<resources>
  <color name="some_color">#bdbdbd</color>
</resources>

Update:

This method was deprecated in API level 23. Use getColor(int, Theme) instead.

Check this.

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

CheckBox in RecyclerView keeps on checking different items

this is due to again and again creating view ,best option is clear cache before setting adapter

recyclerview.setItemViewCacheSize(your array.size());

PHP Redirect to another page after form submit

You can include your header function wherever you like, as long as NO html and/or text has been printed to standard out.

For more information and usage: http://php.net/manual/en/function.header.php


I see in your code that you echo() out some text in case of error or success. Don't do that: you can't. You can only redirect OR show the text. If you show the text you'll then fail to redirect.

java.lang.IllegalStateException: Fragment not attached to Activity

So the base idea is that you are running a UI operation on a fragment that is getting in the onDetach lifecycle.

When this is happening the fragment is getting off the stack and losing the context of the Activity.

So when you call UI related functions for example calling the progress spinner and you want to leave the fragment check if the Fragment is added to the stack, like this:

if(isAdded){ progressBar.visibility=View.VISIBLE }

How to store a dataframe using Pandas

https://docs.python.org/3/library/pickle.html

The pickle protocol formats:

Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python.

Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.

Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.

Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.

Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4.

How to add a default include path for GCC in Linux?

Try setting C_INCLUDE_PATH (for C header files) or CPLUS_INCLUDE_PATH (for C++ header files).

As Ciro mentioned, CPATH will set the path for both C and C++ (and any other language).

More details in GCC's documentation.

Specify multiple attribute selectors in CSS

Just to add that there should be no space between the selector and the opening bracket.

td[someclass] 

will work. But

td [someclass] 

will not.

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

PHP output showing little black diamonds with a question mark

This happened to work in my case:

$text = utf8_decode($text)

I turns the black diamond character into a question mark so you can:

$text = str_replace('?', '', utf8_decode($text));

Git resolve conflict using --ours/--theirs for all files

function gitcheckoutall() {
    git diff --name-only --diff-filter=U | sed 's/^/"/;s/$/"/' | xargs git checkout --$1
}

I've added this function in .zshrc file.

Use them this way: gitcheckoutall theirs or gitcheckoutall ours

How to check whether a int is not null or empty?

I think you can initialize the variables a value like -1, because if the int type variables is not initialized it can't be used. When you want to check if it is not the value you want you can check if it is -1.

Change the background color of a pop-up dialog

You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.

Something like this:

Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);

Add "Are you sure?" to my excel button, how can I?

On your existing button code, simply insert this line before the procedure:

If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub

This will force it to quit if the user presses no.

Java Loop every minute

Use Thread.sleep(long millis).

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.


For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

How do I simulate placeholder functionality on input date field?

As mentionned here, I've made it work with some ":before" pseudo-class and a small bit of javascript. Here is the idea :

 #myInput:before{ content:"Date of birth"; width:100%; color:#AAA; } 
 #myInput:focus:before,
 #myInput.not_empty:before{ content:none }

Then in javascript, add the "not_empty" class depending on the value in the onChange and onKeyUp events.

You can even add all of this dynamically on every date fields. Check my answer on the other thread for the code.

It's not perfect but it's working well in Chrome and iOS7 webviews. Maybe it could help you.

Read Excel sheet in Powershell

There is the possibility of making something really more cool!

# Powershell 
$xl = new-object -ComObject excell.application
$doc=$xl.workbooks.open("Filepath")
$doc.Sheets.item(1).rows |
% { ($_.value2 | Select-Object -first 3 | Select-Object -last 2) -join "," }

display: inline-block extra margin

There are a number of workarounds for this issue which involve word-spacing or font size but this article suggests removing the margin with a right margin of -4px;

http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/

How to clear the entire array?

It is as simple as :

Erase aFirstArray

SQL: Combine Select count(*) from multiple tables

For oracle:

select( 
select count(*) from foo1 where ID = '00123244552000258'
+
select count(*) from foo2 where ID = '00123244552000258'
+
select count(*) from foo3 where ID = '00123244552000258'
) total from dual;

How do I decrease the size of my sql server log file?

This is one of the best suggestion in which is done using query. Good for those who has a lot of databases just like me. Can run it using a script.

https://medium.com/@bharatdwarkani/shrinking-sql-server-db-log-file-size-sql-server-db-maintenance-7ddb0c331668

USE DatabaseName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DatabaseName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DatabaseName_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DatabaseName
SET RECOVERY FULL;
GO

jquery ajax function not working

I think you have putted e.preventDefault(); before ajax call that's why its prevent calling of that function and your Ajax call will not call.

So try to remove that e.prevent Default() before Ajax call and add it to the after Ajax call.

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

adding comment in .properties files

According to the documentation of the PropertyFile task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.

Generating an array of letters in the alphabet

char alphaStart = Char.Parse("A");
char alphaEnd = Char.Parse("Z");
for(char i = alphaStart; i <= alphaEnd; i++) {
    string anchorLetter = i.ToString();
}

How to add external library in IntelliJ IDEA?

Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries

How to print the data in byte array as characters?

How about Arrays.toString(byteArray)?

Here's some compilable code:

byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));

Output:

[-1, -128, 1, 127]

Why re-invent the wheel...

Sending string via socket (python)

client.py

import socket

s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
    str = raw_input("S: ")
    s.send(str.encode());
    if(str == "Bye" or str == "bye"):
        break
    print "N:",s.recv(1024).decode()
s.close()

server.py

import socket

s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
    rcvdData = c.recv(1024).decode()
    print "S:",rcvdData
    sendData = raw_input("N: ")
    c.send(sendData.encode())
    if(sendData == "Bye" or sendData == "bye"):
        break
c.close()

This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.

How to style the parent element when hovering a child element?

I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).

If you set the parent to be with no pointer-events, and then a child div with pointer-events set to auto, it works:)
Note that <img> tag (for example) doesn't do the trick.
Also remember to set pointer-events to auto for other children which have their own event listener, or otherwise they will lose their click functionality.

_x000D_
_x000D_
div.parent {  _x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
div.child {_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
div.parent:hover {_x000D_
    background: yellow;_x000D_
}    
_x000D_
<div class="parent">_x000D_
  parent - you can hover over here and it won't trigger_x000D_
  <div class="child">hover over the child instead!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)

php random x digit number

This is another simple solution to generate random number of N digits:

$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);

Check it here: http://codepad.org/pyVvNiof

Python string prints as [u'String']

Do you really mean u'String'?

In any event, can't you just do str(string) to get a string rather than a unicode-string? (This should be different for Python 3, for which all strings are unicode.)

Python multiprocessing PicklingError: Can't pickle <type 'function'>

I have found that I can also generate exactly that error output on a perfectly working piece of code by attempting to use the profiler on it.

Note that this was on Windows (where the forking is a bit less elegant).

I was running:

python -m profile -o output.pstats <script> 

And found that removing the profiling removed the error and placing the profiling restored it. Was driving me batty too because I knew the code used to work. I was checking to see if something had updated pool.py... then had a sinking feeling and eliminated the profiling and that was it.

Posting here for the archives in case anybody else runs into it.

POST data with request module on Node.JS

I highly recommend axios https://www.npmjs.com/package/axios install it with npm or yarn

const axios = require('axios');

axios.get('http://your_server/your_script.php')
    .then( response => {
    console.log('Respuesta', response.data);
    })
    .catch( response => {
        console.log('Error', response);
    })
    .finally( () => {
        console.log('Finalmente...');
    });

php execute a background process

Use this function to run your program in background. It cross-platform and fully customizable.

<?php
function startBackgroundProcess(
    $command,
    $stdin = null,
    $redirectStdout = null,
    $redirectStderr = null,
    $cwd = null,
    $env = null,
    $other_options = null
) {
    $descriptorspec = array(
        1 => is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),
        2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),
    );
    if (is_string($stdin)) {
        $descriptorspec[0] = array('pipe', 'r');
    }
    $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);
    if (!is_resource($proc)) {
        throw new \Exception("Failed to start background process by command: $command");
    }
    if (is_string($stdin)) {
        fwrite($pipes[0], $stdin);
        fclose($pipes[0]);
    }
    if (!is_string($redirectStdout)) {
        fclose($pipes[1]);
    }
    if (!is_string($redirectStderr)) {
        fclose($pipes[2]);
    }
    return $proc;
}

Note that after command started, by default this function closes the stdin and stdout of running process. You can redirect process output into some file via $redirectStdout and $redirectStderr arguments.

Note for windows users:
You cannot redirect stdout/stderr to nul in the following manner:

startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');

However, you can do this:

startBackgroundProcess('ping yandex.com >nul 2>&1');

Notes for *nix users:

1) Use exec shell command if you want get actual PID:

$proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');
print_r(proc_get_status($proc));

2) Use $stdin argument if you want to pass some data to the input of your program:

startBackgroundProcess('cat > input.txt', "Hello world!\n");

How to convert C++ Code to C

While you can do OO in C (e.g. by adding a theType *this first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).

I would suggest at least looking at a re-design to compare how this would work out.

Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?

Relationship between hashCode and equals method in Java

See JavaDoc of java.lang.Object

In hashCode() it says:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

(Emphasis by me).

If you only override equals() and not hashCode() your class violates this contract.

This is also said in the JavaDoc of the equals() method:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

How to increase the max upload file size in ASP.NET?

I believe this line in the web.config will set the max upload size:

<system.web>

        <httpRuntime maxRequestLength="600000"/>
</system.web>

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

Using pillow's fromarray, for example:

from PIL import Image
from numpy import *

im = array(Image.open('image.jpg'))
Image.fromarray(im).show()

What's the difference between interface and @interface in java?

interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example:

@interface MyAnnotation {

    String   value();

    String   name();
    int      age();
    String[] newNames();

}

This example defines an annotation called MyAnnotation which has four elements. Notice the @interface keyword. This signals to the Java compiler that this is a Java annotation definition.

Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.

To use the above annotation, you could use code like this:

@MyAnnotation(
    value="123",
    name="Jakob",
    age=37,
    newNames={"Jenkov", "Peterson"}
)
public class MyClass {


}

Reference - http://tutorials.jenkov.com/java/annotations.html

How do I detect "shift+enter" and generate a new line in Textarea?

Why not just

$(".commentArea").keypress(function(e) {
    var textVal = $(this).val();
    if(e.which == 13 && e.shiftKey) {

    }
    else if (e.which == 13) {
       e.preventDefault(); //Stops enter from creating a new line
       this.form.submit(); //or ajax submit
    }
});

What's the best way to do a backwards loop in C/C#/C++?

In C I like to do this:


int i = myArray.Length;
while (i--) {
  myArray[i] = 42;
}

C# example added by MusiGenesis:

{int i = myArray.Length; while (i-- > 0)
{
    myArray[i] = 42;
}}

How to get a list of MySQL views?

Try moving that mysql.bak directory out of /var/lib/mysql to say /root/ or something. It seems like mysql is finding that and it may be causing that ERROR 1102 (42000): Incorrect database name 'mysql.bak' error.

Dialog to pick image from gallery or from camera

The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.

To take picture from camera:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)

To pick photo from gallery:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code

onActivityResult code:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
    switch(requestCode) {
    case 0:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }

    break; 
    case 1:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }
    break;
    }
}

Finally add this permission in the manifest file:

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

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:

   export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/

after that everything worked very well, even without any "-extension RANDR" switch.

App.Config change value

For a .NET 4.0 console application, none of these worked for me. So I modified Kevn Aenmey's answer as below and it worked:

private static void UpdateSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.
        OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save();

    ConfigurationManager.RefreshSection("appSettings");
}

Only the first line is different, constructed upon the actual executing assembly.

GET and POST methods with the same Action name in the same Controller

Can not multi action same name and same parameter

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(int id)
    {
        return View();
    }

althought int id is not used

How to convert base64 string to image?

This should do the trick:

image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()

Generate random string/characters in JavaScript

A newer version with es6 spread operator:

[...Array(30)].map(() => Math.random().toString(36)[2]).join('')

  • The 30 is an arbitrary number, you can pick any token length you want
  • The 36 is the maximum radix number you can pass to numeric.toString(), which means all numbers and a-z lowercase letters
  • The 2 is used to pick the 3rd index from the random string which looks like this: "0.mfbiohx64i", we could take any index after 0.

How to securely save username/password (local)?

I have used this before and I think in order to make sure credential persist and in a best secure way is

  1. you can write them to the app config file using the ConfigurationManager class
  2. securing the password using the SecureString class
  3. then encrypting it using tools in the Cryptography namespace.

This link will be of great help I hope : Click here

Best programming based games

There's racing car simulator game TORCS also where on top of the typical end user playing it (you actually "driving" the cars), you can program robots which control the cars. Regular races are held between robots created by different people.

How to set variable from a SQL query?

Using SELECT

SELECT @ModelID = m.modelid 
  FROM MODELS m
 WHERE m.areaid = 'South Coast'

Using SET

SET @ModelID = (SELECT m.modelid 
                  FROM MODELS m
                 WHERE m.areaid = 'South Coast')

See this question for the difference between using SELECT and SET in TSQL.

Warning

If this SELECT statement returns multiple values (bad to begin with):

  • When using SELECT, the variable is assigned the last value that is returned (as womp said), without any error or warning (this may cause logic bugs)
  • When using SET, an error will occur

Can I edit an iPad's host file?

The easiest way to do this is to run an iPad simulator using XCode and then add an entry in the hosts file (/etc/hosts) on the host system to point to your test site.

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.

I wrote an in-depth blog post about this that you can check out here:

https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

line breaks in a textarea

Ahh, it is really simple

just add

white-space:pre-wrap;

to your displaying element css

I mean if you are showing result using <p> then your css should be

p{
   white-space:pre-wrap;
}

Delete last N characters from field in a SQL Server database

This should do it, removing characters from the left by one or however many needed.

lEFT(columnX,LEN(columnX) - 1) AS NewColumnName

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

jQuery Validate - Enable validation for hidden fields

So I'm going to go a bit deeper in to why this doesn't work because I'm the kind of person that can't sleep at night without knowing haha. I'm using jQuery validate 1.10 and Microsoft jQuery Unobtrusive Validation 2.0.20710.0 which was published on 1/29/2013.

I started by searching for the setDefaults method in jQuery Validate and found it on line 261 of the unminified file. All this function really does is merge your json settings in to the existing $.validator.defaults which are initialized with the ignore property being set to ":hidden" along with the other defaults defined in jQuery Validate. So at this point we've overridden ignore. Now let's see where this defaults property is being referenced at.

When I traced through the code to see where $.validator.defaults is being referenced. I noticed that is was only being used by the constructor for a form validator, line 170 in jQuery validate unminified file.

// constructor for validator
$.validator = function( options, form ) {
    this.settings = $.extend( true, {}, $.validator.defaults, options );
    this.currentForm = form;
    this.init();
};

At this point a validator will merge any default settings that were set and attach it to the form validator. When you look at the code that is doing the validating, highlighting, unhighlighting, etc they all use the validator.settings object to pull the ignore property. So we need to make sure if we are to set the ignore with the setDefaults method then it has to occur before the $("form").validate() is called.

If you're using Asp.net MVC and the unobtrusive plugin, then you'll realize after looking at the javascript that validate is called in document.ready. I've also called my setDefaults in the document.ready block which is going to execute after the scripts, jquery validate and unobtrusive because I've defined those scripts in the html before the one that has the call in it. So my call obviously had no impact on the default functionality of skipping hidden elements during validation. There is a couple of options here.

Option 1 - You could as Juan Mellado pointed out have the call outside of the document.ready which would execute as soon as the script has been loaded. I'm not sure about the timing of this since browsers are now capable of doing parallel script loading. If I'm just being over cautious then please correct me. Also, there's probably ways around this but for my needs I did not go down this path.

Option 2a - The safe bet in my eyes is to just replace the $.validator.setDefaults({ ignore: '' }); inside of the document.ready event with $("form").data("validator").settings.ignore = "";. This will modify the ignore property that is actually used by jQuery validate when doing each validation on your elements for the given form.

Options 2b - After looking in to the code a bit more you could also use $("form").validate().settings.ignore = ""; as a way of setting the ignore property. The reason is that when looking at the validate function it checks to see if a validator object has already been stored for the form element via the $.data() function. If it finds a validator object stored with the form element then it just returns the validator object instead of creating another one.

Rename a column in MySQL

You can use following code:

ALTER TABLE `dbName`.`tableName` CHANGE COLUMN `old_columnName` `new_columnName` VARCHAR(45) NULL DEFAULT NULL ;

libxml/tree.h no such file or directory

On Mountain Lion I was facing same issue, which was resolved by adding /usr/include/libxml2 to include paths with flag "recursive", use this if all above is not fruitful.

Passing references to pointers in C++

EDIT: I experimented some, and discovered thing are a bit subtler than I thought. Here's what I now think is an accurate answer.

&s is not an lvalue so you cannot create a reference to it unless the type of the reference is reference to const. So for example, you cannot do

string * &r = &s;

but you can do

string * const &r = &s;

If you put a similar declaration in the function header, it will work.

void myfunc(string * const &a) { ... }

There is another issue, namely, temporaries. The rule is that you can get a reference to a temporary only if it is const. So in this case one might argue that &s is a temporary, and so must be declared const in the function prototype. From a practical point of view it makes no difference in this case. (It's either an rvalue or a temporary. Either way, the same rule applies.) However, strictly speaking, I think it is not a temporary but an rvalue. I wonder if there is a way to distinguish between the two. (Perhaps it is simply defined that all temporaries are rvalues, and all non-lvalues are temporaries. I'm not an expert on the standard.)

That being said, your problem is probably at a higher level. Why do you want a reference to the address of s? If you want a reference to a pointer to s, you need to define a pointer as in

string *p = &s;
myfunc(p);

If you want a reference to s or a pointer to s, do the straightforward thing.

Javascript - How to extract filename from a file input control

var pieces = str.split('\\');
var filename = pieces[pieces.length-1];

What is useState() in React?

useState is one of the hooks available in React v16.8.0. It basically lets you turn your otherwise non-stateful/functional components to one that can have its own state.

At the very basic level, it's used this way:

const [isLoading, setLoading] = useState(true);

This then lets you call setLoading passing a boolean value. It's a cool way of having "stateful" functional component.

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

Assign null to a SqlParameter

Try this:

SqlParameter[] parameters = new SqlParameter[1];    
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);

planIndexParameter.IsNullable = true; // Add this line

planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex== ;
parameters[0] = planIndexParameter;

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

document.ondomcontentready=function(){} should do the trick, but it doesn't have full browser compatibility.

Seems like you should just use jQuery min

Why doesn't height: 100% work to expand divs to the screen height?

Try to play around also with the calc and overflow functions

.myClassName {
    overflow: auto;
    height: calc(100% - 1.5em);
}

Best Practice: Software Versioning

We use a.b.c.d where

  • a - major (incremented on delivery to client)
  • b - minor (incremented on delivery to client)
  • c - revision (incremented on internal releases)
  • d - build (incremented by cruise control)

Read Excel File in Python

The approach I took reads the header information from the first row to determine the indexes of the columns of interest.

You mentioned in the question that you also want the values output to a string. I dynamically build a format string for the output from the FORMAT column list. Rows are appended to the values string separated by a new line char.

The output column order is determined by the order of the column names in the FORMAT list.

In my code below the case of the column name in the FORMAT list is important. In the question above you've got 'Pincode' in your FORMAT list, but 'PinCode' in your excel. This wouldn't work below, it would need to be 'PinCode'.

from xlrd import open_workbook
wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
    formatString = ("%s,"*len(columnIndex))[0:-1] + "\n"

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        values += formatString % tuple(currentRowValues)

print values

For the sample input you gave above this code outputs:

>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0

And because I'm a python noob, props be to: this answer, this answer, this question, this question and this answer.

How to post JSON to PHP with curl

You should escape the quotes like this:

curl -i -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}'  \
  http://localhost:3570/index.php/trainingServer/screencast.json

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

Why is it string.join(list) instead of list.join(string)?

It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.

For example:

'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))
'welcome_to_stack_overflow'

Using something other than strings will raise the following error:

TypeError: sequence item 0: expected str instance, int found

Html attributes for EditorFor() in ASP.NET MVC

Update MVC 5.1 now supports the below approach directly, so it works for built in editor too. http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features (It's either a case of Great mind thinking alike or they read my answer :)

End Update

If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.

@Html.EditorFor(modelItem => item.YourProperty, 
  new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px"  } })

then in your template (not required for simple types in MVC 5.1)

@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])

Reading HTML content from a UIWebView

Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.

Also note that the @"document.body.innerHTML" mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML" you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.

AFNetworking Post Request

for login screen;

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary 

dictionaryWithObjectsAndKeys:_usernametf.text, @"username",_passwordtf.text, @"password", nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

[manager POST:@"enter your url" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"%@", responseObject);

}
      failure:^(NSURLSessionTask *operation, NSError *error) {
          NSLog(@"Error: %@", error);
      }];

}

How to decrease prod bundle size?

If you have run ng build --prod - you shouldn't have vendor files at all.

If I run just ng build - I get these files:

enter image description here

The total size of the folder is ~14MB. Waat! :D

But if I run ng build --prod - I get these files:

enter image description here

The total size of the folder is 584K.

One and the same code. I have enabled Ivy in both cases. Angular is 8.2.13.

So - I guess you didn't add --prod to your build command?

How to display string that contains HTML in twig template?

You can also use:

{{ word|striptags('<b>')|raw }}

so that only <b> tag will be allowed.

How to grant remote access to MySQL for a whole subnet?

MySQL 8.0.23 onwards now support CIDR notation also.

So, basically:

-- CIDR Notation
GRANT ... TO 'user'@'192.168.1.0/24' IDENTIFIED BY ...

-- Netmask Notation
GRANT ... TO 'user'@'192.168.1.0/255.255.255.0' IDENTIFIED BY ...

How to delete and recreate from scratch an existing EF Code First database

How about ..

static void Main(string[] args)
{
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ExampleContext>());  
    // C
    // o
    // d
    // i
    // n
    // g
}

I picked this up from Programming Entity Framework: Code First, Pg 28 First Edition.

Create Pandas DataFrame from a string

A quick and easy solution for interactive work is to copy-and-paste the text by loading the data from the clipboard.

Select the content of the string with your mouse:

Copy data for pasting into a Pandas dataframe

In the Python shell use read_clipboard()

>>> pd.read_clipboard()
  col1;col2;col3
0       1;4.4;99
1      2;4.5;200
2       3;4.7;65
3      4;3.2;140

Use the appropriate separator:

>>> pd.read_clipboard(sep=';')
   col1  col2  col3
0     1   4.4    99
1     2   4.5   200
2     3   4.7    65
3     4   3.2   140

>>> df = pd.read_clipboard(sep=';') # save to dataframe

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

in case some one still get this kind of message. Its happen because you add JVM argument when running maven project. Because it is related with maven you can check your pom.xml file on your project.

find this line <argLine>...</argLine>, on my project I also have argument below

<argLine>-Xmx1024m -XX:MaxPermSize=512m -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>

you should replace MaxPermSize argument as -Xms123m -Xmx123m, since MaxPermSize is already deprecated and wont take any effect on your JVM config :

<argLine>-Xms512m -Xmx512m  -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>

converting CSV/XLS to JSON?

I just found this:

http://tamlyn.org/tools/csv2json/

( Note: you have to have your csv file available via a web address )

Conversion from List<T> to array T[]

To go twice as fast by using multiple processor cores HPCsharp nuget package provides:

list.ToArrayPar();

What is meant by Ems? (Android TextView)

Ems is a typography term, it controls text size, etc. Check here

How do I calculate square root in Python?

If you want to do it the way the calculator actually does it, use the Babylonian technique. It is explained here and here.

Suppose you want to calculate the square root of 2:

a=2

a1 = (a/2)+1
b1 = a/a1
aminus1 = a1
bminus1 = b1


while (aminus1-bminus1 > 0):
    an = 0.5 * (aminus1 + bminus1)
    bn = a / an
    aminus1 = an
    bminus1 = bn
    print(an,bn,an-bn)

MySQL Update Column +1?

update table_name set field1 = field1 + 1;

AngularJS Error: $injector:unpr Unknown Provider

Your angular module needs to be initialized properly. The global object app needs to be defined and initialized correctly to inject the service.

Please see below sample code for reference:

app.js

var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket    

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/', {
      templateUrl:"partials/login.html",
      controller:"login"
    });

  $locationProvider
    .html5Mode(true);
}]);

app.factory('getSettings', ['$http', '$q', function($http, $q) {
  return {
    //Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand...
    getSetting: function (type) { 
      var q = $q.defer();
      $http.get('models/settings.json').success(function (data) {
        q.resolve(function() {
          var settings = jQuery.parseJSON(data);
          return settings[type];
        });
      });
      return q.promise;
    }
  }
}]);

app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
  //Modified the function call for updated service
  var loadSettings = getSettings.getSetting('global');
  loadSettings.then(function(val) {
    $scope.settings = val;
  });
}]);

Sample HTML code should be like this:

<!DOCTYPE html>
<html>
    <head lang="en">
        <title>Sample Application</title>
    </head>
    <body ng-app="SampleApp" ng-controller="globalControl">
        <div>
            Your UI elements go here
        </div>
        <script src="app.js"></script>
    </body>
</html>

Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.

I hope this will solve your basic injection issue.

Adding an onclick function to go to url in JavaScript?

If you would like to open link in a new tab, you can:

$("a#thing_to_click").on('click',function(){
    window.open('https://yoururl.com', '_blank');
});

How does tuple comparison work in Python?

The python 2.5 documentation explains it well.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

Unfortunately that page seems to have disappeared in the documentation for more recent versions.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

In my case, there was no process to kill.

Updating docker fixed the problem.

How to run regasm.exe from command line other than Visual Studio command prompt?

For the 64-bit RegAsm.exe you will need to find it someplace like this:

c:\Windows\Microsoft.NET\Framework64\version_number_stuff\regasm.exe

Git: How do I list only local branches?

To complement @gertvdijk's answer - I'm adding few screenshots in case it helps someone quick.

On my git bash shell

git branch

command without any parameters shows all my local branches. The current branch which is currently checked out is shown in different color (green) along with an asterisk (*) prefix which is really intuitive.

enter image description here

When you try to see all branches including the remote branches using

git branch -a

command then remote branches which aren't checked out yet are shown in red color:

enter image description here

:touch CSS pseudo-class or something similar?

I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

As my purpose is to get an empty version of the test database to import data from an external previous current active source (Access database) once all is fine tuned. I found that using DBCC CloneDatabase with Verify_CloneDB option fits perfectly.

Converting string to double in C#

You can try this example out. A simple C# progaram to convert string to double

class Calculations{

protected double length;
protected double height;
protected double width;

public void get_data(){

this.length = Convert.ToDouble(Console.ReadLine());
this.width  = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());

   }
}

Java: get greatest common divisor

As far as I know, there isn't any built-in method for primitives. But something as simple as this should do the trick:

public int gcd(int a, int b) {
   if (b==0) return a;
   return gcd(b,a%b);
}

You can also one-line it if you're into that sort of thing:

public int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); }

It should be noted that there is absolutely no difference between the two as they compile to the same byte code.

Change a HTML5 input's placeholder color with CSS

Placeholder color on specific element in different browsers.

HTML

<input class='contact' type="email" placeholder="[email protected]">

CSS 

    .contact::-webkit-input-placeholder { /* Chrome/Opera/Safari */
      color: pink;
    }
    .contact::-moz-placeholder { /* Firefox 19+ */
      color: pink;
    }
    .contact:-ms-input-placeholder { /* IE 10+ */
      color: pink;
    }
    .contact:-moz-placeholder { /* Firefox 18- */
      color: pink;
    }

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

Add below code in your client code :

static {
    Security.insertProviderAt(new BouncyCastleProvider(),1);
 }

with this there is no need to add any entry in java.security file.

Measuring text height to be drawn on Canvas ( Android )

@bramp's answer is correct - partially, in that it does not mention that the calculated boundaries will be the minimum rectangle that contains the text fully with implicit start coordinates of 0, 0.

This means, that the height of, for example "Py" will be different from the height of "py" or "hi" or "oi" or "aw" because pixel-wise they require different heights.

This by no means is an equivalent to FontMetrics in classic java.

While width of a text is not much of a pain, height is.

In particular, if you need to vertically center-align the drawn text, try getting the boundaries of the text "a" (without quotes), instead of using the text you intend to draw. Works for me...

Here's what I mean:

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);

paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(textSize);

Rect bounds = new Rect();
paint.getTextBounds("a", 0, 1, bounds);

buffer.drawText(this.myText, canvasWidth >> 1, (canvasHeight + bounds.height()) >> 1, paint);
// remember x >> 1 is equivalent to x / 2, but works much much faster

Vertically center aligning the text means vertically center align the bounding rectangle - which is different for different texts (caps, long letters etc). But what we actually want to do is to also align the baselines of rendered texts, such that they did not appear elevated or grooved. So, as long as we know the center of the smallest letter ("a" for example) we then can reuse its alignment for the rest of the texts. This will center align all the texts as well as baseline-align them.

JavaScript function in href vs. onclick

I experienced that the javascript: hrefs did not work when the page was embedded in Outlook's webpage feature where a mail folder is set to instead show an url

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Android button background color

Just use a MaterialButton and the app:backgroundTint attribute:

<MaterialButton
  app:backgroundTint="@color/my_color_selector"

enter image description here

Can I configure a subdomain to point to a specific port on my server

If you only got one IP on the server, there is no chance to do that. DNS is a simple name to number (IP) resolver. If you have two IPs on the server, you can point each subdomain to each of the IP-addresses and run both servers on the default port on each IP.
one.example.com -> 127.0.0.1 (server: 127.0.0.1:25565)
two.example.com -> 127.0.0.2 (server: 127.0.0.2:25565)

git push says "everything up-to-date" even though I have local changes

Another situation that is important to be aware of: The sort of default state for git is that you are working in the "master" branch. And for a lot of situations, you'll just hang out in that as your main working branch (although some people get fancy and do other things).

Anyway, that's just one branch. So a situation I might get into is:

My active branch is actually NOT the master branch. ... But I habitually do the command: git push (and I had previously done git push origin master, so it's a shortcut for THAT).

So I'm habitually pushing the master branch to the shared repo ... which is probably a good clean thing, in my case ...

But I have forgotten that the changes I have been working on are not yet IN the master branch !!!

So therefore everytime I try git push, and I see "Everything up to date", I want to scream, but of course, it is not git's fault! It's mine.

So instead, I merge my branch into master, and then do push, and everything is happy again.

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

How can I render a list select box (dropdown) with bootstrap?

Another way without using the .form-control is this:

  $(".dropdown-menu li a").click(function(){
        $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');
        $(this).parents(".btn-group").find('.btn').val($(this).data('value'));
      });

_x000D_
_x000D_
$(".dropdown-menu li a").click(function(){_x000D_
  $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');_x000D_
  $(this).parents(".btn-group").find('.btn').val($(this).data('value'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button  type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
                  Test <span class="caret"> </span>_x000D_
  </button>_x000D_
  <ul class="dropdown-menu">_x000D_
    <li><a href='#'>test 1</a></li>_x000D_
    <li><a href='#'>test 2</a></li>_x000D_
    <li><a href='#'>test 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Read specific columns with pandas or other python module

An easy way to do this is using the pandas library like this.

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name

The problem here was the skipinitialspace which remove the spaces in the header. So ' star_name' becomes 'star_name'

Making a UITableView scroll when text field is selected

in viewdidload

-(void)viewdidload{

[super viewdidload];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

    -(void)keyboardWillChange:(NSNotification*)sender{

        NSLog(@"keyboardwillchange sender %@",sender);

float margin=0  // set your own topmargin


        CGFloat originY = [[sender.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;


        if (originY >= self.view.frame.size.height){

            NSLog(@"keyboardclose");



            [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, self.view.frame.size.height-margin)];

        }else{

            NSLog(@"keyobard on");

            float adjustedHeight = self.view.frame.size.height - margin - (self.view.frame.size.height-originY);

            [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, adjustedHeight)];
        }







    }

What issues should be considered when overriding equals and hashCode in Java?

There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!

Lazy loaded objects are subclasses

If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass() will return false. For example:

Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy

If you're dealing with an ORM, using o instanceof Person is the only thing that will behave correctly.

Lazy loaded objects have null-fields

ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name will be null if person is lazy loaded, even if person.getName() forces loading and returns "John Doe". In my experience, this crops up more often in hashCode() and equals().

If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode() and equals().

Saving an object will change its state

Persistent objects often use a id field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode(). But you can use it in equals().

A pattern I often use is

if (this.getId() == null) {
    return this == other;
}
else {
    return this.getId().equals(other.getId());
}

But: you cannot include getId() in hashCode(). If you do, when an object is persisted, its hashCode changes. If the object is in a HashSet, you'll "never" find it again.

In my Person example, I probably would use getName() for hashCode and getId() plus getName() (just for paranoia) for equals(). It's okay if there are some risk of "collisions" for hashCode(), but never okay for equals().

hashCode() should use the non-changing subset of properties from equals()

What's the best UI for entering date of birth?

I would take a DatePicker. It's the only component that allows expert users to enter it manually and guides novices to enter a date very easy.

The calendar should not pop up if you enter via pressing tab, but clicking on a button. So no expert user is annoyed of it.

How to make sure docker's time syncs with that of the host?

I was facing a time offset of -1hour and 4min

Restarting Docker itself fixed the issue for me.

To set the timezone in general:

  1. ssh into your container: docker exec -it my_website_name bash

  2. run dpkg-reconfigure tzdata

  3. run date

Get bitcoin historical data

Bitstamp has live bitcoin data that are publicly available in JSON at this link. Do not try to access it more than 600 times in ten minutes or else they'll block your IP (plus, it's unnecessary anyway; read more here). The below is a C# approach to getting live data:

using (var WebClient = new System.Net.WebClient())
{
     var json = WebClient.DownloadString("https://www.bitstamp.net/api/ticker/");
     string value = Convert.ToString(json);
     // Parse/use from here
}

From here, you can parse the JSON and store it in a database (or with MongoDB insert it directly) and then access it.

For historic data (depending on the database - if that's how you approach it), do an insert from a flat file, which most databases allow you to use (for instance, with SQL Server you can do a BULK INSERT from a CSV file).

How to decompile to java files intellij idea

You could use one of these (you can both use them online or download them, there is some info about each of them) : http://www.javadecompilers.com/

The one IntelliJ IDEA uses is fernflower, but it can't handle recent things - like String/Enum switches, generics (didn't test this one personally, only read about it), ... I just tried cfr from the above website and the result was the same as with the built-in decompiler (except for the Enum switch I had in my class).

What is LDAP used for?

Light weight directory access protocal is used to authenticate users to access AD information

How to support UTF-8 encoding in Eclipse

You can set a default encoding-set whenever you run eclipse.exe.

  1. Open eclipse.ini in your eclipse home directory Or STS.ini in case of STS(Spring Tool Suite)
  2. put the line below at the end of the file

-Dfile.encoding=UTF-8

What is the proper declaration of main in C++?

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

as the type of main.

This makes it clear that alternative spellings are permitted so long as the type of main is the type int() or int(int, char**). So the following are also permitted:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

How to return JSON with ASP.NET & jQuery

Just return object: it will be parser to JSON.

public Object Get(string id)
{
    return new { id = 1234 };
}

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

In my case (Windows 10 + IIS 10) i had to open "Turn Windows Features On or Off" and then go to Internet Information Services > World Wide Web Services > Application Development Features > and check ASP.NET 4.6

CSS image resize percentage of itself?

This is a very old thread but I found it while searching for a simple solution to display retina (high res) screen capture on standard resolution display.

So there is an HTML only solution for modern browsers :

<img srcset="image.jpg 100w" sizes="50px" src="image.jpg"/>

This is telling the browser that the image is twice the dimension of it intended display size. The value are proportional and do not need to reflect the actual size of the image. One can use 2w 1px as well to achieve the same effect. The src attribute is only used by legacy browsers.

The nice effect of it is that it display the same size on retina or standard display, shrinking on the latter.

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

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

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

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Why won't bundler install JSON gem?

bundle update json. Helped to get through.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

It looks like you're trying to run it on a version of ASP.NET which is running CLR v2. It's hard to know exactly what's going on without more information about how you've deployed it, what version of IIS you're running etc (and to be frank I wouldn't be very much help at that point anyway, though others would). But basically, check your IIS and ASP.NET set-up, and make sure that everything is running v4. Check your application pool configuration, etc.

Detecting IE11 using CSS Capability/Feature Detection

Detecting IE and its versions actually is extremely easy, at least extremely intuitive:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8
    browser = 'IE';
    ieVersion = document.documentMode;
}

.

This way, ou're also catching high IE versions in Compatibility Mode/View. Next, its a matter of assigning conditional classes:

var htmlTag = document.documentElement;
if (browser == 'IE' && ieVersion <= 11)
    htmlTag.className += ' ie11-';

How to get Git to clone into current directory

Improving on @GoZoner's answer:

git clone <repository> foo; shopt -s dotglob nullglob; mv foo/* .; rmdir foo

The shopt command is taken from this SO answer and changes the behavior of the 'mv' command on Bash to include dotfiles, which you'll need to include the .git directory and any other hidden files.

Also note that this is only guaranteed to work as-is if the current directory (.) is empty, but it will work as long as none of the files in the cloned repo have the same name as files in the current directory. If you don't care what's in the current directory, you can add the -f (force) option to the 'mv' command.

Why is C so fast, and why aren't other languages as fast or faster?

Back in the good ole days, there were just two types of languages: compiled and interpreted.

Compiled languages utilized a "compiler" to read the language syntax and convert it into identical assembly language code, which could than just directly on the CPU. Interpreted languages used a couple of different schemes, but essentially the language syntax was converted into an intermediate form, and then run in a "interpreter", an environment for executing the code.

Thus, in a sense, there was another "layer" -- the interpreter -- between the code and the machine. And, as always the case in a computer, more means more resources get used. Interpreters were slower, because they had to perform more operations.

More recently, we've seen more hybrid languages like Java, that employ both a compiler and an interpreter to make them work. It's complicated, but a JVM is faster, more sophisticated and way more optimized than the old interpreters, so it stands a much better change of performing (over time) closer to just straight compiled code. Of course, the newer compilers also have more fancy optimizing tricks so they tend to generate way better code than they used to as well. But most optimizations, most often (although not always) make some type of trade-off such that they are not always faster in all circumstances. Like everything else, nothing comes for free, so the optimizers must get their boast from somewhere (although often times it using compile-time CPU to save runtime CPU).

Getting back to C, it is a simple language, that can be compiled into fairly optimized assembly and then run directly on the target machine. In C, if you increment an integer, it's more than likely that it is only one assembler step in the CPU, in Java however, it could end up being a lot more than that (and could include a bit of garbage collection as well :-) C offers you an abstraction that is way closer to the machine (assembler is the closest), but you end up having to do way more work to get it going and it is not as protected, easy to use or error friendly. Most other languages give you a higher abstraction and take care of more of the underlying details for you, but in exchange for their advanced functionality they require more resources to run. As you generalize some solutions, you have to handle a broader range of computing, which often requires more resources.

Paul.

CakePHP find method with JOIN

        $services = $this->Service->find('all', array(
            'limit' =>4,
            'fields' => array('Service.*','ServiceImage.*'),
            'joins' => array(
                array(
                        'table' => 'services_images',
                        'alias' => 'ServiceImage',
                        'type' => 'INNER',
                        'conditions' => array(
                        'ServiceImage.service_id' =>'Service.id'
                        )
                    ),
                ),
            )
        );

It goges to array is null.

How to customize listview using baseadapter

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

custom.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

        <LinearLayout
            android:layout_width="255dp"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Video1"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#339966"
                    android:textStyle="bold" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/detail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="video1"
                    android:textColor="#606060" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

</LinearLayout>

main.java:

package com.example.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends Activity {

    ListView l1;
    String[] t1={"video1","video2"};
    String[] d1={"lesson1","lesson2"};
    int[] i1 ={R.drawable.ic_launcher,R.drawable.ic_launcher};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        l1=(ListView)findViewById(R.id.list);
        l1.setAdapter(new dataListAdapter(t1,d1,i1));
    }

    class dataListAdapter extends BaseAdapter {
        String[] Title, Detail;
        int[] imge;

        dataListAdapter() {
            Title = null;
            Detail = null;
            imge=null;
        }

        public dataListAdapter(String[] text, String[] text1,int[] text3) {
            Title = text;
            Detail = text1;
            imge = text3;

        }

        public int getCount() {
            // TODO Auto-generated method stub
            return Title.length;
        }

        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = getLayoutInflater();
            View row;
            row = inflater.inflate(R.layout.custom, parent, false);
            TextView title, detail;
            ImageView i1;
            title = (TextView) row.findViewById(R.id.title);
            detail = (TextView) row.findViewById(R.id.detail);
            i1=(ImageView)row.findViewById(R.id.img);
            title.setText(Title[position]);
            detail.setText(Detail[position]);
            i1.setImageResource(imge[position]);

            return (row);
        }
    }
}

Try this.

Php, wait 5 seconds before executing an action

In Jan2018 the only solution worked for me:

<?php

if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){

    echo "<br> Line to show.";
    echo str_pad('',4096)."\n";    

    ob_flush();
    flush();
    sleep(2);
}

echo "Done.";

ob_end_flush();

?>

jquery to change style attribute of a div class

Try with

$('.handle').css({'left': '300px'});

Instead of

$('.handle').css({'style':'left: 300px'})

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Others have answered so I'll add my 2-cents.

You can either use autoconfiguration (i.e. don't use a @Configuration to create a datasource) or java configuration.

Auto-configuration:

define your datasource type then set the type properties. E.g.

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
spring.datasource.hikari.username=sa
spring.datasource.hikari.password=password
spring.datasource.hikari.max-wait=10000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.leak-detection-threshold=600000
spring.datasource.hikari.maximum-pool-size=100
spring.datasource.hikari.pool-name=MyDataSourcePoolName

Java configuration:

Choose a prefix and define your data source

spring.mysystem.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.mysystem.datasource.jdbc- 
url=jdbc:sqlserver://databaseserver.com:18889;Database=MyDatabase;
spring.mysystem.datasource.username=dsUsername
spring.mysystem.datasource.password=dsPassword
spring.mysystem.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.mysystem.datasource.max-wait=10000
spring.mysystem.datasource.connection-timeout=30000
spring.mysystem.datasource.idle-timeout=600000
spring.mysystem.datasource.max-lifetime=1800000
spring.mysystem.datasource.leak-detection-threshold=600000
spring.mysystem.datasource.maximum-pool-size=100
spring.mysystem.datasource.pool-name=MySystemDatasourcePool

Create your datasource bean:

@Bean(name = { "dataSource", "mysystemDataSource" })
@ConfigurationProperties(prefix = "spring.mysystem.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

You can leave the datasource type out, but then you risk spring guessing what datasource type to use.

Erasing elements from a vector

  1. You can iterate using the index access,

  2. To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.

code:

void erase(std::vector<int>& v, int num)
{
  size_t j = 0;
  for (size_t i = 0; i < v.size(); ++i) {
    if (v[i] != num) v[j++] = v[i];
  }
  // trim vector to new size
  v.resize(j);
}

In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.

This code does not use erase method, but solves your task.

Using pure stl you can do this in the following way (this is similar to the Motti's answer):

#include <algorithm>

void erase(std::vector<int>& v, int num) {
    vector<int>::iterator it = remove(v.begin(), v.end(), num);
    v.erase(it, v.end());
}

Purpose of __repr__ method?

The __repr__ method simply tells Python how to print objects of a class

How do you know if Tomcat Server is installed on your PC

Open your windows search bar, and search for the keyword Tomcat. If a shortcut file is found instead, you can open the source file location of the shortcut by right-clicking the shortcut file and selecting the Properties.

How to set a cookie for another domain

Here is what I've used. Note, this cookie is passed in the open (http) and is therefore insecure. I don't use it for anything which requires security.

  1. Site A generates a token and passes as a URL parameter to site B.
  2. Site B takes the token and sets it as a session cookie.

You could probably add encryption/signatures to make this secure. Do your research on how to do that correctly.

Jquery - How to get the style display attribute "none / block"

You could try:

$j('div.contextualError.ckgcellphone').css('display')