Programs & Examples On #Jflow

Wampserver icon not going green fully, mysql services not starting up?

I was running on the same problem, wampmysqld64 did not start, so I checked the Mysql log which you should find it inside the main wamp64 folder, and I found all the details on why is not working. on my computer I found another mysql instance is running so it prevents the wampmysqld64 to start. I stopped the other instance, and everything works fine after.

How to resize superview to fit all subviews with autolayout?

You can do this by creating a constraint and connecting it via interface builder

See explanation: Auto_Layout_Constraints_in_Interface_Builder

raywenderlich beginning-auto-layout

AutolayoutPG Articles constraint Fundamentals

@interface ViewController : UIViewController {
    IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
    IBOutlet NSLayoutConstraint *topSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;

connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this

 self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign

I hope this clarifies it.

Disable scrolling on `<input type=number>`

First you must stop the mousewheel event by either:

  1. Disabling it with mousewheel.disableScroll
  2. Intercepting it with e.preventDefault();
  3. By removing focus from the element el.blur();

The first two approaches both stop the window from scrolling and the last removes focus from the element; both of which are undesirable outcomes.

One workaround is to use el.blur() and refocus the element after a delay:

$('input[type=number]').on('mousewheel', function(){
  var el = $(this);
  }, 10);

How can I regenerate ios folder in React Native project?

? react-native eject

error Unrecognized command "eject". info Run "react-native --help" to see a list of all available commands.

? react-native upgrade --legacy true

error: unknown option `--legacy'

You can init a new project that's named the same in another folder and copy ios dir over:

inside YourProjectName directory

npx react-native init YourProjectName
mv YourProjectName/ios ios
rm -rf YourProjectName

Make sure you have clean git history before doing so, in case you need to revert

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Here is the swift version (by using @Nitesh Borad objective C code) :-

   if let img: UIImage = UIImage(data: previewImg[indexPath.row]) {
                cell.cardPreview.image = img
            } else {
                // The image isn't cached, download the img data
                // We should perform this in a background thread
                let imgURL = NSURL(string: "webLink URL")
                let request: NSURLRequest = NSURLRequest(URL: imgURL!)
                let session = NSURLSession.sharedSession()
                let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
                    let error = error
                    let data = data
                    if error == nil {
                        // Convert the downloaded data in to a UIImage object
                        let image = UIImage(data: data!)
                        // Store the image in to our cache
                        self.previewImg[indexPath.row] = data!
                        // Update the cell
                        dispatch_async(dispatch_get_main_queue(), {
                            if let cell: YourTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as? YourTableViewCell {
                                cell.cardPreview.image = image
                    } else {
                        cell.cardPreview.image = UIImage(named: "defaultImage")

Can you get the number of lines of code from a GitHub repository?

There in another online tool that counts lines of code for public and private repos without having to clone/download them -


How to create an empty array in PHP with predefined size?

Possibly related, if you want to initialize and fill an array with a range of values, use PHP's (wait for it...) range function:

$a = range(1, 5);  // array(1,2,3,4,5)
$a = range(0, 10, 2); // array(0,2,4,6,8,10)

How to POST JSON data with Python Requests?

From requests 2.4.2 (, the "json" parameter is supported. No need to specify "Content-Type". So the shorter version:'', json={'test': 'cheers'})

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: Any string value you assign to will stay there until the window is closed.

To test it out, just open the console and type = "foo", then refresh the page and type; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider. has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

javascript: using a condition in switch case

You can use fall-through method in switch case.

const x = 'Welcome';

switch (x) {
  case 'Come':

  case 'Welcome':
  case 'Wel':
  case 'come':

  case 'Wel':


> Result => 2

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');

How to set HTML5 required attribute in Javascript?

try out this..

document.getElementById("edName").required = true;

How to return a file using Web API?

Better to return HttpResponseMessage with StreamContent inside of it.

Here is example:

public HttpResponseMessage GetFile(string id)
    if (String.IsNullOrEmpty(id))
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    string fileName;
    string localFilePath;
    int fileSize;

    localFilePath = getFileFromID(id, out fileName, out fileSize);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return response;

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

RelativeLayout center vertical



How does a PreparedStatement avoid or prevent SQL injection?

Prepared statement is more secure. It will convert a parameter to the specified type.

For example stmt.setString(1, user); will convert the user parameter to a String.

Suppose that the parameter contains a SQL string containing an executable command: using a prepared statement will not allow that.

It adds metacharacter (a.k.a. auto conversion) to that.

This makes it is more safe.

Lodash - difference between .extend() / .assign() and .merge()

Another difference to pay attention to is handling of undefined values:

mergeInto = { a: 1}
toMerge = {a : undefined, b:undefined}
lodash.extend({}, mergeInto, toMerge) // => {a: undefined, b:undefined}
lodash.merge({}, mergeInto, toMerge)  // => {a: 1, b:undefined}

So merge will not merge undefined values into defined values.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I had this problem after changing the password for the root user in phpMyAdmin. I know nothing about programming but I solved it by doing the following:

  1. Go to file C:\wamp\apps\phpmyadmin3.2.0.1\ (I guess you would replace "wamp" with the name of your server if you're not using Wamp Server)

  2. Find the line $cfg['Servers'][$i]['password']='' and change this to

  3. Try opening phpMyAdmin again, and hopefully the message will now read "Access denied for user 'root'@'localhost' (using password: YES)

  4. Now change the password in the above line to 'yourpassword' (whatever you had set it to before)

Hope this helps somebody.

Why don’t my SVG images scale using the CSS "width" property?

The transform CSS property lets you rotate, scale, skew, or translate an element.

So you can easily use the transform: scale(2.5); option to scale 2.5 times for example.

Speed up rsync with Simultaneous/Concurrent File Transfers?

The shortest version I found is to use the --cat option of parallel like below. This version avoids using xargs, only relying on features of parallel:

cat files.txt | \
  parallel -n 500 --lb --pipe --cat rsync --files-from={} user@remote:/dir /dir -avPi

#### Arg explainer
# -n 500           :: split input into chunks of 500 entries
# --cat            :: create a tmp file referenced by {} containing the 500 
#                     entry content for each process
# user@remote:/dir :: the root relative to which entries in files.txt are considered
# /dir             :: local root relative to which files are copied

Sample content from files.txt:


Note that this doesn't use -j 50 for job count, that didn't work on my end here. Instead I've used -n 500 for record count per job, calculated as a reasonable number given the total number of records.

Select default option value from typescript angular 6

In my case I'm using the same markup for editing an existing entity, or creating a brand new one (so far anyway).

I want to display a default-value that is "selected" in the select-elements when in creationMode, while displaying the values form the backend in editMode.

My solution is:

<select [(ngModel)]="" id="property" name="property" required>
  <option disabled hidden value="undefined">Enter prop</option>
  <option *ngFor="let prop of sortedProps" value="{{prop.value}}">{{prop.displayName}}</option>

for the regular available options I'm using a sortedProps Array to provide option choices. But that's not the important part here.

What did the trick for me is setting value="undefined" to let the angular-model-binding (?) select this option automatically when in creationMode. Not sure if its a hack, but does exactly what i want. No addtionally typeScript necessary.

Additionally, sepcifing hidden makes sure the option in my case is not selectable, while required makes sure the form is invalid unless something gets selected there.

How to pipe list of files returned by find command to cat to view all the files

The find command has an -exec argument that you can use for things like this, you could just do the grep directly using that.

For example (from here, other good examples at this page):

find . -exec grep "www.athabasca" '{}' \; -print 

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You can trigger a file input element by sending it a Javascript click event, e.g.

<input type="file" ... id="file-input">


You could put this in a click event handler for the image, for instance, then hide the file input with CSS. It'll still work even if it's invisible.

Once you've got that part working, you can set a change event handler on the input element to see when the user puts a file into it. This event handler can create a temporary "blob" URL for the image by using window.URL.createObjectURL, e.g.:

var file = document.getElementById("file-input").files[0];
var blob_url = window.URL.createObjectURL(file);

That URL can be set as the src for an image on the page. (It only works on that page, though. Don't try to save it anywhere.)

Note that not all browsers currently support camera capture. (In fact, most desktop browsers don't.) Make sure your interface still makes sense if the user gets asked to pick a file.

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

Convert tuple to list and back

Why don't you try converting its type from a tuple to a list and vice versa.

level1 = (


level1 = list(level1)


level1 = tuple(level1)


display: flex not working on Internet Explorer

Internet Explorer doesn't fully support Flexbox due to:

Partial support is due to large amount of bugs present (see known issues).

enter image description here Screenshot and infos taken from


Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.

Known issues

  • IE 11 requires a unit to be added to the third argument, the flex-basis property see MSFT documentation.
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property. See bug.
  • In IE10 the default value for flex is 0 0 auto rather than 0 1 auto as defined in the latest spec.
  • IE 11 does not vertically align items correctly when min-height is used. See bug.


Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.

  1. Minimum content sizing of flex items not honored
  2. Column flex items set to align-items: center overflow their container
  3. min-height on a flex container won't apply to its flex items
  4. flex shorthand declarations with unitless flex-basis values are ignored
  5. Column flex items don't always preserve intrinsic aspect ratios
  6. The default flex value has changed
  7. flex-basis doesn't account for box-sizing: border-box
  8. flex-basis doesn't support calc()
  9. Some HTML elements can't be flex containers
  10. align-items: baseline doesn't work with nested flex containers
  11. Min and max size declarations are ignored when wrapping flex items
  12. Inline elements are not treated as flex-items
  13. Importance is ignored on flex-basis when using flex shorthand
  14. Shrink-to-fit containers with flex-flow: column wrap do not contain their items
  15. Column flex items ignore margin: auto on the cross axis
  16. flex-basis cannot be animated
  17. Flex items are not correctly justified when max-width is used

Appending to an object

jQuery $.extend(obj1, obj2) would merge 2 objects for you, but you should really be using an array.

var alertsObj = {
    1: {app:'helloworld','message'},
    2: {app:'helloagain',message:'another message'}

var alertArr = [
    {app:'helloagain',message:'another message'}

var newAlert = {app:'new',message:'message'};

$.extend(alertsObj, newAlert);

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

CodeIgniter - File upload required validation

you can use call back function, like this

  $this->form_validation->set_rules('userfile', 'Document', 'callback_file_selected_test');

    if ($this->form_validation->run() == FALSE) {
           // success       

function file_selected_test(){

    $this->form_validation->set_message('file_selected_test', 'Please select file.');
    if (empty($_FILES['userfile']['name'])) {
            return false;
            return true;

How do you get the width and height of a multi-dimensional array?

Use GetLength(), rather than Length.

int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);

How to force a component's re-rendering in Angular 2?

I force reload my component using *ngIf.

All the components inside my container goes back to the full lifecycle hooks .

In the template :

<ng-container *ngIf="_reload">
    components here 

Then in the ts file :

public _reload = true;

private reload() {
    setTimeout(() => this._reload = false);
    setTimeout(() => this._reload = true);

Select data between a date/time range

In a simple way it can be queried as

select * from hockey_stats 
where game_date between '2018-01-01' and '2018-01-31';

This works if time is not a concern.

Considering time also follow in the following way:

select * from hockey_stats where (game_date between '2018-02-05 01:20:00' and '2018-02-05 03:50:00');

Note this is for MySQL server.

Multiple -and -or in PowerShell Where-Object statement

I found the solution here:

How to properly -filter multiple strings in a PowerShell copy script

You have to use -Include flag for Get-ChildItem

My Example:

$Location = "C:\user\files" 
$result = (Get-ChildItem $Location\* -Include *.png, *.gif, *.jpg)

Dont forget put "*" after path location.

how to remove the first two columns in a file using shell (awk, sed, whatever)

Thanks for posting the question. I'd also like to add the script that helped me.

awk '{ $1=""; print $0 }' file

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

Here a minimal POC class w/ all the cruft removed

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

public class UncShareWithCredentials : IDisposable
    private string _uncShare;

    public UncShareWithCredentials(string uncShare, string userName, string password)
        var nr = new Native.NETRESOURCE
            dwType = Native.RESOURCETYPE_DISK,
            lpRemoteName = uncShare

        int result = Native.WNetUseConnection(IntPtr.Zero, nr, password, userName, 0, null, null, null);
        if (result != Native.NO_ERROR)
            throw new Win32Exception(result);
        _uncShare = uncShare;

    public void Dispose()
        if (!string.IsNullOrEmpty(_uncShare))
            Native.WNetCancelConnection2(_uncShare, Native.CONNECT_UPDATE_PROFILE, false);
            _uncShare = null;

    private class Native
        public const int RESOURCETYPE_DISK = 0x00000001;
        public const int CONNECT_UPDATE_PROFILE = 0x00000001;
        public const int NO_ERROR = 0;

        public static extern int WNetUseConnection(IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID,
            int dwFlags, string lpAccessName, string lpBufferSize, string lpResult);

        public static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);

        public class NETRESOURCE
            public int dwScope;
            public int dwType;
            public int dwDisplayType;
            public int dwUsage;
            public string lpLocalName;
            public string lpRemoteName;
            public string lpComment;
            public string lpProvider;

You can directly use \\server\share\folder w/ WNetUseConnection, no need to strip it to \\server part only beforehand.

How do I find the data directory for a SQL Server instance?

You can find default Data and Log locations for the current SQL Server instance by using the following T-SQL:

DECLARE @defaultDataLocation nvarchar(4000)
DECLARE @defaultLogLocation nvarchar(4000)

EXEC master.dbo.xp_instance_regread
    @defaultDataLocation OUTPUT

EXEC master.dbo.xp_instance_regread
    @defaultLogLocation OUTPUT

SELECT @defaultDataLocation AS 'Default Data Location',
       @defaultLogLocation AS 'Default Log Location'

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

How to run or debug php on Visual Studio Code (VSCode)

XDebug changed some configuration settings.

Old settings:

xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_port = 9000

New settings:


So you should paste the latter in php.ini file. More info: XDebug Changed Configuration Settings

git push rejected

Is your repository at "upstream" a bare repository? I got the same error, but when I change to bare they no longer happen.

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

PostgreSQL doesn't support storing NULL (\0x00) characters in text fields (this is obviously different from the database NULL value, which is fully supported).


If you need to store the NULL character, you must use a bytea field - which should store anything you want, but won't support text operations on it.

Given that PostgreSQL doesn't support it in text values, there's no good way to get it to remove it. You could import your data into bytea and later convert it to text using a special function (in perl or something, maybe?), but it's likely going to be easier to do that in preprocessing before you load it.

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity =

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    return result;

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

Multiple SQL joins

It will be something like this:

SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
    Books b
    JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
    JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
    JOIN Publishers p ON p._PublisherID = b.PublisherID
    JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
    JOIN Writer w ON w._WritersID = wb._Writers_WriterID

You use the join statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b the Books table will be referred to as b in the rest of the query. This makes for less typing.

FYI your naming convention is very strange, I would expect it to be more like this:

Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID

String comparison in bash. [[: not found

[[ is a bash-builtin. Your /bin/bash doesn't seem to be an actual bash.

From a comment:

Add #!/bin/bash at the top of file

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Minimal settings to prevent resize events

form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;

Multiple commands in an alias for bash

Does this not work?

alias whatever='gnome-screensaver ; gnome-screensaver-command --lock'

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  for(y in list2){
    n<-c(n, y)

It just creates a new list and adds items from two supplied lists to create one.

How do I convert a Python 3 byte-string variable into a regular string?

You had it nearly right in the last line. You want

str(bytes_string, 'utf-8')

because the type of bytes_string is bytes, the same as the type of b'abc'.

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

How to run a shell script at startup

In the file you put in /etc/init.d/ you have to set it executable with:

chmod +x /etc/init.d/start_my_app

Thanks to @meetamit, if this does not run you have to create a symlink to /etc/rc.d/

ln -s /etc/init.d/start_my_app /etc/rc.d/

Please note that on latest Debian, this will not work as your script have to be LSB compliant (provide, at least, the following actions: start, stop, restart, force-reload, and status):

As a note, you should put the absolute path of your script instead of a relative one, it may solves unexpected issues:


And don't forget to add on top of that file:


resize font to fit in a div (on one line)

This may be overkill for what you require, but I found this library to be very helpful:

It's only good for single lines though, so I'm not certain if that fits your requirement.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

The problem is that you are calling ToString in a LINQ to Entities query. That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).

All you have to do is move the ToString call to a separate line:

var keyString = item.Key.ToString();

var pages = from p in context.entities
            where p.Serial == keyString
            select p;

How to examine processes in OS X's Terminal?

if you are using ps, you can check the manual

man ps

there is a list of keywords allowing you to build what you need. for example to show, userid / processid / percent cpu / percent memory / work queue / command :

ps -e -o "uid pid pcpu pmem wq comm"

-e is similar to -A (all inclusive; your processes and others), and -o is to force a format.

if you are looking for a specific uid, you can chain it using awk or grep such as :

ps -e -o "uid pid pcpu pmem wq comm" | grep 501

this should (almost) show only for userid 501. try it.

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

ReactJS lifecycle method inside a function Component

According to the documentation:

import React, { useState, useEffect } from 'react'
// Similar to componentDidMount and componentDidUpdate:

useEffect(() => {


see React documentation

Generate a random double in a range

Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {

Generate MD5 hash string with T-SQL

CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)

What does the question mark in Java generics' type parameter mean?

In English:

It's a List of some type that extends the class HasWord, including HasWord

In general the ? in generics means any class. And the extends SomeClass specifies that that object must extend SomeClass (or be that class).

How do I create a readable diff of two spreadsheets using git diff?

Diff Doc may be what you're looking for.

  • Compare documents of MS Word (DOC, DOCX etc), Excel, PDF, Rich Text (RTF), Text, HTML, XML, PowerPoint, or Wordperfect and retain formatting
  • Choose any portion of any document (file) and compare it against any portion of the same or different document (file).

Apple Cover-flow effect using jQuery or other library?

the effect that happens when you hit the space bar in a folder of documents, allowing you to preview them in a lightbox fashion

Looks like a classic lightbox plugin is needed. This is my favorite jQuery lightbox plugin: It's easy to customize, etc.

When does a process get SIGABRT (signal 6)?

It usually happens when there is a problem with memory allocation.

It happened to me when my program was trying to allocate an array with negative size.

Passing a 2D array to a C++ function

A modification to shengy's first suggestion, you can use templates to make the function accept a multi-dimensional array variable (instead of storing an array of pointers that have to be managed and deleted):

template <size_t size_x, size_t size_y>
void func(double (&arr)[size_x][size_y])
    printf("%p\n", &arr);

int main()
    double a1[10][10];
    double a2[5][5];

    printf("%p\n%p\n\n", &a1, &a2);

    return 0;

The print statements are there to show that the arrays are getting passed by reference (by displaying the variables' addresses)

How to add an Android Studio project to GitHub

  1. Sign up and create a GitHub account in
  2. Download git from and install it in your system.
  3. Open the project in android studio and go to File -> Settings -> Version Control -> Git.
  4. Click on test button to test "path to Git executables". If successful message is shown everything is ok, else navigate to git.exe from where you installed git and test again.
  5. Go to File -> Settings -> Version Control -> GitHub. Enter your email and password used to create GitHub account and click on OK button.
  6. Then go to VCS -> Import into Version Control -> Share Project on GitHub. Enter Repository name, Description and click Share button.
  7. In the next window check all files inorder to add files for initial commit and click OK.
  8. Now the project will be uploaded to the GitHub repository and when uploading is finished we will get a message in android studio showing "Successfully shared project on GitHub". Click on the link provided in that message to go to GitHub repository.

ASP.NET Core configuration for .NET Core console application

You can use LiteWare.Configuration library for that. It is very similar to .NET Framework original ConfigurationManager and works for .NET Core/Standard. Code-wise, you'll end up with something like:

string cacheDirectory = ConfigurationManager.AppSettings.GetValue<string>("CacheDirectory");
ulong cacheFileSize = ConfigurationManager.AppSettings.GetValue<ulong>("CacheFileSize");

Disclaimer: I am the author of LiteWare.Configuration.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:


Insert value into a string at a certain position?

If you just want to insert a value at a certain position in a string, you can use the String.Insert method:

public string Insert(int startIndex, string value)


"abc".Insert(2, "XYZ") == "abXYZc"

Trim characters in Java

Here is another non-regexp, non-super-awesome, non-super-optimized, however very easy to understand non-external-lib solution:

public static String trimStringByString(String text, String trimBy) {
    int beginIndex = 0;
    int endIndex = text.length();

    while (text.substring(beginIndex, endIndex).startsWith(trimBy)) {
        beginIndex += trimBy.length();

    while (text.substring(beginIndex, endIndex).endsWith(trimBy)) {
        endIndex -= trimBy.length();

    return text.substring(beginIndex, endIndex);


String trimmedString = trimStringByString(stringToTrim, "/");

Using SUMIFS with multiple AND OR conditions

With the following, it is easy to link the Cell address...


Can use address / substitute / Column functions as required to use Cell addresses in full DYNAMIC.

Javascript : calling function from another file

Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.

 /******** PUT THIS CODE IN ONE JS FILE *******/

    var secondFileFuntion = function(){ = 'XYZ';

    secondFileFuntion.prototype.getSurname = function(){
     return 'ABC';

    var secondFileObject = new secondFileFuntion();

    /******** Till Here *******/

    /******** PUT THIS CODE IN SECOND JS FILE *******/

    function firstFileFunction(){
      var name =;
      var surname = secondFileObject.getSurname()
      alert(surname );


If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.

Just take care of sequence of including these files in index.html

Amazon S3 direct file upload from client browser - private key disclosure

To create a signature, I must use my secret key. But all things happens on a client side, so, the secret key can be easily revealed from page source (even if I obfuscate/encrypt my sources).

This is where you have misunderstood. The very reason digital signatures are used is so that you can verify something as correct without revealing your secret key. In this case the digital signature is used to prevent the user from modifying the policy you set for the form post.

Digital signatures such as the one here are used for security all around the web. If someone (NSA?) really were able to break them, they would have much bigger targets than your S3 bucket :)

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Say you have that looks like this that is currently enable.

<button id="btnSave" class="btn btn-info">Save</button>

Just add this:

$("#btnSave").prop('disabled', true);

and you will get this which will disable button

<button id="btnSave" class="btn btn-primary" disabled>Save</button>

How to delete a record by id in Flask-SQLAlchemy

Just want to share another option:

# mark two objects to be deleted

# commit (or flush)

In this example, the following codes shall works fine:

obj = User.query.filter_by(id=123).one()

How to get a vCard (.vcf file) into Android contacts from website

I'm running 2.2 and there is no change, reports from others on 2.3 say the same. Android (bug) does not handle a .vcf nor a link to such a file on a web page via port 80, neither via http headers or direct streaming. It just is NOT SUPPORTED AT ALL.

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

For Windows (Thanks to the owner f040225), go to here: to fetch the url for your environment based on the combination of "tf + python + cpu_instruction_extension". Then use this cmd to install:

pip install --ignore-installed --upgrade "URL"

If you encounter the "File is not a zip file" error, download the .whl to your local computer, and use this cmd to install:

pip install --ignore-installed --upgrade /path/target.whl

IE9 jQuery AJAX with CORS returns "Access is denied"

Note -- Note

do not use "" or "http://localhost/" or "IP >>" for URL in ajax. only use path(directory) and page name without address.

false state:

var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;'POST', '', true);
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

true state:

var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;'POST', 'dir/getSecurityCode.php', true);   // <<--- note
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

How to set the style -webkit-transform dynamically using JavaScript?

Try using = "rotate(60deg)"

Java Object Null Check for method

public static double calculateInventoryTotal(Book[] arrayBooks) {

    final AtomicReference<BigDecimal> total = new AtomicReference<>(BigDecimal.ZERO);
    Optional.ofNullable(arrayBooks).map(Arrays::asList).ifPresent(books -> books.forEach(book -> total.accumulateAndGet(book.getPrice(), BigDecimal::add)));
    return total.get().doubleValue();


sizing div based on window width

A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.

Transpose list of lists

Three options to choose from:

1. Map with Zip

solution1 = map(list, zip(*l))

2. List Comprehension

solution2 = [list(i) for i in zip(*l)]

3. For Loop Appending

solution3 = []
for i in zip(*l):

And to view the results:


# [1, 4, 7], [2, 5, 8], [3, 6, 9]

How can I color Python logging output?

import logging

logging.basicConfig(filename="f.log" filemode='w', level=logging.INFO,
                    format = "%(logger_name)s %(color)s  %(message)s %(endColor)s")

class Logger(object):
    __GREEN = "\033[92m"
    __RED = '\033[91m'
    __ENDC = '\033[0m'

    def __init__(self, name):
        self.logger = logging.getLogger(name)
        self.extra={'logger_name': name, 'endColor': self.__ENDC, 'color': self.__GREEN}

    def info(self, msg):
        self.extra['color'] = self.__GREEN, extra=self.extra)

    def error(self, msg):
        self.extra['color'] = self.__RED
        self.logger.error(msg, extra=self.extra)


Logger("File Name").info("This shows green text")

File Upload ASP.NET MVC 3.0

Simple way to save multiple files


@using (Html.BeginForm("Index","Home",FormMethod.Post,new { enctype = "multipart/form-data" }))
    <label for="file">Upload Files:</label>
    <input type="file" multiple name="files" id="files" /><br><br>
    <input type="submit" value="Upload Files" />


        public ActionResult Index(HttpPostedFileBase[] files)
            foreach (HttpPostedFileBase file in files)
                if (file != null && file.ContentLength > 0)
                        string path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
                        ViewBag.Message = "File uploaded successfully";
                    catch (Exception ex)
                        ViewBag.Message = "ERROR:" + ex.Message.ToString();

                    ViewBag.Message = "You have not specified a file.";
            return View();

Permutations in JavaScript?

I had a crack at making a version of this that attempts to be concise yet readable, and purely functional programming.

function stringPermutations ([...input]) {
  if (input.length === 1) return input;

  return input
    .map((thisChar, index) => {
      const remainingChars = [...input.slice(0, index), ...input.slice(index + 1)];
      return stringPermutations(remainingChars)
        .map(remainder => thisChar + remainder);
    .reduce((acc, cur) => [...acc, ...cur]);

Note that the argument formatting turns an input string into an array. Not sure if that's a bit too magical.. Not sure I've seen it in the wild. For real readability I'd probably instead do input = [...input] for the first line of the function.

How to efficiently use try...catch blocks in PHP

There is no any problem to write multiple lines of execution withing a single try catch block like below

catch(Exception $e){

The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

    catch(Exception $e){
catch(Exception $e){
throw new exception('Body Makeover faield')

Git push results in "Authentication Failed"

If you enabled two-factor authentication in your Github account you won't be able to push via HTTPS using your accounts password. Instead you need to generate a personal access token. This can be done in the application settings of your Github account. Using this token as your password should allow you to push to your remote repository via HTTPS. Use your username as usual.

You may also need to update the origin for your repository if set to https:

git remote -v 
git remote remove origin 
git remote add origin [email protected]:user/repo.git  

Stop node.js program from command line

Though this is a late answer, I found this from NodeJS docs:

The 'exit' event is emitted when the REPL is exited either by receiving the .exit command as input, the user pressing <ctrl>-C twice to signal SIGINT, or by pressing <ctrl>-D to signal 'end' on the input stream. The listener callback is invoked without any arguments.

So to summarize you can exit by:

  1. Typing .exit in nodejs REPL.
  2. Pressing <ctrl>-C twice.
  3. pressing <ctrl>-D.
  4. process.exit(0) meaning a natural exit from REPL. If you want to return any other status you can return a non zero number.
  5. process.kill( is the way to kill using nodejs api from within your code or from REPL.

"The Controls collection cannot be modified because the control contains code blocks"

Place the javascript under a div tag.

<div runat="server"> //div tag must have runat server
  //Your Jave script code goes here....

It'll work!!

How to display Oracle schema size with SQL query?

SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
  (SELECT in_tbl.table_name,   to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``

Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.

How to connect wireless network adapter to VMWare workstation?

Change your network adapter to a bridged connection, this will directly connect to your computers physical network.

<script> tag vs <script type = 'text/javascript'> tag

You only need <script></script> Tag that's it. <script type="text/javascript"></script> is not a valid HTML tag, so for best SEO practice use <script></script>

Scanning Java annotations at runtime

Google Reflection if you want to discover interfaces as well.

Spring ClassPathScanningCandidateComponentProvider is not discovering interfaces.

Can we pass an array as parameter in any function in PHP?

Its no different to any other variable, e.g.

function sendemail($id,$userid){
  echo $arr["foo"]; 

$arr = array("foo" => "bar");
sendemail($arr, $userid);

Switch to another Git tag

Clone the repository as normal:

git clone git:// RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I found this arrow(start, end) function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.

Password encryption/decryption code in .NET

I use RC2CryptoServiceProvider.

    public static string EncryptText(string openText)
        RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
        ICryptoTransform encryptor = rc2CSP.CreateEncryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
        using (MemoryStream msEncrypt = new MemoryStream())
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                byte[] toEncrypt = Encoding.Unicode.GetBytes(openText);

                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);

                byte[] encrypted = msEncrypt.ToArray();

                return Convert.ToBase64String(encrypted);

    public static string DecryptText(string encryptedText)
        RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
        ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
        using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)))
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                List<Byte> bytes = new List<byte>();
                int b;
                    b = csDecrypt.ReadByte();
                    if (b != -1)

                while (b != -1);

                return Encoding.Unicode.GetString(bytes.ToArray());

iOS 9 not opening Instagram app with URL SCHEME

When I tried to call Facebook from my own app today, I found that there is no a LSApplicationQueriesSchemes key I can add to the Info.plist (Xcode Version 8.2.1 (8C1002)). I opened the Info.plist with Sublime Text and manually added it into the file, then it worked. Just to let you know that if you cannot find the key, simply add it yourself.

good postgresql client for windows?

I like Postgresql Maestro. I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.

How to use GROUP_CONCAT in a CONCAT in MySQL



INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);

  FROM test
) AS A

SQL Fiddle:!2/b5abe/9/0

case statement in SQL, how to return multiple variables?

A CASE statement can return only one value.

You may be able to turn this into a subquery and then JOIN it to whatever other relations you're working with. For example (using SQL Server 2K5+ CTEs):

  SELECT a1 AS value1, b1 AS value2
  FROM table
  WHERE condition1
), C2 AS (
  SELECT a2 AS value1, b2 AS value2
  FROM table
  WHERE condition2
), C3 AS (
  SELECT a3 AS value1, b3 AS value2
  FROM table
  WHERE condition3
SELECT value1, value2
FROM -- some table, joining C1, C2, C3 CTEs to get the cased values

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

var result1 = lst.OrderBy(a=>a.Name);// for ascending order. 
 var result1 = lst.OrderByDescending(a=>a.Name);// for desc order. 

setting JAVA_HOME & CLASSPATH in CentOS 6

I had to change /etc/profile.d/ to point to the new path and then logout/login.

OpenCV with Network Cameras

Use ffmpeglib to connect to the stream.

These functions may be useful. But take a look in the docs


You would need a little algo to get a complete frame, which is available here

Once you get a frame you could copy the video data (for each plane if needed) into a IplImage which is an OpenCV image object.

You can create an IplImage using something like...

IplImage *p_gray_image = cvCreateImage(size, IPL_DEPTH_8U, 1);

Once you have an IplImage, you could perform all sorts of image operations available in the OpenCV lib

How to send a html email with the bash command "sendmail"?

It's simpler to use, the -a option :

cat ~/campaigns/release-status.html | mail -s "Release Status [Green]" -a "Content-Type: text/html" [email protected]

jQuery add class .active on menu

$(function() {
     var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
     $(".nav li").each(function(){
          if($('a',this).attr("href") == pgurl || $('a', this).attr("href") == '' )

How to change the background color on a Java panel?

You could call:


Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call


on the JPanel to set the background color.

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

How can I check if a user is logged-in in php?

else if (isset($_GET['actie']) && $_GET['actie']== "aanmelden"){

    $username= $_POST['username'];
    $password= md5($_POST['password']);
    $query = "SELECT password FROM tbl WHERE username = '$username'";
    $result= mysql_query($query);
    $row= mysql_fetch_array($result);

    if($password == $row['password']){
            $_SESSION['logged in'] = true;
            echo "Logged in";


awk - concatenate two string variable and assign to a third

Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

Fastest way to convert string to integer in PHP

I've just set up a quick benchmarking exercise:

Function             time to run 1 million iterations
(int) "123":                0.55029
intval("123"):              1.0115  (183%)

(int) "0":                  0.42461
intval("0"):                0.95683 (225%)

(int) int:                  0.1502
intval(int):                0.65716 (438%)

(int) array("a", "b"):      0.91264
intval(array("a", "b")):    1.47681 (162%)

(int) "hello":              0.42208
intval("hello"):            0.93678 (222%)

On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.

I'd be interested to know why though.

Update: I've run the tests again, this time with coercion (0 + $var)

| INPUT ($x)      |  (int) $x  |intval($x) |  0 + $x   |
| "123"           |   0.51541  |  0.96924  |  0.33828  |
| "0"             |   0.42723  |  0.97418  |  0.31353  |
| 123             |   0.15011  |  0.61690  |  0.15452  |
| array("a", "b") |   0.8893   |  1.45109  |  err!     |
| "hello"         |   0.42618  |  0.88803  |  0.1691   |

Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:

$x = "11";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11)

$x = "0x11";
(int) $x;      // int(0)
intval($x);    // int(0)
$x + 0;        // int(17) !

$x = "011";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11) (not 9)

Tested using PHP 5.3.1

Spring Boot + JPA : Column name annotation ignored

Turns out that I just have to convert @column name testName to all small letters, since it was initially in camel case.

Although I was not able to use the official answer, the question was able to help me solve my problem by letting me know what to investigate.


private String testName;


private String testName;

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

I had a similar issue and upgrading pip fixed it for me.

python -m pip install --upgrade pip 

This was on Windows and the path to python inside pip.exe was incorrect. See Archimedix answer for more information about the path.

PHPMyAdmin Default login password

I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )

Anyway, coming to the solution, this is what I was required to do:

su -
gedit /etc/phpMyAdmin/

if not found... try phpmyadmin - all small caps.

gedit /etc/phpmyadmin/



and set it to:

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Save it.

Change auto increment starting number?

If you need this procedure for variable fieldnames instead of id this might be helpful:

DROP PROCEDURE IF EXISTS update_auto_increment;
CREATE PROCEDURE update_auto_increment (_table VARCHAR(128), _fieldname VARCHAR(128))
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(',_fieldname,'), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
END //

CALL update_auto_increment('your_table_name', 'autoincrement_fieldname');

How can I get the IP address from NIC in Python?

This will gather all IPs on the host and filter out loopback/link-local and IPv6. This can also be edited to allow for IPv6 only, or both IPv4 and IPv6, as well as allowing loopback/link-local in IP list.

from socket import getaddrinfo, gethostname
import ipaddress

def get_ip(ip_addr_proto="ipv4", ignore_local_ips=True):
    # By default, this method only returns non-local IPv4 Addresses
    # To return IPv6 only, call get_ip('ipv6')
    # To return both IPv4 and IPv6, call get_ip('both')
    # To return local IPs, call get_ip(None, False)
    # Can combime options like so get_ip('both', False)

    af_inet = 2
    if ip_addr_proto == "ipv6":
        af_inet = 30
    elif ip_addr_proto == "both":
        af_inet = 0

    system_ip_list = getaddrinfo(gethostname(), None, af_inet, 1, 0)
    ip_list = []

    for ip in system_ip_list:
        ip = ip[4][0]

            ip_address_valid = True
        except ValueError:
            ip_address_valid = False
            if ipaddress.ip_address(ip).is_loopback and ignore_local_ips or ipaddress.ip_address(ip).is_link_local and ignore_local_ips:
            elif ip_address_valid:

    return ip_list

print(f"Your IP Address is: {get_ip()}")

Returns Your IP Address is: ['']

If I run get_ip('both', False), it returns

Your IP Address is: ['::1', 'fe80::1', '', '', 'fe80::cb9:d2dd:a505:423a']

Attempted to read or write protected memory

Hi There are two possible reasons.

  1. We have un-managed code and we are calling it from managed code. that is preventing to run this code. try running these commands and restart your pc

    cmd: netsh winsock reset

open cmd.exe and run command "netsh winsock reset catalog"

  1. Anti-virus is considering un-managed code as harmful and restricting to run this code disable anti-virus and then check

Char array to hex string C++

Using boost:

#include <boost/algorithm/hex.hpp>

std::string s("tralalalala");
std::string result;
boost::algorithm::hex(s.begin(), s.end(), std::back_inserter(result));

URL encoding in Android

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

If you don't have permissions to change your default DB you could manually select a different DB at the top of your queries...

USE [SomeOtherDb]
SELECT 'I am now using a different DB'

Will work as long as you have permission to the other DB

Should I use alias or alias_method?

alias_method new_method, old_method

old_method will be declared in a class or module which is being inherited now to our class where new_method will be used.

these can be variable or method both.

Suppose Class_1 has old_method, and Class_2 and Class_3 both of them inherit Class_1.

If, initialization of Class_2 and Class_3 is done in Class_1 then both can have different name in Class_2 and Class_3 and its usage.

Why I got " cannot be resolved to a type" error?

Maybe wrong path..? Check your .classpath file.

DateTime2 vs DateTime in SQL Server

DATETIME2 has a date range of "0001 / 01 / 01" through "9999 / 12 / 31" while the DATETIME type only supports year 1753-9999.

Also, if you need to, DATETIME2 can be more precise in terms of time; DATETIME is limited to 3 1/3 milliseconds, while DATETIME2 can be accurate down to 100ns.

Both types map to System.DateTime in .NET - no difference there.

If you have the choice, I would recommend using DATETIME2 whenever possible. I don't see any benefits using DATETIME (except for backward compatibility) - you'll have less trouble (with dates being out of range and hassle like that).

Plus: if you only need the date (without time part), use DATE - it's just as good as DATETIME2 and saves you space, too! :-) Same goes for time only - use TIME. That's what these types are there for!

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

Explicitly calling return in a function or not

I think of return as a trick. As a general rule, the value of the last expression evaluated in a function becomes the function's value -- and this general pattern is found in many places. All of the following evaluate to 3:



(function() {

What return does is not really returning a value (this is done with or without it) but "breaking out" of the function in an irregular way. In that sense, it is the closest equivalent of GOTO statement in R (there are also break and next). I use return very rarely and never at the end of a function.

 if(a) {
 } else {

... this can be rewritten as if(a) a else b which is much better readable and less curly-bracketish. No need for return at all here. My prototypical case of use of "return" would be something like ...

ugly <- function(species, x, y){
   if(length(species)>1) stop("First argument is too long.")
   if(species=="Mickey Mouse") return("You're kidding!")
   ### do some calculations 
   if(grepl("mouse", species)) {
      ## do some more calculations
      if(species=="Dormouse") return(paste0("You're sleeping until", x+y))
      ## do some more calculations
      return(paste0("You're a mouse and will be eating for ", x^y, " more minutes."))
   ## some more ugly conditions
   # ...
   ### finally
   return("The end")

Generally, the need for many return's suggests that the problem is either ugly or badly structured.


return doesn't really need a function to work: you can use it to break out of a set of expressions to be evaluated.

getout <- TRUE 
# if getout==TRUE then the value of EXP, LOC, and FUN will be "OUTTA HERE"
# .... if getout==FALSE then it will be `3` for all these variables    

EXP <- eval(expression({
   if(getout) return("OUTTA HERE")

LOC <- local({
   if(getout) return("OUTTA HERE")

FUN <- (function(){
   if(getout) return("OUTTA HERE")


How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

FontAwesome icons not showing. Why?

I got mine to work by editing the main font-awesome.css file. It has urls to the src (woff, eot, etc...) I had to change them to the absolute path eg: Then it worked!

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

git diff between two different files

I believe using --no-index is what you're looking for:

git diff [<options>] --no-index [--] <path> <path>

as mentioned in the git manual:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

undefined reference to 'std::cout'

Assuming code.cpp is the source code, the following will not throw errors:

make code

Here the first command compiles the code and creates an executable with the same name, and the second command runs it. There is no need to specify g++ keyword in this case.

Update Tkinter Label from variable

Maybe I'm not understanding the question but here is my simple solution that works -

# I want to Display total heads bent this machine so I define a label -
TotalHeadsLabel3 = Label(leftFrame)
TotalHeadsLabel3.config(font=Helv12,fg='blue',text="Total heads " + str(TotalHeads))

# I update the int variable adding the quantity bent -
TotalHeads = TotalHeads + headQtyBent # update ready to write to file & display
TotalHeadsLabel3.config(text="Total Heads "+str(TotalHeads)) # update label with new qty

I agree that labels are not automatically updated but can easily be updated with the

<label name>.config(text="<new text>" + str(<variable name>))

That just needs to be included in your code after the variable is updated.

VBA vlookup reference in different sheet

The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

  1. The value is actually not present (pointed out by chris nielsen).

  2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

    Sub srch()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim srchres As Variant
        Set ws1 = Worksheets("Sheet1")
        Set ws2 = Worksheets("Sheet2")
        On Error Resume Next
        srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
        On Error GoTo 0
        If (IsEmpty(srchres)) Then
          ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
          ws2.Range("E2").Value = srchres
        End If
    End Sub

I will point out a few additional notable points:

  1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

  2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

  3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

  4. Both solutions by L42 qualify Ranges suitably.

  5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

img {max-width:100%;} is one way of doing this. Just add it to your CSS code.

How do I convert a string to a double in Python?

Be aware that if your string number contains more than 15 significant digits float(s) will round it.In those cases it is better to use Decimal

Here is an explanation and some code samples:

How can I switch themes in Visual Studio 2012

Try the steps in here: If you don't have Visual Studio 2010 installed, some icons are provided.

React.js: Identifying different inputs with one onChange handler

You can use the .bind method to pre-build the parameters to the handleChange method. It would be something like:

  var Hello = React.createClass({
    getInitialState: function() {
        return {input1:0, 
    render: function() {
      var total = this.state.input1 + this.state.input2;
      return (
          <input type="text" value={this.state.input1} 
                             onChange={this.handleChange.bind(this, 'input1')} />
          <input type="text" value={this.state.input2} 
                             onChange={this.handleChange.bind(this, 'input2')} />
    handleChange: function (name, e) {
      var change = {};
      change[name] =;

  React.renderComponent(<Hello />, document.getElementById('content'));

(I also made total be computed at render time, as it is the recommended thing to do.)

How do I correctly detect orientation change using Phonegap on iOS?

if (window.DeviceOrientationEvent) {
    // Listen for orientation changes
    window.addEventListener("orientationchange", orientationChangeHandler);
    function orientationChangeHandler(evt) {
        // Announce the new orientation number
        // alert(screen.orientation);
        // Find matches
        var mql = window.matchMedia("(orientation: portrait)");

        if (mql.matches)  //true

Difference between numpy.array shape (R, 1) and (R,)

The difference between (R,) and (1,R) is literally the number of indices that you need to use. ones((1,R)) is a 2-D array that happens to have only one row. ones(R) is a vector. Generally if it doesn't make sense for the variable to have more than one row/column, you should be using a vector, not a matrix with a singleton dimension.

For your specific case, there are a couple of options:

1) Just make the second argument a vector. The following works fine:[:,0], np.ones(R))

2) If you want matlab like matrix operations, use the class matrix instead of ndarray. All matricies are forced into being 2-D arrays, and operator * does matrix multiplication instead of element-wise (so you don't need dot). In my experience, this is more trouble that it is worth, but it may be nice if you are used to matlab.

IDENTITY_INSERT is set to OFF - How to turn it ON?

The Reference:

My table is named Genre with the 3 columns of Id, Name and SortOrder

The code that I used is as:


INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

None of the above answers worked for me but I finally found what my issue was. Hopefully this will help someone down the line.

First run IIS Express from command prompt to validate that the site can or cannot be run

Im my case, i got an error saying that C:\Windows\Microsoft.NET\Framework64\v4.0.30319\CONFIG\web.config had malformed xml on line 14. Looking at that line in the file it just said null null null null null etc.

The fix for me was to replace the web.config file with one from my coworkers. IMPORTANT you must get the file from someone running the same version ie if you are VS2015 get a copy from someone running VS2015. If you get it from someone running a different version you will see an error saying it could not load an assembly from the manifest.

Hopefully this helps someone that has tried all the suggestions above. I think the cause of this for me was updating from trial mode and adding a product key within VS2017

How to check the value given is a positive or negative integer?

I thought here you wanted to do the action if it is positive.

Then would suggest:

if (Math.sign(number_to_test) === 1) {

How do I install Java on Mac OSX allowing version switching?

Note: These solutions work for various versions of Java including Java 8, Java 11, and the new Java 15, and for any other previous Java version covered by the listed version managers. This includes alternative JDK's from OpenJDK, Oracle, IBM, Azul, Amazon Correto, Graal and more. Easily work with Java 7, Java 8, Java 9, Java 10, Java 11, Java 12, Java 13, Java 14, and Java 15!

You have a few options for how to do the installation as well as manage JDK switching. Installation can be done by Homebrew, SDKMAN, Jabba, or a manual install. Switching can be done by JEnv, SDKMAN, Jabba, or manually by setting JAVA_HOME. All of these are described below.


First, install Java using whatever method you prefer including Homebrew, SDKMAN or a manual install of the tar.gz file. The advantage of a manual install is that the location of the JDK can be placed in a standardized location for Mac OSX. Otherwise, there are easier options such as SDKMAN that also will install other important and common tools for the JVM.

Installing and Switching versions with SDKMAN

SDKMAN is a bit different and handles both the install and the switching. SDKMAN also places the installed JDK's into its own directory tree, which is typically ~/.sdkman/candidates/java. SDKMAN allows setting a global default version, and a version specific to the current shell.

  1. Install SDKMAN from

  2. List the Java versions available to make sure you know the version ID

    sdk list java
  3. Install one of those versions, for example, Java 15:

    sdk install java 15-open 
  4. Make 15 the default version:

    sdk default java 15-open

    Or switch to 15 for the session:

    sdk use java 15-open

When you list available versions for installation using the list command, you will see a wide variety of distributions of Java:

sdk list java

And install additional versions, such as JDK 8:

sdk install java 8.0.181-oracle

SDKMAN can work with previously installed existing versions. Just do a local install giving your own version label and the location of the JDK:

sdk install java my-local-13 /Library/Java/JavaVirtualMachines/jdk-13.jdk/Contents/Home

And use it freely:

sdk use java my-local-13

More information is available in the SDKMAN Usage Guide along with other SDK's it can install and manage.

SDKMAN will automatically manage your PATH and JAVA_HOME for you as you change versions.

Install manually from OpenJDK download page:

  1. Download OpenJDK for Mac OSX from (for example Java 15)

  2. Unarchive the OpenJDK tar, and place the resulting folder (i.e. jdk-15.jdk) into your /Library/Java/JavaVirtualMachines/ folder since this is the standard and expected location of JDK installs. You can also install anywhere you want in reality.

Install with Homebrew

The version of Java available in Homebrew Cask previous to October 3, 2018 was indeed the Oracle JVM. Now, however, it has now been updated to OpenJDK. Be sure to update Homebrew and then you will see the lastest version available for install.

  1. install Homebrew if you haven't already. Make sure it is updated:

     brew update
  2. Add the casks tap, if you want to use the AdoptOpenJDK versions (which tend to be more current):

     brew tap adoptopenjdk/openjdk

    These casks change their Java versions often, and there might be other taps out there with additional Java versions.

  3. Look for installable versions:

     brew search java   

    or for AdoptOpenJDK versions:

     brew search jdk     
  4. Check the details on the version that will be installed:

     brew info java

    or for the AdoptOpenJDK version:

     brew info adoptopenjdk
  5. Install a specific version of the JDK such as java11, adoptopenjdk8, or adoptopenjdk13, or just java or adoptopenjdk for the most current of that distribution. For example:

     brew install java
     brew cask install adoptopenjdk13

And these will be installed into /Library/Java/JavaVirtualMachines/ which is the traditional location expected on Mac OSX.

Other installation options:

Some other flavours of OpenJDK are:

Azul Systems Java Zulu certified builds of OpenJDK can be installed by following the instructions on their site.

Zulu® is a certified build of OpenJDK that is fully compliant with the Java SE standard. Zulu is 100% open source and freely downloadable. Now Java developers, system administrators, and end-users can enjoy the full benefits of open source Java with deployment flexibility and control over upgrade timing.

Amazon Correto OpenJDK builds have an easy to use an installation package for Java 8 or Java 11, and installs to the standard /Library/Java/JavaVirtualMachines/ directory on Mac OSX.

Amazon Corretto is a no-cost, multiplatform, production-ready distribution of the Open Java Development Kit (OpenJDK). Corretto comes with long-term support that will include performance enhancements and security fixes. Amazon runs Corretto internally on thousands of production services and Corretto is certified as compatible with the Java SE standard. With Corretto, you can develop and run Java applications on popular operating systems, including Linux, Windows, and macOS.

Where is my JDK?!?!

To find locations of previously installed Java JDK's installed at the default system locations, use:

/usr/libexec/java_home -V

Matching Java Virtual Machines (8):
15, x86_64: "OpenJDK 15" /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home 14, x86_64: "OpenJDK 14" /Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home 13, x86_64: "OpenJDK 13" /Library/Java/JavaVirtualMachines/openjdk-13.jdk/Contents/Home 12, x86_64: "OpenJDK 12" /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
11, x86_64: "Java SE 11" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.2, x86_64: "Java SE 10.0.2" /Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
9, x86_64: "Java SE 9" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
1.8.0_144, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home

You can also report just the location of a specific Java version using -v. For example for Java 15:

/usr/libexec/java_home -v 15


Knowing the location of the installed JDK's is also useful when using tools like JEnv, or adding a local install to SDKMAN, or linking a system JDK in Jabba -- and you need to know where to find them.

If you need to find JDK's installed by other tools, check these locations:

  • SDKMAN installs to ~/.sdkman/candidates/java/
  • Jabba installs to ~/.jabba/jdk

Switching versions manually

The Java executable is a wrapper that will use whatever JDK is configured in JAVA_HOME, so you can change that to also change which JDK is in use.

For example, if you installed or untar'd JDK 15 to /Library/Java/JavaVirtualMachines/jdk-15.jdk if it is the highest version number it should already be the default, if not you could simply set:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home

And now whatever Java executable is in the path will see this and use the correct JDK.

Using the /usr/libexec/java_home utility as previously described helps you to create aliases or to run commands to change Java versions by identifying the locations of different JDK installations. For example, creating shell aliases in your .profile or .bash_profile to change JAVA_HOME for you:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_9_HOME=$(/usr/libexec/java_home -v9)
export JAVA_10_HOME=$(/usr/libexec/java_home -v10)
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)
export JAVA_12_HOME=$(/usr/libexec/java_home -v12)
export JAVA_13_HOME=$(/usr/libexec/java_home -v13)
export JAVA_14_HOME=$(/usr/libexec/java_home -v14)
export JAVA_15_HOME=$(/usr/libexec/java_home -v15)

alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java9='export JAVA_HOME=$JAVA_9_HOME'
alias java10='export JAVA_HOME=$JAVA_10_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'
alias java12='export JAVA_HOME=$JAVA_12_HOME'
alias java13='export JAVA_HOME=$JAVA_13_HOME'
alias java14='export JAVA_HOME=$JAVA_14_HOME'
alias java15='export JAVA_HOME=$JAVA_15_HOME'

# default to Java 15

Then to change versions, just use the alias.

java -version

java version "1.8.0_144"

Of course, setting JAVA_HOME manually works too!

Switching versions with JEnv

JEnv expects the Java JDK's to already exist on the machine and can be in any location. Typically you will find installed Java JDK's in /Library/Java/JavaVirtualMachines/. JEnv allows setting the global version of Java, one for the current shell, and a per-directory local version which is handy when some projects require different versions than others.

  1. Install JEnv if you haven't already, instructions on the site for manual install or using Homebrew.

  2. Add any Java version to JEnv (adjust the directory if you placed this elsewhere):

    jenv add /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home
  3. Set your global version using this command:

    jenv global 15

You can also add other existing versions using jenv add in a similar manner, and list those that are available. For example Java 8:

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home 
jenv versions

See the JEnv docs for more commands. You may now switch between any Java versions (Oracle, OpenJDK, other) at any time either for the whole system, for shells, or per local directory.

To help manage JAVA_HOME while using JEnv you can add the export plugin to do this for you.

$ jenv enable-plugin export
  You may restart your session to activate jenv export plugin echo export plugin activated

The export plugin may not adjust JAVA_HOME if it is already set, so you may need to clear this variable in your profile so that it can be managed by JEnv.

You can also use jenv exec <command> <parms...> to run single commands with JAVA_HOME and PATH set correctly for that one command, which could include opening another shell.

Installing and Switching versions with Jabba

Jabba also handles both the install and the switching. Jabba also places the installed JDK's into its own directory tree, which is typically ~/.jabba/jdk.

  1. Install Jabba by following the instructions on the home page.

  2. List available JDK's

    jabba ls-remote

  3. Install Java JDK 12

    jabba install [email protected]

  4. Use it:

    jabba use [email protected]

You can also alias version names, link to existing JDK's already installed, and find a mix of interesting JDK's such as GraalVM, Adopt JDK, IBM JDK, and more. The complete usage guide is available on the home page as well.

Jabba will automatically manage your PATH and JAVA_HOME for you as you change versions.

Mean of a column in a data frame, given the column's name

Use summarise in the dplyr package:

summarise(df, Average = mean(col_name, na.rm = T))

note: dplyr supports both summarise and summarize.

Correct way to create rounded corners in Twitter Bootstrap

In Bootstrap 4, the correct way to border your elements is to name them as follows in the class list of your elements:

For a slight rounding effect on all corners; class="rounded"
For a slight rounding on the left; class="rounded-left"
For a slight rounding on the top; class="rounded-top"
For a slight rounding on the right; class="rounded-right"
For a slight rounding on the bottom; class="rounded-bottom" 
For a circle rounding, i.e. your element is made circular; class="rounded-circle"
And to remove rounding effects; class="rounded-0"

To use Bootstrap 4 css files, you can simply use the CDN, and use the following link in the of your HTML file:

<script src="" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

This will provided you with the basics of Bootstrap 4. However if you would like to use the majority of Bootstrap 4 components, including tooltips, popovers, and dropdowns, then you are best to use the following code instead:

<script src="" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

Alternatively, you can install Bootstrap using NPM, or Bower, and link to the files there.

*Note that the bottom tag of the three is the same as the first tag in the first link path.

A full working example, could be :

<img src="path/to/my/image/image.jpg" width="150" height="150" class="rounded-circle mx-auto">

In the above example, the image is centered by using the Bootstrap auto margin on left and right.

Keeping ASP.NET Session Open / Alive

you can just write this code in you java script file thats it.

$(document).ready(function () {
        var delay = (20-1)*60*1000;
        window.setInterval(function () {
            var url = 'put the url of some Dummy page';
        }, delay);

The (20-1)*60*1000 is refresh time, it will refresh the session timeout. Refresh timeout is calculated as default time out of iis = 20 minutes, means 20 × 60000 = 1200000 milliseconds - 60000 millisecond (One minutes before session expires ) is 1140000.

jQuery get specific option tag text

This worked perfectly for me, I was looking for a way to send two different values with options generated by MySQL, and the following is generic and dynamic:


As mentioned in one of the comments. With this I was able to create a dynamic function that works with all my selection boxes that I want to get both values, the option value and the text.

Few days ago I noticed that when updating the jQuery from 1.6 to 1.9 of the site I used this code, this stop working... probably was a conflict with another piece of code... anyway, the solution was to remove option from the find() call:


That was my solution... use it only if you have any problem after updating your jQuery.

Way to get all alphabetic chars in an array in PHP?

If you need an array that has alphabetical keys as well as elements (for an alphabetical dropdown list, for example), you could do this:

$alphas = array_combine(range('A','Z'),range('A','Z'))


array (size=26)
  'A' => string 'A' (length=1)
  'B' => string 'B' (length=1)
  'C' => string 'C' (length=1)
  'D' => string 'D' (length=1)

Java 256-bit AES Password-Based Encryption

Share the password (a char[]) and salt (a byte[]—8 bytes selected by a SecureRandom makes a good salt—which doesn't need to be kept secret) with the recipient out-of-band. Then to derive a good key from this information:

/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

The magic numbers (which could be defined as constants somewhere) 65536 and 256 are the key derivation iteration count and the key size, respectively.

The key derivation function is iterated to require significant computational effort, and that prevents attackers from quickly trying many different passwords. The iteration count can be changed depending on the computing resources available.

The key size can be reduced to 128 bits, which is still considered "strong" encryption, but it doesn't give much of a safety margin if attacks are discovered that weaken AES.

Used with a proper block-chaining mode, the same derived key can be used to encrypt many messages. In Cipher Block Chaining (CBC), a random initialization vector (IV) is generated for each message, yielding different cipher text even if the plain text is identical. CBC may not be the most secure mode available to you (see AEAD below); there are many other modes with different security properties, but they all use a similar random input. In any case, the outputs of each encryption operation are the cipher text and the initialization vector:

/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes(StandardCharsets.UTF_8));

Store the ciphertext and the iv. On decryption, the SecretKey is regenerated in exactly the same way, using using the password with the same salt and iteration parameters. Initialize the cipher with this key and the initialization vector stored with the message:

/* Decrypt the message, given derived key and initialization vector. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);

Java 7 included API support for AEAD cipher modes, and the "SunJCE" provider included with OpenJDK and Oracle distributions implements these beginning with Java 8. One of these modes is strongly recommended in place of CBC; it will protect the integrity of the data as well as their privacy.

A with the message "Illegal key size or default parameters" means that the cryptography strength is limited; the unlimited strength jurisdiction policy files are not in the correct location. In a JDK, they should be placed under ${jdk}/jre/lib/security

Based on the problem description, it sounds like the policy files are not correctly installed. Systems can easily have multiple Java runtimes; double-check to make sure that the correct location is being used.

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Convert string to buffer Node

This is working for me, you might change your code like this

var responseData=x.toString();


var responseData=x.toString("binary");

and finally

response.write(new Buffer(toTransmit, "binary"));

how to change background image of button when clicked/focused?

you can implement in a xml file for this as follows:

<selector xmlns:android="">
<item android:state_focused="true" android:drawable="@drawable/your_imagename_while_focused"/>
<item android:state_pressed="true" android:drawable="@drawable/your_imagename_while_pressed" />
<item android:drawable="@drawable/image_name_while_notpressed" />  //means normal

now save this xml file in drawable folder and name it suppos abc.xml and set it as follows

 Button tiny = (Button)findViewById(;

Hope it will help you. :)

Adding an .env file to React Project

Today there is a simpler way to do that.

Just create the .env.local file in your root directory and set the variables there. In your case:

REACT_APP_API_KEY = 'my-secret-api-key'

Then you call it en your js file in that way:


React supports environment variables since [email protected] .You don't need external package to do that.

*note: I propose .env.local instead of .env because create-react-app add this file to gitignore when create the project.

Files priority:

npm start: .env.development.local, .env.development, .env.local, .env

npm run build: .env.production.local, .env.production, .env.local, .env

npm test: .env.test.local, .env.test, .env (note .env.local is missing)

More info:

Nodejs - Redirect url

To indicate a missing file/resource and serve a 404 page, you need not redirect. In the same request you must generate the response with the status code set to 404 and the content of your 404 HTML page as response body. Here is the sample code to demonstrate this in Node.js.

var http = require('http'),
    fs = require('fs'),
    util = require('util'),
    url = require('url');

var server = http.createServer(function(req, res) {
    if(url.parse(req.url).pathname == '/') {
        res.writeHead(200, {'content-type': 'text/html'});
        var rs = fs.createReadStream('index.html');
        util.pump(rs, res);
    } else {
        res.writeHead(404, {'content-type': 'text/html'});
        var rs = fs.createReadStream('404.html');
        util.pump(rs, res);


Show and hide a View with a slide up/down animation

You can used the simple three lines of code to show the animation...

//getting the hiding view by animation

 mbinding.butn.setOnClickListener {

                val SlideOutLeft = AnimationUtils.loadAnimation(this, R.anim.slide_out_left)
                simplelayout.visibility = View.INVISIBLE

                val SlideInRight = AnimationUtils.loadAnimation(applicationContext, R.anim.slide_in_right)
                animation1.visibility = View.VISIBLE

            //again unhide the view animation
            mbinding.buttn.setOnClickListener {

               val SlideInLeft=AnimationUtils.loadAnimation(this,R.anim.slide_in_left)
                //set the layout

               val SlideOutRight=AnimationUtils.loadAnimation(this,R.anim.slide_out_right)


How do I get an object's unqualified (short) class name?

Here is simple solution for PHP 5.4+

namespace {
    trait Names {
        public static function getNamespace() {
            return implode('\\', array_slice(explode('\\', get_called_class()), 0, -1));

        public static function getBaseClassName() {
            return basename(str_replace('\\', '/', get_called_class()));

What will be return?

namespace x\y\z {
    class SomeClass {
        use \Names;

    echo \x\y\z\SomeClass::getNamespace() . PHP_EOL; // x\y\z
    echo \x\y\z\SomeClass::getBaseClassName() . PHP_EOL; // SomeClass

Extended class name and namespace works well to:

namespace d\e\f {

    class DifferentClass extends \x\y\z\SomeClass {


    echo \d\e\f\DifferentClass::getNamespace() . PHP_EOL; // d\e\f
    echo \d\e\f\DifferentClass::getBaseClassName() . PHP_EOL; // DifferentClass

What about class in global namespace?

namespace {

    class ClassWithoutNamespace {
        use \Names;

    echo ClassWithoutNamespace::getNamespace() . PHP_EOL; // empty string
    echo ClassWithoutNamespace::getBaseClassName() . PHP_EOL; // ClassWithoutNamespace

How to deal with page breaks when printing a large HTML table

None of the answers here worked for me in Chrome. AAverin on GitHub has created some useful Javascript for this purpose and this worked for me:

Just add the js to your code and add the class 'splitForPrint' to your table and it will neatly split the table into multiple pages and add the table header to each page.

How to show all rows by default in JQuery DataTable


    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    iDisplayLength: -1

Or if using 1.10+

    paging: false

The option you should use is iDisplayLength:

  'iDisplayLength': 100

   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]

It will Load by default all entries.

    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    iDisplayLength: -1

Or if using 1.10+

    paging: false

If you want to load by default 25 not all do this.

    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]

While variable is not defined - wait

Very late to the party but I want to supply a more modern solution to any future developers looking at this question. It's based off of Toprak's answer but simplified to make it clearer as to what is happening.

<div>Result: <span id="result"></span></div>

    var output = null;
    // Define an asynchronous function which will not block where it is called.
    async function test(){
        // Create a promise with the await operator which instructs the async function to wait for the promise to complete.
        await new Promise(function(resolve, reject){
            // Execute the code that needs to be completed.
            // In this case it is a timeout that takes 2 seconds before returning a result. 
                // Just call resolve() with the result wherever the code completes.
                resolve("success output");
            }, 2000);
            // Just for reference, an 'error' has been included.
            // It has a chance to occur before resolve() is called in this case, but normally it would only be used when your code fails.
                // Use reject() if your code isn't successful.
                reject("error output");
            }, Math.random() * 4000);
            // The result variable comes from the first argument of resolve().
            output = result; 
            // The error variable comes from the first argument of reject().
            // Catch will also catch any unexpected errors that occur during execution.
            // In this case, the output variable will be set to either of those results.
            if (error) output = error; 
        // Set the content of the result span to output after the promise returns.
        document.querySelector("#result").innerHTML = output;
    // Execute the test async function.

    // Executes immediately after test is called.
    document.querySelector("#result").innerHTML = "nothing yet";

Here's the code without comments for easy visual understanding.

var output = null;

async function test(){
    await new Promise(function(resolve, reject){
            resolve("success output");
        }, 2000);

            reject("error output");
        }, Math.random() * 4000);
        output = result; 
        if (error) output = error; 

    document.querySelector("#result").innerHTML = output;


document.querySelector("#result").innerHTML = "nothing yet";

On a final note, according to MDN, Promises are supported on all modern browsers with Internet Explorer being the only exception. This compatibility information is also supported by caniuse. However with Bootstrap 5 dropping support for Internet Explorer, and the new Edge based on webkit, it is unlikely to be an issue for most developers.

Get refresh token google api

Since March 2016, use prompt=consent to regenerate Google API refresh token.

As mentioned in,

approval_prompt=force has been replaced with prompt=none|consent|select_account

Netbeans - class does not have a main method

Sometimes passing parameters in the main method causes this problem eg. public static void main(String[] args,int a). If you declare the variable outside the main method, it might help :)

SQL Server : converting varchar to INT

This is more for someone Searching for a result, than the original post-er. This worked for me...

declare @value varchar(max) = 'sad';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 0

declare @value varchar(max) = '3';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 3

Creating a ZIP archive in memory using System.IO.Compression

Function to return stream that contain zip file

public static Stream ZipGenerator(List<string> files)
        ZipArchiveEntry fileInArchive;
        Stream entryStream;
        int i = 0;
        List<byte[]> byteArray = new List<byte[]>();

        foreach (var file in files)

        var outStream = new MemoryStream();

        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
            foreach (var file in files)
                fileInArchive=(archive.CreateEntry(Path.GetFileName(file), CompressionLevel.Optimal));

                using (entryStream = fileInArchive.Open())
                        using (var fileToCompressStream = new MemoryStream(byteArray[i]))
        outStream.Position = 0;
        return outStream;

If you want , write zip to file stream.

using (var fileStream = new FileStream(@"D:\Tools\DBExtractor\DBExtractor\bin\Debug\", FileMode.Create))
   outStream.Position = 0;


How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all

You need to change: AllowOverride None To: AllowOverride All

Capitalize only first character of string and leave others alone? (Rails)

Rails starting from version 5.2.3 has upcase_first method.

For example, "my Test string".upcase_first will return My Test string.

How do I vertically center an H1 in a div?

You can achieve this with the display property:

html, body {
#section1 {
    width:100%; /*full width*/
    display:table; /*acts like a table*/
    vertical-align:middle; /*middle centred*/
    display:table-cell; /*acts like a table cell*/


Evenly distributing n points on a sphere

with small numbers of points you could run a simulation:

from random import random,randint
r = 10
n = 20
best_closest_d = 0
best_points = []
points = [(r,0,0) for i in range(n)]
for simulation in range(10000):
    x = random()*r
    y = random()*r
    z = r-(x**2+y**2)**0.5
    if randint(0,1):
        x = -x
    if randint(0,1):
        y = -y
    if randint(0,1):
        z = -z
    closest_dist = (2*r)**2
    closest_index = None
    for i in range(n):
        for j in range(n):
            if i==j:
            p1,p2 = points[i],points[j]
            x1,y1,z1 = p1
            x2,y2,z2 = p2
            d = (x1-x2)**2+(y1-y2)**2+(z1-z2)**2
            if d < closest_dist:
                closest_dist = d
                closest_index = i
    if simulation % 100 == 0:
        print simulation,closest_dist
    if closest_dist > best_closest_d:
        best_closest_d = closest_dist
        best_points = points[:]

print best_points
>>> best_points
[(9.921692138442777, -9.930808529773849, 4.037839326088124),
 (5.141893371460546, 1.7274947332807744, -4.575674650522637),
 (-4.917695758662436, -1.090127967097737, -4.9629263893193745),
 (3.6164803265540666, 7.004158551438312, -2.1172868271109184),
 (-9.550655088997003, -9.580386054762917, 3.5277052594769422),
 (-0.062238110294250415, 6.803105171979587, 3.1966101417463655),
 (-9.600996012203195, 9.488067284474834, -3.498242301168819),
 (-8.601522086624803, 4.519484132245867, -0.2834204048792728),
 (-1.1198210500791472, -2.2916581379035694, 7.44937337008726),
 (7.981831370440529, 8.539378431788634, 1.6889099589074377),
 (0.513546008372332, -2.974333486904779, -6.981657873262494),
 (-4.13615438946178, -6.707488383678717, 2.1197605651446807),
 (2.2859494919024326, -8.14336582650039, 1.5418694699275672),
 (-7.241410895247996, 9.907335206038226, 2.271647103735541),
 (-9.433349952523232, -7.999106443463781, -2.3682575660694347),
 (3.704772125650199, 1.0526567864085812, 6.148581714099761),
 (-3.5710511242327048, 5.512552040316693, -3.4318468250897647),
 (-7.483466337225052, -1.506434920354559, 2.36641535124918),
 (7.73363824231576, -8.460241422163824, -1.4623228616326003),
 (10, 0, 0)]

Ruby on Rails: Where to define global constants?

According your condition, you can also define some environmental variables, and fetch it via ENV['some-var'] in ruby code, this solution may not fit for you, but I hope it may help others.

Example: you can create different files .development_env, .production_env, .test_env and load it according your application environments, check this gen dotenv-rails which automate this for your.

how to compare the Java Byte[] array?

have you looked at Arrays.equals()?

Edit: if, as per your comment, the issue is using a byte array as a HashMap key then see this question.

How to pass the password to su/sudo/ssh without overriding the TTY?

Building on @Jahid's answer, this worked for me on macOS 10.13:

ssh <remote_username>@<remote_server> sudo -S <<< <remote_password> cat /etc/sudoers

Multiline string literal in C#

The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:

    var someString = @"The


So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:

var someString = String.Join(

And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine for " ".

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox

Here is demo in JSFiddle.

And here is a demo which solves exactly your problem

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');

"SMTP Error: Could not authenticate" in PHPMailer

I received the same error and in mycase it was the password. My password has special characters for and if you supply the password without escaping the special characters the error will continue to show. E.g $mail->Password = " por$ch3"; is valid but will not work using the code above . The solution should be as follows: $mail->Password = "por\$ch3"; Note the Backslash I placed before the dollar character within my password. That should work if you have a password using special characters

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Give full access of .composer to user.

sudo chown -R 'user-name' /home/'user-name'/.composer


sudo chmod 777 -R /home/'user-name'/.composer

user-name is your system user-name.

to get user-name type "whoami" in terminal:

enter image description here

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

How to store the hostname in a variable in a .bat file?

Why not so?:

echo %host%

Write / add data in JSON file using Node.js

For synchronous approach

const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));

Java 8 NullPointerException in Collectors.toMap

I have slightly modified Emmanuel Touzery's implementation.

This version;

  • Allows null keys
  • Allows null values
  • Detects duplicate keys (even if they are null) and throws IllegalStateException as in the original JDK implementation.
  • Detects duplicate keys also when the key already mapped to the null value. In other words, separates a mapping with null-value from no-mapping.
public static <T, K, U> Collector<T, ?, Map<K, U>> toMapOfNullables(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
    return Collectors.collectingAndThen(
        list -> {
            Map<K, U> map = new LinkedHashMap<>();
            list.forEach(item -> {
                K key = keyMapper.apply(item);
                if (map.containsKey(key)) {
                    throw new IllegalStateException(String.format("Duplicate key %s", key));
                map.put(key, valueMapper.apply(item));
            return map;

Unit tests:

public void toMapOfNullables_WhenHasNullKey() {
    assertEquals(singletonMap(null, "value"),
        Stream.of("ignored").collect(Utils.toMapOfNullables(i -> null, i -> "value"))

public void toMapOfNullables_WhenHasNullValue() {
    assertEquals(singletonMap("key", null),
        Stream.of("ignored").collect(Utils.toMapOfNullables(i -> "key", i -> null))

public void toMapOfNullables_WhenHasDuplicateNullKeys() {
    assertThrows(new IllegalStateException("Duplicate key null"),
        () -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> null, i -> i))

public void toMapOfNullables_WhenHasDuplicateKeys_NoneHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))

public void toMapOfNullables_WhenHasDuplicateKeys_OneHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(1, null, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))

public void toMapOfNullables_WhenHasDuplicateKeys_AllHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(null, null, null).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))

Forwarding port 80 to 8080 using NGINX

You can define an upstream and use it in proxy_pass

server {  
   listen        8082;

   location ~ /(.*) {  
       proxy_pass  test_server;  
       proxy_set_header Host $host;  
       proxy_set_header X-Real-IP $remote_addr;  
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
       proxy_set_header X-Forwarded-Proto $scheme;  
       proxy_redirect    off;  


  upstream test_server  
         server test-server:8989  

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

How can I generate Javadoc comments in Eclipse?

You mean menu Project -> Generate Javadoc ?

Android ListView Divider

From the doc:

public void setDivider(Drawable divider) on ListView

 * Sets the drawable that will be drawn between each item in the list. If the drawable does
 * not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
 * @param divider The drawable to use.

Looks like setDividerHeight() must be called in order for the divider to show up if it has no intrinsic height

Set Radiobuttonlist Selected from Codebehind

Try this option:

radio1.Items.FindByValue("1").Selected = true;

How do I check if a string is unicode or ascii?

In python 3.x all strings are sequences of Unicode characters. and doing the isinstance check for str (which means unicode string by default) should suffice.

isinstance(x, str)

With regards to python 2.x, Most people seem to be using an if statement that has two checks. one for str and one for unicode.

If you want to check if you have a 'string-like' object all with one statement though, you can do the following:

isinstance(x, basestring)

How can I get just the first row in a result set AFTER ordering?

This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.

It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.

The relevant section is:

select *
  ( select * 
  from emp 
  order by sal desc ) 
  where ROWNUM <= 5;

Good Java graph algorithm library?

JUNG is a good option for visualisation, and also has a fairly good set of available graph algorithms, including several different mechanisms for random graph creation, rewiring, etc. I've also found it to be generally fairly easy to extend and adapt where necessary.

How to convert minutes to hours/minutes and add various time values together using jQuery?

The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.

function display(a){
  var hours = Math.trunc(a/60);
  var minutes = a % 60;
  console.log(hours +":"+ minutes);

display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"

What is special about /dev/tty?

The 'c' means it's a character special file.

Declaring variable workbook / Worksheet vba

to your surprise, you do need to declare variable for workbook and worksheet in excel 2007 or later version. Just add single line expression.

Sub kl()

    Set ws = ThisWorkbook.Sheets("name")
End Sub

Remove everything else and enjoy. But why to select a sheet? selection of sheets is now old fashioned for calculation and manipulation. Just add formula like this

Sub kl()

    Set ws = ThisWorkbook.Sheets("name")
    ws.range("cell reference").formula = "your formula"
'OR in case you are using copy paste formula, just use 'insert or formula method instead of ActiveSheet.paste e.g.:
   ws.range("your cell").formula
   ws.colums("your col: one col e.g. "A:A").insert
'if you need to clear the previous value, just add the following above insert line
   ws.columns("your column").delete

End Sub

Show/hide forms using buttons and JavaScript

Use the following code fragment to hide the form on button click.

document.getElementById("your form id").style.display="none";

And the following code to display it:

document.getElementById("your form id").style.display="block";

Or you can use the same function for both purposes:

function asd(a)

And the HTML:

<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>

How can I check what version/edition of Visual Studio is installed programmatically?

In Visual Studio, the Tab 'Help'-> 'About Microsoft Visual Studio' should give you the desired infos.

using href links inside <option> tag

    <select name="career" id="career" onchange="location = this.value;">
        <option value="resume" selected> All Applications </option>
        <option value="resume&j=14">Seo Expert</option>
        <option value="resume&j=21">Project Manager</option>
        <option value="resume&j=33">Php Developer</option>

How to sort a data frame by date

You can use order() to sort date data.

# Sort date ascending order
d[order(as.Date(d$V3, format = "%d/%m/%Y")),]

# Sort date descending order
d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]

Hope this helps,

Link to my quora answer


Timestamp Difference In Hours for PostgreSQL

This might sound crazy to a lot of developers who like to take advantage of database functions,

But after exhaustive problems thinking, creating and bugfixing applications for mysql and postgrsql with php comparing date functions, I've come to the conclusion (for myself), that the easiest way, that is the simplest with less SQL headaches is not to take advantage of any of them.

Why? because if you are developing in a middleware language like PHP, PHP has all of these functions, and they are easier to implement in the application ode as comparing integers. PostgreSQL timestamp is NOT == UNIX TIMESTAMP and MySQL's UNIX TIMESTAMP is NOT PostgresQL's or Oracles timestamp.. it gets harder to port if you use database timestamps..

so just use an integer, not a timestamp, as the number of seconds since january 1st 1970 midnight. and never mind database timestamps. , and use gmdate() and store everything as gmt time to avoid timezone issues.

if you need to search, sort or compare the day from other data, or the month or the year or the day of the week, or anything, in your application, and INTEGER datatype for time_day, time_hour, time_seconds.. or whatever you wnat to index to be searched will make for smoother and more portable databases. you can just use one field, in most instances: INTEGER time_created NOT NULL

(more fields in your database row is the only drawback to this solution that i have found, and that doesnt cause as many headaches, or cups of coffee :)

php's date functions are outstanding to compare dates, but in mysql or postgresql, comparing dates ? nah.. use integer sql comparisons

i realize it may SEEM easier to use CURRENT_TIMESTAMP on an insert function. HA! don't be fooled.

You cant do DELETE FROM SESSION_TABLE WHERE time-initialized < '2 days' if time-intitialized is a postgresql timestamp. but you CAN do:

DELETE FROM SESSION_TABLE WHERE time_initialized < '$yesterday'

As long as you set $yesterday in php as the integer of seconds since 1970 that yesterday was.

This is easier housekeeping of session records than comparing timestamps in postgresql select statements.

SELECT age(), SELECT extract(), and asbtime are headaches in an of themselves. this is just my opinion.

you can do addition, substraction, <, >, all with php date objects

_peter_sysko U4EA Networks, Inc.

How to get a subset of a javascript object's properties

  1. convert arguments to array

  2. use Array.forEach() to pick the property

    Object.prototype.pick = function(...args) {
       var obj = {};
       args.forEach(k => obj[k] = this[k])
       return obj
    var a = {0:"a",1:"b",2:"c"}
    var b = a.pick('1','2')  //output will be {1: "b", 2: "c"}