Programs & Examples On #Flex datagrid

Grid component, part of Adobe Flex framework.

Disable XML validation in Eclipse

Window > Preferences > Validation > uncheck XML Validator Manual and Build enter image description here and pass parameters by post method

Even though I am 3 years late, but to simplify Guffa's example, you don't even need to have the form on the page at all:

$('<form method="post" action="test.asp" target="TheWindow">
       <input type="hidden" name="something" value="something">


$('<form method="post" action="test.asp" target="TheWindow">
       <input type="hidden" name="something" value="something">

Maybe a helpful tip for someone :)

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

The TensorFlow package couldn't be found by the latest version of the "pip".
To be honest, I really don't know why this is...
but, the quick fix that worked out for me was:
[In case you are using a virtual environment]
downgrade the virtual environment to python-3.8.x and pip-20.2.x In case of anaconda, try:

conda install python=3.8

This should install the latest version of python-3.8 and pip-20.2.x for you.
And then, try

pip install tensorflow

Again, this worked fine for me, not sure if it'll work the same for you.

How to process a file in PowerShell line-by-line as a stream

If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:

# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }

# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }

# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }

UPDATE: If you are still not scared then try to use the .NET reader:

$reader = [System.IO.File]::OpenText("my.log")
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        # process the line
finally {


There are comments about possibly better / shorter code. There is nothing wrong with the original code with for and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {

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

Other answers here provide solutions for triggering change detection cycles that will update component's view (which is not same as full re-render).

Full re-render, which would destroy and reinitialize component (calling all lifecycle hooks and rebuilding view) can be done by using ng-template, ng-container and ViewContainerRef in following way:

  <ng-container #outlet >

<ng-template #content>

Then in component having reference to both #outlet and #content we can clear outlets' content and insert another instance of child component:

@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;

private rerender() {

Additionally initial content should be inserted on AfterContentInit hook:

ngAfterContentInit() {

Full working solution can be found here .

How to add a string to a string[] array? There's no .Add function

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)

Config Error: This configuration section cannot be used at this path

You need to unlock handlers. This can be done using following cmd command:

%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers

Maybe another info for people that are getting this error on IIS 8, in my case was on Microsoft Server 2012 platform. I had spend couple of hours battling with other errors that bubbled up after executing appcmd. In the end I was able to fix it by removing Web Server Role and installing it again.

How to create a delay in Swift? .background).async {
    print("Active after 4 sec, and doesn't block main")
        //do stuff in the main thread here

What is the meaning of "operator bool() const"

I'd like to give more codes to make it clear.

struct A
    operator bool() const { return true; }

struct B
    explicit operator bool() const { return true; }

int main()
    A a1;
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

    B b1;     
    if (b1) cout << "true" << endl; // OK: B::operator bool()
    // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization

Negate if condition in bash script

If you're feeling lazy, here's a terse method of handling conditions using || (or) and && (and) after the operation:

wget -q --tries=10 --timeout=20 --spider || \
{ echo "Sorry you are Offline" && exit 1; }

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site:

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

Spring Boot JPA - configuring auto reconnect

As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1. Here's what you would need for DB2 for example: spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1

Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none

Xcode 6 Bug: Unknown class in Interface Builder file

My solution was to remove @objc from Custom class definition.

Difference between null and empty ("") Java String

In Java a reference type assigned null has no value at all. A string assigned "" has a value: an empty string, which is to say a string with no characters in it. When a variable is assigned null it means there is no underlying object of any kind, string or otherwise.

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>

If diff is not performed then, you will get null.

Java: Sending Multiple Parameters to Method

Suppose you have void method that prints many objects;

public static void print( Object... values){
   for(Object c : values){

Above example I used vararge as an argument that accepts values from 0 to N.

From comments: What if 2 strings and 5 integers ??



ImportError in importing from sklearn: cannot import name check_build

If you use Anaconda 2.7 64 bit, try

conda upgrade scikit-learn

and restart the python shell, that works for me.

Second edit when I faced the same problem and solved it:

conda upgrade scikit-learn

also works for me

How to merge two PDF files into one in Java?

A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".

It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.

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

.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred

How to comment out particular lines in a shell script

Yes (although it's a nasty hack). You can use a heredoc thus:


# do valuable stuff here
touch /tmp/a

# now comment out all the stuff below up to the EOF
echo <<EOF

What's this doing ? A heredoc feeds all the following input up to the terminator (in this case, EOF) into the nominated command. So you can surround the code you wish to comment out with

echo <<EOF

and it'll take all the code contained between the two EOFs and feed them to echo (echo doesn't read from stdin so it all gets thrown away).

Note that with the above you can put anything in the heredoc. It doesn't have to be valid shell code (i.e. it doesn't have to parse properly).

This is very nasty, and I offer it only as a point of interest. You can't do the equivalent of C's /* ... */

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 

   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

Can't import Numpy in Python

Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.

Try find / -iname '*numpy*'

"query function not defined for Select2 undefined error"

I got the same error. I have been using select2-3.5.2

This was my code which had error


Below code fixed the issue.



In a POST method, you can put an array. However, in a PUT method, you should use http_build_query to build the params like this:

curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );

Visual Studio loading symbols

The only thing that worked for me was changing the code type.

In the Attach to Process window, I changed the Attach to: selection to Automatically determine the type of code to debug, then my breakpoints were hit.

I previously had only Native code selected.

Unresolved external symbol on static class members

In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]

Java: Get first item from a collection

Looks like that is the best way to do it:

String first = strs.iterator().next();

Great question... At first, it seems like an oversight for the Collection interface.

Note that "first" won't always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn't a get(item) call, since the order isn't necessarily preserved.

While it might seem a bit wasteful, it might not be as bad as you think. The Iterator really just contains indexing information into the collection, not a usually a copy of the entire collection. Invoking this method does instantiate the Iterator object, but that is really the only overhead (not like copying all the elements).

For example, looking at the type returned by the ArrayList<String>.iterator() method, we see that it is ArrayList::Itr. This is an internal class that just accesses the elements of the list directly, rather than copying them.

Just be sure you check the return of iterator() since it may be empty or null depending on the implementation.

Create table with jQuery - append

<table id="game_table" border="1">

and Jquery

var i;
for (i = 0; ii < 10; i++) 

        var tr = $("<tr></tr>")
        var ii;
        for (ii = 0; ii < 10; ii++) 


Recommended way of making React component/div draggable

I've updated solution to React 16 / ES6 with enhancements like touch handling and snapping to a grid which is what I need for a game. Snapping to a grid alleviates the performance issues.

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

class Draggable extends React.Component {
    constructor(props) {
        this.state = {
            relX: 0,
            relY: 0,
            x: props.x,
            y: props.y
        this.gridX = props.gridX || 1;
        this.gridY = props.gridY || 1;
        this.onMouseDown = this.onMouseDown.bind(this);
        this.onMouseMove = this.onMouseMove.bind(this);
        this.onMouseUp = this.onMouseUp.bind(this);
        this.onTouchStart = this.onTouchStart.bind(this);
        this.onTouchMove = this.onTouchMove.bind(this);
        this.onTouchEnd = this.onTouchEnd.bind(this);

    static propTypes = {
        onMove: PropTypes.func,
        onStop: PropTypes.func,
        x: PropTypes.number.isRequired,
        y: PropTypes.number.isRequired,
        gridX: PropTypes.number,
        gridY: PropTypes.number

    onStart(e) {
        const ref = ReactDOM.findDOMNode(this.handle);
        const body = document.body;
        const box = ref.getBoundingClientRect();
            relX: e.pageX - (box.left + body.scrollLeft - body.clientLeft),
            relY: e.pageY - ( + body.scrollTop - body.clientTop)

    onMove(e) {
        const x = Math.trunc((e.pageX - this.state.relX) / this.gridX) * this.gridX;
        const y = Math.trunc((e.pageY - this.state.relY) / this.gridY) * this.gridY;
        if (x !== this.state.x || y !== this.state.y) {
            this.props.onMove && this.props.onMove(this.state.x, this.state.y);

    onMouseDown(e) {
        if (e.button !== 0) return;
        document.addEventListener('mousemove', this.onMouseMove);
        document.addEventListener('mouseup', this.onMouseUp);

    onMouseUp(e) {
        document.removeEventListener('mousemove', this.onMouseMove);
        document.removeEventListener('mouseup', this.onMouseUp);
        this.props.onStop && this.props.onStop(this.state.x, this.state.y);

    onMouseMove(e) {

    onTouchStart(e) {
        document.addEventListener('touchmove', this.onTouchMove, {passive: false});
        document.addEventListener('touchend', this.onTouchEnd, {passive: false});

    onTouchMove(e) {

    onTouchEnd(e) {
        document.removeEventListener('touchmove', this.onTouchMove);
        document.removeEventListener('touchend', this.onTouchEnd);
        this.props.onStop && this.props.onStop(this.state.x, this.state.y);

    render() {
        return <div
                position: 'absolute',
                left: this.state.x,
                top: this.state.y,
                touchAction: 'none'
            ref={(div) => { this.handle = div; }}

export default Draggable;

PHP, MySQL error: Column count doesn't match value count at row 1

Your query has 8 or possibly even 9 variables, ie. Name, Description etc. But the values, these things ---> '', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", only total 7, the number of variables have to be the same as the values.

I had the same problem but I figured it out. Hopefully it will also work for you.

How to execute Python code from within Visual Studio Code

So there are four ways to run Python in Visual Studio Code so far:

  1. Via an integrated terminal (come on, it's integrated! So technically you run it from within Visual Studio Code ;)
  • No need to install any extension.
  • No need to create and configure anything (assuming that you already have python in your $PATH).
  • ^Space (open terminal) and python (run file).
  1. Via custom Task (accepted Fenton's answer):
  • No need to install any extension.
  • Default Visual Studio Code's way of doing things.
  • Beware not to copy-paste the answer because its problemMatcher.pattern.regexp is broken and it hangs the editor. It's better to either delete problemMatcher or change the regexp to at least ^\\s+(.*)$.
  1. Via Code Runner extension (@JanHan's answer):
  • Need to configure code-runner.executorMap in User Settings (add path to your python).
  • Very helpful extension especially if you run not only Python in Visual Studio Code.
  1. Via Microsoft's official Python extension (vlad2135's answer):
  • Need to create launch.js (a couple of clicks in Visual Studio Code's Debug tab).
  • The extension is a must-have for those who wants to use Visual Studio Code as a primary IDE for Python.

Add comma to numbers every three digits

Use function Number();

$(function() {_x000D_
  var price1 = 1000;_x000D_
  var price2 = 500000;_x000D_
  var price3 = 15245000;_x000D_
<script src=""></script>_x000D_
<span id="s1"></span><br />_x000D_
<span id="s2"></span><br />_x000D_
<span id="s3"></span><br />

How to maintain aspect ratio using HTML IMG tag

Set width and height of the images to auto, but limit both max-width and max-height:

img {


If you want to display images of arbitrary size in the 64x64px "frames", you can use inline-block wrappers and positioning for them, like in this fiddle.

Android; Check if file exists without creating a new one

When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.

File file = new File(filePath);
    //do something

Microsoft Excel ActiveX Controls Disabled?

I know many answers have already been posted for this, but neither one answer independently worked for my site. So here is what worked for me:

Step 1: Uninstall the following updates - KB2920789, KB2920790, KB2920792, KB2920793, KB2984942, KB2596927

Step 2: Hide these updates so they do not get installed on subsequent reboots

Step 3: Delete folder Excel8.0 from C:\Users\<>\AppData\Local\Temp

Step 4: Restart workstatiion (I would also make sure the above mentioned KBs did not inadvertently get applied)

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

Converting a list to a set changes element order

In mathematics, there are sets and ordered sets (osets).

  • set: an unordered container of unique elements (Implemented)
  • oset: an ordered container of unique elements (NotImplemented)

In Python, only sets are directly implemented. We can emulate osets with regular dict keys (3.7+).


a = [1, 2, 20, 6, 210, 2, 1]
b = {2, 6}


oset = dict.fromkeys(a).keys()
# dict_keys([1, 2, 20, 6, 210])


Replicates are removed, insertion-order is preserved.

# [1, 2, 20, 6, 210]

Set-like operations on dict keys.

oset - b
# {1, 20, 210}

oset | b
# {1, 2, 5, 6, 20, 210}

oset & b
# {2, 6}

oset ^ b
# {1, 5, 20, 210}


Note: an unordered structure does not preclude ordered elements. Rather, maintained order is not guaranteed. Example:

assert {1, 2, 3} == {2, 3, 1}                    # sets (order is ignored)

assert [1, 2, 3] != [2, 3, 1]                    # lists (order is guaranteed)

One may be pleased to discover that a list and multiset (mset) are two more fascinating, mathematical data structures:

  • list: an ordered container of elements that permits replicates (Implemented)
  • mset: an unordered container of elements that permits replicates (NotImplemented)*


Container | Ordered | Unique | Implemented
set       |    n    |    y   |     y
oset      |    y    |    y   |     n
list      |    y    |    n   |     y
mset      |    n    |    n   |     n*  

*A multiset can be indirectly emulated with collections.Counter(), a dict-like mapping of multiplicities (counts).

assign function return value to some variable using javascript

The only way to retrieve the correct value in your context is to run $.ajax() function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async you should set to false. In that case the main scope which actually contains $.ajax() function call is paused until the synchronous function is done, so, the return is called only after $.ajax().

function doSomething() {
    var status = 0;
        url: 'action.php',
        type: 'POST',
        data: dataString,
        async: false,
        success: function (txtBack) {
            if (txtBack == 1)
                status = 1;

    return status;

var response = doSomething();

jQuery Set Select Index

select 3rd option

$('#selectBox').val($('#selectBox option').eq(2).val());

Example on jsfiddle

Converting newline formatting from Mac to Windows

The following is a complete script based on the above answers along with sanity checking and works on Mac OS X and should work on other Linux / Unix systems as well (although this has not been tested).



# =============================================================================
# =
# =
# =
# = MODE is one of unix2dos, dos2unix, tounix, todos, tomac
# = FILENAME is modified in-place
# = If SCRIPT is one of the modes (with or without .sh extension), then MODE
# =   can be omitted - it is inferred from the script name.
# = The script does use the file command to test if it is a text file or not,
# =   but this is not a guarantee.
# =
# =============================================================================

modes="unix2dos dos2unix todos tounix tomac"

usage() {
    echo "USAGE:  $script [ mode ] filename"
    echo "MODE is one of:"
    echo $modes
    echo "NOTE:  The tomac mode is intended for old Mac OS versions and should not be"
    echo "used without good reason."
    echo "The file is modified in-place so there is no output filename."
    echo "USE AT YOUR OWN RISK."
    echo "The script does try to check if it's a binary or text file for sanity, but"
    echo "this is not guaranteed."
    echo "Symbolic links to this script may use the above names and be recognized as"
    echo "mode operators."
    echo "Press RETURN to exit."
    read answer

# -- Look for the mode as the scriptname
mode="`basename "$0" .sh`"

# -- If 2 arguments use as mode and filename
if [ ! -z "$2" ] ; then mode="$1"; fname="$2"; fi

# -- Check there are 1 or 2 arguments or print usage.
if [ ! -z "$3" -o -z "$1" ] ; then usage; fi

# -- Check if the mode found is valid.
for checkmode in $modes; do if [ $mode = $checkmode ] ; then validmode=yes; fi; done
# -- If not a valid mode, abort.
if [ $validmode = no ] ; then echo Invalid mode $mode...aborting.; echo; usage; fi

# -- If the file doesn't exist, abort.
if [ ! -e "$fname" ] ; then echo Input file $fname does not exist...aborting.; echo; usage; fi

# -- If the OS thinks it's a binary file, abort, displaying file information.
if [ -z "`file "$fname" | grep text`" ] ; then echo Input file $fname may be a binary file...aborting.; echo; file "$fname"; echo; usage; fi

# -- Do the in-place conversion.
case "$mode" in
#   unix2dos ) # sed does not behave on Mac - replace w/ "todos" and "tounix"
#       # Plus, these variants are more universal and assume less.
#       sed -e 's/$/\r/' -i '' "$fname"             # UNIX to DOS  (adding CRs)
#       ;;
#   dos2unix )
#       sed -e 's/\r$//' -i '' "$fname"             # DOS  to UNIX (removing CRs)
#           ;;
    "unix2dos" | "todos" )
        perl -pi -e 's/\r\n|\n|\r/\r\n/g' "$fname"  # Convert to DOS
    "dos2unix" | "tounix" )
        perl -pi -e 's/\r\n|\n|\r/\n/g'   "$fname"  # Convert to UNIX
    "tomac" )
        perl -pi -e 's/\r\n|\n|\r/\r/g'   "$fname"  # Convert to old Mac
    * ) # -- Not strictly needed since mode is checked first.
        echo Invalid mode $mode...aborting.; echo; usage

# -- Display result.
if [ "$?" = "0" ] ; then echo "File $fname updated with mode $mode."; else echo "Conversion failed return code $?."; echo; usage; fi

How to add a classname/id to React-Bootstrap Component?

1st way is to use props

<Row id = "someRandomID">

Wherein, in the Definition, you may just go

const Row = props  => {
 div id = {}

The same could be done with class, replacing id with className in the above example.

You might as well use react-html-id, that is an npm package. This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.

Ref: react-html-id


Adding a new value to an existing ENUM Type

NOTE if you're using PostgreSQL 9.1 or later, and you are ok with making changes outside of a transaction, see this answer for a simpler approach.

I had the same problem few days ago and found this post. So my answer can be helpful for someone who is looking for solution :)

If you have only one or two columns which use the enum type you want to change, you can try this. Also you can change the order of values in the new type.

-- 1. rename the enum type you want to change
alter type some_enum_type rename to _some_enum_type;
-- 2. create new type
create type some_enum_type as enum ('old', 'values', 'and', 'new', 'ones');
-- 3. rename column(s) which uses our enum type
alter table some_table rename column some_column to _some_column;
-- 4. add new column of new type
alter table some_table add some_column some_enum_type not null default 'new';
-- 5. copy values to the new column
update some_table set some_column = _some_column::text::some_enum_type;
-- 6. remove old column and type
alter table some_table drop column _some_column;
drop type _some_enum_type;

3-6 should be repeated if there is more than 1 column.

React Native Responsive Font Size

We can use flex layout and use adjustsFontSizeToFit={true} for responsive font sizes.And the text would adjust according to the size of the container.


But in styles you need to put a fontsize as well only then will adjustsFontSizeToFit work.

    valueField: {
    flex: 3,
    fontSize: 48,
    marginBottom: 5,
    color: '#00A398',

Fatal error: Namespace declaration statement has to be the very first statement in the script in

Sometimes this issue come because of space in PHP start tag of controller facing same issue just removed whitespace in:

namespace App\Http\Controllers\Auth;

removing the space resolved my error

`getchar()` gives the same output as the input string

In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

How to convert a timezone aware string to datetime in Python without dateutil?

You can convert like this.

date = datetime.datetime.strptime('2019-3-16T5-49-52-595Z','%Y-%m-%dT%H-%M-%S-%f%z')
date_time = date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')

What causing this "Invalid length for a Base-64 char array"

As others have mentioned this can be caused when some firewalls and proxies prevent access to pages containing a large amount of ViewState data.

ASP.NET 2.0 introduced the ViewState Chunking mechanism which breaks the ViewState up into manageable chunks, allowing the ViewState to pass through the proxy / firewall without issue.

To enable this feature simply add the following line to your web.config file.

<pages maxPageStateFieldLength="4000">

This should not be used as an alternative to reducing your ViewState size but it can be an effective backstop against the "Invalid length for a Base-64 char array" error resulting from aggressive proxies and the like.

How can I disable a button on a jQuery UI dialog?

This worked for me --

$("#dialog-confirm").html('Do you want to permanently delete this?');
$( "#dialog-confirm" ).dialog({
    resizable: false,
    modal: true,
    buttons: {
        Cancel: function() {
            $( this ).dialog( "close" );
                        var resp = JSON.parse(data);
                        $( "#dialog-confirm" ).dialog({
                                resizable: false,
                                modal: true,
                                buttons: {
                                    Close: function() {
                                        $( this ).dialog( "close" );

How do I convert an Array to a List<object> in C#?

The List<> constructor can accept anything which implements IEnumerable, therefore...

        object[] testArray = new object[] { "blah", "blah2" };
        List<object> testList = new List<object>(testArray);

display: flex not working on Internet Explorer

Am afraid this question has been answered a few times, Pls take a look at the following if it's related

It is more efficient to use if-return-return or if-else-return?

With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.

SQL Server - after insert trigger - update another column in the same table

Yea...having an additional step to update a table in which you can set the value in the inital insert is probably an extra, avoidable process. Do you have access to the original insert statement where you can actually just insert the part_description into the part_description_upper column using UPPER(part_description) value?

After thinking, you probably don't have access as you would have probably done that so should also give some options as well...

1) Depends on the need for this part_description_upper column, if just for "viewing" then can just use the returned part_description value and "ToUpper()" it (depending on programming language).

2) If want to avoid "realtime" processing, can just create a sql job to go through your values once a day during low traffic periods and update that column to the UPPER part_description value for any that are currently not set.

3) go with your trigger (and watch for recursion as others have mentioned)...



The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

Ensure you set SmtpClient.Credentials after calling SmtpClient.UseDefaultCredentials = false.

The order is important as setting SmtpClient.UseDefaultCredentials = false will reset SmtpClient.Credentials to null.

how to reference a YAML "setting" from elsewhere in the same YAML file?

I have wrote my own library on Python to expand variables being loaded from directories with a hierarchy like:

 +- /proj1
     +- config.yaml
     +- /proj2
         +- config.yaml
         ... and so on ...

The key difference here is that the expansion must be applied only after all the config.yaml files is loaded, where the variables from the next file can override the variables from the previous, so the pseudocode should look like this:

env = YamlEnv()

As an additional option the xonsh script can export the resulting variables into environment variables (see the yaml_update_global_vars function).

The scripts:


  • simple, does not support recursion and nested variables
  • can replace an undefined variable to a placeholder (${MYUNDEFINEDVAR} -> *$/{MYUNDEFINEDVAR})
  • can expand a reference from environment variable (${env:MYVAR})
  • can replace all \\ to / in a path variable (${env:MYVAR:path})


  • does not support nested variables, so can not expand values in nested dictionaries (something like ${MYSCOPE.MYVAR} is not implemented)
  • does not detect expansion recursion, including recursion after a placeholder put

How to resize Twitter Bootstrap modal dynamically based on the content

As of Bootstrap 4 - it has a style of:

@media (min-width: 576px)
.modal-dialog {
    max-width: 500px;

so if you are looking to resize the modal width to some-width larger, I would suggest using this in your css for example:

.modal-dialog { max-width: 87vw; }

Note that setting width: 87vw; will not override bootstrap's max-width: 500px;.

Deleting an element from an array in PHP

$key = array_search($needle, $array);
if ($key !== false) {

Display an array in a readable/hierarchical format

I assume one uses print_r for debugging. I would then suggest using libraries like Kint. This allows displaying big arrays in a readable format:

$data = [['Natural Child 1', 'Natural Child 2', 'Natural Child 3']];
Kint::dump($data, $_SERVER);

enter image description here

How to declare a inline object with inline variables without a parent class

You can also do this:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }

And if they are the same anonymous type (firstName and lastName), you won't need to cast as object.

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }

How to avoid 'cannot read property of undefined' errors?

If you are using lodash, you could use their "has" function. It is similar to the native "in", but allows paths.

var testObject = {a: {b: {c: 'walrus'}}};
if(_.has(testObject, 'a.b.c')) {
  //Safely access your walrus here

How to read text files with ANSI encoding and non-English letters?

You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.

You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:

String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />");  // change linebreaks to HTML

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

How to Clear Console in Java?


You need to replace "PlatformDependentCode" with your platform's clear console command.

The exec() method executes the command you entered as the argument, just as if it is entered in the console.

In Windows you would write it as Runtime.getRuntime().exec("cls");.

jquery get all form elements: input, textarea & select

all inputs:

var inputs = $("#formId :input");

all buttons

var button = $("#formId :button")

How to reload a page using Angularjs?

$scope.rtGo = function(){

How can I remove punctuation from input text in Java?

This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:

String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");

Spaces are initially left in the input so the split will still work.

By removing the rubbish characters before splitting, you avoid having to loop through the elements.

How do I put a clear button inside my HTML text input box like the iPhone does?

You can't actually put it inside the text box unfortunately, only make it look like its inside it, which unfortunately means some css is needed :P

Theory is wrap the input in a div, take all the borders and backgrounds off the input, then style the div up to look like the box. Then, drop in your button after the input box in the code and the jobs a good'un.

Once you've got it to work anyway ;)

Why does the order in which libraries are linked sometimes cause errors in GCC?

I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs.

Depending on different linkers HP/Intel/GCC/SUN/SGI/IBM/etc you can get unresolved functions/variables etc, on some platforms you have to list libraries twice.

For the most part we use structured hierarchy of libraries, core, platform, different layers of abstraction, but for some systems you still have to play with the order in the link command.

Once you hit upon a solution document it so the next developer does not have to work it out again.

My old lecturer used to say, "high cohesion & low coupling", it’s still true today.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I encountered the same problem with Android devices but not iOS devices. Managed to resolve by specifying position:relative in the outer div of the absolutely positioned elements (with overflow:hidden for outer div)

Copying data from one SQLite database to another

Objective-C code for copy Table from a Database to another Database

-(void) createCopyDatabase{

          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
          NSString *documentsDir = [paths objectAtIndex:0];

          NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;

          NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
          NSFileManager *fileManager = [NSFileManager defaultManager];
          char *error;

         if ([fileManager fileExistsAtPath:newdbPath]) {
             [fileManager removeItemAtPath:newdbPath error:nil];
         sqlite3 *database;
         //open database
        if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
            NSLog(@"Error to open database");

        NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];

       sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
       if (error) {
           NSLog(@"Error to Attach = %s",error);

       //Query for copy Table
       NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
       sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);

        //Query for copy Table with Where Clause

        sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
        sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);

git - remote add origin vs remote set-url origin

  • When you run git remote add origin [email protected]:User/UserRepo.git, then a new remote created named origin.
  • When you run git remote set-url origin [email protected]:User/UserRepo.git,git searches for existing remote having name origin and change it's remote repository url. If git unable to find any remote having name origin, It raise an error fatal: No such remote 'origin'.

If you are going to create a new repository then use git remote add origin [email protected]:User/UserRepo.git to add remote.

Function to calculate distance between two coordinates

I implemeneted this algorithm in typescript and ES6

export type Coordinate = {
  lat: number;
  lon: number;

get the distance between two points:

function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
  if ( == && cord1.lon == cord2.lon) {
    return 0;

  const radlat1 = (Math.PI * / 180;
  const radlat2 = (Math.PI * / 180;

  const theta = cord1.lon - cord2.lon;
  const radtheta = (Math.PI * theta) / 180;

  let dist =
    Math.sin(radlat1) * Math.sin(radlat2) +
    Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);

  if (dist > 1) {
    dist = 1;

  dist = Math.acos(dist);
  dist = (dist * 180) / Math.PI;
  dist = dist * 60 * 1.1515;
  dist = dist * 1.609344; //convert miles to km
  return dist;

get the distance between an array of coordinates

export function getTotalDistance(coordinates: Coordinate[]) {
  coordinates = coordinates.filter((cord) => {
    if ( && cord.lon) {
      return true;
  let totalDistance = 0;

  if (!coordinates) {
    return 0;

  if (coordinates.length < 2) {
    return 0;

  for (let i = 0; i < coordinates.length - 2; i++) {
    if (
      !coordinates[i].lon ||
      !coordinates[i].lat ||
      !coordinates[i + 1].lon ||
      !coordinates[i + 1].lat
    ) {
      totalDistance = totalDistance;
    totalDistance =
      totalDistance +
      getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);

  return totalDistance.toFixed(2);

How to echo in PHP, HTML tags

Try the heredoc-based solution:

echo <<<HTML
    <h3><a href="#">First</a></h3>
    <div>Lorem ipsum dolor sit amet.</div>

Online PHP syntax checker / validator performs syntax check and a custom check for common errors.

I'm a novice, but it helped me.

Delete specific line from a text file?

The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.

There is no generic delete-a-line-from-file function, as far as I know.

How should I tackle --secure-file-priv in MySQL?

Without changing any of the configuration files..

  1. look for the value of secure_file_priv using the command posted by @vhu: SHOW VARIABLES LIKE "secure_file_priv".
  2. define the full path for your query such as: select * from table into outfile 'secure_file_priv_PATH/OUTPUT-FILE' ... rest of your query

this worked for my in mysql-shell on ubuntu 18.04 LTS mysql 5.7.29

Insert using LEFT JOIN and INNER JOIN

INSERT INTO Test([col1],[col2]) (
        a.Name AS [col1],
        b.sub AS [col2] 
    FROM IdTable b 
    INNER JOIN Nametable a ON =

Is there a difference between "==" and "is"?

is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
>>> b == a

# Make a new copy of list `a` via the slice operator, 
# and assign it to variable `b`
>>> b = a[:] 
>>> b is a
>>> b == a

In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:

>>> 1000 is 10**3
>>> 1000 == 10**3

The same holds true for string literals:

>>> "a" is "a"
>>> "aa" is "a" * 2
>>> x = "a"
>>> "aa" is x * 2
>>> "aa" is intern(x*2)

Please see this question as well.

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Passing arguments to C# generic new() of templated type

I found that I was getting an error "cannot provide arguments when creating an instance of type parameter T" so I needed to do this:

var x = Activator.CreateInstance(typeof(T), args) as T;

Subtracting 2 lists in Python

Try this:


Effective way to find any file's Encoding

The StreamReader.CurrentEncoding property rarely returns the correct text file encoding for me. I've had greater success determining a file's endianness, by analyzing its byte order mark (BOM). If the file does not have a BOM, this cannot determine the file's encoding.

*UPDATED 4/08/2020 to include UTF-32LE detection and return correct encoding for UTF-32BE

/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
public static Encoding GetEncoding(string filename)
    // Read the BOM
    var bom = new byte[4];
    using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
        file.Read(bom, 0, 4);

    // Analyze the BOM
    if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
    if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
    if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) return Encoding.UTF32; //UTF-32LE
    if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
    if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
    if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return new UTF32Encoding(true, true);  //UTF-32BE

    // We actually have no idea what the encoding is if we reach this point, so
    // you may wish to return null instead of defaulting to ASCII
    return Encoding.ASCII;

How do you install an APK file in the Android emulator?

go to ADT/Android-sdk/tools directory in command prompt 1. adb install fileName.apk (Windows)

  1. ./adb install fileName.apk (Ubuntu/Linux or Mac)

How to change lowercase chars to uppercase using the 'keyup' event?

I work with telerik radcontrols that's why I Find a control, but you can find control directly like: $('#IdExample').css({

this code works for me, I hope help you and sorry my english.

Code Javascript:

<script type="javascript"> 
function changeToUpperCase(event, obj) {
var txtDescripcion = $("#%=RadPanelBar1.Items(0).Items(0).FindControl("txtDescripcion").ClientID%>");
                 "text-transform": "uppercase"
} </script>


<asp:TextBox ID="txtDescripcion" runat="server" MaxLength="80" Width="500px"                                                             onkeypress="return changeToUpperCase(event,this)"></asp:TextBox>

VBA setting the formula for a cell

If you want to make address directly, the worksheet must exist.

Turning off automatic recalculation want help you :)

But... you can get value indirectly...

.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"

At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.

But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.

Hide strange unwanted Xcode logs

This solution has been working for me:

  1. Run the app in the simulator
  2. Open the system log (? + /)

This will dump out all of the debug data and also your NSLogs.

To filter just your NSLog statements:

  1. Prefix each with a symbol, for example: NSLog(@"^ Test Log")
  2. Filter the results using the search box on the top right, "^" in the case above

This is what you should get:

Screenshot of console

Remove all spaces from a string in SQL Server

This does the trick of removing the spaces on the strings:

    columnname = replace(columnname, ' ', '');

Operator overloading in Java

One can try Java Operator Overloading. It has its own limitations, but it worth trying if you really want to use operator overloading.

Command / failed with exit code 1

In my case it was a duplicate Swift Flag entry inside my Target's Build Settings > Other Swift Flags. I had two -Xfrontend entries in it.

Remove Trailing Spaces and Update in Columns in SQL Server

Well here is a nice script to TRIM all varchar columns on a table dynamically:

--Just change table name
declare @MyTable varchar(100)
set @MyTable = 'MyTable'

--temp table to get column names and a row id
select column_name, ROW_NUMBER() OVER(ORDER BY column_name) as id into #tempcols from INFORMATION_SCHEMA.COLUMNS 
WHERE   DATA_TYPE IN ('varchar', 'nvarchar') and TABLE_NAME = @MyTable

declare @tri int
select @tri = count(*) from #tempcols
declare @i int
select @i = 0
declare @trimmer nvarchar(max)
declare @comma varchar(1)
set @comma = ', '

--Build Update query
select @trimmer = 'UPDATE [dbo].[' + @MyTable + '] SET '

WHILE @i <= @tri 

    IF (@i = @tri)
        set @comma = ''
    SELECT  @trimmer = @trimmer + CHAR(10)+ '[' + COLUMN_NAME + '] = LTRIM(RTRIM([' + COLUMN_NAME + ']))'+@comma
    FROM    #tempcols
    where id = @i

    select @i = @i+1

--execute the entire query
EXEC sp_executesql @trimmer

drop table #tempcols

Border color on default input style

If it is an Angular application you can simply do this
    border: 1px solid red !important; 

JQuery - $ is not defined

That error can only be caused by one of three things:

  1. Your JavaScript file is not being properly loaded into your page
  2. You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
  3. You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.

First of all, ensure, what script is call properly, it should looks like

<script src="" type="text/javascript"></script>

and shouldn't have attributes async or defer.

Then you should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.

Make sure all jQuery javascript code is being run inside a code block such as:

$(document).ready(function () {
  //your code here

This will ensure that your code is being loaded after jQuery has been initialized.

One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.

Note: If you're loading code which does not require jQuery to run it does not need to be placed inside the jQuery ready handler. That code may be separated using document.readyState.

XmlSerializer: remove unnecessary xsi and xsd namespaces

I'm using:

public class Person
    public string FirstName { get; set; }
    public string LastName { get; set; }

class Program
    static void Main(string[] args)
        const string DEFAULT_NAMESPACE = "";
        var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", DEFAULT_NAMESPACE);

        using (var stream = new MemoryStream())
            var someone = new Person
                FirstName = "Donald",
                LastName = "Duck"
            serializer.Serialize(stream, someone, namespaces);
            stream.Position = 0;
            using (var reader = new StreamReader(stream))

To get the following XML:

<?xml version="1.0"?>
<Person xmlns="">

If you don't want the namespace, just set DEFAULT_NAMESPACE to "".

How to change UIButton image in Swift

assume that this is your connected UIButton Name like

@IBOutlet var btn_refresh: UIButton!

your can directly place your image in three modes

 // for normal state
btn_refresh.setImage(UIImage(named: "xxx.png"), forState: UIControlState.Normal)
     // for Highlighted state
      btn_refresh.setImage(UIImage(named: "yyy.png"), forState: UIControlState.Highlighted)

        // for Selected state
         btn_refresh.setImage(UIImage(named: "zzzz.png"), forState: UIControlState.Selected)

on your button action

  //MARK: button_refresh action
@IBAction func button_refresh_touchup_inside(sender: UIButton)
    //if you set the image on same  UIButton
    sender.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)

    //if you set the image on another  UIButton
       youranotherbuttonName.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)

How to convert a data frame column to numeric type?

I would have added a comment (cant low rating)

Just to add on user276042 and pangratz

dat$x = as.numeric(as.character(dat$x))

This will override the values of existing column x

How to convert hex to rgb using Java?

Convert it to an integer, then divmod it twice by 16, 256, 4096, or 65536 depending on the length of the original hex string (3, 6, 9, or 12 respectively).

Convert Json string to Json object in Swift 4

I used below code and it's working fine for me. :

let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
     do {
            dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
            if let myDictionary = dictonary
                  print(" User name is: \(myDictionary["userName"]!)")
            } catch let error as NSError {

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

Get key and value of object in JavaScript?

$.each(top_brands, function() {
  var key = Object.keys(this)[0];
  var value = this[key];
  brand_options.append($("<option />").val(key).text(key + " "  + value));

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I had gotten a little too aggressive about removing some directories in my project area when I was running out of disk space, and deleted this directory. Eclipse can leave some huge core files if it crashes in your workspace directories, (I had 35 gig of them) so it's worth taking a look there in your workspaces occasionally.

Anyway, as per the problem I tried the 'create a directory' approach. And it worked.

I was also seeing this error when I closed Eclipse by the way, not only after the 'periodic save'. So the exit/restart was also part of this.

Note that the last item on the directory path specified in the error message is a file -- not a directory, so don't get confused here. Probably worth checking that the directory permissions are created correctly as well (as the other projects in the workspace I think).

Obviously this is a bug in the Eclipse code base, (creating the full directory path under the file that is being created), but had I not deleted it in the first place, I would not have caused it in the first place.

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1'); = btoa(;

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:


<div class="abc"></div>
<div class="abc"></div>


var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div'); = 'hello1';

var body = document.querySelector('body');


You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0]; = btoa({{str(produit["avt"]["fto"])}});

Your requirements still aren't 100% clear though.

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

Python code to remove HTML tags from a string

Using a regex

Using a regex, you can clean everything inside <> :

import re

def cleanhtml(raw_html):
  cleanr = re.compile('<.*?>')
  cleantext = re.sub(cleanr, '', raw_html)
  return cleantext

Some HTML texts can also contain entities that are not enclosed in brackets, such as '&nsbm'. If that is the case, then you might want to write the regex as

cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')

This link contains more details on this.

Using BeautifulSoup

You could also use BeautifulSoup additional package to find out all the raw text.

You will need to explicitly set a parser when calling BeautifulSoup I recommend "lxml" as mentioned in alternative answers (much more robust than the default one (html.parser) (i.e. available without additional install).

from bs4 import BeautifulSoup
cleantext = BeautifulSoup(raw_html, "lxml").text

But it doesn't prevent you from using external libraries, so I recommend the first solution.

EDIT: To use lxml you need to pip install lxml.

Convert True/False value read from file to boolean

Using dicts to convert "True" in True:

def str_to_bool(s: str):
    status = {"True": True,
                "False": False}
        return status[s]
    except KeyError as e:

Image comparison - fast algorithm

Below are three approaches to solving this problem (and there are many others).

  • The first is a standard approach in computer vision, keypoint matching. This may require some background knowledge to implement, and can be slow.

  • The second method uses only elementary image processing, and is potentially faster than the first approach, and is straightforward to implement. However, what it gains in understandability, it lacks in robustness -- matching fails on scaled, rotated, or discolored images.

  • The third method is both fast and robust, but is potentially the hardest to implement.

Keypoint Matching

Better than picking 100 random points is picking 100 important points. Certain parts of an image have more information than others (particularly at edges and corners), and these are the ones you'll want to use for smart image matching. Google "keypoint extraction" and "keypoint matching" and you'll find quite a few academic papers on the subject. These days, SIFT keypoints are arguably the most popular, since they can match images under different scales, rotations, and lighting. Some SIFT implementations can be found here.

One downside to keypoint matching is the running time of a naive implementation: O(n^2m), where n is the number of keypoints in each image, and m is the number of images in the database. Some clever algorithms might find the closest match faster, like quadtrees or binary space partitioning.

Alternative solution: Histogram method

Another less robust but potentially faster solution is to build feature histograms for each image, and choose the image with the histogram closest to the input image's histogram. I implemented this as an undergrad, and we used 3 color histograms (red, green, and blue), and two texture histograms, direction and scale. I'll give the details below, but I should note that this only worked well for matching images VERY similar to the database images. Re-scaled, rotated, or discolored images can fail with this method, but small changes like cropping won't break the algorithm

Computing the color histograms is straightforward -- just pick the range for your histogram buckets, and for each range, tally the number of pixels with a color in that range. For example, consider the "green" histogram, and suppose we choose 4 buckets for our histogram: 0-63, 64-127, 128-191, and 192-255. Then for each pixel, we look at the green value, and add a tally to the appropriate bucket. When we're done tallying, we divide each bucket total by the number of pixels in the entire image to get a normalized histogram for the green channel.

For the texture direction histogram, we started by performing edge detection on the image. Each edge point has a normal vector pointing in the direction perpendicular to the edge. We quantized the normal vector's angle into one of 6 buckets between 0 and PI (since edges have 180-degree symmetry, we converted angles between -PI and 0 to be between 0 and PI). After tallying up the number of edge points in each direction, we have an un-normalized histogram representing texture direction, which we normalized by dividing each bucket by the total number of edge points in the image.

To compute the texture scale histogram, for each edge point, we measured the distance to the next-closest edge point with the same direction. For example, if edge point A has a direction of 45 degrees, the algorithm walks in that direction until it finds another edge point with a direction of 45 degrees (or within a reasonable deviation). After computing this distance for each edge point, we dump those values into a histogram and normalize it by dividing by the total number of edge points.

Now you have 5 histograms for each image. To compare two images, you take the absolute value of the difference between each histogram bucket, and then sum these values. For example, to compare images A and B, we would compute

|A.green_histogram.bucket_1 - B.green_histogram.bucket_1| 

for each bucket in the green histogram, and repeat for the other histograms, and then sum up all the results. The smaller the result, the better the match. Repeat for all images in the database, and the match with the smallest result wins. You'd probably want to have a threshold, above which the algorithm concludes that no match was found.

Third Choice - Keypoints + Decision Trees

A third approach that is probably much faster than the other two is using semantic texton forests (PDF). This involves extracting simple keypoints and using a collection decision trees to classify the image. This is faster than simple SIFT keypoint matching, because it avoids the costly matching process, and keypoints are much simpler than SIFT, so keypoint extraction is much faster. However, it preserves the SIFT method's invariance to rotation, scale, and lighting, an important feature that the histogram method lacked.


My mistake -- the Semantic Texton Forests paper isn't specifically about image matching, but rather region labeling. The original paper that does matching is this one: Keypoint Recognition using Randomized Trees. Also, the papers below continue to develop the ideas and represent the state of the art (c. 2010):

getElementById returns null?

It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

Please, post your code.

How can I remove duplicate rows?

I thought I'd share my solution since it works under special circumstances. I my case the table with duplicate values did not have a foreign key (because the values were duplicated from another db).

begin transaction
-- create temp table with identical structure as source table
Select * Into #temp From tableName Where 1 = 2

-- insert distinct values into temp
insert into #temp 
select distinct * 
from  tableName

-- delete from source
delete from tableName 

-- insert into source from temp
insert into tableName 
select * 
from #temp

rollback transaction
-- if this works, change rollback to commit and execute again to keep you changes!!

PS: when working on things like this I always use a transaction, this not only ensures everything is executed as a whole, but also allows me to test without risking anything. But off course you should take a backup anyway just to be sure...

Filtering a spark dataframe based on date

I find the most readable way to express this is using a sql expression:

df.filter("my_date < date'2015-01-01'")

we can verify this works correctly by looking at the physical plan from .explain()

+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))

How do you specify a byte literal in Java?

You can use a byte literal in Java... sort of.

    byte f = 0;
    f = 0xa;

0xa (int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.

What you can't do is this:

void foo(byte a) {

 foo( 0xa ); // will not compile

You have to cast as follows:

 foo( (byte) 0xa ); 

But keep in mind that these will all compile, and they are using "byte literals":

void foo(byte a) {

    byte f = 0;

    foo( f = 0xa ); //compiles

    foo( f = 'a' ); //compiles

    foo( f = 1 );  //compiles

Of course this compiles too

    foo( (byte) 1 );  //compiles

Python using enumerate inside list comprehension

Or, if you don't insist on using a list comprehension:

>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

How to print an exception in Python 3?

I've use this :

except (socket.timeout, KeyboardInterrupt) as e:
    logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))

Let me know if it does not work for you !!

Use of True, False, and None as return values in Python functions

You can directly check that a variable contains a value or not, like if var or not var.

How to find reason of failed Build without any error or warning

On my side, i got this problem when i added a new project (Library)

How i solved it

Right click the new added Library go to Properties then Application, under Application change the Target Framework to the framework of all projects.

The problem is that you have project using different target frameworks.

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,


input file appears to be a text format dump. Please use psql

If you have a full DB dump:

PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql

If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers. You can then use this:

cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin

On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump is incompatible with pg_restore. With some additional keys, however, it is. WTF?

How to add 30 minutes to a JavaScript Date object?

The easiest way to solve is the to recognize that in javascript dates are just numbers. It starts 0 or 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST). Every 1 represents a millisecond. You can add or subtract milliseconds by getting the value and instantiating a new date using that value. You can manage it pretty easy with that mind.

const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));

console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)

Maven: Failed to retrieve plugin descriptor error

I was having exactly the same problem.I went to my IE setting->LAN Settings.Then copied the Address as host and port as the port and it worked. Following is the snapshot of the proxies tag in the Settings.xml that I changed.


How to force garbage collection in Java?

If you are running out of memory and getting an OutOfMemoryException you can try increasing the amount of heap space available to java by starting you program with java -Xms128m -Xmx512m instead of just java. This will give you an initial heap size of 128Mb and a maximum of 512Mb, which is far more than the standard 32Mb/128Mb.

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

This worked for me on Mac

sudo chown -R $(whoami) $(brew --prefix)/*

How to secure MongoDB with username and password

User creation with password for a specific database to secure database access :

use dbName

     user: "dbUser",
     pwd: "dbPassword",
     roles: [ "readWrite", "dbAdmin" ]

Disabling enter key for form

The better way I found here:


action="javascript: void(0)" or action="return false;" (doesn't work on me)

regular expression for DOT

. matches any character so needs escaping i.e. \., or \\. within a Java string (because \ itself has special meaning within Java strings.)

You can then use \.\. or \.{2} to match exactly 2 dots.

How to obtain the number of CPUs/cores in Linux from the command line?

Here's the way I use for counting the number of physical cores that are online on Linux:

lscpu --online --parse=Core,Socket | grep --invert-match '^#' | sort --unique | wc --lines

or in short:

lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l

Example (1 socket):

> lscpu
CPU(s):                28
Thread(s) per core:    2
Core(s) per socket:    14
Socket(s):             1
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l

Example (2 sockets):

> lscpu
CPU(s):                56
Thread(s) per core:    2
Core(s) per socket:    14
Socket(s):             2
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l

Example (4 sockets):

> lscpu
CPU(s):                64
Thread(s) per core:    2
Core(s) per socket:    8
Socket(s):             4
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The documentation on MSDN about the ItemsSource of the DataGridComboBoxColumn says that only static resources, static code or inline collections of combobox items can be bound to the ItemsSource:

To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options:

  • A static resource. For more information, see StaticResource Markup Extension.
  • An x:Static code entity. For more information, see x:Static Markup Extension.
  • An inline collection of ComboBoxItem types.

Binding to a DataContext's property is not possible if I understand that correctly.

And indeed: When I make CompanyItems a static property in ViewModel ...

public static ObservableCollection<CompanyItem> CompanyItems { get; set; }

... add the namespace where the ViewModel is located to the window ...


... and change the binding to ...

    ItemsSource="{Binding Source={x:Static vm:ViewModel.CompanyItems}}" 
    SelectedValueBinding="{Binding CompanyID}" />

... then it works. But having the ItemsSource as a static property might be sometimes OK, but it is not always what I want.

Convert char array to string use C

You're saying you have this:

char array[20]; char string[100];

And you'd like to have this:

string[0]= "178.9"; // where it was stored 178.9 position [0]

You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

Now if you want to copy the first x characters out of array to string you can do that with memcpy():

memcpy(string, array, x);
string[x] = '\0'; 

How to obfuscate Python code effectively?


Opy will obfuscate your extensive, real world, multi module Python source code for free! And YOU choose per project what to obfuscate and what not, by editing the config file:

You can recursively exclude all identifiers of certain modules from obfuscation.
You can exclude human readable configuration files containing Python code.
You can use getattr, setattr, exec and eval by excluding the identifiers they use.
You can even obfuscate module file names and string literals.
You can run your obfuscated code from any platform.

Unlike some of the other options posted, this works for both Python 2 and 3! It is also free / opensource, and it is not an online only tool (unless you pay) like some of the others out there.

I am admittedly still evaluating this myself, but all of initial tests of it worked perfectly. It appears this is exactly what I was looking for!

The official version runs as a standalone utility, with the original intended design being that you drop a script into the root of the directory you want to obfuscate, along with a config file to define the details/options you want to employ. I wasn't in love with that plan, so I added a fork from project, allowing you to import and utilize the tool from a library instead. That way, you can roll this directly into a more encompassing packaging script. (You could of course wrap multiple py scripts in bash/batch, but I think a pure python solution is ideal). I requested my fork be merged into the original work, but in case that never happens, here's the url to my revised version:

Why Is `Export Default Const` invalid?

The answer shared by Paul is the best one. To expand more,

There can be only one default export per file. Whereas there can be more than one const exports. The default variable can be imported with any name, whereas const variable can be imported with it's particular name.

var message2 = 'I am exported';
export default message2;
export const message = 'I am also exported'

At the imports side we need to import it like this:

import { message } from './test';


import message from './test';

With the first import, the const variable is imported whereas, with the second one, the default one will be imported.

Replace contents of factor column in R dataframe

You can use the function revalue from the package plyr to replace values in a factor vector.

In your example to replace the factor virginica by setosa:

 revalue(iris$Species, c("virginica" = "setosa")) -> iris$Species

How To Include CSS and jQuery in my WordPress plugin?

Accepted answer is incomplete. You should use the right hook: wp_enqueue_scripts


    function add_my_css_and_my_js_files(){
        wp_enqueue_script('your-script-name', $this->urlpath  . '/your-script-filename.js', array('jquery'), '1.2.3', true);
        wp_enqueue_style( 'your-stylesheet-name', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
    add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files");

MongoDB query with an 'or' condition

MongoDB query with an 'or' condition


MongoDB query with an 'or', 'and', condition combined.


Create Excel file in Java

Changing the extension of a file does not in any way change its contents. The extension is just a label.

If you want to work with Excel spreadsheets using Java, read up on the Apache POI library.

jQuery: how to get which button was clicked upon form submission?

I found that this worked.

$(document).ready(function() {
    $( "form" ).submit(function () {
        // Get the submit button element
        var btn = $(this).find("input[type=submit]:focus" );

Rails: How to run `rails generate scaffold` when the model already exists?

Great answer by Lee Jarvis, this is just the command e.g; we already have an existing model called User:

rails g scaffold_controller User

Read file line by line using ifstream in C++

This answer is for visual studio 2017 and if you want to read from text file which location is relative to your compiled console application.

first put your textfile (test.txt in this case) into your solution folder. After compiling keep text file in same folder with applicationName.exe


#include <iostream>
#include <fstream>

using namespace std;
int main()
    ifstream inFile;
    // open the file stream".\\test.txt");
    // check if opening a file failed
    if ( {
        cerr << "Error opeing a file" << endl;
    string line;
    while (getline(inFile, line))
        cout << line << endl;
    // close the file stream

python convert list to dictionary

Not sure whether it would help you or not but it works to me:

l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))

How do you render primitives as wireframes in OpenGL?


// Turn on wireframe mode
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);

// Draw the box

// Turn off wireframe mode
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);

How can I add 1 day to current date?

To add one day to a date object:

var date = new Date();

// add a day
date.setDate(date.getDate() + 1);

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

What is (functional) reactive programming?

This article by Andre Staltz is the best and clearest explanation I've seen so far.

Some quotes from the article:

Reactive programming is programming with asynchronous data streams.

On top of that, you are given an amazing toolbox of functions to combine, create and filter any of those streams.

Here's an example of the fantastic diagrams that are a part of the article:

Click event stream diagram

Dynamic constant assignment

Many thanks to Dorian and Phrogz for reminding me about the array (and hash) method #replace, which can "replace the contents of an array or hash."

The notion that a CONSTANT's value can be changed, but with an annoying warning, is one of Ruby's few conceptual mis-steps -- these should either be fully immutable, or dump the constant idea altogether. From a coder's perspective, a constant is declarative and intentional, a signal to other that "this value is truly unchangeable once declared/assigned."

But sometimes an "obvious declaration" actually forecloses other, future useful opportunities. For example...

There are legitimate use cases where a "constant's" value might really need to be changed: for example, re-loading ARGV from a REPL-like prompt-loop, then rerunning ARGV thru more (subsequent) OptionParser.parse! calls -- voila! Gives "command line args" a whole new dynamic utility.

The practical problem is either with the presumptive assumption that "ARGV must be a constant", or in optparse's own initialize method, which hard-codes the assignment of ARGV to the instance var @default_argv for subsequent processing -- that array (ARGV) really should be a parameter, encouraging re-parse and re-use, where appropriate. Proper parameterization, with an appropriate default (say, ARGV) would avoid the need to ever change the "constant" ARGV. Just some 2¢-worth of thoughts...

How to kill/stop a long SQL query immediately?

You can use a keyboard shortcut ALT + Break to stop the query execution. However, this may not succeed in all cases.

Difference between two dates in Python

pd.date_range('2019-01-01', '2019-02-01').shape[0]

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
// If $multi is boolean return $hash
} else return $hash;


How to simulate POST request?

Postman is the best application to test your APIs !

You can import or export your routes and let him remember all your body requests ! :)

EDIT : This comment is 5 yea's old and deprecated :D

Here's the new Postman App :

Programmatically switching between tabs within Swift

To expand on @codester's answer, you don't need to check and then assign, you can do it in one step:

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    // Override point for customization after application launch.

    if let tabBarController = self.window!.rootViewController as? UITabBarController {
        tabBarController.selectedIndex = 1

    return true

Make a number a percentage

@xtrem's answer is good, but I think the toFixed and the makePercentage are common use. Define two functions, and we can use that at everywhere.

const R = require('ramda')
const RA = require('ramda-adjunct')

const fix = R.invoker(1, 'toFixed')(2)

const makePercentage = R.when(
  R.compose(R.flip(R.concat)('%'), fix, R.multiply(100)),

let a = 0.9988
let b = null

makePercentage(b) // -> null
makePercentage(a) // -> ?????99.88%?????

Why Java Calendar set(int year, int month, int date) not returning correct date?

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();


and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

How do I import/include MATLAB functions?

If the folder just contains functions then adding the folders to the path at the start of the script will suffice.


If they are Packages, folders starting with a '+' then they also need to be imported.

import package_x.*
import package_y.*

You need to add the package folders parent to the search path.

How do I get PHP errors to display?

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;


Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this setting is set to 1 then errors will always be displayed, no matter what the setting of PHP's display_errors is.


Type: int, Default value: 0, Introduced in Xdebug >= 2.3 This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().

in a "using" block is a SqlConnection closed on return or exception?

Here is my Template. Everything you need to select data from an SQL server. Connection is closed and disposed and errors in connection and execution are caught.

string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CompanyServer"].ConnectionString;
string selectStatement = @"
    SELECT TOP 1 Person
    FROM CorporateOffice
    WHERE HeadUpAss = 1 AND Title LIKE 'C-Level%'
    ORDER BY IntelligenceQuotient DESC
using (SqlConnection conn = new SqlConnection(connString))
    using (SqlCommand comm = new SqlCommand(selectStatement, conn))
            using (SqlDataReader dr = comm.ExecuteReader())
                if (dr.HasRows)
                    while (dr.Read())
                else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
        catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
        if (conn.State == System.Data.ConnectionState.Open) conn.Close();

* Revised: 2015-11-09 *
As suggested by NickG; If too many braces are annoying you, format like this...

using (SqlConnection conn = new SqlConnection(connString))
   using (SqlCommand comm = new SqlCommand(selectStatement, conn))
         using (SqlDataReader dr = comm.ExecuteReader())
            if (dr.HasRows)
               while (dr.Read()) Console.WriteLine(dr["Person"].ToString());
            else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
      catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
      if (conn.State == System.Data.ConnectionState.Open) conn.Close();

Then again, if you work for EA or DayBreak games, you can just forgo any line-breaks as well because those are just for people who have to come back and look at your code later and who really cares? Am I right? I mean 1 line instead of 23 means I'm a better programmer, right?

using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand comm = new SqlCommand(selectStatement, conn)) { try { conn.Open(); using (SqlDataReader dr = comm.ExecuteReader()) if (dr.HasRows) while (dr.Read()) Console.WriteLine(dr["Person"].ToString()); else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)"); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } if (conn.State == System.Data.ConnectionState.Open) conn.Close(); }

Phew... OK. I got that out of my system and am done amusing myself for a while. Carry on.

Tell Ruby Program to Wait some amount of time

I find until very useful with sleep. example:

> time =
> sleep 2.seconds until > time + 10.seconds # breaks when true
# or something like
> sleep 1.seconds until !req.loading # suggested by ohsully

How to get a jqGrid cell value when editing

My workaround is to attach an object containing orignal values to each tr element in the grid. I've used afterAddRecord callback to get my hands on the values before jqGrid throws them away and jQuery's "data" method to store them in the work.


afterInsertRow: function( rowid, rowdata, rowelem ) {
  var tr = $("#"+rowid);
  $(tr).data("jqgrid.record_data", rowelem);

“rowelem” is the array of cell values from our JSON data feed or [jsonReader] (

Then at any point I can fetch those attributes using:


More at:

denied: requested access to the resource is denied : docker

Use Below commands:

$ docker login
<enter user name and password for Docker Hub Repository>

$ docker tag first-image {docker-hub-username}/{default-repo-folder-name}:first-image

$ docker push {docker-hub-username}/{default-repo-folder-name}:first-image

e.g. I have public repository like manjeet86/docker-repo so commands would be:

$ docker tag first-image manjeet86/docker-repo:first-image

$ docker push manjeet86/docker-repo:first-image

Just see : instead of / that was the trick. It works for me. I do not know if it lets you tag with / as well in place of : but that may be for some other purpose.

how to remove json object key and value.?

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_

  1. By making key value undefined: Alternate & a faster way:

let myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_

  1. With es6 spread Operator:

const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

Check if inputs form are empty jQuery

You can do it using simple jQuery loop.

Total code

<!DOCTYPE html>
 <html lang="en">
   <meta charset="UTF-8">
  <script type="text/javascript" src=""></script>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
#country{height: 30px;}
    border: 1px solid red !important;
function test()
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        isFormValid = false;

    if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");

return isFormValid;
<div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    <button type="submit" class="btn btn-primary">Login</button>

"PKIX path building failed" and "unable to find valid certification path to requested target"

Try copying java cacerts:

cp /usr/lib/jvm/java-1.8.0-openjdk- $JAVA_HOME/jre/lib/security/cacerts

Eclipse Intellisense?

You don't have to press CTRL * space but maybe the delay is too big or you don't like the trigger (default is '.'). Go to

Window -> Preferences -> Java/Editor/Content Assist

And change the settings under Auto Activation to your likings.

If this does not work for windows users then see this answer.

PHP PDO with foreach and fetch

This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.

If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.

JavaScript: How to find out if the user browser is Chrome?

Update: Please see Jonathan's answer for an updated way to handle this. The answer below may still work, but it could likely trigger some false positives in other browsers.

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

However, as mentioned User Agents can be spoofed so it is always best to use feature-detection (e.g. Modernizer) when handling these issues, as other answers mention.

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

How do I access (read, write) Google Sheets spreadsheets with Python?

The latest google api docs document how to write to a spreadsheet with python but it's a little difficult to navigate to. Here is a link to an example of how to append.

The following code is my first successful attempt at appending to a google spreadsheet.

import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

        Credentials, the obtained credential.
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
    credential_path = os.path.join(credential_dir,

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials =, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def add_todo():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('$discovery/rest?'
    service ='sheets', 'v4', http=http,

    spreadsheetId = 'PUT YOUR SPREADSHEET ID HERE'
    rangeName = 'A1:A'

    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,

if __name__ == '__main__':

How can I put a ListView into a ScrollView without it collapsing?

Instead of putting the listview inside Scrollview, put the rest of the content between listview and the opening of the Scrollview as a separate view and set that view as the header of the listview. So you will finally end up only list view taking charge of Scroll.

Getting Google+ profile picture url with user_id

Google, no API needed:

$data = file_get_contents('<USER_ID>?alt=json');
$d = json_decode($data);
$avatar = $d->{'entry'}->{'gphoto$thumbnail'}->{'$t'};

// Outputs example:

CHANGE: the 64 in "s64" for the size

Creating files in C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename.c_str());

  o << "Hello, World\n" << std::endl;

  return 0;

This is what I had to do in order to use a variable for the filename instead of a regular string.

Is there any way to change input type="date" format?

Try this if you need a quick solution To make yyyy-mm-dd go "dd- Sep -2016"

1) Create near your input one span class (act as label)

2) Update the label everytime your date is changed by user, or when need to load from data.

Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date

$("#date_input").on("change", function () {_x000D_
     $(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));_x000D_
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<input id ="date_input" dateformat="d M y" type="date"/>_x000D_
<span class="datepicker_label" style="pointer-events: none;"></span>

How can I debug my JavaScript code?

My first step is always to validate the HTML and to check syntax with JSLint. If you have clean markup and valid JavaScript code then it is time for Firebug or another debugger.

Download data url file

If you also want to give a suggested name to the file (instead of the default 'download') you can use the following in Chrome, Firefox and some IE versions:

function downloadURI(uri, name) {
  var link = document.createElement("a"); = name;
  link.href = uri;
  delete link;

And the following example shows it's use:

downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");

Get List of connected USB Devices

  foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
       foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
            foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
                  foreach (var item in disk.Properties)
                       object value = disk.GetPropertyValue(item.Name);
                  string valor = disk["Name"].ToString();

Taking multiple inputs from user in python

  1. a, b, c = input().split() # for space seperated inputs
  2. a, b, c = input().split(",") # for comma seperated inputs

How to get previous page url using jquery

Do you mean something like history.go(-1);? It will go back to the previous page.

window.history on MDN

Determining Referer in PHP

What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer.

So if you are generating a FB callback then it would look something like this:

$token = uniqid(mt_rand(), TRUE);
$_SESSION['token'] = $token;
$url = "{$token}";

Then the index.php will look like this:

if(empty($_GET['token']) || $_GET['token'] !== $_SESSION['token'])

//Continue with the rest of code

I do know of secure sites that do the equivalent of this for all their secure pages.

How can I make the cursor turn to the wait cursor?

OK so I created a static async method. That disabled the control that launches the action and changes the application cursor. It runs the action as a task and waits for to finish. Control returns to the caller while it waits. So the application remains responsive, even while the busy icon spins.

async public static void LengthyOperation(Control control, Action action)
        control.Enabled = false;
        Application.UseWaitCursor = true;
        Task doWork = new Task(() => action(), TaskCreationOptions.LongRunning);
        Log.Info("Task Start");
        Log.Info("Before Await");
        await doWork;
        Log.Info("After await");
        Application.UseWaitCursor = false;
        control.Enabled = true;

Here's the code form the main form

    private void btnSleep_Click(object sender, EventArgs e)
        var control = sender as Control;
        if (control != null)
            Log.Info("Launching lengthy operation...");
            CursorWait.LengthyOperation(control, () => DummyAction());
            Log.Info("...Lengthy operation launched.");


    private void DummyAction()
            var _log = NLog.LogManager.GetLogger("TmpLogger");
            _log.Info("Action - Sleep");
            TimeSpan sleep = new TimeSpan(0, 0, 16);
            _log.Info("Action - Wakeup");

I had to use a separate logger for the dummy action (I am using Nlog) and my main logger is writing to the UI (a rich text box). I wasn't able to get the busy cursor show only when over a particular container on the form (but I didn't try very hard.) All controls have a UseWaitCursor property, but it doesn't seem have any effect on the controls I tried (maybe because they weren't on top?)

Here's the main log, which shows things happening in the order we expect:

16:51:33.1064 Launching lengthy operation...
16:51:33.1215 Task Start
16:51:33.1215 Before Await
16:51:33.1215 ...Lengthy operation launched.
16:51:49.1276 After await
16:51:49.1537 Finally

How to create permanent PowerShell Aliases

This is a little bit fancy... but it works:

Step 1: Create a Powershell Profile:

FILE: install_profile.ps1

$ErrorActionPreference = "Stop"

function print ([string]$msg)
    Write-Host -ForegroundColor Green $msg

print ""

# User's Powershell Profile
$psdir  = "$env:USERPROFILE\Documents\WindowsPowerShell"
$psfile = $psdir + "\Microsoft.PowerShell_profile.ps1"

print "Creating Directory: $psdir"
md $psdir -ErrorAction SilentlyContinue | out-null

# this is your auto-generated powershell profile to be installed
$content = @(
    ". ~/Documents/tools/profile.ps1",

print "Creating File: $psfile"
[System.IO.File]::WriteAllLines($psfile, $content)

print ""

# Make sure Powershell profile is readable
Set-ExecutionPolicy -Scope CurrentUser Unrestricted

Step 2: then in tools ~/Documents/tools/profile.ps1:

function Do-ActualThing {
    # do actual thing

Set-Alias MyAlias Do-ActualThing

Step 3:

$ Set-ExecutionPolicy -Scope CurrentUser Unrestricted $ . ./install_profile.ps1

How can I show/hide a specific alert with twitter bootstrap?

Just use the ID instead of the class?? I dont really understand why you would ask though when it looks like you know Jquery ?



Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

Try changing the Web Client request authentication part to:

NetworkCredential myCreds = new NetworkCredential(userName, passWord);
client.Credentials = myCreds;

Then make your call, seems to work fine for me.

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in


In the VM Arguments the Paths are listed and changeable

How permission can be checked at runtime without throwing SecurityException?

Sharing my methods in case someone needs them:

 /** Determines if the context calling has the required permission
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
public static boolean hasPermission(Context context, String permission) {

    int res = context.checkCallingOrSelfPermission(permission);

    Log.v(TAG, "permission: " + permission + " = \t\t" + 
    (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));

    return res == PackageManager.PERMISSION_GRANTED;


/** Determines if the context calling has the required permissions
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
public static boolean hasPermissions(Context context, String... permissions) {

    boolean hasAllPermissions = true;

    for(String permission : permissions) {
        //you can return false instead of assigning, but by assigning you can log all permission values
        if (! hasPermission(context, permission)) {hasAllPermissions = false; }

    return hasAllPermissions;


And to call it:

boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {

python replace single backslash with double backslash


string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")

Escape the \ character.

What is the purpose of the : (colon) GNU Bash builtin?

A useful application for : is if you're only interested in using parameter expansions for their side-effects rather than actually passing their result to a command. In that case you use the PE as an argument to either : or false depending upon whether you want an exit status of 0 or 1. An example might be : "${var:=$1}". Since : is a builtin it should be pretty fast.

How to destroy JWT Tokens on logout?

On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.

But, What if you want to destroy the token on the Node server -

The problem with JWT package is that it doesn't provide any method or way to destroy the token.

So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

it works in this way :

1) Install jwt-redis from npm

2) To Create -

var redis = require('redis');
var JWTR =  require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);

jwtr.sign(payload, secret)
            // your code
            // error handling

3) To verify -

jwtr.verify(token, secret);

4) To Destroy -


Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

Hibernate: best practice to pull all lazy collections

Try use Gson library to convert objects to Json

Example with servlets :

  List<Party> parties = bean.getPartiesByIncidentId(incidentId);
        String json = "";
        try {
            json = new Gson().toJson(parties);
        } catch (Exception ex) {

operator << must take exactly one argument

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

Can I do Model->where('id', ARRAY) multiple where conditions?

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();

How to remove all namespaces from XML with C#?

my answer, string-manipulation-based,
lite-most code,

public static string hilangkanNamespace(string instrXML)
        char chrOpeningTag = '<';
        char chrClosingTag = '>';
        char chrSpasi = ' ';
        int intStartIndex = 0;
            int intIndexKu = instrXML.IndexOf(chrOpeningTag, intStartIndex);
            if (intIndexKu < 0)
                break; //kalau dah ga ketemu keluar
            int intStart = instrXML.IndexOfAny(new char[] { chrSpasi, chrClosingTag }, intIndexKu + 1); //mana yang ketemu duluan
            if (intStart < 0)
                break; //kalau dah ga ketemu keluar
            int intStop = instrXML.IndexOf(chrClosingTag, intStart);
            if (intStop < 0)
                break; //kalau dah ga ketemu keluar
                intStop--; //exclude si closingTag
            int intLengthToStrip = intStop - intStart + 1;
            instrXML = instrXML.Remove(intStart, intLengthToStrip);
            intStartIndex = intStart;
        } while (true);

        return instrXML;

Select rows which are not present in other table

this can also be tried...

SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM   login_log l 
LEFT   JOIN (SELECT ip_location.ip, ip_location.hostname
             FROM ip_location
             WHERE ip_location.ip is null)tbl2

What is a .NET developer?

I'd say the minimum would be to

  • know one of the .Net Languages (C#, VB.NET, etc.)
  • know the basic working of the .Net runtime
  • know and understand the core parts of the .Net class libraries
  • have an understanding about what additional classes and functions are available as part of the .Net class libraries

Parameterize an SQL IN clause

In SQL Server 2016+ another possibility is to use the OPENJSON function.

This approach is blogged about in OPENJSON - one of best ways to select rows by list of ids.

A full worked example below

     Name  VARCHAR(50),
     Count INT

VALUES      ('VB',982), ('ruby',1306), ('rails',1478), ('scruffy',1), ('C#',1784)


CREATE PROC dbo.SomeProc
FROM   dbo.Tags T
WHERE  T.Name IN (SELECT J.Value COLLATE Latin1_General_CI_AS
                  FROM   OPENJSON(CONCAT('[', @Tags, ']')) J)


EXEC dbo.SomeProc @Tags = '"ruby","rails","scruffy","rubyonrails"'

DROP TABLE dbo.Tags 

Removing App ID from Developer Connection

When I do what explains some answers:

Screen Shot 1

The result is:

Screen Shot 2

So, anybody can explain really really how to delete an old App ID?

My opinion is: Apple does not let you remove them. I suppose it is a way to maintain the traceability or the historical of the published.

And of course: application is no longer available in the App Store. It was available (in the past), yes.

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :


use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0);

Ellipsis for overflow text in dropdown boxes

Found this absolute hack that actually works quite well:

Not CSS only though.

The basic gist is to have a container on the dropdown, .select-container in this case. That container has it's ::before set up to display content based on its data-content attribute/dataset, along with all of the overflow:hidden; text-overflow: ellipsis; and sizing necessary to make the ellipsis work.

When the select changes, javascript assigns the value (or you could retrieve the text of the option out of the select.options list) to the dataset.content of the container, and voila!

Copying content of the codepen here:

var selectContainer = document.querySelector(".select-container");_x000D_
var select = selectContainer.querySelector(".select");_x000D_
select.value = "lingua latina non penis canina";_x000D_
selectContainer.dataset.content = select.value;_x000D_
function handleChange(e) {_x000D_
  selectContainer.dataset.content = e.currentTarget.value;_x000D_
select.addEventListener("change", handleChange);
span {_x000D_
  margin: 0 10px 0 0;_x000D_
.select-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
.select-container::before {_x000D_
  content: attr(data-content);_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 10px;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  padding: 7px;_x000D_
  font: 11px Arial, sans-serif;_x000D_
  white-space: nowrap;_x000D_
  text-overflow: ellipsis;_x000D_
  overflow: hidden;_x000D_
  text-transform: capitalize;_x000D_
  pointer-events: none;_x000D_
.select {_x000D_
  width: 80px;_x000D_
  padding: 5px;_x000D_
  appearance: none;_x000D_
  background: transparent url("") no-repeat calc(~"100% - 5px") 7px;_x000D_
  background-size: 10px 10px;_x000D_
  color: transparent;_x000D_
.regular {_x000D_
  display: inline-block;_x000D_
  margin: 10px 0 0;_x000D_
  .select {_x000D_
    color: #000;_x000D_
<span>Hack:</span><div class="select-container" data-content="">_x000D_
  <select class="select" id="words">_x000D_
    <option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
    <option value="lorem">Lorem</option>_x000D_
    <option value="ipsum">Ipsum</option>_x000D_
    <option value="dolor">Dolor</option>_x000D_
    <option value="sit">Sit</option>_x000D_
    <option value="amet">Amet</option>_x000D_
    <option value="lingua">Lingua</option>_x000D_
    <option value="latina">Latina</option>_x000D_
    <option value="non">Non</option>_x000D_
    <option value="penis">Penis</option>_x000D_
    <option value="canina">Canina</option>_x000D_
<br />_x000D_
<div class="regular">_x000D_
  <select style="width: 80px;">_x000D_
    <option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
    <option value="lorem">Lorem</option>_x000D_
    <option value="ipsum">Ipsum</option>_x000D_
    <option value="dolor">Dolor</option>_x000D_
    <option value="sit">Sit</option>_x000D_
    <option value="amet">Amet</option>_x000D_
    <option value="lingua">Lingua</option>_x000D_
    <option value="latina">Latina</option>_x000D_
    <option value="non">Non</option>_x000D_
    <option value="penis">Penis</option>_x000D_
    <option value="canina">Canina</option>_x000D_

Sql Server : How to use an aggregate function like MAX in a WHERE clause

yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......

How do I set a cookie on HttpClient's HttpRequestMessage

Here's how you could set a custom cookie value for the request:

var baseAddress = new Uri("");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
    var content = new FormUrlEncodedContent(new[]
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = await client.PostAsync("/test", content);