Programs & Examples On #Subreports

Node.js Error: Cannot find module express

In your case your express module is installed at C:\Users\Dmitry\AppData\Roaming\npm\node_modules\express, but you need to get this module in to your project directory. So you should copy the file the express module folders from C:\Users\Dmitry\AppData\Roaming\npm\node_modules\ to your project directory as : C:\ChatServer\Server\node_modules. If you do not have a folder named 'node_modules' in your project folder, then create it first and paste those files into this folder. This method worked for me on my windows pc. Restart your node server and once again run the command node C:\ChatServer\Server>node server.js. It should work now !!!!

Is there a C++ gdb GUI for Linux?

Have you ever taken a look at DS-5 debugger?

There is a paid version which includes a lot of helpful features, but you can also use Community Edition for free (which is also quite useful especially for embedded systems).

I have a positive experience with this tool when debugging Android applications on real device using eclipse.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

If anyone is having this exception and is building the query using Scala multi-line strings:

Looks like there is a problem with some JPA drivers in this situation. I'm not sure what is the character Scala uses for LINE END, but when you have a parameter right at the end of the line, the LINE END character seems to be attached to the parameter and so when the driver parses the query, this error comes up. A simple work around is to leave an empty space right after the param at the end:

SELECT * FROM some_table a
WHERE a.col = ?param
AND a.col2 = ?param2

So, just make sure to leave an empty space after param (and param2, if you have a line break there).

How to append one DataTable to another DataTable

The datatype in the same columns name must be equals.

dataTable1.Merge(dataTable2);

After that the result is:

dataTable1 = dataTable1 + dataTable2

Could not load type from assembly error

Just run into this with another cause:

I was using a merged assembly created with ILRepack. The assembly you are querying the types from must be the first one passed to ILRepack or its types will not be available.

How to make lists contain only distinct element in Python?

one-liner and preserve order

list(OrderedDict.fromkeys([2,1,1,3]))

although you'll need

from collections import OrderedDict

Executable directory where application is running from?

This is the first post on google so I thought I'd post different ways that are available and how they compare. Unfortunately I can't figure out how to create a table here, so it's an image. The code for each is below the image using fully qualified names.

enter image description here

My.Application.Info.DirectoryPath

Environment.CurrentDirectory

System.Windows.Forms.Application.StartupPath

AppDomain.CurrentDomain.BaseDirectory

System.Reflection.Assembly.GetExecutingAssembly.Location

System.Reflection.Assembly.GetExecutingAssembly.CodeBase

New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase)

Path.GetDirectoryName(Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path)))

Uri.UnescapeDataString((New System.UriBuilder(System.Reflection.Assembly.GetExecutingAssembly.CodeBase).Path))

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
{
public :
    PetStore()
    : Farm()     // <---- Call base-class constructor in initialision list
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

Cannot send a content-body with this verb-type

Please set the request Content Type before you read the response stream;

 request.ContentType = "text/xml";

How to put the legend out of the plot

I simply used the string 'center left' for the location, like in matlab. I imported pylab from matplotlib.

see the code as follow:

from matplotlib as plt
from matplotlib.font_manager import FontProperties
t = A[:,0]
sensors = A[:,index_lst]
    
for i in range(sensors.shape[1]):
    plt.plot(t,sensors[:,i])
        
plt.xlabel('s')
plt.ylabel('°C')
lgd = plt.legend(loc='center left', bbox_to_anchor=(1, 0.5),fancybox = True, shadow = True)

enter image description here

How can I get a list of all open named pipes in Windows?

The second pipe was interpreted by this web site when submitted... You need two backslashes at the beginning. So make sure to use System.IO.Directory.GetFiles(@"\\.\pipe\").

Note that I have seen this function call throw an 'illegal characters in path.' exception when one of the pipes on my machine had invalid characters. PipleList.exe worked ok though, so it seems like a bug in MS's .net code.

Exec : display stdout "live"

There are already several answers however none of them mention the best (and easiest) way to do this, which is using spawn and the { stdio: 'inherit' } option. It seems to produce the most accurate output, for example when displaying the progress information from a git clone.

Simply do this:

var spawn = require('child_process').spawn;

spawn('coffee', ['-cw', 'my_file.coffee'], { stdio: 'inherit' });

Credit to @MorganTouvereyQuilling for pointing this out in this comment.

Java: Clear the console

Try the following :

System.out.print("\033\143");

This will work fine in Linux environment

PHP replacing special characters like à->a, è->e

The string $chain is in the same character encoding as the characters in the array - it's possible, even likely, that the $first_name string is in a different encoding, and so those characters don't match. You might want to try using the multibyte string functions instead.

Try mb_convert_encoding. You might also want to try using HTML_ENTITIES as the to_encoding parameter, then you don't need to worry about how the characters will get converted - it will be very predictable.

Assuming your input to this script is in UTF-8, probably not a bad place to start...

$first_name = mb_convert_encoding($first_name, "HTML-ENTITIES", "UTF-8"); 

How to change the color of progressbar in C# .NET 3.5?

The VB.Net colored progressbar which respects WXP Visual Styles answer is ...

I started with the answer from 'user1032613' on 3/17/12. Note that this is now a Module, not a class. From there I converted the code but more was needed. In particular the converted code showed a DirectCast function to convert the 'state' integer to a IntPtr type which didn't work.

Imports System.Runtime.InteropServices

Public Module ModifyProgressBarColor

    Private Declare Function SendMessage Lib "User32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long

    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=False)> _
    Private Function SendMessage(hWnd As IntPtr, Msg As UInteger, w As IntPtr, l As IntPtr) As IntPtr
    End Function

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub SetState(pBar As ProgressBar, state As Integer)

        '-- Convert state as integer to type IntPtr
        Dim s As IntPtr
        Dim y As Integer = state
        s = IntPtr.op_Explicit(y)

        '-- Modify bar color
        SendMessage(pBar.Handle, 1040, s, IntPtr.Zero)

    End Sub

End Module

And again just call this in the using code with this line:

Call ModifyProgressBarColor.SetState(prb, 2)

BTW - I tried other colors - 0, 4, 5 - they all just displayed green.

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

As another option, you can do look ups like:

class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')

    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'

Downloading Java JDK on Linux via wget is shown license page instead

I know that Oracle made everything possible to make their Java Runtime and Java SDK as hard as possible.

Here are some guides for command line lovers.

For Debian like systems (tested on Debian squeeze and Ubuntu 12.x+)

su -
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886
apt-get update
apt-get install --yes oracle-java7-installer
exit

Note: if you know a better or easier way add a comment, I will update the guide.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I got the same error for pandas latest version. Then saw this warning

FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.

This shall work for you.

Row count where data exists

Have you tried this?:

    countif(rangethatyouhave, not(""))

I don't think you need to open the code editor, you can just do it in the spreadsheet itself.

Custom Cell Row Height setting in storyboard is not responding

I have recently been wrestling with this. My issue was the solutions posted above using the heightForRowAtIndexPath: method would work for iOS 7.1 in the Simulator but then have completely screwed up results by simply switching to iOS 8.1.

I began reading more about self-sizing cells (introduced in iOS 8, read here). It was apparent that the use of UITableViewAutomaticDimension would help in iOS 8. I tried using that technique and deleted the use of heightForRowAtIndexPath: and voila, it was working perfect in iOS 8 now. But then iOS 7 wasn't. What was I to do? I needed heightForRowAtIndexPath: for iOS 7 and not for iOS 8.

Here is my solution (trimmed up for brevity's sake) which borrow's from the answer @JosephH posted above:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 50.;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    // ...
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        return UITableViewAutomaticDimension;

    } else {
        NSString *cellIdentifier = [self reuseIdentifierForCellAtIndexPath:indexPath];
        static NSMutableDictionary *heightCache;
        if (!heightCache)
            heightCache = [[NSMutableDictionary alloc] init];
        NSNumber *cachedHeight = heightCache[cellIdentifier];
        if (cachedHeight)
            return cachedHeight.floatValue;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    CGFloat height = cell.bounds.size.height;
    heightCache[cellIdentifier] = @(height);
    return height;
    }
}

- (NSString *)reuseIdentifierForCellAtIndexPath:(NSIndexPath *)indexPath {
    NSString * reuseIdentifier;
    switch (indexPath.row) {
        case 0:
            reuseIdentifier = EventTitleCellIdentifier;
            break;
        case 2:
            reuseIdentifier = EventDateTimeCellIdentifier;
            break;
        case 4:
            reuseIdentifier = EventContactsCellIdentifier;
            break;
        case 6:
            reuseIdentifier = EventLocationCellIdentifier;
            break;
        case 8:
            reuseIdentifier = NotesCellIdentifier;
            break;
        default:
            reuseIdentifier = SeparatorCellIdentifier;
            break;
    }

    return reuseIdentifier;
}

SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0") is actually from a set of macro definitions I am using which I found somewhere (very helpful). They are defined as:

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

Android: How to set password property in an edit text?

I found when doing this that in order to set the gravity to center, and still have your password hint show when using inputType, the android:gravity="Center" must be at the end of your XML line.

<EditText android:textColor="#000000" android:id="@+id/editText2" 
    android:layout_width="fill_parent" android:hint="Password" 
    android:background="@drawable/rounded_corner" 
    android:layout_height="fill_parent" 
    android:nextFocusDown="@+id/imageButton1" 
    android:nextFocusRight="@+id/imageButton1" 
    android:nextFocusLeft="@+id/editText1"
    android:nextFocusUp="@+id/editText1" 
    android:inputType="textVisiblePassword" 
    android:textColorHint="#999999" 
    android:textSize="16dp" 
    android:gravity="center">
</EditText>

Find duplicate records in MySQL

Find duplicate users by email address with this query...

SELECT users.name, users.uid, users.mail, from_unixtime(created)
FROM users
INNER JOIN (
  SELECT mail
  FROM users
  GROUP BY mail
  HAVING count(mail) > 1
) dupes ON users.mail = dupes.mail
ORDER BY users.mail;

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

http://msdn.microsoft.com/en-us/library/ms186862.aspx

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

The ToString method on the DateTime struct can take a format parameter:

var dateAsString = DateTime.Now.ToString("yyyy-MM-dd");
// dateAsString = "2011-02-17"

Documentation for standard and custom format strings is available on MSDN.

How to switch a user per task or set of tasks?

You can specify become_method to override the default method set in ansible.cfg (if any), and which can be set to one of sudo, su, pbrun, pfexec, doas, dzdo, ksu.

- name: I am confused
  command: 'whoami'
  become: true
  become_method: su
  become_user: some_user
  register: myidentity

- name: my secret identity
  debug:
    msg: '{{ myidentity.stdout }}'

Should display

TASK [my-task : my secret identity] ************************************************************
ok: [my_ansible_server] => {
    "msg": "some_user"
}

How do I install the ext-curl extension with PHP 7?

First Login to your server and check the PHP version which is installed on your server.

And then run the following commands:

sudo apt-get install php7.2-curl

sudo service apache2 restart

Replace the PHP version ( php7.2 ), with your PHP version.

How to use a class object in C++ as a function parameter

class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.

e.g.

class ANewType
{
    // ... details
};

This defines a new type called ANewType which is a class type.

You can then use this in function declarations:

void function(ANewType object);

You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

void function(ANewType& object); // object passed by reference

This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

[* The class keyword is also used in template definitions, but that's a different subject.]

Difference between ref and out parameters in .NET

out parameters are initialized by the method called, ref parameters are initialized before calling the method. Therefore, out parameters are used when you just need to get a secondary return value, ref parameters are used to get a value and potentially return a change to that value (secondarily to the main return value).

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

jackson deserialization json to java-objects

 JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"

 System.out.println("id : "+node.findValues("id").get(0).asText());

this also done the trick.

disable all form elements inside div

Try using the :input selector, along with a parent selector:

$("#parent-selector :input").attr("disabled", true);

JSON.parse unexpected token s

You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.

If you want an equivalent to your first example:

var s = '"something"';
var result = JSON.parse(s);

Should I return EXIT_SUCCESS or 0 from main()?

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

Get path from open file in Python

And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os Python module.

>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'

This way you can get hold of the directory structure.

jQuery & CSS - Remove/Add display:none

You're not giving us much information but in general this might be a solution:

$("div.news").css("display", "block");

How to update parent's state in React?

I found the following working solution to pass onClick function argument from child to the parent component:

Version with passing a method()

//ChildB component
class ChildB extends React.Component {

    render() {

        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div><button onClick={() => handleToUpdate('someVar')}>
            Push me
          </button>
        </div>)
    }
}

//ParentA component
class ParentA extends React.Component {

    constructor(props) {
        super(props);
        var handleToUpdate  = this.handleToUpdate.bind(this);
        var arg1 = '';
    }

    handleToUpdate(someArg){
            alert('We pass argument from Child to Parent: ' + someArg);
            this.setState({arg1:someArg});
    }

    render() {
        var handleToUpdate  =   this.handleToUpdate;

        return (<div>
                    <ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <ParentA />,
        document.querySelector("#demo")
    );
}

Look at JSFIDDLE

Version with passing an Arrow function

//ChildB component
class ChildB extends React.Component {

    render() {

        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div>
          <button onClick={() => handleToUpdate('someVar')}>
            Push me
          </button>
        </div>)
    }
}

//ParentA component
class ParentA extends React.Component { 
    constructor(props) {
        super(props);
    }

    handleToUpdate = (someArg) => {
            alert('We pass argument from Child to Parent: ' + someArg);
    }

    render() {
        return (<div>
            <ChildB handleToUpdate = {this.handleToUpdate} /></div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <ParentA />,
        document.querySelector("#demo")
    );
}

Look at JSFIDDLE

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

WHERE vs HAVING

The main difference is that WHERE cannot be used on grouped item (such as SUM(number)) whereas HAVING can.

The reason is the WHERE is done before the grouping and HAVING is done after the grouping is done.

Why is using "for...in" for array iteration a bad idea?

Here are the reasons why this is (usually) a bad practice:

  1. for...in loops iterate over all their own enumerable properties and the enumerable properties of their prototype(s). Usually in an array iteration we only want to iterate over the array itself. And even though you yourself may not add anything to the array, your libraries or framework might add something.

Example:

_x000D_
_x000D_
Array.prototype.hithere = 'hithere';_x000D_
_x000D_
var array = [1, 2, 3];_x000D_
for (let el in array){_x000D_
    // the hithere property will also be iterated over_x000D_
    console.log(el);_x000D_
}
_x000D_
_x000D_
_x000D_

  1. for...in loops do not guarantee a specific iteration order. Although is order is usually seen in most modern browsers these days, there is still no 100% guarantee.
  2. for...in loops ignore undefined array elements, i.e. array elements which not have been assigned yet.

Example::

_x000D_
_x000D_
const arr = []; _x000D_
arr[3] = 'foo';   // resize the array to 4_x000D_
arr[4] = undefined; // add another element with value undefined to it_x000D_
_x000D_
// iterate over the array, a for loop does show the undefined elements_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
    console.log(arr[i]);_x000D_
}_x000D_
_x000D_
console.log('\n');_x000D_
_x000D_
// for in does ignore the undefined elements_x000D_
for (let el in arr) {_x000D_
    console.log(arr[el]);_x000D_
}
_x000D_
_x000D_
_x000D_

Showing Difference between two datetime values in hours

a more precise way for employee paid hours or other precision requirement::

decimal DeterminePreciseHours(DateTime startTimestamp, DateTime stopTimestamp)
{
    var span = (stopTimestamp - startTimestamp).Value;
    decimal total = (decimal)span.TotalMilliseconds / 60 / 60 / 1000;
    return Math.Round(total, PRECISION_CONSTANT);
}

https://dotnetfiddle.net/tVIoVJ

Split a string by another string in C#

The previous answers are all correct. I go one step further and make C# work for me by defining an extension method on String:

public static class Extensions
{
    public static string[] Split(this string toSplit, string splitOn) {
        return toSplit.Split(new string[] { splitOn }, StringSplitOptions.None);
    }
}

That way I can call it on any string in the simple way I naively expected the first time I tried to accomplish this:

"a big long string with stuff to split on".Split("g str");

NVIDIA NVML Driver/library version mismatch

I committed the container into a docker image. Then I recreate another container using this docker image and the problem was gone.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

In my case none of the other answers worked because I previously downgraded to node8. So instead of doing above, following worked for me:

which node

which returned /usr/local/bin/node@8 instead of /usr/local/bin/node

so i executed this command:

brew uninstall node@8

which worked and then downloaded latest pkg from official site and installed. After that I had to close my terminal and start again to access new version

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

Kill some processes by .exe file name

My solution is to use Process.GetProcess() for listing all the processes.

By filtering them to contain the processes I want, I can then run Process.Kill() method to stop them:

var chromeDriverProcesses = Process.GetProcesses().
    Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
    
foreach (var process in chromeDriverProcesses)
{
     process.Kill();
}

Update:

In case if want to use async approach with some useful recent methods from the C# 8 (Async Enumerables), then check this out:

const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
             .Where(pr => pr.ProcessName == processName)
             .ToAsyncEnumerable()
             .ForEachAsync(p => p.Kill());

Note: using async methods doesn't always mean code will run faster, but it will not waste the CPU time and prevent the foreground thread from hanging while doing the operations. In any case, you need to think about what version you might want.

Running Node.Js on Android

Dory - node.js

Great New Application
No Need to root your Phone and You Can Run your js File From anywere.

  • node.js runtime(run ES2015/ES6, ES2016 javascript and node.js APIs in android)
  • API Documents and instant code run from doc
  • syntax highlighting code editor
  • npm supports
  • linux terminal(toybox 0.7.4). node.js REPL and npm command in shell (add '--no-bin-links' option if you execute npm in /sdcard)
  • StartOnBoot / LiveReload
  • native node.js binary and npm are included. no need to be online.

Update instruction to node js 8 (async await)

  1. Download node.js v8.3.0 arm zip file and unzip.

  2. copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)

  3. open the shell(check it out in the app's menu)

  4. cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )

  5. rm node

  6. cp /sdcard/node .

  7. (chmod a+x node

(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)

Scroll RecyclerView to show selected item on top

You just need to call recyclerview.scrollToPosition(position). That's fine!

If you want to call it in adapter, just let your adapter has the instance of recyclerview or the activity or fragment which contains recyclerview,than implements the method getRecyclerview() in them.

I hope it can help you.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to convert SQL Server's timestamp column to datetime format

After impelemtation of conversion to integer CONVERT(BIGINT, [timestamp]) as Timestamp I've got the result like

446701117 446701118 446701119 446701120 446701121 446701122 446701123 446701124 446701125 446701126

Yes, this is not a date and time, It's serial numbers

UnicodeEncodeError: 'charmap' codec can't encode characters

if you are using windows try to pass encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' example:

csv_data = pd.read_csv(csvpath,encoding='iso-8859-1')
print(print(soup.encode('iso-8859-1')))

SQL Server add auto increment primary key to existing table

You can't "turn on" the IDENTITY: it's a table rebuild.

If you don't care about the number order, you'd add the column, NOT NULL, with IDENTITY in one go. 150k rows isn't a lot.

If you need to preserve some number order, then add the numbers accordingly. Then use the SSMS table designer to set the IDENTITY property. This allows you to generate a script which will do the column drop/add/keep numbers/reseed for you.

How to call a method after bean initialization is complete?

There are three different approaches to consider, as described in the reference

Use init-method attribute

Pros:

  • Does not require bean to implement an interface.

Cons:

  • No immediate indication this method is required after construction to ensure the bean is correctly configured.

Implement InitializingBean

Pros:

  • No need to specify init-method, or turn on component scanning / annotation processing.
  • Appropriate for beans supplied with a library, where we don't want the application using this library to concern itself with bean lifecycle.

Cons:

  • More invasive than the init-method approach.

Use JSR-250 @PostConstruct lifecyle annotation

Pros:

  • Useful when using component scanning to autodetect beans.
  • Makes it clear that a specific method is to be used for initialisation. Intent is closer to the code.

Cons:

  • Initialisation no longer centrally specified in configuration.
  • You must remember to turn on annotation processing (which can sometimes be forgotten)

How to compare two tables column by column in oracle

As an alternative which saves from full scanning each table twice and also gives you an easy way to tell which table had more rows with a combination of values than the other:

SELECT col1
     , col2
     -- (include all columns that you want to compare)
     , COUNT(src1) CNT1
     , COUNT(src2) CNT2
  FROM (SELECT a.col1
             , a.col2
             -- (include all columns that you want to compare)
             , 1 src1
             , TO_NUMBER(NULL) src2
          FROM tab_a a
         UNION ALL
        SELECT b.col1
             , b.col2
             -- (include all columns that you want to compare)
             , TO_NUMBER(NULL) src1
             , 2 src2
          FROM tab_b b
       )
 GROUP BY col1
        , col2
HAVING COUNT(src1) <> COUNT(src2) -- only show the combinations that don't match

Credit goes here: http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1417403971710

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I simply converted the varchar field that I wanted to convert into a new table (with a DateTime filed) to a DateTime compatible layout first and then SQL will do the conversion from varchar to DateTime without problems.

In the below (not my created table with those names !) I simply make the varchar field to be a DateTime lookalike if you want to:

update report1455062507424 
set [Move Time] = substring([Move Time], 7, 4) + '-'+ substring([Move Time], 4, 2) + '-'+ substring([Move Time], 1, 2) + ' ' + 
    substring([Move Time], 12, 5)  

Best way to get user GPS location in background in Android

I have try to my code and got success try this

package com.mobeyosoft.latitudelongitude;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by 5943 6417 on 14-09-2016.
 */
public class LocationService extends Service
{
    public static final String BROADCAST_ACTION = "Hello World";
    private static final int TWO_MINUTES = 1000 * 60 * 1;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;

    Context context;

    Intent intent;
    int counter = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);
        context=this;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
    }

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

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

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

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

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

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

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



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



    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.v("STOP_SERVICE", "DONE");
        locationManager.removeUpdates(listener);
    }

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {

                }
            }
        };
        t.start();
        return t;
    }




    public class MyLocationListener implements LocationListener{

        public void onLocationChanged(final Location loc)
        {
            Log.i("**********", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                loc.getLatitude();
                loc.getLongitude();
                Toast.makeText(context, "Latitude" + loc.getLatitude() + "\nLongitude"+loc.getLongitude(),Toast.LENGTH_SHORT).show();
                intent.putExtra("Latitude", loc.getLatitude());
                intent.putExtra("Longitude", loc.getLongitude());
                intent.putExtra("Provider", loc.getProvider());
                sendBroadcast(intent);

            }
        }

        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }


        public void onProviderEnabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }


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

        }

    }
}

Using regular expressions to do mass replace in Notepad++ and Vim

This will work. Tested it in my vim. the single quotes are the trouble.

1,$s/^<option value value=['].['] >/

Fully change package name including company domain

I also faced same problem & here is how I solved :-

I want to change package name np.com.shivakrstha.userlog to np.edu.khec.userlog

I selected shivakrstha and I pressed Shift + F6 for Rename Refract and renamed to khec.

Finally, use the same package name in AndroidManifest.xml, applicationId in build.gradle and don't forget to Rebuild Your Project.

Note:- I tried to change np to jp, so I selected np and I pressed Shift + F6 for Rename Refract and renamed to jp, it's ok to change others too.

ArrayList - How to modify a member of an object?

You can iterate through arraylist to identify the index and eventually the object which you need to modify. You can use for-each for the same as below:

for(Customer customer : myList) {
    if(customer!=null && "Doe".equals(customer.getName())) {
        customer.setEmail("[email protected]");
        break;
    }
}

Here customer is a reference to the object present in Arraylist, If you change any property of this customer reference, these changes will reflect in your object stored in Arraylist.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

How should I make my VBA code compatible with 64-bit Windows?

Office 2007 is 32 bit only so there is no issue there. Your problems arise only with Office 64 bit which has both 32 and 64 bit versions.

You cannot hope to support users with 64 bit Office 2010 when you only have Office 2007. The solution is to upgrade.

If the only Declare that you have is that ShellExecute then you won't have much to do once you get hold of 64 bit Office, but it's not really viable to support users when you can't run the program that you ship! Just think what you would do you do when they report a bug?

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

How to printf "unsigned long" in C?

int main()
{
    unsigned long long d;
    scanf("%llu",&d);
    printf("%llu",d);
    getch();
}

This will be helpful . . .

Is there an operator to calculate percentage in Python?

There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.

How can I force component to re-render with hooks in React?

react-tidy has a custom hook just for doing that called useRefresh:

import React from 'react'
import {useRefresh} from 'react-tidy'

function App() {
  const refresh = useRefresh()
  return (
    <p>
      The time is {new Date()} <button onClick={refresh}>Refresh</button>
    </p>
  )
}

Learn more about this hook

Disclaimer I am the writer of this library.

How to get current working directory in Java?

If you want the absolute path of the current source code, my suggestion is:

String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));

CMake does not find Visual C++ compiler

This might be another solution for those with the latest Windows 10 creator version:

Stack Overflow post Fatal error LNK1104: cannot open file 'gdi32.lib'

Using CSS in Laravel views?

Put them in public folder and call it in the view with something like href="{{ asset('public/css/style.css') }}". Note that the public should be included when you call the assets.

Remove decimal values using SQL query

Here column name must be decimal.

select CAST(columnname AS decimal(38,0)) from table

Git push failed, "Non-fast forward updates were rejected"

Before pushing, do a git pull with rebase option. This will get the changes that you made online (in your origin) and apply them locally, then add your local changes on top of it.

git pull --rebase

Now, you can push to remote

git push 

For more information take a look at Git rebase explained and Chapter 3.6 Git Branching - Rebasing.

Converting String To Float in C#

First, it is just a presentation of the float number you see in the debugger. The real value is approximately exact (as much as it's possible).

Note: Use always CultureInfo information when dealing with floating point numbers versus strings.

float.Parse("41.00027357629127",
      System.Globalization.CultureInfo.InvariantCulture);

This is just an example; choose an appropriate culture for your case.

What's the difference between jquery.js and jquery.min.js?

In easy language, both versions are absolutely the same. Only difference is:

  • min.js is for websites (online)

  • .js is for developers, guys who needs to read, learn about or/and understand jquery codes, for ie plugin development (offline, local work).

how to get the value of a textarea in jquery?

$('textarea#message') cannot be undefined (if by $ you mean jQuery of course).

$('textarea#message') may be of length 0 and then $('textarea#message').val() would be empty that's all

jQuery window scroll event does not fire up

  1. Declare your jQuery between <script> and </script> in the <head>,
  2. Wrap your .scroll() event within
$(document).ready(function(){
  //do something
});

How to set web.config file to show full error message

This can also help you by showing full details of the error on a client's browser.

<system.web>
    <customErrors mode="Off"/>
</system.web>
<system.webServer>
    <httpErrors errorMode="Detailed" />
</system.webServer>

Java null check why use == instead of .equals()

I have encountered this case last night.
I determine that simply that:

Don't exist equals() method for null
So, you can not invoke an inexistent method if you don't have
-->>> That is reason for why we use == to check null

Conversion failed when converting the varchar value 'simple, ' to data type int

If you are converting a varchar to int make sure you do not have decimal places.

For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.

CONVERT(int, replace(FIELD_NAME,'.0',''))

Multiple bluetooth connection

Yes, your device can simultaneously connect to 7 other Bluetooth devices at the same time, in theory. Such a connection is called a piconet. A more complex connection pattern is the scatternet.

The reason it is limited to 7 other devices is because the assigned bit field for LT_ADDR in L2CAP protocol is only 3.

How can I change the current URL?

Simple assigning to window.location or window.location.href should be fine:

window.location = newUrl;

However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:

  1. Use the URL hash. For example, you can go from example.com to example.com#foo without loading a new page. You can simply set window.location.hash to make this easy. Then, you should listen to the HTML5 hashchange event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.

  2. You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo to example.com/bar. Using this is easy:

    window.history.pushState("example.com/foo");

    When the user presses "back", you'll receive the window's popstate event, which you can easily listen to (jQuery):

    $(window).bind("popstate", function(e) { alert("location changed"); });

    Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.

Limit length of characters in a regular expression?

If you want numbers from 1 up to 100:

100|[1-9]\d?

How to sort an array of associative arrays by value of a given key in PHP?

You can use usort with anonymous function, e.g.

usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });

Java 8 lambda Void argument

Use Supplier if it takes nothing, but returns something.

Use Consumer if it takes something, but returns nothing.

Use Callable if it returns a result and might throw (most akin to Thunk in general CS terms).

Use Runnable if it does neither and cannot throw.

How to write text on a image in windows using python opencv2

This is indeed a bit of an annoying problem. For python 2.x.x you use:

cv2.CV_FONT_HERSHEY_SIMPLEX

and for Python 3.x.x:

cv2.FONT_HERSHEY_SIMPLEX

I recommend using a autocomplete environment(pyscripter or scipy for example). If you lookup example code, make sure they use the same version of Python(if they don't make sure you change the code).

How to POST the data from a modal form of Bootstrap?

I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
                    method="post"
                    action="abc.php">
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
                                    name="planform">

                </form>

You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {
        document.getElementById("paymentitrform").submit();
   }  

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

When your code does the following:

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

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

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

Example (derived from Josh's example):

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

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

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

Using Position Relative/Absolute within a TD?

also works if you do a "display: block;" on the td, destroying the td identity, but works!

How to have multiple colors in a Windows batch file?

Actually this can be done without creating a temporary file. The method described by jeb and dbenham will work even with a target file that contains no backspaces. The critical point is that the line recognized by findstr.exe must not end with a CRLF. So the obvious text file to scan with a line not ending with a CRLF is the invoking batch itself, provided that we end it with such a line! Here's an updated example script working this way...

Changes from the previous example:

  • Uses a single dash on the last line as the searchable string. (Must be short and not appear anywhere else like this in the batch.)
  • Renamed routines and variables to be a little more object-oriented :-)
  • Removed one call level, to slightly improve performance.
  • Added comments (Beginning with :# to look more like most other scripting languages.)

@echo off
setlocal

call :Echo.Color.Init

goto main

:Echo.Color %1=Color %2=Str [%3=/n]
setlocal enableDelayedExpansion
set "str=%~2"
:Echo.Color.2
:# Replace path separators in the string, so that the final path still refers to the current path.
set "str=a%ECHO.DEL%!str:\=a%ECHO.DEL%\..\%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%!"
set "str=!str:/=a%ECHO.DEL%/..\%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%!"
set "str=!str:"=\"!"
:# Go to the script directory and search for the trailing -
pushd "%ECHO.DIR%"
findstr /p /r /a:%~1 "^^-" "!str!\..\!ECHO.FILE!" nul
popd
:# Remove the name of this script from the output. (Dependant on its length.)
for /l %%n in (1,1,12) do if not "!ECHO.FILE:~%%n!"=="" <nul set /p "=%ECHO.DEL%"
:# Remove the other unwanted characters "\..\: -"
<nul set /p "=%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%"
:# Append the optional CRLF
if not "%~3"=="" echo.
endlocal & goto :eof

:Echo.Color.Var %1=Color %2=StrVar [%3=/n]
if not defined %~2 goto :eof
setlocal enableDelayedExpansion
set "str=!%~2!"
goto :Echo.Color.2

:Echo.Color.Init
set "ECHO.COLOR=call :Echo.Color"
set "ECHO.DIR=%~dp0"
set "ECHO.FILE=%~nx0"
set "ECHO.FULL=%ECHO.DIR%%ECHO.FILE%"
:# Use prompt to store a backspace into a variable. (Actually backspace+space+backspace)
for /F "tokens=1 delims=#" %%a in ('"prompt #$H# & echo on & for %%b in (1) do rem"') do set "ECHO.DEL=%%a"
goto :eof

:main
call :Echo.Color 0a "a"
call :Echo.Color 0b "b"
set "txt=^" & call :Echo.Color.Var 0c txt
call :Echo.Color 0d "<"
call :Echo.Color 0e ">"
call :Echo.Color 0f "&"
call :Echo.Color 1a "|"
call :Echo.Color 1b " "
call :Echo.Color 1c "%%%%"
call :Echo.Color 1d ^"""
call :Echo.Color 1e "*"
call :Echo.Color 1f "?"
:# call :Echo.Color 2a "!"
call :Echo.Color 2b "."
call :Echo.Color 2c ".."
call :Echo.Color 2d "/"
call :Echo.Color 2e "\"
call :Echo.Color 2f "q:" /n
echo(
set complex="c:\hello world!/.\..\\a//^<%%>&|!" /^^^<%%^>^&^|!\
call :Echo.Color.Var 74 complex /n

exit /b

:# The following line must be last and not end by a CRLF.
-

PS. I'm having a problem with the output of the ! character that you did not have in the previous example. (Or at least you did not have the same symptoms.) To be investigated.

What's the best way to determine which version of Oracle client I'm running?

You should put a semicolon at the end of select * from v$version;.

Like this you will get all info you need...

If you are looking just for Oracle for example you can do as:

SQL> select * from v$version where banner like 'Oracle%';

How can I scale an image in a CSS sprite

Set the width and height to wrapper element of the sprite image. Use this css.

{
    background-size: cover;
}

Hadoop/Hive : Loading data from .csv on a local machine

You may try this, Following are few examples on how files are generated. Tool -- https://sourceforge.net/projects/csvtohive/?source=directory

  1. Select a CSV file using Browse and set hadoop root directory ex: /user/bigdataproject/

  2. Tool Generates Hadoop script with all csv files and following is a sample of generated Hadoop script to insert csv into Hadoop

    #!/bin/bash -v
    hadoop fs -put ./AllstarFull.csv /user/bigdataproject/AllstarFull.csv hive -f ./AllstarFull.hive

    hadoop fs -put ./Appearances.csv /user/bigdataproject/Appearances.csv hive -f ./Appearances.hive

    hadoop fs -put ./AwardsManagers.csv /user/bigdataproject/AwardsManagers.csv hive -f ./AwardsManagers.hive

  3. Sample of generated Hive scripts

    CREATE DATABASE IF NOT EXISTS lahman;
    USE lahman;
    CREATE TABLE AllstarFull (playerID string,yearID string,gameNum string,gameID string,teamID string,lgID string,GP string,startingPos string) row format delimited fields terminated by ',' stored as textfile;
    LOAD DATA INPATH '/user/bigdataproject/AllstarFull.csv' OVERWRITE INTO TABLE AllstarFull;
    SELECT * FROM AllstarFull;

Thanks Vijay

Tracking CPU and Memory usage per process

Hmm, I see that Process Explorer can do it, although its graphs are not too convenient. Still looking for alternative / better ways to do it.

How to convert md5 string to normal text?

Md5 is a hashing algorithm. There is no way to retrieve the original input from the hashed result.

If you want to add a "forgotten password?" feature, you could send your user an email with a temporary link to create a new password.

Note: Sending passwords in plain text is a BAD idea :)

Eclipse: Java was started but returned error code=13

My solution: Because all others did not work for me. I deleted the symlinks at C:\ProgramData\Oracle\Java\javapath. this makes eclipse to run with the jre declared in the PATH. This is better for me because I want to develop Java with the JRE I chose, not the system JRE. Often you want to develop with older versions and such

How to do a Jquery Callback after form submit?

The form's "on submit" handlers are called before the form is submitted. I don't know if there is a handler to be called after the form is submited. In the traditional non-Javascript sense the form submission will reload the page.

String comparison using '==' vs. 'strcmp()'

strcmp will return different values based on the environment it is running(Linux/Windows)!

The reason is the that it has a bug as the bug report says https://bugs.php.net/bug.php?id=53999

Please handle with care!!Thank you.

PowerShell script to return members of multiple security groups

This is cleaner and will put in a csv.

Import-Module ActiveDirectory

$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)


$Table = @()

$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}



Foreach ($Group in $Groups)
{

$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname

foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}

}

$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

How to add a new line in textarea element?

You might want to use \n instead of /n.

Generating random strings with T-SQL

I'm not expert in T-SQL, but the simpliest way I've already used it's like that:

select char((rand()*25 + 65))+char((rand()*25 + 65))

This generates two char (A-Z, in ascii 65-90).

Configure hibernate to connect to database via JNDI Datasource

Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.

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



  <jee:jndi-lookup id="dataSource"
                 jndi-name="Give_DataSource_Path_From_Your_Server"
                 expected-type="javax.sql.DataSource" />


Hope It will help someone.Thanks!

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

How to implement reCaptcha for ASP.NET MVC?

Simple and Complete Solution working for me. Supports ASP.NET MVC 4 and 5 (Supports ASP.NET 4.0, 4.5, and 4.5.1)

Step 1: Install NuGet Package by "Install-Package reCAPTCH.MVC"

Step 2: Add your Public and Private key to your web.config file in appsettings section

<appSettings>
    <add key="ReCaptchaPrivateKey" value=" -- PRIVATE_KEY -- " />
    <add key="ReCaptchaPublicKey" value=" -- PUBLIC KEY -- " />
</appSettings>  

You can create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page

Step 3: Modify your form to include reCaptcha

@using reCAPTCHA.MVC
@using (Html.BeginForm())
{
    @Html.Recaptcha()
    @Html.ValidationMessage("ReCaptcha")
    <input type="submit" value="Register" />
}

Step 4: Implement the Controller Action that will handle the form submission and Captcha validation

[CaptchaValidator(
PrivateKey = "your private reCaptcha Google Key",
ErrorMessage = "Invalid input captcha.",
RequiredMessage = "The captcha field is required.")]
public ActionResult MyAction(myVM model)
{
    if (ModelState.IsValid) //this will take care of captcha
    {
    }
}

OR

public ActionResult MyAction(myVM model, bool captchaValid)
{
    if (captchaValid) //manually check for captchaValid 
    {
    }
}

Check/Uncheck a checkbox on datagridview

The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code

private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];

    if (chk.Value == chk.TrueValue)
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
    }
    else
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
    }

}

Get unicode value of a character

You can do it for any Java char using the one liner here:

System.out.println( "\\u" + Integer.toHexString('÷' | 0x10000).substring(1) );

But it's only going to work for the Unicode characters up to Unicode 3.0, which is why I precised you could do it for any Java char.

Because Java was designed way before Unicode 3.1 came and hence Java's char primitive is inadequate to represent Unicode 3.1 and up: there's not a "one Unicode character to one Java char" mapping anymore (instead a monstrous hack is used).

So you really have to check your requirements here: do you need to support Java char or any possible Unicode character?

Filezilla FTP Server Fails to Retrieve Directory Listing

My issue was also the firewall. I'm using a Linux server with WHM/cPanel. Adding my IP to the quick allow solved my issue. I hadn't updated Filezilla and I don't think there were any changes to the server that should have caused it. However, I did move and my IP changed so maybe that was the problem. Good luck to everyone else with this insanely annoying issue.

how to access WHM firewall config

jQuery Screen Resolution Height Adjustment

Here is an example on how to center an object vertically with jQuery:

var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2  + 'px');

But you could easily change that to whatever your needs are.

Django database query: How to get object by id?

You can use:

objects_all=Class.objects.filter(filter_condition="")

This will return a query set even if it gets one object. If you need exactly one object use:

obj=Class.objects.get(conditon="")

How to get ID of the last updated row in MySQL?

If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.

If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.

Having set this, you can then use a query like: SELECT id FROM table ORDER BY last_modified DESC LIMIT 1; to get the most recently modified row.

Is there a conditional ternary operator in VB.NET?

Just for the record, here is the difference between If and IIf:

IIf(condition, true-part, false-part):

  • This is the old VB6/VBA Function
  • The function always returns an Object type, so if you want to use the methods or properties of the chosen object, you have to re-cast it with DirectCast or CType or the Convert.* Functions to its original type
  • Because of this, if true-part and false-part are of different types there is no matter, the result is just an object anyway

If(condition, true-part, false-part):

  • This is the new VB.NET Function
  • The result type is the type of the chosen part, true-part or false-part
  • This doesn't work, if Strict Mode is switched on and the two parts are of different types. In Strict Mode they have to be of the same type, otherwise you will get an Exception
  • If you really need to have two parts of different types, switch off Strict Mode (or use IIf)
  • I didn't try so far if Strict Mode allows objects of different type but inherited from the same base or implementing the same Interface. The Microsoft documentation isn't quite helpful about this issue. Maybe somebody here knows it.

Why should I use a pointer rather than the object itself?

Let's say that you have class A that contain class B When you want to call some function of class B outside class A you will simply obtain a pointer to this class and you can do whatever you want and it will also change context of class B in your class A

But be careful with dynamic object

I can not find my.cnf on my windows computer

Start->Search->For Files and Folders->All Files and Folders

type "my.cnf" and hit search.

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Regex for parsing directory and filename

A very late answer, but hope this will help

^(.+?)/([\w]+\.log)$

This uses lazy check for /, and I just modified the accepted answer

http://regex101.com/r/gV2xB7/1

Cannot ignore .idea/workspace.xml - keeps popping up

I had this problem just now, I had to do git rm -f .idea/workspace.xml now it seems to be gone (I also had to put it into .gitignore)

Regular expression to match balanced parentheses

I was also stuck in this situation where nested patterns comes.

Regular Expression is right thing to solve the above problem. Use below pattern

'/(\((?>[^()]+|(?1))*\))/'

iterating through json object javascript

Here is my recursive approach:

function visit(object) {
    if (isIterable(object)) {
        forEachIn(object, function (accessor, child) {
            visit(child);
        });
    }
    else {
        var value = object;
        console.log(value);
    }
}

function forEachIn(iterable, functionRef) {
    for (var accessor in iterable) {
        functionRef(accessor, iterable[accessor]);
    }
}

function isIterable(element) {
    return isArray(element) || isObject(element);
}

function isArray(element) {
    return element.constructor == Array;
}

function isObject(element) {
    return element.constructor == Object;
}

ORA-01882: timezone region not found

Facing the same issue using Eclipse and a distant Oracle Database, changing my system time zone to match the time zone of the database server fixed the problem. Re-start the machine after changing system time zone.

I hope this can help someone

Clear listview content?

I guess you passed a List or an Array to the Adapter. If you keep the instance of this added collection, you can do a

collection.clear();
listview.getAdapter().notifyDataSetChanged();

this'll work only if you instantiated the adapter with collection and it's the same instance.

Also, depending on the Adapter you extended, you may not be able to do this. SimpleAdapter is used for static data, thus it can't be updated after creation.

PS. not all Adapters have a clear() method. ArrayAdapter does, but ListAdapter or SimpleAdapter don't

Get value of a specific object property in C# without knowing the class behind

Use reflection

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

No resource found - Theme.AppCompat.Light.DarkActionBar

If you are using Eclipse just copying android-support-v7-appcompat.jar to libs folder will not work if you are going to use resources.

Follow steps from here for "Adding libraries with resources".

How to check if NSString begins with a certain character

This nice little bit of code I found by chance, and I have yet to see it suggested on Stack. It only works if the characters you want to remove or alter exist, which is convenient in many scenarios. If the character/s does not exist, it won't alter your NSString:

NSString = [yourString stringByReplacingOccurrencesOfString:@"YOUR CHARACTERS YOU WANT TO REMOVE" withString:@"CAN either be EMPTY or WITH TEXT REPLACEMENT"];

This is how I use it:

//declare what to look for
NSString * suffixTorRemove = @"&lt;/p&gt;";
NSString * prefixToRemove = @"&lt;p&gt;";
NSString * randomCharacter = @"&lt;/strong&gt;";
NSString * moreRandom = @"&lt;strong&gt;";
NSString * makeAndSign = @"&amp;amp;";

//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:@"&"];

//check the output
NSLog(@"returnStr IS NOW: %@", returnStr);

This one line is super easy to perform three actions in one:

  1. Checks your string for the character/s you do not want
  2. Can replaces them with whatever you like
  3. Does not affect surrounding code

Can I use a case/switch statement with two variables?

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

Syntax for async arrow function

Immediately Invoked Async Arrow Function:

(async () => {
    console.log(await asyncFunction());
})();

Immediately Invoked Async Function Expression:

(async function () {
    console.log(await asyncFunction());
})();

Blue and Purple Default links, how to remove?

Hey define color #000 into as like you and modify your css as like this

.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }

or this

 li a { text-decoration: none; color:#000; }
 li a:visited { text-decoration: none; color:#000; }
 li a:hover { text-decoration: none; color:#000; }
 li a:focus { text-decoration: none; color:#000; }
 li a:hover, .navBtn:active { text-decoration: none; color:#000; }

"column not allowed here" error in INSERT statement

INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');

the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10). you should have used ' '.

try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

Try executing below command,

java -help

It gives option as,

-version print product version and exit

java -version is the correct command to execute

File Upload in WebView

Ive actually managed to get the file picker to appear in Kitkat, to select a image and to get the filepath in activity result but the only thing that im not able to "fix" (cause this workaround) is to make the input filed to fill out with file data.

Does anyone know any way how to access the input-field from a activity ? Am using this example comment. Is just this last piece, the last brick in the wall that i just have to put into right place (tho i could trigger upload of image file directly from code.

UPDATE #1

Im no hardcore Android dev so i'll show code on newbie level. Im creating a new Activity in already existing Activity

Manifest part

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application android:label="TestApp">
 <activity android:name=".BrowseActivity"></activity>
</application>

Am creating my BrowseActivity class from this example answer. The WebChromeClient() instance basically looks the same, except last piece, triggering the picker UI part...

private final static int FILECHOOSER_RESULTCODE=1;  
private final static int KITKAT_RESULTCODE = 2;

...

// The new WebChromeClient() looks pretty much the same, except one piece...

WebChromeClient chromeClient = new WebChromeClient(){  
    // For Android 3.0+
    public void openFileChooser(ValueCallback<Uri> uploadMsg) { /* Default code */ }  

    // For Android 3.0+
    public void openFileChooser( ValueCallback uploadMsg, String acceptType ) { /* Default code */ }  

    //For Android 4.1, also default but it'll be as example
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        BrowseActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), BrowseActivity.FILECHOOSER_RESULTCODE);

    }  

    // The new code
    public void showPicker( ValueCallback<Uri> uploadMsg ){  
        // Here is part of the issue, the uploadMsg is null since it is not triggered from Android
        mUploadMessage = uploadMsg; 
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        BrowseActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), BrowseActivity.KITKAT_RESULTCODE);
    }}

And some more stuff

web = new WebView(this);
// Notice this part, setting chromeClient as js interface is just lazy
web.getSettings().setJavaScriptEnabled(true);
web.addJavascriptInterface(chromeClient, "jsi" );
web.getSettings().setAllowFileAccess(true);
web.getSettings().setAllowContentAccess(true);
web.clearCache(true);
web.loadUrl( "http://as3breeze.com/upload.html" );
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(chromeClient);


@Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) {  
  Log.d("Result", "("+requestCode+ ") - (" +resultCode  + ") - (" + intent + ") - " + mUploadMessage);  
    if (null == intent) return;  
    Uri result = null;  
    if(requestCode==FILECHOOSER_RESULTCODE)  
    {  
        Log.d("Result","Old android");  
        if (null == mUploadMessage) return;  
        result = intent == null || resultCode != RESULT_OK ? null  : intent.getData();  
        mUploadMessage.onReceiveValue(result);  
        mUploadMessage = null;  
    } else if (requestCode == KITKAT_RESULTCODE) {  
        Log.d("Result","Kitkat android");  
        result = intent.getData();  
        final int takeFlags = intent.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION  | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);  
        String path = getPath( this, result);  
        File selectedFile = new File(path); 
//I used you example with a bit of editing so thought i would share, here i added a method to upload the file to the webserver
File selectedFile = new File(path);  
            UploadFile(selectedFile);


        //mUploadMessage.onReceiveValue( Uri.parse(selectedFile.toString()) );  
        // Now we have the file but since mUploadMessage was null, it gets errors
    }  
}

 public void UploadFile(File selectedFile)
{
    Random rnd = new Random();
    String sName = "File" + rnd.nextInt(999999) + selectedFile.getAbsolutePath().substring(selectedFile.getAbsolutePath().lastIndexOf("."));
    UploadedFileName = sName;
    uploadFile = selectedFile;
    if (progressBar != null && progressBar.isShowing())
    {
        progressBar.dismiss();
    }
 // prepare for a progress bar dialog
    progressBar = new ProgressDialog(mContext);
    progressBar.setCancelable(true);
    progressBar.setMessage("Uploading File");
    progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);            
    progressBar.show();
    new Thread() {

        public void run() 
        {
            int serverResponseCode;
            String serverResponseMessage;
            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            DataInputStream inputStream = null;
            String pathToOurFile = uploadFile.getAbsolutePath();
            String urlServer = "http://serveraddress/Scripts/UploadHandler.php?name" + UploadedFileName;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****";

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;

            try
            {
                FileInputStream fileInputStream = new FileInputStream(uploadFile);

                URL url = new URL(urlServer);
                connection = (HttpURLConnection) url.openConnection();
                Log.i("File", urlServer);

                // Allow Inputs &amp; Outputs.
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);

                // Set HTTP method to POST.
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                Log.i("File", "Open conn");

                outputStream = new DataOutputStream( connection.getOutputStream() );

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
                outputStream.writeBytes(lineEnd);
                Log.i("File", "write bytes");

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                Log.i("File", "available: " + fileInputStream.available());

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                Log.i("file", "Bytes Read: " + bytesRead);
                while (bytesRead > 0)
                {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = connection.getResponseCode();
                serverResponseMessage = connection.getResponseMessage();
                Log.i("file repsonse", serverResponseMessage);

//once the file is uploaded call a javascript function to verify the user wants to save the image
                progressBar.dismiss();
                runOnUiThread(new Runnable() 
                {

                    @Override
                    public void run() 
                    {
                        Log.i("start", "File name: " + UploadedFileName);
                        WebView myWebView = (WebView) findViewById(R.id.webview);
                        myWebView.loadUrl("javascript:CheckImage('" + UploadedFileName + "')");
                    }
                });


                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
            }
            catch (Exception ex)
            {
                Log.i("exception", "Error: " + ex.toString());
            }               
        }
    }.start();

}

Lastly, some more code to get the actual file path, code found on SO, ive added post url in comments as well so the author gets credits for his work.

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 * @source https://stackoverflow.com/a/20559175
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 * @source https://stackoverflow.com/a/20559175
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 * @source https://stackoverflow.com/a/20559175
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 * @source https://stackoverflow.com/a/20559175
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 * @source https://stackoverflow.com/a/20559175
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}  

Lastly, the HTML page needs to trigger that new method of showPicker (specificaly when on A4.4)

<form id="form-upload" method="post" enctype="multipart/form-data">
    <input id="fileupload" name="fileupload" type="file" onclick="javascript:prepareForPicker();"/>
</form>
<script type="text/javascript">
function getAndroidVersion() {
    var ua = navigator.userAgent; 
    var match = ua.match(/Android\s([0-9\.]*)/);
    return match ? match[1] : false;
};
function prepareForPicker(){
    if(getAndroidVersion().indexOf("4.4") != -1){
        window.jsi.showPicker();
        return false;
    }
}

function CheckImage(name)
{
//Check to see if user wants to save I used some ajax to save the file if necesarry
}
</script>

How to combine two byte arrays

You're just trying to concatenate the two byte arrays?

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
{
    combined[i] = i < one.length ? one[i] : two[i - one.length];
}

Or you could use System.arraycopy:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);

Or you could just use a List to do the work:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));

byte[] combined = list.toArray(new byte[list.size()]);

Or you could simply use ByteBuffer with the advantage of adding many arrays.

byte[] allByteArray = new byte[one.length + two.length + three.length];

ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);

byte[] combined = buff.array();

Gray out image with CSS?

Better to support all the browsers:

img.lessOpacity {               
   opacity: 0.4;
   filter: alpha(opacity=40);
   zoom: 1;  /* needed to trigger "hasLayout" in IE if no width or height is set */ 
}

Properties private set;

This is one possible solution although not very clean:

  1. Make the property you need to expose to BAL & DAL internal
  2. Mark BAL.dll & DAL.dll Internal Visible in assemblyinfo.cs

public class Person
{
    public Person(int id)
    {
         this.Id=id;
    }

    public string Name { get;  set; }
    public int Id { get; internal set; }
    public int Age { get; set; }
}

AssemblyInfo.cs for Entities.dll

[assembly: InternalsVisibleTo("DAL"), InternalsVisibleTo("BAL")]

That way all your internals will be visible to DAL & BAL. This may not be desirable but I'm just suggesting one possible solution.

Get list of filenames in folder with Javascript

I use the following (stripped-down code) in Firefox 69.0 (on Ubuntu) to read a directory and show the image as part of a digital photo frame. The page is made in HTML, CSS, and JavaScript, and it is located on the same machine where I run the browser. The images are located on the same machine as well, so there is no viewing from "outside".

var directory = <path>;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', directory, false); // false for synchronous request
xmlHttp.send(null);
var ret = xmlHttp.responseText;
var fileList = ret.split('\n');
for (i = 0; i < fileList.length; i++) {
    var fileinfo = fileList[i].split(' ');
    if (fileinfo[0] == '201:') {
        document.write(fileinfo[1] + "<br>");
        document.write('<img src=\"' + directory + fileinfo[1] + '\"/>');
    }
}

This requires the policy security.fileuri.strict_origin_policy to be disabled. This means it might not be a solution you want to use. In my case I deemed it ok.

What is the difference between a static and const variable?

A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.

These two concepts are not mutually exclusive, and can be used together.

TypeError: unhashable type: 'list' when using built-in set function

Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.

Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.

result = sorted(set(map(tuple, my_list)), reverse=True)

Additional note: If a tuple contains a list, the tuple is still considered mutable.

Some examples:

>>> hash( tuple() )
3527539
>>> hash( dict() )

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    hash( list() )
TypeError: unhashable type: 'list'

Create a Date with a set timezone without using a string representation

Simply Set the Time Zone and Get Back According

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

Other Time-zones are as Following

var world_timezones =
[
    'Europe/Andorra',
    'Asia/Dubai',
    'Asia/Kabul',
    'Europe/Tirane',
    'Asia/Yerevan',
    'Antarctica/Casey',
    'Antarctica/Davis',
    'Antarctica/DumontDUrville', 
    'Antarctica/Mawson',
    'Antarctica/Palmer',
    'Antarctica/Rothera',
    'Antarctica/Syowa',
    'Antarctica/Troll',
    'Antarctica/Vostok',
    'America/Argentina/Buenos_Aires',
    'America/Argentina/Cordoba',
    'America/Argentina/Salta',
    'America/Argentina/Jujuy',
    'America/Argentina/Tucuman',
    'America/Argentina/Catamarca',
    'America/Argentina/La_Rioja',
    'America/Argentina/San_Juan',
    'America/Argentina/Mendoza',
    'America/Argentina/San_Luis',
    'America/Argentina/Rio_Gallegos',
    'America/Argentina/Ushuaia',
    'Pacific/Pago_Pago',
    'Europe/Vienna',
    'Australia/Lord_Howe',
    'Antarctica/Macquarie',
    'Australia/Hobart',
    'Australia/Currie',
    'Australia/Melbourne',
    'Australia/Sydney',
    'Australia/Broken_Hill',
    'Australia/Brisbane',
    'Australia/Lindeman',
    'Australia/Adelaide',
    'Australia/Darwin',
    'Australia/Perth',
    'Australia/Eucla',
    'Asia/Baku',
    'America/Barbados',
    'Asia/Dhaka',
    'Europe/Brussels',
    'Europe/Sofia',
    'Atlantic/Bermuda',
    'Asia/Brunei',
    'America/La_Paz',
    'America/Noronha',
    'America/Belem',
    'America/Fortaleza',
    'America/Recife',
    'America/Araguaina',
    'America/Maceio',
    'America/Bahia',
    'America/Sao_Paulo',
    'America/Campo_Grande',
    'America/Cuiaba',
    'America/Santarem',
    'America/Porto_Velho',
    'America/Boa_Vista',
    'America/Manaus',
    'America/Eirunepe',
    'America/Rio_Branco',
    'America/Nassau',
    'Asia/Thimphu',
    'Europe/Minsk',
    'America/Belize',
    'America/St_Johns',
    'America/Halifax',
    'America/Glace_Bay',
    'America/Moncton',
    'America/Goose_Bay',
    'America/Blanc-Sablon',
    'America/Toronto',
    'America/Nipigon',
    'America/Thunder_Bay',
    'America/Iqaluit',
    'America/Pangnirtung',
    'America/Atikokan',
    'America/Winnipeg',
    'America/Rainy_River',
    'America/Resolute',
    'America/Rankin_Inlet',
    'America/Regina',
    'America/Swift_Current',
    'America/Edmonton',
    'America/Cambridge_Bay',
    'America/Yellowknife',
    'America/Inuvik',
    'America/Creston',
    'America/Dawson_Creek',
    'America/Fort_Nelson',
    'America/Vancouver',
    'America/Whitehorse',
    'America/Dawson',
    'Indian/Cocos',
    'Europe/Zurich',
    'Africa/Abidjan',
    'Pacific/Rarotonga',
    'America/Santiago',
    'America/Punta_Arenas',
    'Pacific/Easter',
    'Asia/Shanghai',
    'Asia/Urumqi',
    'America/Bogota',
    'America/Costa_Rica',
    'America/Havana',
    'Atlantic/Cape_Verde',
    'America/Curacao',
    'Indian/Christmas',
    'Asia/Nicosia',
    'Asia/Famagusta',
    'Europe/Prague',
    'Europe/Berlin',
    'Europe/Copenhagen',
    'America/Santo_Domingo',
    'Africa/Algiers',
    'America/Guayaquil',
    'Pacific/Galapagos',
    'Europe/Tallinn',
    'Africa/Cairo',
    'Africa/El_Aaiun',
    'Europe/Madrid',
    'Africa/Ceuta',
    'Atlantic/Canary',
    'Europe/Helsinki',
    'Pacific/Fiji',
    'Atlantic/Stanley',
    'Pacific/Chuuk',
    'Pacific/Pohnpei',
    'Pacific/Kosrae',
    'Atlantic/Faroe',
    'Europe/Paris',
    'Europe/London',
    'Asia/Tbilisi',
    'America/Cayenne',
    'Africa/Accra',
    'Europe/Gibraltar',
    'America/Godthab',
    'America/Danmarkshavn',
    'America/Scoresbysund',
    'America/Thule',
    'Europe/Athens',
    'Atlantic/South_Georgia',
    'America/Guatemala',
    'Pacific/Guam',
    'Africa/Bissau',
    'America/Guyana',
    'Asia/Hong_Kong',
    'America/Tegucigalpa',
    'America/Port-au-Prince',
    'Europe/Budapest',
    'Asia/Jakarta',
    'Asia/Pontianak',
    'Asia/Makassar',
    'Asia/Jayapura',
    'Europe/Dublin',
    'Asia/Jerusalem',
    'Asia/Kolkata',
    'Indian/Chagos',
    'Asia/Baghdad',
    'Asia/Tehran',
    'Atlantic/Reykjavik',
    'Europe/Rome',
    'America/Jamaica',
    'Asia/Amman',
    'Asia/Tokyo',
    'Africa/Nairobi',
    'Asia/Bishkek',
    'Pacific/Tarawa',
    'Pacific/Enderbury',
    'Pacific/Kiritimati',
    'Asia/Pyongyang',
    'Asia/Seoul',
    'Asia/Almaty',
    'Asia/Qyzylorda',
    'Asia/Qostanay', 
    'Asia/Aqtobe',
    'Asia/Aqtau',
    'Asia/Atyrau',
    'Asia/Oral',
    'Asia/Beirut',
    'Asia/Colombo',
    'Africa/Monrovia',
    'Europe/Vilnius',
    'Europe/Luxembourg',
    'Europe/Riga',
    'Africa/Tripoli',
    'Africa/Casablanca',
    'Europe/Monaco',
    'Europe/Chisinau',
    'Pacific/Majuro',
    'Pacific/Kwajalein',
    'Asia/Yangon',
    'Asia/Ulaanbaatar',
    'Asia/Hovd',
    'Asia/Choibalsan',
    'Asia/Macau',
    'America/Martinique',
    'Europe/Malta',
    'Indian/Mauritius',
    'Indian/Maldives',
    'America/Mexico_City',
    'America/Cancun',
    'America/Merida',
    'America/Monterrey',
    'America/Matamoros',
    'America/Mazatlan',
    'America/Chihuahua',
    'America/Ojinaga',
    'America/Hermosillo',
    'America/Tijuana',
    'America/Bahia_Banderas',
    'Asia/Kuala_Lumpur',
    'Asia/Kuching',
    'Africa/Maputo',
    'Africa/Windhoek',
    'Pacific/Noumea',
    'Pacific/Norfolk',
    'Africa/Lagos',
    'America/Managua',
    'Europe/Amsterdam',
    'Europe/Oslo',
    'Asia/Kathmandu',
    'Pacific/Nauru',
    'Pacific/Niue',
    'Pacific/Auckland',
    'Pacific/Chatham',
    'America/Panama',
    'America/Lima',
    'Pacific/Tahiti',
    'Pacific/Marquesas',
    'Pacific/Gambier',
    'Pacific/Port_Moresby',
    'Pacific/Bougainville',
    'Asia/Manila',
    'Asia/Karachi',
    'Europe/Warsaw',
    'America/Miquelon',
    'Pacific/Pitcairn',
    'America/Puerto_Rico',
    'Asia/Gaza',
    'Asia/Hebron',
    'Europe/Lisbon',
    'Atlantic/Madeira',
    'Atlantic/Azores',
    'Pacific/Palau',
    'America/Asuncion',
    'Asia/Qatar',
    'Indian/Reunion',
    'Europe/Bucharest',
    'Europe/Belgrade',
    'Europe/Kaliningrad',
    'Europe/Moscow',
    'Europe/Simferopol',
    'Europe/Kirov',
    'Europe/Astrakhan',
    'Europe/Volgograd',
    'Europe/Saratov',
    'Europe/Ulyanovsk',
    'Europe/Samara',
    'Asia/Yekaterinburg',
    'Asia/Omsk',
    'Asia/Novosibirsk',
    'Asia/Barnaul',
    'Asia/Tomsk',
    'Asia/Novokuznetsk',
    'Asia/Krasnoyarsk',
    'Asia/Irkutsk',
    'Asia/Chita',
    'Asia/Yakutsk',
    'Asia/Khandyga',
    'Asia/Vladivostok',
    'Asia/Ust-Nera',
    'Asia/Magadan',
    'Asia/Sakhalin',
    'Asia/Srednekolymsk',
    'Asia/Kamchatka',
    'Asia/Anadyr',
    'Asia/Riyadh',
    'Pacific/Guadalcanal',
    'Indian/Mahe',
    'Africa/Khartoum',
    'Europe/Stockholm',
    'Asia/Singapore',
    'America/Paramaribo',
    'Africa/Juba',
    'Africa/Sao_Tome',
    'America/El_Salvador',
    'Asia/Damascus',
    'America/Grand_Turk',
    'Africa/Ndjamena',
    'Indian/Kerguelen',
    'Asia/Bangkok',
    'Asia/Dushanbe',
    'Pacific/Fakaofo',
    'Asia/Dili',
    'Asia/Ashgabat',
    'Africa/Tunis',
    'Pacific/Tongatapu',
    'Europe/Istanbul',
    'America/Port_of_Spain',
    'Pacific/Funafuti',
    'Asia/Taipei',
    'Europe/Kiev',
    'Europe/Uzhgorod',
    'Europe/Zaporozhye',
    'Pacific/Wake',
    'America/New_York',
    'America/Detroit',
    'America/Kentucky/Louisville',
    'America/Kentucky/Monticello',
    'America/Indiana/Indianapolis',
    'America/Indiana/Vincennes',
    'America/Indiana/Winamac',
    'America/Indiana/Marengo',
    'America/Indiana/Petersburg',
    'America/Indiana/Vevay',
    'America/Chicago',
    'America/Indiana/Tell_City',
    'America/Indiana/Knox',
    'America/Menominee',
    'America/North_Dakota/Center',
    'America/North_Dakota/New_Salem',
    'America/North_Dakota/Beulah',
    'America/Denver',
    'America/Boise',
    'America/Phoenix',
    'America/Los_Angeles',
    'America/Anchorage',
    'America/Juneau',
    'America/Sitka',
    'America/Metlakatla',
    'America/Yakutat',
    'America/Nome',
    'America/Adak',
    'Pacific/Honolulu',
    'America/Montevideo',
    'Asia/Samarkand',
    'Asia/Tashkent',
    'America/Caracas',
    'Asia/Ho_Chi_Minh',
    'Pacific/Efate',
    'Pacific/Wallis',
    'Pacific/Apia',
    'Africa/Johannesburg'
];

How can I compile a Java program in Eclipse without running it?

You will need to go to Project->Clean...,then build your project. This will work, even when your source code does not contain any main method to run as an executable program. The .class files will appear in the bin folder of your project, in your workspace.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

With me, although I ran 'git clone ssh://[email protected]:7999/projName/projA.git' I was still being prompted for password for this new repo that I cloned, so by comparing its .git/config file to other repos that work, It turned out to be the url under the [remote "origin"] section, it was set to the ssh path above for the new repo, but was set to https:xxx for the working one.

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

PHP validation/regex for URL

    function validateURL($URL) {
      $pattern_1 = "/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
      $pattern_2 = "/^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";       
      if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){
        return true;
      } else{
        return false;
      }
    }

TextView bold via xml file?

Just you need to use 

//for bold
android:textStyle="bold"

//for italic
android:textStyle="italic"

//for normal
android:textStyle="normal"

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:text="@string/userName"
    android:layout_gravity="left"
    android:textSize="16sp"
/>

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Check The data you are writing to Server. May be data has delimiter which is not used.

like

045|2272575|0.000|0.000|2013-10-07
045|2272585|0.000|0.000;2013-10-07

your delimiter is '|' but data has a delimiter ';'. So for this you are getting the error.

What does 'x packages are looking for funding' mean when running `npm install`?

First of all, try to support open source developers when you can, they invest quite a lot of their (free) time into these packages. But if you want to get rid of funding messages, you can configure NPM to turn these off. The command to do this is:

npm config set fund false --global

... or if you just want to turn it off for a particular project, run this in the project directory:

npm config set fund false 

For details why this was implemented, see @Stokely's and @ArunPratap's answers.

Comment out HTML and PHP together

PHP parser will search your entire code for <?php (or <? if short_open_tag = On), so HTML comment tags have no effect on PHP parser behavior & if you don't want to parse your PHP code, you have to use PHP commenting directives(/* */ or //).

How to use Oracle's LISTAGG function with a unique filter?

below is undocumented and not recomended by oracle. and can not apply in function, show error

select wm_concat(distinct name) as names from demotable group by group_id

regards zia

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

How to generate a Dockerfile from an image?

Update Dec 2018 to BMW's answer

chenzj/dfimage - as described on hub.docker.com regenerates Dockerfile from other images. So you can use it as follows:

docker pull chenzj/dfimage
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
dfimage IMAGE_ID > Dockerfile

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

CURL and HTTPS, "Cannot resolve host"

I found that CURL can decide to use IPv6, in which case it tries to resolve but doesn't get an IPv6 answer (or something to that effect) and times out.

You can try the command line switch -4 to test this out.

In PHP, you can configure this line by setting this:

curl_setopt($_h, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

When does Git refresh the list of remote branches?

To update the local list of remote branches:

git remote update origin --prune

To show all local and remote branches that (local) Git knows about

git branch -a

JavaScript or jQuery browser back button click detector

Found this to work well cross browser and mobile back_button_override.js .

(Added a timer for safari 5.0)

// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () { 
    if (typeof history.pushState === "function") { 
        history.pushState("back", null, null);          
        window.onpopstate = function () { 
            history.pushState('back', null, null);              
            if(count == 1){window.location = 'your url';}
         }; 
     }
 }  
setTimeout(function(){count = 1;},200);

How can I disable a tab inside a TabControl?

Using events, and the properties of the tab control you can enable/disable what you want when you want. I used one bool that is available to all methods in the mdi child form class where the tabControl is being used.

Remember the selecting event fires every time any tab is clicked. For large numbers of tabs a "CASE" might be easier to use than a bunch of ifs.

public partial class Form2 : Form
    {
        bool formComplete = false;

        public Form2()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {


            formComplete = true;
            tabControl1.SelectTab(1);

        }

        private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (tabControl1.SelectedTab == tabControl1.TabPages[1])
            {

                tabControl1.Enabled = false;

                if (formComplete)
                {
                    MessageBox.Show("You will be taken to next tab");
                    tabControl1.SelectTab(1);

                }
                else
                {
                    MessageBox.Show("Try completing form first");
                    tabControl1.SelectTab(0);
                }
                tabControl1.Enabled = true;
            }
        }
    }

Reading *.wav files in Python

u can also use simple import wavio library u also need have some basic knowledge of the sound.

How to add a char/int to an char array in C?

Suggest replacing this:

char str[1024];
char tmp = '.';

strcat(str, tmp);

with this:

char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()

strcat(str, tmp); // 

Algorithm to calculate the number of divisors of a given number

Here is a function that I wrote. it's worst time complexity is O(sqrt(n)),best time on the other hand is O(log(n)). It gives you all the prime divisors along with the number of its occurence.

public static List<Integer> divisors(n) {   
    ArrayList<Integer> aList = new ArrayList();
    int top_count = (int) Math.round(Math.sqrt(n));
    int new_n = n;

    for (int i = 2; i <= top_count; i++) {
        if (new_n == (new_n / i) * i) {
            aList.add(i);
            new_n = new_n / i;
            top_count = (int) Math.round(Math.sqrt(new_n));
            i = 1;
        }
    }
    aList.add(new_n);
    return aList;
}

git commit error: pathspec 'commit' did not match any file(s) known to git

I would just like to add--

In windows the commit message should be in double quotes (git commit -m "initial commit" instead of git commit -m 'initial commit'), as I spent about an hour, just to figure out that single quote is not working in windows.

How to target the href to div

You can put all your #m1...#m9 divs into .target and display them based on fragment identifier (hash) using :target pseudo-class. It doesn't move the contents between divs, but I think the effect is close to what you wanted to achieve.

Fiddle

HTML

<div class="target">
    <div id="m1">
        dasdasdasd m1
    </div>
    <!-- etc... -->
    <div id="m9">
        dasdasdsgaswa m9
    </div>   
</div>

CSS

.target {
    width:50%;
    height:200px;
    border:solid black 1px; 
}
.target > div {
    display:none;
}

.target > div:target{
    display:block;
}

How to select label for="XYZ" in CSS?

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

Docker CE on RHEL - Requires: container-selinux >= 2.9

Error: Package: 2:container-selinux-2.74-1.el7.noarch (rhel-7-server-extras-rpms)

Requires: selinux-policy >= 3.13.1-216.el7

Installed: selinux-policy-3.13.1-192.el7_5.6.noarch (@rhel-7-server-rpms)

selinux-policy = 3.13.1-192.el7_5.6

there is dependency issue with the container-selinux version

to fix this error on rhel 7.x i have performed the below things

1) yum install http://vault.centos.org/centos/7.3.1611/extras/x86_64/Packages/container-selinux-2.9-4.el7.noarch.rpm

2) yum install -y yum-utils device-mapper-persistent-data lvm2

3) yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

4 ) yum install docker-ce

now start the docker service

Difference between "char" and "String" in Java

Char is a single alphabet where as String is a sequence of characters. Char is primitive datatype where as String is a class.

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

Viewing full version tree in git

There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":

[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"

Spring can you autowire inside an abstract class?

Normally, Spring should do the autowiring, as long as your abstract class is in the base-package provided for component scan.

See this and this for further reference.

@Service and @Component are both stereotypes that creates beans of the annotated type inside the Spring container. As Spring Docs state,

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

Installed Java 7 on Mac OS X but Terminal is still using version 6

You can execute following command in your terminal :

export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

And this replaces the java old with new one.

How to return an array from a function?

int* test();

but it would be "more C++" to use vectors:

std::vector< int > test();

EDIT
I'll clarify some point. Since you mentioned C++, I'll go with new[] and delete[] operators, but it's the same with malloc/free.

In the first case, you'll write something like:

int* test() {
    return new int[size_needed];
}

but it's not a nice idea because your function's client doesn't really know the size of the array you are returning, although the client can safely deallocate it with a call to delete[].

int* theArray = test();
for (size_t i; i < ???; ++i) { // I don't know what is the array size!
    // ...
}
delete[] theArray; // ok.

A better signature would be this one:

int* test(size_t& arraySize) {
    array_size = 10;
    return new int[array_size];
}

And your client code would now be:

size_t theSize = 0;
int* theArray = test(theSize);
for (size_t i; i < theSize; ++i) { // now I can safely iterate the array
    // ...
}
delete[] theArray; // still ok.

Since this is C++, std::vector<T> is a widely-used solution:

std::vector<int> test() {
    std::vector<int> vector(10);
    return vector;
}

Now you don't have to call delete[], since it will be handled by the object, and you can safely iterate it with:

std::vector<int> v = test();
std::vector<int>::iterator it = v.begin();
for (; it != v.end(); ++it) {
   // do your things
}

which is easier and safer.

on change event for file input element

For someone who want to use onchange event directly on file input, set onchange="somefunction(), example code from the link:

<html>
<body>
    <script language="JavaScript">
    function inform(){
        document.form1.msg.value = "Filename has been changed";
    }
    </script>
    <form name="form1">
    Please choose a file.
    <input type="file" name="uploadbox" size="35" onChange='inform()'>
    <br><br>
    Message:
    <input type="text" name="msg" size="40">
    </form>
</body>
</html>

n-grams in python, four, five, six grams?

People have already answered pretty nicely for the scenario where you need bigrams or trigrams but if you need everygram for the sentence in that case you can use nltk.util.everygrams

>>> from nltk.util import everygrams

>>> message = "who let the dogs out"

>>> msg_split = message.split()

>>> list(everygrams(msg_split))
[('who',), ('let',), ('the',), ('dogs',), ('out',), ('who', 'let'), ('let', 'the'), ('the', 'dogs'), ('dogs', 'out'), ('who', 'let', 'the'), ('let', 'the', 'dogs'), ('the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs'), ('let', 'the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs', 'out')]

Incase you have a limit like in case of trigrams where the max length should be 3 then you can use max_len param to specify it.

>>> list(everygrams(msg_split, max_len=2))
[('who',), ('let',), ('the',), ('dogs',), ('out',), ('who', 'let'), ('let', 'the'), ('the', 'dogs'), ('dogs', 'out')]

You can just modify the max_len param to achieve whatever gram i.e four gram, five gram, six or even hundred gram.

The previous mentioned solutions can be modified to implement the above mentioned solution but this solution is much straight forward than that.

For further reading click here

And when you just need a specific gram like bigram or trigram etc you can use the nltk.util.ngrams as mentioned in M.A.Hassan's answer.

Pandas Merge - How to avoid duplicating columns

This is a bit of going around the problem, but I have written a function that basically deals with the extra columns:

def merge_fix_cols(df_company,df_product,uniqueID):
    
    df_merged = pd.merge(df_company,
                         df_product,
                         how='left',left_on=uniqueID,right_on=uniqueID)    
    for col in df_merged:
        if col.endswith('_x'):
            df_merged.rename(columns = lambda col:col.rstrip('_x'),inplace=True)
        elif col.endswith('_y'):
            to_drop = [col for col in df_merged if col.endswith('_y')]
            df_merged.drop(to_drop,axis=1,inplace=True)
        else:
            pass
    return df_merged

Seems to work well with my merges!

Cannot install packages inside docker Ubuntu image

Add following command in Dockerfile:

RUN apt-get update

Batch file to perform start, run, %TEMP% and delete all

The following batch commands are used to delete all your temp, recent and prefetch files on your System.

Save the following code as "Clear.bat" on your local system

*********START CODE************

@ECHO OFF

del /s /f /q %userprofile%\Recent\*.*

del /s /f /q C:\Windows\Prefetch\*.*

del /s /f /q C:\Windows\Temp\*.*

del /s /f /q %USERPROFILE%\appdata\local\temp\*.*


/Below command to Show the folder after deleted files

Explorer %userprofile%\Recent

Explorer C:\Windows\Prefetch

Explorer C:\Windows\Temp

Explorer %USERPROFILE%\appdata\local\temp


*********END CODE************

Convert Json Array to normal Java list

Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

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

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();


                        adapter.notifyDataSetChanged();

...

How to get the cursor to change to the hand when hovering a <button> tag

All u need is just use one of the attribute of CSS , which is---->

cursor:pointer

just use this property in css , no matter its inline or internal or external

for example(for inline css)

<form>
<input type="submit" style= "cursor:pointer" value="Button" name="Button">
</form>

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

" app-release.apk" how to change this default generated apk name

Not renaming it, but perhaps generating the name correctly in the first place would help? Change apk name with Gradle

'list' object has no attribute 'shape'

If you have list, you can print its shape as if it is converted to array

import numpy as np
print(np.asarray(X).shape)

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

How to export table as CSV with headings on Postgresql?

For version 9.5 I use, it would be like this:

COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Is an empty href valid?

Try to do <a href="#" class="arrow"> instead. (Note the sharp # character).

What is the purpose of the var keyword and when should I use it (or omit it)?

I would say it's better to use var in most situations.

Local variables are always faster than the variables in global scope.

If you do not use var to declare a variable, the variable will be in global scope.

For more information, you can search "scope chain JavaScript" in Google.

MySQL error code: 1175 during UPDATE in MySQL Workbench

SET SQL_SAFE_UPDATES = 0;

# your code SQL here

SET SQL_SAFE_UPDATES = 1;

How to convert integer into date object python?

Here is what I believe answers the question (Python 3, with type hints):

from datetime import date


def int2date(argdate: int) -> date:
    """
    If you have date as an integer, use this method to obtain a datetime.date object.

    Parameters
    ----------
    argdate : int
      Date as a regular integer value (example: 20160618)

    Returns
    -------
    dateandtime.date
      A date object which corresponds to the given value `argdate`.
    """
    year = int(argdate / 10000)
    month = int((argdate % 10000) / 100)
    day = int(argdate % 100)

    return date(year, month, day)


print(int2date(20160618))

The code above produces the expected 2016-06-18.

Check if a row exists, otherwise insert

This is something I just recently had to do:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[cjso_UpdateCustomerLogin]
    (
      @CustomerID AS INT,
      @UserName AS VARCHAR(25),
      @Password AS BINARY(16)
    )
AS 
    BEGIN
        IF ISNULL((SELECT CustomerID FROM tblOnline_CustomerAccount WHERE CustomerID = @CustomerID), 0) = 0
        BEGIN
            INSERT INTO [tblOnline_CustomerAccount] (
                [CustomerID],
                [UserName],
                [Password],
                [LastLogin]
            ) VALUES ( 
                /* CustomerID - int */ @CustomerID,
                /* UserName - varchar(25) */ @UserName,
                /* Password - binary(16) */ @Password,
                /* LastLogin - datetime */ NULL ) 
        END
        ELSE
        BEGIN
            UPDATE  [tblOnline_CustomerAccount]
            SET     UserName = @UserName,
                    Password = @Password
            WHERE   CustomerID = @CustomerID    
        END

    END

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

I had the same issue - it turned out that i was using a deprecated angular-cli instead of @angular/cli. The latter was used by my dev team and it took me some time to notice that we were using a different versions of angular-cli.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Change to root build.gradle file

to

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Why is Git better than Subversion?

With Git, you can do practically anything offline, because everybody has their own repository.

Making branches and merging between branches is really easy.

Even if you don't have commit rights for a project, you can still have your own repository online, and publish "push requests" for your patches. Everybody who likes your patches can pull them into their project, including the official maintainers.

It's trivial to fork a project, modify it, and still keep merging in the bugfixes from the HEAD branch.

Git works for the Linux kernel developers. That means it is really fast (it has to be), and scales to thousands of contributors. Git also uses less space (up to 30 times less space for the Mozilla repository).

Git is very flexible, very TIMTOWTDI (There is more than one way to do it). You can use whatever workflow you want, and Git will support it.

Finally, there's GitHub, a great site for hosting your Git repositories.

Drawbacks of Git:

  • it's much harder to learn, because Git has more concepts and more commands.
  • revisions don't have version numbers like in subversion
  • many Git commands are cryptic, and error messages are very user-unfriendly
  • it lacks a good GUI (such as the great TortoiseSVN)

Display a tooltip over a button using Windows Forms

For default tooltip this can be used -

System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip(this.textBox1, "Hello world");

A customized tooltip can also be used in case if formatting is required for tooltip message. This can be created by custom formatting the form and use it as tooltip dialog on mouse hover event of the control. Please check following link for more details -

http://newapputil.blogspot.in/2015/08/create-custom-tooltip-dialog-from-form.html

How do I turn off the mysql password validation?

Uninstall:

mysql> uninstall plugin validate_password;

An uninstalled plugin is not displayed by show plugins;

Install:

mysql> install plugin validate_password SONAME 'validate_password.so';

Disabled by configuration:

[mysqld]
validate_password = OFF

A plugin can be disabled by configuration only if installed.

Batch not-equal (inequality) operator

NEQ is usually used for numbers and == is typically used for string comparison.

I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ). The solution using IF NOT == seems the most sound approach. I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.

I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?

Getting json body in aws Lambda via API gateway

I am using lambda with Zappa; I am sending data with POST in json format:

My code for basic_lambda_pure.py is:

import time
import requests
import json
def my_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:", context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    print("Time remaining (MS):", context.get_remaining_time_in_millis())

    if event["httpMethod"] == "GET":
        hub_mode = event["queryStringParameters"]["hub.mode"]
        hub_challenge = event["queryStringParameters"]["hub.challenge"]
        hub_verify_token = event["queryStringParameters"]["hub.verify_token"]
        return {'statusCode': '200', 'body': hub_challenge, 'headers': 'Content-Type': 'application/json'}}

    if event["httpMethod"] == "post":
        token = "xxxx"
    params = {
        "access_token": token
    }
    headers = {
        "Content-Type": "application/json"
    }
        _data = {"recipient": {"id": 1459299024159359}}
        _data.update({"message": {"text": "text"}})
        data = json.dumps(_data)
        r = requests.post("https://graph.facebook.com/v2.9/me/messages",params=params, headers=headers, data=data, timeout=2)
        return {'statusCode': '200', 'body': "ok", 'headers': {'Content-Type': 'application/json'}}

I got the next json response:

{
"resource": "/",
"path": "/",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"Host": "ox53v9d8ug.execute-api.us-east-1.amazonaws.com",
"Via": "1.1 f1836a6a7245cc3f6e190d259a0d9273.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "LVcBZU-YqklHty7Ii3NRFOqVXJJEr7xXQdxAtFP46tMewFpJsQlD2Q==",
"X-Amzn-Trace-Id": "Root=1-59ec25c6-1018575e4483a16666d6f5c5",
"X-Forwarded-For": "69.171.225.87, 52.46.17.84",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Hub-Signature": "sha1=10504e2878e56ea6776dfbeae807de263772e9f2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/dev",
"accountId": "001513791584",
"resourceId": "i6d2tyihx7",
"stage": "dev",
"requestId": "d58c5804-b6e5-11e7-8761-a9efcf8a8121",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": "",
"sourceIp": "69.171.225.87",
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": null,
"user": null
},
"resourcePath": "/",
"httpMethod": "POST",
"apiId": "ox53v9d8ug"
},
"body": "eyJvYmplY3QiOiJwYWdlIiwiZW50cnkiOlt7ImlkIjoiMTA3OTk2NDk2NTUxMDM1IiwidGltZSI6MTUwODY0ODM5MDE5NCwibWVzc2FnaW5nIjpbeyJzZW5kZXIiOnsiaWQiOiIxNDAzMDY4MDI5ODExODY1In0sInJlY2lwaWVudCI6eyJpZCI6IjEwNzk5NjQ5NjU1MTAzNSJ9LCJ0aW1lc3RhbXAiOjE1MDg2NDgzODk1NTUsIm1lc3NhZ2UiOnsibWlkIjoibWlkLiRjQUFBNHo5RmFDckJsYzdqVHMxZlFuT1daNXFaQyIsInNlcSI6MTY0MDAsInRleHQiOiJob2xhIn19XX1dfQ==",
"isBase64Encoded": true
}

my data was on body key, but is code64 encoded, How can I know this? I saw the key isBase64Encoded

I copy the value for body key and decode with This tool and "eureka", I get the values.

I hope this help you. :)

Getting Google+ profile picture url with user_id

trying to access the /s2/profile/photo url works for most users but not all.

The only full proof method is to use the Google+ API. You don't need user authentication to request public profile data so it's a rather simple method:

  1. Get a Google+ API key on https://cloud.google.com/console

  2. Make a simple GET request to: https://www.googleapis.com/plus/v1/people/+< username >?key=

Note the + before the username. If you use user ids instead (the long string of digits), you don't need the +

  1. you will get a very comprehensive JSON representation of the profile data which includes: "image":{"url": "https://lh4.googleusercontent.com/..... the rest of the picture url...."}

How to fix Terminal not loading ~/.bashrc on OS X Lion

I have the following in my ~/.bash_profile:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

If I had .bashrc instead of ~/.bashrc, I'd be seeing the same symptom you're seeing.