Programs & Examples On #Servicepacks

0

Attempted to read or write protected memory

In my case this was fixed when I set up 'Enable 32 Bit applications'=True for Application pool in IIS server.

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

Operand type clash: uniqueidentifier is incompatible with int

The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.

The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier

This is a simiple example:

use example
go
create table Test1 (
    id int primary key,
    item uniqueidentifier,
    inserted_at datetime
    )
go
create table Test2 (
    id int primary key,
    inserted_at datetime
    )
go
alter table Test2 add item uniqueidentifier;
go

--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());


insert into Test2 select * from Test1;

select * from Test1;
select * from Test2;


The error message is:

Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime

How are Anonymous inner classes used in Java?

An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.

Consider the example from doc where we have a Person class:

public class Person {

    public enum Sex {
        MALE, FEMALE
    }

    String name;
    LocalDate birthday;
    Sex gender;
    String emailAddress;

    public int getAge() {
        // ...
    }

    public void printPerson() {
        // ...
    }
}

and we have a method to print members that match search criteria as:

public static void printPersons(
    List<Person> roster, CheckPerson tester) {
    for (Person p : roster) {
        if (tester.test(p)) {
            p.printPerson();
        }
    }
}

where CheckPerson is an interface like:

interface CheckPerson {
    boolean test(Person p);
}

Now we can make use of anonymous class which implements this interface to specify search criteria as:

printPersons(
    roster,
    new CheckPerson() {
        public boolean test(Person p) {
            return p.getGender() == Person.Sex.MALE
                && p.getAge() >= 18
                && p.getAge() <= 25;
        }
    }
);

Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.

Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:

printPersons(
                roster,
                (Person p) -> p.getGender() == Person.Sex.MALE
                        && p.getAge() >= 18
                        && p.getAge() <= 25
        );

We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.

Defining Z order of views of RelativeLayout in Android

I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:

childView1.bringToFront();

parentView.invalidate();

RecyclerView - How to smooth scroll to top of item on a certain position?

We can try like this

    recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), recyclerView.getAdapter().getItemCount());

Post form data using HttpWebRequest

Try this:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

How I can delete in VIM all text from current line to end of file?

Go to the first line from which you would like to delete, and press the keys dG

Remove characters from a string

Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.

Creating an Array from a Range in VBA

This function returns an array regardless of the size of the range.

Ranges will return an array unless the range is only 1 cell and then it returns a single value instead. This function will turn the single value into an array (1 based, the same as the array's returned by ranges)

This answer improves on previous answers as it will return an array from a range no matter what the size. It is also more efficient that other answers as it will return the array generated by the range if possible. Works with single dimension and multi-dimensional arrays

The function works by trying to find the upper bounds of the array. If that fails then it must be a single value so we'll create an array and assign the value to it.

Public Function RangeToArray(inputRange As Range) As Variant()
Dim size As Integer
Dim inputValue As Variant, outputArray() As Variant

    ' inputValue will either be an variant array for ranges with more than 1 cell
    ' or a single variant value for range will only 1 cell
    inputValue = inputRange

    On Error Resume Next
    size = UBound(inputValue)

    If Err.Number = 0 Then
        RangeToArray = inputValue
    Else
        On Error GoTo 0
        ReDim outputArray(1 To 1, 1 to 1)
        outputArray(1,1) = inputValue
        RangeToArray = outputArray
    End If

    On Error GoTo 0

End Function

How can I check if a view is visible or not in Android?

Or you could simply use

View.isShown()

Converting a string to a date in DB2

You can use:

select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name

Calculating the angle between the line defined by two points

Assumptions: x is the horizontal axis, and increases when moving from left to right. y is the vertical axis, and increases from bottom to top. (touch_x, touch_y) is the point selected by the user. (center_x, center_y) is the point at the center of the screen. theta is measured counter-clockwise from the +x axis. Then:

delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)

Edit: you mentioned in a comment that y increases from top to bottom. In that case,

delta_y = center_y - touch_y

But it would be more correct to describe this as expressing (touch_x, touch_y) in polar coordinates relative to (center_x, center_y). As ChrisF mentioned, the idea of taking an "angle between two points" is not well defined.

Reverse a string in Java

You can use this:

new StringBuilder(hi).reverse().toString()

Or, for versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have the same API. Thanks commentators for pointing out that StringBuilder is preferred nowadays when there is no concurrency concern.

List of All Folders and Sub-folders

You can use find

find . -type d > output.txt

or tree

tree -d > output.txt

tree, If not installed on your system.

If you are using ubuntu

sudo apt-get install tree

If you are using mac os.

brew install tree

Invalid argument supplied for foreach()

If you're using php7 and you want to handle only undefined errors this is the cleanest IMHO

$array = [1,2,3,4];
foreach ( $array ?? [] as $item ) {
  echo $item;
}

Save array in mysql database

To convert any array (or any object) into a string using PHP, call the serialize():

$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;

$string will now hold a string version of the array. The output of the above code is as follows:

a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}

To convert back from the string to the array, use unserialize():

// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );

SQL SERVER: Get total days between two dates

PRINT DATEDIFF(DAY, '1/1/2011', '3/1/2011') will give you what you're after.

This gives the number of times the midnight boundary is crossed between the two dates. You may decide to need to add one to this if you're including both dates in the count - or subtract one if you don't want to include either date.

How to fix Error: listen EADDRINUSE while using nodejs?

Just a head's up, Skype will sometimes listen on port 80 and therefore cause this error if you try to listen on port 80 from Node.js or any other app.

You can turn off that behaviour in Skype by accessing the options and clicking Advanced -> Connection -> Use port 80 (Untick this)

Turn off Skype port 80 usage

P.S. After making that change, don't forget to restart Skype!

Is there way to use two PHP versions in XAMPP?

Yes you can. I assume you have a xampp already installed. So,

  • Close all xampp instances. Using task manager stop apache and mysqld.
  • Then rename the xampp to xampp1 or something after xampp name.
  • Now Download the other xampp version. Create a folder name xampp only. Install the downloaded xampp there.
  • Now depending on the xampp version of your requirement, just rename the target folder to xampp only and other folder to different name.

That's how I am working with multiple xampp installed

How to write a:hover in inline CSS?

using Javascript:

a) Adding inline style

document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');

b) or a bit harder method - adding "mouseover"

document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };

Note: multi-word styles (i.e.font-size) in Javascript are written together:

element.style.fontSize="12px"

Convert a space delimited string to list

try

states.split()

it returns the list

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

Convert a Python int into a big-endian string of bytes

Very easy with pwntools , the tools created for software hacking

(Un-ironically, I stumbled across this thread and tried solutions here, until I realised there exists conversion functionality in pwntools)

import pwntools

x2 = p32(x1)

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

Adding an img element to a div with javascript

The following solution seems to be a much shorter version for that:

<div id="imageDiv"></div>

In Javascript:

document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';

How to change the color of text in javafx TextField?

If you are designing your Javafx application using SceneBuilder then use -fx-text-fill(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield.

I came here for the same problem and solved it in this way.

Unable to verify leaf signature

For Create React App (where this error occurs too and this question is the #1 Google result), you are probably using HTTPS=true npm start and a proxy (in package.json) which goes to some HTTPS API which itself is self-signed, when in development.

If that's the case, consider changing proxy like this:

"proxy": {
  "/api": {
    "target": "https://localhost:5001",
    "secure": false
  }
}

secure decides whether the WebPack proxy checks the certificate chain or not and disabling that ensures the API self-signed certificate is not verified so that you get your data.

Trying to use Spring Boot REST to Read JSON String from POST

To further work with array of maps, the followings could help:

@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {

  List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
  maps.addAll(payload);

}

How to hide code from cells in ipython notebook visualized with nbviewer?

The accepted solution also works in julia Jupyter/IJulia with the following modifications:

display("text/html", """<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 \$("div.input").hide();
 } else {
 \$("div.input").show();
 }
 code_show = !code_show
} 
\$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>""")

note in particular:

  • use the display function
  • escape the $ sign (otherwise seen as a variable)

Creating Dynamic button with click event in JavaScript

Firstly, you need to change this line:

element.setAttribute("onclick", alert("blabla"));

To something like this:

element.setAttribute("onclick", function() { alert("blabla"); });

Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.

React - How to get parameter value from query string?

When using React hooks there is no access to access to this.props.location. To capture url parameters use window object.

const search = window.location.search;
const params = new URLSearchParams(search);
const foo = params.get('bar');

How do I show the changes which have been staged?

For Staging Area vs Repository(last commit) comparison use

 $git diff --staged

The command compares your staged($ git add fileName) changes to your last commit. If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged. This command compares your staged changes to your last commit.

For Working vs Staging comparison use

$ git diff 

The command compares what is in your working directory with what is in your staging area. It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes($ git add fileName), git diff will give you no output.

Also, if you stage a file($ git add fileName) and then edit it, you can use git diff to see the changes in the file that are staged and the changes that are unstaged.

How can I call a method in Objective-C?

calling the method is like this

[className methodName] 

however if you want to call the method in the same class you can use self

[self methodName] 

all the above is because your method was not taking any parameters

however if your method takes parameters you will need to do it like this

[self methodName:Parameter]

Calculate rolling / moving average in C++

I use this quite often in hard realtime systems that have fairly insane update rates (50kilosamples/sec) As a result I typically precompute the scalars.

To compute a moving average of N samples: scalar1 = 1/N; scalar2 = 1 - scalar1; // or (1 - 1/N) then:

Average = currentSample*scalar1 + Average*scalar2;

Example: Sliding average of 10 elements

double scalar1 = 1.0/10.0;  // 0.1
double scalar2 = 1.0 - scalar1; // 0.9
bool first_sample = true;
double average=0.0;
while(someCondition)
{
   double newSample = getSample();
   if(first_sample)
   {
    // everybody forgets the initial condition *sigh*
      average = newSample;
      first_sample = false;
   }
   else
   {
      average = (sample*scalar1) + (average*scalar2);
   }
 }

Note: this is just a practical implementation of the answer given by steveha above. Sometimes it's easier to understand a concrete example.

Get all unique values in a JavaScript array (remove duplicates)

I think this this is most easiest way to get unique item from array.

var arr = [1,2,4,1,4];
arr = Array.from(new Set(arr))
console.log(arr)

How to create an array containing 1...N

Performance

Today 2020.12.11 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.

Results

For all browsers

  • solution O (based on while) is fastest (except Firefox for big N - but it's fast there)
  • solution T is fastest on Firefox for big N
  • solutions M,P are fast for small N
  • solution V (lodash) is fast for big N
  • solution W,X are slow for small N
  • solution F is slow

enter image description here

Details

I perform 2 tests cases:

  • for small N = 10 - you can run it HERE
  • for big N = 1000000 - you can run it HERE

Below snippet presents all tested solutions A B C D E F G H I J K L M N O P Q R S T U V W X

_x000D_
_x000D_
function A(N) {
  return Array.from({length: N}, (_, i) => i + 1)
}

function B(N) {
  return Array(N).fill().map((_, i) => i+1);
}

function C(N) {
  return Array(N).join().split(',').map((_, i) => i+1 );
}

function D(N) {
  return Array.from(Array(N), (_, i) => i+1)
}

function E(N) {
  return Array.from({ length: N }, (_, i) => i+1)
}

function F(N) {
  return Array.from({length:N}, Number.call, i => i + 1)
}

function G(N) {
  return (Array(N)+'').split(',').map((_,i)=> i+1)
}

function H(N) {
  return [ ...Array(N).keys() ].map( i => i+1);
}

function I(N) {
  return [...Array(N).keys()].map(x => x + 1);
}

function J(N) {
  return [...Array(N+1).keys()].slice(1)
}

function K(N) {
  return [...Array(N).keys()].map(x => ++x);
}

function L(N) {
  let arr; (arr=[ ...Array(N+1).keys() ]).shift();
  return arr;
}

function M(N) {
  var arr = [];
  var i = 0;

  while (N--) arr.push(++i);

  return arr; 
}

function N(N) {
  var a=[],b=N;while(b--)a[b]=b+1;
  return a;
}

function O(N) {
  var a=Array(N),b=0;
  while(b<N) a[b++]=b;
  return a;
}

function P(N) {
  var foo = [];
  for (var i = 1; i <= N; i++) foo.push(i);
  return foo;
}

function Q(N) {
  for(var a=[],b=N;b--;a[b]=b+1);
  return a;
}

function R(N) {
  for(var i,a=[i=0];i<N;a[i++]=i);
  return a;
}

function S(N) {
    let foo,x;
    for(foo=[x=N]; x; foo[x-1]=x--);
  return foo;
}

function T(N) {
  return new Uint8Array(N).map((item, i) => i + 1);
}

function U(N) {
  return '_'.repeat(5).split('').map((_, i) => i + 1);
}

function V(N) {
  return _.range(1, N+1);
}

function W(N) {
  return [...(function*(){let i=0;while(i<N)yield ++i})()]
}

function X(N) {
  function sequence(max, step = 1) {
    return {
      [Symbol.iterator]: function* () {
        for (let i = 1; i <= max; i += step) yield i
      }
    }
  }

  return [...sequence(N)];
}


[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X].forEach(f=> {
  console.log(`${f.name} ${f(5)}`);
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

How to use Macro argument as string literal?

#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian

Throw HttpResponseException or return Request.CreateErrorResponse?

As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions

Ajax Upload image

Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
                                            </div>
                                        </div>
                                    </div>
                                    </form>     
                                    
                                    </div>  
                      
    
      $.validator.setDefaults({
       submitHandler: function (form) 
         {
               $.ajax({
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    dataType:'json',
                    processData: false,
                    success: function(data)
                    {
                        if(data.status =='success')
                            {
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                 });
                                 setTimeout(function(){
                                    window.location.reload(); 
                                },1200);
                            }
                            else
                            {
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                            }   
                    },
                    error:function(data)
                    {
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
                    }
                });
            }
      });
    
      $('#document_form').validate({
        rules: {
            "name[]": {
              required: true
          },
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
          }
        },
        messages: {
            "name[]": {
            required: "Please enter name"
          },
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
          }
        },
        errorElement: 'span',
        errorPlacement: function (error, element) {
          error.addClass('invalid-feedback');
          element.closest('.col-3').append(error);
        },
        highlight: function (element, errorClass, validClass) {
          $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
          $(element).removeClass('is-invalid');
        }
      });
    
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');

How to get a value from a cell of a dataframe?

I needed the value of one cell, selected by column and index names. This solution worked for me:

original_conversion_frequency.loc[1,:].values[0]

How do I check if an array includes a value in JavaScript?

Use lodash's some function.

It's concise, accurate and has great cross platform support.

The accepted answer does not even meet the requirements.

Requirements: Recommend most concise and efficient way to find out if a JavaScript array contains an object.

Accepted Answer:

$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
> -1

My recommendation:

_.some([{'a': 1}, {'b': 2}], {'b': 2})
> true

Notes:

$.inArray works fine for determining whether a scalar value exists in an array of scalars...

$.inArray(2, [1,2])
> 1

... but the question clearly asks for an efficient way to determine if an object is contained in an array.

In order to handle both scalars and objects, you could do this:

(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)

How to append elements into a dictionary in Swift?

you can add using the following way and change Dictionary to NSMutableDictionary

dict["key"] = "value"

How to compare two java objects

You have to correctly override method equals() from class Object

Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.

Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.

For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().

But now, we come to another problem. Let's imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.

There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.

Some of the collections that use hashCode()

  • HashSet
  • LinkedHashSet
  • HashMap

Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily

How to use local docker images with Minikube?

There is one essay and effective way to push your local Docker image directly to minikube, which will save time from building the images in minikube again.

minikube cache add <Image name>

More details here

All possible method to push images to minikube are mention here: https://minikube.sigs.k8s.io/docs/handbook/pushing/

Undefined symbols for architecture x86_64 on Xcode 6.1

Check if that file is included in Build Phases -> Compiled Sources

Counter in foreach loop in C#

From MSDN:

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable(Of T) interface.

So, it's not necessarily Array. It could even be a lazy collection with no idea about the count of items in the collection.

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

Is Android using NTP to sync time?

Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf - obviously this file can only be edited with root access, but is viewable on non-rooted devices.

MySQL - Trigger for updating same table after insert

This is how I update a row in the same table on insert

activationCode and email are rows in the table USER. On insert I don't specify a value for activationCode, it will be created on the fly by MySQL.

Change username with your MySQL username and db_name with your db name.

CREATE DEFINER=`username`@`localhost` 
       TRIGGER `db_name`.`user_BEFORE_INSERT` 
       BEFORE INSERT ON `user` 
       FOR EACH ROW
         BEGIN
            SET new.activationCode = MD5(new.email);
         END

try/catch blocks with async/await

Alternative Similar To Error Handling In Golang

Because async/await uses promises under the hood, you can write a little utility function like this:

export function catchEm(promise) {
  return promise.then(data => [null, data])
    .catch(err => [err]);
}

Then import it whenever you need to catch some errors, and wrap your async function which returns a promise with it.

import catchEm from 'utility';

async performAsyncWork() {
  const [err, data] = await catchEm(asyncFunction(arg1, arg2));
  if (err) {
    // handle errors
  } else {
    // use data
  }
}

Set "Homepage" in Asp.Net MVC

Step 1: Click on Global.asax File in your Solution.

Step 2: Then Go to Definition of

RouteConfig.RegisterRoutes(RouteTable.Routes);

Step 3: Change Controller Name and View Name

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(name: "Default",
                        url: "{controller}/{action}/{id}",
                        defaults: new { controller = "Home", 
                                        action = "Index", 
                                        id = UrlParameter.Optional }
                        );
    }
}

Communicating between a fragment and an activity - best practices

I'm not sure I really understood what you want to do, but the suggested way to communicate between fragments is to use callbacks with the Activity, never directly between fragments. See here http://developer.android.com/training/basics/fragments/communicating.html

How can I use a reportviewer control in an asp.net mvc 3 razor view?

the documentations refers to an ASP.NET application.
You can try and have a look at my answer here.
I have an example attached to my reply.
Another example for ASP.NET MVC3 can be found here.

Comparing user-inputted characters in C

answer shouldn't be a pointer, the intent is obviously to hold a character. scanf takes the address of this character, so it should be called as

char answer;
scanf(" %c", &answer);

Next, your "or" statement is formed incorrectly.

if (answer == 'Y' || answer == 'y')

What you wrote originally asks to compare answer with the result of 'Y' || 'y', which I'm guessing isn't quite what you wanted to do.

Difference between abstract class and interface in Python

In general, interfaces are used only in languages that use the single-inheritance class model. In these single-inheritance languages, interfaces are typically used if any class could use a particular method or set of methods. Also in these single-inheritance languages, abstract classes are used to either have defined class variables in addition to none or more methods, or to exploit the single-inheritance model to limit the range of classes that could use a set of methods.

Languages that support the multiple-inheritance model tend to use only classes or abstract base classes and not interfaces. Since Python supports multiple inheritance, it does not use interfaces and you would want to use base classes or abstract base classes.

http://docs.python.org/library/abc.html

'float' vs. 'double' precision

Do doubles always have 16 significant figures while floats always have 7 significant figures?

No. Doubles always have 53 significant bits and floats always have 24 significant bits (except for denormals, infinities, and NaN values, but those are subjects for a different question). These are binary formats, and you can only speak clearly about the precision of their representations in terms of binary digits (bits).

This is analogous to the question of how many digits can be stored in a binary integer: an unsigned 32 bit integer can store integers with up to 32 bits, which doesn't precisely map to any number of decimal digits: all integers of up to 9 decimal digits can be stored, but a lot of 10-digit numbers can be stored as well.

Why don't doubles have 14 significant figures?

The encoding of a double uses 64 bits (1 bit for the sign, 11 bits for the exponent, 52 explicit significant bits and one implicit bit), which is double the number of bits used to represent a float (32 bits).

Remove style attribute from HTML tags

I'm using such thing to clean-up the style='...' section out of tags with keeping of other attributes at the moment.

$output = preg_replace('/<([^>]+)(\sstyle=(?P<stq>["\'])(.*)\k<stq>)([^<]*)>/iUs', '<$1$5>', $input);

How can I rename a single column in a table at select?

If, like me, you are doing this for a column which then goes through COALESCE / array_to_json / ARRAY_AGG / row_to_json (PostgreSQL) and want to keep the capitals in the column name, double quote the column name, like so:

SELECT a.price AS "myFirstPrice", b.price AS "mySecondPrice"

Without the quotes (and when using those functions), my column names in camelCase would lose the capital letters.

Hide Command Window of .BAT file that Executes Another .EXE File

I haven't really found a good way to do that natively, so I just use a utility called hstart which does it for me. If there's a neater way to do it, that would be nice.

HttpRequest maximum allowable size in tomcat?

The connector section has the parameter

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Another Limit is:

maxHttpHeaderSize The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

You find them in

$TOMCAT_HOME/conf/server.xml

How do I read / convert an InputStream into a String in Java?

Also you can get InputStream from a specified resource path:

public static InputStream getResourceAsStream(String path)
{
    InputStream myiInputStream = ClassName.class.getResourceAsStream(path);
    if (null == myiInputStream)
    {
        mylogger.info("Can't find path = ", path);
    }

    return myiInputStream;
}

To get InputStream from a specific path:

public static URL getResource(String path)
{
    URL myURL = ClassName.class.getResource(path);
    if (null == myURL)
    {
        mylogger.info("Can't find resource path = ", path);
    }
    return myURL;
}

How to insert blank lines in PDF?

Instead of using:

document.add( Chunk.NEWLINE );

use this:

document.add(new Paragraph(""));

it makes small space

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.

You need to put a > tbody in between > table and > tr:

$("div.custList > table > tbody > tr")

Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):

$("div.custList table tr")

That said, you can get the immediate <td> children there by $(this).children('td').

Android button background color

In addition to Mark Proctor's answer:

If you want to keep the default styling, but have a conditional coloring on the button, just set the backgroundTint property like so:

android:backgroundTint="@drawable/styles_mybutton"

Create the associated file /res/drawable/styles_mybutton.xml, then use the following template and change the colors as per your tastes:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Disabled state-->
    <item android:state_enabled="false"
        android:color="@android:color/white">
    </item>
    <!-- Default state-->
    <item
        android:color="#cfc">
    </item>
</selector>

App store link for "rate/review this app"

Swift 2 version that actually takes you to the review page for your app on both iOS 8 and iOS 9:

let appId = "YOUR_APP_ID"
let url = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=\(appId)"

UIApplication.sharedApplication().openURL(NSURL(string: url)!)

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

You are missing commons-digester3-3.2.jar from Apache Commons Digester. If you are using Maven you can add:

<dependency>
    <groupId>commons-digester</groupId>
    <artifactId>commons-digester</artifactId>
    <version>2.1</version>
</dependency>

to your project dependencies.

Update: The jar from the latest download page has a slightly different package structure to what your application expects. You can use this older jar instead.

Select all where [first letter starts with B]

SQL Statement:

 SELECT * FROM employee WHERE employeeName LIKE 'A%';

Result:

Number of Records: 4

employeeID  employeeName    employeeName    Address City    PostalCode  Country

1           Alam             Wipro          Delhi   Delhi   11005      India

2           Aditya           Wipro          Delhi   Delhi   11005      India

3           Alok             HCL            Delhi   Delhi   11005      India

4           Ashok            IBM            Delhi   Delhi   11005      India

How to set the JDK Netbeans runs on?

Thanks to KasunBG's tip, I found the solution in the "suggested" link, update the following file (replace 7.x with your Netbeans version) :

C:\Program Files\NetBeans 7.x\etc\netbeans.conf

Change the following line to point it where your java installation is :

netbeans_jdkhome="C:\Program Files\Java\jdk1.7xxxxx"

You may need Administrator privileges to edit netbeans.conf

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

Do I commit the package-lock.json file created by npm 5?

To the people complaining about the noise when doing git diff:

git diff -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'

What I did was use an alias:

alias gd="git diff --ignore-all-space --ignore-space-at-eol --ignore-space-change --ignore-blank-lines -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'"

To ignore package-lock.json in diffs for the entire repository (everyone using it), you can add this to .gitattributes:

package-lock.json binary
yarn.lock binary

This will result in diffs that show "Binary files a/package-lock.json and b/package-lock.json differ whenever the package lock file was changed. Additionally, some Git services (notably GitLab, but not GitHub) will also exclude these files (no more 10k lines changed!) from the diffs when viewing online when doing this.

How do I kill the process currently using a port on localhost in Windows?

In case you want to do it using Python: check Is it possible in python to kill process that is listening on specific port, for example 8080?

The answer from Smunk works nicely. I repeat his code here:

from psutil import process_iter
from signal import SIGTERM # or SIGKILL

for proc in process_iter():
    for conns in proc.connections(kind='inet'):
        if conns.laddr.port == 8080:
            proc.send_signal(SIGTERM) # or SIGKILL
            continue

How to unpack an .asar file?

https://www.electronjs.org/apps/asarui

UI for Asar, Extract All, or drag extract file/directory

How to declare a global variable in JavaScript

If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu under jQuery, and I place everything there.

The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.

Also, for convenience, I usually sub-space the plugin namespace with an i namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.

This is how it works:

// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();

Now I can just do $.miniMenu.i.globalVar = 3 or $.miniMenu.i.parseSomeStuff = function(...) {...} whenever I need to save something globally, and I still keep it out of the global namespace.

How to find all trigger associated with a table with SQL Server?

 select o1.name as trigger_name,o2.name as table_name from sys.objects o1 
 join sys.objects o2 on 
 o1.parent_object_id=o2.object_id     
 where o1.type='TR' 
 and o2.name='my_table'
 
  

Are HTTPS URLs encrypted?

Since nobody provided a wire capture, here's one.
Server Name (the domain part of the URL) is presented in the ClientHello packet, in plain text.

The following shows a browser request to:
https://i.stack.imgur.com/path/?some=parameters&go=here

ClientHello SNI See this answer for more on TLS version fields (there are 3 of them - not versions, fields that each contain a version number!)

From https://www.ietf.org/rfc/rfc3546.txt:

3.1. Server Name Indication

[TLS] does not provide a mechanism for a client to tell a server the name of the server it is contacting. It may be desirable for clients to provide this information to facilitate secure connections to servers that host multiple 'virtual' servers at a single underlying network address.

In order to provide the server name, clients MAY include an extension of type "server_name" in the (extended) client hello.


In short:

  • FQDN (the domain part of the URL) MAY be transmitted in clear inside the ClientHello packet if SNI extension is used

  • The rest of the URL (/path/?some=parameters&go=here) has no business being inside ClientHello since the request URL is a HTTP thing (OSI Layer 7), therefore it will never show up in a TLS handshake (Layer 4 or 5). That will come later on in a GET /path/?some=parameters&go=here HTTP/1.1 HTTP request, AFTER the secure TLS channel is established.


EXECUTIVE SUMMARY

Domain name MAY be transmitted in clear (if SNI extension is used in the TLS handshake) but URL (path and parameters) is always encrypted.


MARCH 2019 UPDATE

Thank you carlin.scott for bringing this one up.

The payload in the SNI extension can now be encrypted via this draft RFC proposal. This capability only exists in TLS 1.3 (as an option and it's up to both ends to implement it) and there is no backwards compatibility with TLS 1.2 and below.

CloudFlare is doing it and you can read more about the internals here — If the chicken must come before the egg, where do you put the chicken?

In practice this means that instead of transmitting the FQDN in plain text (like the Wireshark capture shows), it is now encrypted.

NOTE: This addresses the privacy aspect more than the security one since a reverse DNS lookup MAY reveal the intended destination host anyway.

SEPTEMBER 2020 UPDATE

There's now a draft RFC for encrypting the entire Client Hello message, not just the SNI part: https://datatracker.ietf.org/doc/draft-ietf-tls-esni/?include_text=1

At the time of writing this browser support is VERY limited.

React fetch data in server before render

What you're looking for is componentWillMount.

From the documentation:

Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

So you would do something like this:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},

This way, render() will only be called once, and you'll have the data you're looking for in the initial render.

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

How do you change the value inside of a textfield flutter?

You can use the text editing controller to manipulate the value inside a textfield.

var textController = new TextEditingController();

Now, create a new textfield and set textController as the controller for the textfield as shown below.

 new TextField(controller: textController)

Now, create a RaisedButton anywhere in your code and set the desired text in the onPressed method of the RaisedButton.

new RaisedButton(
       onPressed: () {
          textController.text = "New text";
       }
    ),

Postgres user does not exist?

psql: Logs me in with my default username

psql -U postgres: Logs me in as the postgres user

Sudo doesn't seem to be required for me.

I use Postgres.app for my OS X postgres database. It removed the headache of making sure the installation was working and the database server was launched properly. Check it out here: http://postgresapp.com

Edit: Credit to @Erwin Brandstetter for correcting my use of the arguments.

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

How to dismiss a Twitter Bootstrap popover by clicking outside?

With bootstrap 2.3.2 you can set the trigger to 'focus' and it just works:

$('#el').popover({trigger:'focus'});

Spring Boot Multiple Datasource

Use multiple datasource or realizing the separation of reading & writing. you must have a knowledge of Class AbstractRoutingDataSource which support dynamic datasource choose.

Here is my datasource.yaml and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.

dbServer:
  default: localhost:3306
  read: localhost:3306
  write: localhost:3306
datasource:
  default:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: default
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  read:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: read
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  write:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: write
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false

Is it acceptable and safe to run pip install under sudo?

Use a virtual environment:

$ virtualenv myenv
.. some output ..
$ source myenv/bin/activate
(myenv) $ pip install what-i-want

You only use sudo or elevated permissions when you want to install stuff for the global, system-wide Python installation.

It is best to use a virtual environment which isolates packages for you. That way you can play around without polluting the global python install.

As a bonus, virtualenv does not need elevated permissions.

C# 4.0 optional out/ref arguments

No.

A workaround is to overload with another method that doesn't have out / ref parameters, and which just calls your current method.

public bool SomeMethod(out string input)
{
    ...
}

// new overload
public bool SomeMethod()
{
    string temp;
    return SomeMethod(out temp);
}

If you have C# 7.0, you can simplify:

// new overload
public bool SomeMethod()
{
    return SomeMethod(out _);    // declare out as an inline discard variable
}

(Thanks @Oskar / @Reiner for pointing this out.)

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The system function requires const char *, and your expression is of the type std::string. You should write

string name = "john";
string system_str = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'";
system(system_str.c_str ());

SSIS how to set connection string dynamically from a config file

Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.

You can add Environment variable also in this process

How to implement "select all" check box in HTML?

You may have different sets of checkboxes on the same form. Here is a solution that selects/unselects checkboxes by class name, using vanilla javascript function document.getElementsByClassName

The Select All button

<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All

Some of the checkboxes to select

<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />

The javascript

    function selectAll() {
        var blnChecked = document.getElementById("select_all_invoices").checked;
        var check_invoices = document.getElementsByClassName("check_invoice");
        var intLength = check_invoices.length;
        for(var i = 0; i < intLength; i++) {
            var check_invoice = check_invoices[i];
            check_invoice.checked = blnChecked;
        }
    }

XPath to select multiple tags

You can avoid the repetition with an attribute test instead:

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self:: axis is namespace restrictive, local-name() is not. If the OP's intention is to capture c|d|e regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.

You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.

C-like structures in Python

Personally, I like this variant too. It extends @dF's answer.

class struct:
    def __init__(self, *sequential, **named):
        fields = dict(zip(sequential, [None]*len(sequential)), **named)
        self.__dict__.update(fields)
    def __repr__(self):
        return str(self.__dict__)

It supports two modes of initialization (that can be blended):

# Struct with field1, field2, field3 that are initialized to None.
mystruct1 = struct("field1", "field2", "field3") 
# Struct with field1, field2, field3 that are initialized according to arguments.
mystruct2 = struct(field1=1, field2=2, field3=3)

Also, it prints nicer:

print(mystruct2)
# Prints: {'field3': 3, 'field1': 1, 'field2': 2}

In C#, how to check if a TCP port is available?

From the avalaible ports i would exclude:

  • active TCP connections
  • active TCP listeners
  • active UDP listeners

With the following import:

using System.Net.NetworkInformation;

You can use the following function to check if a port is avalaible or not:

private bool isPortAvalaible(int myPort)
{
    var avalaiblePorts = new List<int>();
    var properties = IPGlobalProperties.GetIPGlobalProperties();

    // Active connections
    var connections = properties.GetActiveTcpConnections();
    avalaiblePorts.AddRange(connections);

    // Active tcp listners
    var endPointsTcp = properties.GetActiveTcpListeners();
    avalaiblePorts.AddRange(endPointsTcp);

    // Active udp listeners
    var endPointsUdp = properties.GetActiveUdpListeners();
    avalaiblePorts.AddRange(endPointsUdp);

    foreach (int p in avalaiblePorts){
        if (p == myPort) return false;
    }
    return true;
}

I give you a similar function for those who use VB.NET:

Imports System.Net.NetworkInformation
Private Function isPortAvalaible(ByVal myPort As Integer) As Boolean
  Dim props As IPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties()

  ' ignore active connections
  Dim tcpConnInfoArray() As TcpConnectionInformation = props.GetActiveTcpConnections()
  For Each tcpi As Net.NetworkInformation.TcpConnectionInformation In tcpConnInfoArray
    If tcpi.LocalEndPoint.Port = myPort Then
      Return False
    End If
  Next tcpi

  ' ignore active TCP listeners
  Dim activeTcpListeners() As Net.IPEndPoint = props.GetActiveTcpListeners
  For Each tcpListener As Net.IPEndPoint In activeTcpListeners
    If tcpListener.Port = myPort Then
      Return False
    End If
  Next tcpListener

  ' ignore active UPD listeners
  Dim activeUdpListeners() As Net.IPEndPoint = props.GetActiveUdpListeners
  For Each udpListener As Net.IPEndPoint In activeUdpListeners
    If udpListener.Port = myPort Then
      Return False
    End If
  Next udpListener

  Return True
End Function

Create two threads, one display odd & other even numbers

Pretty much all that is necessary if you are asked to print even odd numbers in synchronized manner.

public class ThreadingOddEvenNumbers {

    void main(String[] args) throws InterruptedException {
        Printer printer = new Printer(57);
        Thread t1 = new Thread(new MyRunner(printer, true), "EvenPrinter");
        Thread t2 = new Thread(new MyRunner(printer, false), "OddPrinter");
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }

}

class MyRunner implements Runnable {
    private Printer p;
    private boolean evenProperty;

    public MyRunner(Printer p, boolean evenNess) {
        this.p = p;
        evenProperty = evenNess;
    }

    public void run() {
        try {
            print();
        } catch (InterruptedException ex) {
            System.out.println(this.getClass().getName() + " "
                    + ex.getMessage());
        }
    }


    public void print() throws InterruptedException {
        while (!p.isJobComplete()) {
            synchronized (p) {
                if (evenProperty)
                    while (p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
                else
                    while (!p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
            }

            synchronized (p) {
                if (evenProperty)
                    p.printEven(Thread.currentThread().getName());
                else
                    p.printOdd(Thread.currentThread().getName());
                p.notifyAll();
                System.out.println("notify called: by: "
                        + Thread.currentThread().getName());
            }
        }
    }
}

class Printer {
    private volatile boolean evenPrinted;
    private volatile boolean jobComplete;
    private int limit;
    private int counter;

    public Printer(int lim) {
        limit = lim;
        counter = 1;
        evenPrinted = true;
        jobComplete = false;
    }

    public void printEven(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = true;
    }

    public void printOdd(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = false;
    }

    private void incrCounter() {
        counter++;
        if (counter >= limit)
            jobComplete = true;
    }

    public int getLimit() {
        return limit;
    }

    public boolean isEvenPrinted() {
        return evenPrinted;
    }

    public boolean isJobComplete() {
        return jobComplete;
    }
}

CSS: create white glow around image

late to the party here; however just wanted to add a bit of extra fun..

box-shadow: 0px 0px 5px rgba(0,0,0,.3);
padding:7px;

will give you a nice looking padded in image. The padding will give you a simulated white border (or whatever border you have set). the rgba is just allowing you to do an opicity on the particular color; 0,0,0 being black. You could just as easily use any other RGB color.

Hope this helps someone!

How to filter files when using scp to copy dir recursively?

I'd probably recommend using something like rsync for this due to its include and exclude flags, e.g:-

rsync -rav -e ssh --include '*/' --include='*.class' --exclude='*' \
server:/usr/some/unknown/number/of/sub/folders/ \ 
/usr/project/backup/some/unknown/number/of/sub/folders/

Some other useful flags:

  • -r for recursive
  • -a for archive (mostly all files)
  • -v for verbose output
  • -e to specify ssh instead of the default (which should be ssh, actually)

What is the best IDE for C Development / Why use Emacs over an IDE?

Netbeans has great C and C++ support. Some people complain that it's bloated and slow, but I've been using it almost exclusively for personal projects and love it. The code assistance feature is one of the best I've seen.

How to convert a date string to different format

If you can live with 01 for January instead of 1, then try...

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")

You can check the docs for other formatting directives.

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

clear javascript console in Google Chrome

On MacOS:

  1. Chrome - CMD+K
  2. Safari - CMD+K
  3. Firefox - No shortcut

On Linux:

  1. Chrome - CTRL+L
  2. Firefox - No shortcut

On Windows:

  1. Chrome - CTRL+L
  2. IE - CTRL+L
  3. Edge - CTRL+L
  4. Firefox - No shortcut

To make it work in Firefox, userscripts can be used. Download GreaseMonkey extension for FF.

document.addEventListener("keydown",function(event){
    if(event.metaKey && event.which==75) //CMD+K
    {
        console.clear();
    }
});

In the script, update the metadata with the value, //@include *://*/*, to make it run on every pages. It will work only when the focus is on the page. It's just a workaround.

How to change onClick handler dynamically?

Nobody addressed the actual problem which was happening, to explain why the alert was issued.

This code: document.getElementById("foo").click = new function() { alert('foo'); }; assigns the click property of the #foo element to an empty object. The anonymous function in here is meant to initialize the object. I like to think of this type of function as a constructor. You put the alert in there, so it gets called because the function gets called immediately.

See this question.

Quotation marks inside a string

You can add escaped double quotes like this: String name = "\"john\"";

Display PNG image as response to jQuery AJAX request

This allows you to just get the image data and set to the img src, which is cool.

var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );        
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
    var blob = oReq.response;
    var imgSrc = URL.createObjectURL( blob );                        
    var $img = $( '<img/>', {                
        "alt": "test image",
        "src": imgSrc
    } ).appendTo( $( '#bb_theImageContainer' ) );
    window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );

The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I faced this issue once, and I solved this by wrapping the LayoutManager and disabling predictive animations.

Here an example:

public class LinearLayoutManagerWrapper extends LinearLayoutManager {

  public LinearLayoutManagerWrapper(Context context) {
    super(context);
  }

  public LinearLayoutManagerWrapper(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
  }

  public LinearLayoutManagerWrapper(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
  }

  @Override
  public boolean supportsPredictiveItemAnimations() {
    return false;
  }
}

And set it to RecyclerView:

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManagerWrapper(context, LinearLayoutManager.VERTICAL, false);

Dynamically access object property using variable

You can achieve this in quite a few different ways.

let foo = {
    bar: 'Hello World'
};

foo.bar;
foo['bar'];

The bracket notation is specially powerful as it let's you access a property based on a variable:

let foo = {
    bar: 'Hello World'
};

let prop = 'bar';

foo[prop];

This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'
};

for (let prop in foo.getOwnPropertyNames()) {
    console.log(foo[prop]);
}

Both dot and bracket notation also work as expected for nested objects:

let foo = {
    bar: {
        baz: 'Hello World'
    }
};

foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;

Object destructuring

We could also consider object destructuring as a means to access a property in an object, but as follows:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'
};

let prop = 'last';
let { bar, baz, [prop]: customName } = foo;

// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'

Python def function: How do you specify the end of the function?

Interestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line. This does not work:

def foo(x):
  return x+1
print "last"

although it is perfectly legal python syntax in a file. There are other syntactic differences when typing to the interpreter too, so beware.

Change GridView row color based on condition

 protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl_Code = (Label)e.Row.FindControl("lblCode");
            if (lbl_Code.Text == "1")
            {
                e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#f2d9d9");
            }
        }
    }

Setting a WebRequest's body data

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

Creating a new ArrayList in Java

Fixed the code for you:

ArrayList<Class> myArray= new ArrayList<Class>();

Best way to restrict a text field to numbers only?

There is my current solution of numeric input, need to test in different browsers but seems to work

Support comma and period delimiter (czech native is comma), space and numpad/keyboard numbers input. Allow Ctrl+C Ctrl+A or Ctrl+X, arrow navigation and delete block Ctrl+V. React on escape key by blurring input.

Watch my Coffee script:

(($) ->
  $.fn.onlyNumbers = ->
    @each ->
      $(@).keydown (e) ->
        # get code of key
        code = if e.keyCode then e.keyCode else e.which

        return $(@).blur() if code is 27 # blur on escape
        return if code in [46, 8, 9, 13] # 46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
        return if (e.ctrlKey or e.metaKey) and code in [65, 67, 88] # ctrl|command + [a, c, x]
        return if code in [96..105] # numpad numbers
        return if code in [48..57] # numbers on keyboard
        return if code in [35..39] # 35..39 - home, end, left, right
        return if code in [188, 190, 32] # comma, period, space
        return if code in [44] # comma, period,

        e.returnValue = false # IE hate you
        e.preventDefault();

      $(@).keypress (e) ->
        code = if e.keyCode then e.keyCode else e.which
        return if code in [44, 46, 32] # comma, period, space
        return if code in [48..57] # numbers on keyboard
        e.returnValue = false # IE hate you
        e.preventDefault();

) jQuery

You can get compiled Javascript here http://goo.gl/SbyhXN

Limit length of characters in a regular expression?

If you want numbers from 1 up to 100:

100|[1-9]\d?

Java web start - Unable to load resource

If anyone else gets here because they're trying to set up a Jenkins slave, then you need to set the url of the host to the one it's actually using.

On the host, go to Manage Jenkins > Configure System and edit "Jenkins URL"

How do I get textual contents from BLOB in Oracle SQL

SQL Developer provides this functionality too :

Double click the results grid cell, and click edit :

enter image description here

Then on top-right part of the pop up , "View As Text" (You can even see images..)

enter image description here

And that's it!

enter image description here

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

There is now a new way of addressing this issue - if you remove position: relative from the container which needs to have the overflow-y visible, you can have overflow-y visible and overflow-x hidden, and vice versa (have overflow-x visible and overflow-y hidden, just make sure the container with the visible property is not relatively positioned).

See this post from CSS Tricks for more details - it worked for me: https://css-tricks.com/popping-hidden-overflow/

How do I get the title of the current active window using c#?

If it happens that you need the Current Active Form from your MDI application: (MDI- Multi Document Interface).

Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;

Detecting IE11 using CSS Capability/Feature Detection

I ran into the same problem with a Gravity Form (WordPress) in IE11. The form's column style "display: inline-grid" broke the layout; applying the answers above resolved the discrepancy!

@media all and (-ms-high-contrast:none){
  *::-ms-backdrop, .gfmc-column { display: inline-block;} /* IE11 */
}

ggplot2 legend to bottom and horizontal

Here is how to create the desired outcome:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
  theme(legend.position="bottom",
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

Created on 2019-12-07 by the reprex package (v0.3.0)


Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

fastest MD5 Implementation in JavaScript

Currently the fastest implementation of md5 (based on Joseph Myers' code):

https://github.com/iReal/FastMD5

jsPerf comparaison: http://jsperf.com/md5-shootout/63

What is the difference between java and core java?

Java has mainly three sub categories :

  1. Java Standard Edition (JSE) or Core Java
  2. Java Enterprise Edition (JEE)
  3. Java Mobile Edition (JME)

where core java is the first and basic step of all to start or learn java from beginning.

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

Creating a .dll file in C#.Net

To create a DLL File, click on New project, then select Class Library.

Enter your code into the class file that was automatically created for you and then click Build Solution from the Debug menu.

Now, look in your directory: ../debug/release/YOURDLL.dll

There it is! :)

P.S. DLL files cannot be run just like normal applciation (exe) files. You'll need to create a separate project (probably a win forms app) and then add your dll file to that project as a "Reference", you can do this by going to the Solution explorer, right clicking your project Name and selecting Add Reference then browsing to whereever you saved your dll file.

For more detail please click HERE

Multi-dimensional associative arrays in JavaScript

Javascript is flexible:

var arr = {
  "fred": {"apple": 2, "orange": 4},
  "mary": {}
  //etc, etc
};

alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
    alert(key + ": " + arr.fred[key]);

Entity Framework rollback and remove bad migration

For those using EF Core with ASP.NET Core v1.0.0 I had a similar problem and used the following commands to correct it (@DavidSopko's post pointed me in the right direction, but the details are slightly different for EF Core):

Update-Database <Name of last good migration>
Remove-Migration

For example, in my current development the command became

PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM> 

The Remove-Migration will remove the last migration you applied. If you have a more complex scenario with multiple migrations to remove (I only had 2, the initial and the bad one), I suggest you test the steps in a dummy project.

There doesn't currently appear to be a Get-Migrations command in EF Core (v1.0.0) so you must look in your migrations folder and be familiar with what you have done. However, there is a nice help command:

PM> get-help entityframework

Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)

Initially I tried Remove-Migration by itself and found the error command confusing:

System.InvalidOperationException: The migration '...' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.

There are already suggestions on improving this wording, but I'd like the error to say something like this:

Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will unapply all migrations that occurred after the migration specified to Update-Database. You may then run Remove-Migration (migration name to remove)

Output from the EF Core help command follows:

 PM> get-help entityframework
                     _/\__
               ---==/    \\
         ___  ___   |.    \|\
        | __|| __|  |  )   \\\
        | _| | _|   \_/ |  //|\\
        |___||_|       /   \\\/\\

TOPIC
    about_EntityFrameworkCore

SHORT DESCRIPTION
    Provides information about Entity Framework Core commands.

LONG DESCRIPTION
    This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.

    The following Entity Framework cmdlets are included.

        Cmdlet                      Description
        --------------------------  ---------------------------------------------------
        Add-Migration               Adds a new migration.

        Remove-Migration            Removes the last migration.

        Scaffold-DbContext          Scaffolds a DbContext and entity type classes for a specified database.

        Script-Migration            Generates a SQL script from migrations.

        Update-Database             Updates the database to a specified migration.

        Use-DbContext               Sets the default DbContext to use.

SEE ALSO
    Add-Migration
    Remove-Migration
    Scaffold-DbContext
    Script-Migration
    Update-Database
    Use-DbContext

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

disable textbox using jquery?

I'm not sure why some of these solutions use .each() - it's not necessary.

Here's some working code that disables if the 3rd checkbox is clicked, otherwise is removes the disabled attribute.

Note: I added an id to the checkbox. Also, remember that ids must be unique in your document, so either remove the ids on the radiobuttons, or make them unique

$("input:radio[name='userradiobtn']").click(function() {
    var isDisabled = $(this).is(":checked") && $(this).val() == "3";
    $("#chkbox").attr("disabled", isDisabled);
    $("#usertxtbox").attr("disabled", isDisabled);
});

How to detect DataGridView CheckBox event change?

In the event CellContentClick you can use this strategy:

private void myDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{    
    if (e.ColumnIndex == 2)//set your checkbox column index instead of 2
    {   //When you check
        if (Convert.ToBoolean(myDataGrid.Rows[e.RowIndex].Cells[2].EditedFormattedValue) == true)
        {
            //EXAMPLE OF OTHER CODE
            myDataGrid.Rows[e.RowIndex].Cells[5].Value = DateTime.Now.ToShortDateString();

            //SET BY CODE THE CHECK BOX
            myDataGrid.Rows[e.RowIndex].Cells[2].Value = 1;
        }
        else //When you decheck
        {
            myDataGrid.Rows[e.RowIndex].Cells[5].Value = String.Empty;

            //SET BY CODE THE CHECK BOX
            myDataGrid.Rows[e.RowIndex].Cells[2].Value = 0;
        }
    }
}

How can I make a link from a <td> table cell

You can creat the table you want, save it as an image and then use an image map to creat the link (this way you can put the coords of the hole td to make it in to a link).

How to read XML response from a URL in java?

If you specifically want to use SwingX-WS, then have a look at XmlHttpRequest and JSONHttpRequest.

More on those classes in the XMLHttpRequest and Swing blog post.

How do you run a script on login in *nix?

The script ~/.bash_profile is run on login.

how to add <script>alert('test');</script> inside a text box?

I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).

<input type="text" value="<script>alert('test');</script>" />

Produces:

enter image description here

You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value attribute.

var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

no module named zlib

By default when you configuring Python source, zlib module is disabled, so you can enable it using option --with-zlib when you configure it. So it becomes

./configure --with-zlib

How can I get the full/absolute URL (with domain) in Django?

You can either pass request reverse('view-name', request=request) or enclose reverse() with build_absolute_uri request.build_absolute_uri(reverse('view-name'))

How to convert a GUID to a string in C#?

Did you write

String guid = System.Guid.NewGuid().ToString;

or

String guid = System.Guid.NewGuid().ToString();

notice the paranthesis

nil detection in Go

I have created some sample code which creates new variables using a variety of ways that I can think of. It looks like the first 3 ways create values, and the last two create references.

package main

import "fmt"

type Config struct {
    host string
    port float64
}

func main() {
    //value
    var c1 Config
    c2 := Config{}
    c3 := *new(Config)

    //reference
    c4 := &Config{}
    c5 := new(Config)

    fmt.Println(&c1 == nil)
    fmt.Println(&c2 == nil)
    fmt.Println(&c3 == nil)
    fmt.Println(c4 == nil)
    fmt.Println(c5 == nil)

    fmt.Println(c1, c2, c3, c4, c5)
}

which outputs:

false
false
false
false
false
{ 0} { 0} { 0} &{ 0} &{ 0}

Unbound classpath container in Eclipse

To fix this:

  • Right click your project –> Build Path –>Configure Build Path
  • Select JRE Library and click Edit and from Edit library window choose alternate JRE whatever been configured with your eclipse then click Finish

Updating GUI (WPF) using a different thread

As akjoshi and Julio say this is about dispatching an Action to update the GUI on the same thread as the GUI item but from the method that is handling the background data. You can see this code in specific form in akjoshi's answer above. This is a general version.

myTextBlock.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                   new Action(delegate() 
                                      {
                                      myTextBlock.Text = Convert.ToString(myDataObject.getMeData());
                                      }));

The critical part is to call the dispatcher of your UI object - that ensures you have the correct thread.

From personal experience it seems much easier to create and use the Action inline like this. Declaring it at class level gave me lots of problems with static/non-static contexts.

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

How to serve static files in Flask

The URL for a static file can be created using the static endpoint as following:

url_for('static', filename = 'name_of_file')
<link rel="stylesheet" href="{{url_for('static', filename='borders.css')}}" />

How to execute Python code from within Visual Studio Code

There is a lot of confusion around Visual Studio Code tasks and the debugger. Let's discuss about it first so that we understand when to use tasks and when to use the debugger.

Tasks

The official documentation says -

Lots of tools exist to automate tasks like linting, building, packaging, testing, or deploying software systems. Examples include the TypeScript Compiler, linters like ESLint and TSLint as well as build systems like Make, Ant, Gulp, Jake, Rake, and MSBuild.

.... Tasks in VS Code can be configured to run scripts and start processes so that many of these existing tools can be used from within VS Code without having to enter a command line or write new code.

So, tasks are not for debugging, compiling or executing our programs.

Debugger

If we check the debugger documentation, we will find there is something called run mode. It says -

In addition to debugging a program, VS Code supports running the program. The Debug: Start Without Debugging action is triggered with Ctrl+F5 and uses the currently selected launch configuration. Many of the launch configuration attributes are supported in 'Run' mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.

So, press F5 and Visual Studio Code will try to debug your currently active file.

Press Ctrl + F5 and Visual Studio Code will ignore your breakpoints and run the code.

Configuring the debugger

To configure the debugger, go through the documentation. In summary it says, you should modify the launch.json file. For starters, to run the code in integrated terminal (inside Visual Studio Code), use -

{
    "name": "Python: Current File (Integrated Terminal)",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal"
}

To run the code in an external terminal (outside of Visual Studio Code), use -

{
    "name": "Python: Current File (External Terminal)",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "externalTerminal"
}

N.B. If all documentation was easy to search and understand then we probably would not need Stack Overflow. Fortunately, the documentation I mentioned in this post is really easy to understand. Please feel free to read, ponder and enjoy.

Why cannot change checkbox color whatever I do?

Although the question is answered and is older, In exploring some options to overcome the the styling of check boxes issue I encountered this awesome set of CSS3 only styling of check boxes and radio buttons controlling background colors and other appearances. Thought this might be right up the alley of this question.

JSFiddle

_x000D_
_x000D_
body {_x000D_
    background: #555;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
    color: #eee;_x000D_
    font: 30px Arial, sans-serif;_x000D_
    -webkit-font-smoothing: antialiased;_x000D_
    text-shadow: 0px 1px black;_x000D_
    text-align: center;_x000D_
    margin-bottom: 50px;_x000D_
}_x000D_
_x000D_
input[type=checkbox] {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
/* SLIDE ONE */_x000D_
.slideOne {_x000D_
    width: 50px;_x000D_
    height: 10px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideOne label {_x000D_
    display: block;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: -3px;_x000D_
    left: -3px;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideOne input[type=checkbox]:checked + label {_x000D_
    left: 37px;_x000D_
}_x000D_
_x000D_
/* SLIDE TWO */_x000D_
.slideTwo {_x000D_
    width: 80px;_x000D_
    height: 30px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideTwo:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 14px;_x000D_
    left: 14px;_x000D_
    height: 2px;_x000D_
    width: 52px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    background: #111;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideTwo label {_x000D_
    display: block;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: 4px;_x000D_
    z-index: 1;_x000D_
    left: 4px;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideTwo label:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 10px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    background: #333;_x000D_
    left: 6px;_x000D_
    top: 6px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9);_x000D_
}_x000D_
_x000D_
.slideTwo input[type=checkbox]:checked + label {_x000D_
    left: 54px;_x000D_
}_x000D_
_x000D_
.slideTwo input[type=checkbox]:checked + label:after {_x000D_
    background: #00bf00;_x000D_
}_x000D_
_x000D_
/* SLIDE THREE */_x000D_
.slideThree {_x000D_
    width: 80px;_x000D_
    height: 26px;_x000D_
    background: #333;_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    position: relative;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);_x000D_
}_x000D_
_x000D_
.slideThree:after {_x000D_
    content: 'OFF';_x000D_
    font: 12px/26px Arial, sans-serif;_x000D_
    color: #000;_x000D_
    position: absolute;_x000D_
    right: 10px;_x000D_
    z-index: 0;_x000D_
    font-weight: bold;_x000D_
    text-shadow: 1px 1px 0px rgba(255,255,255,.15);_x000D_
}_x000D_
_x000D_
.slideThree:before {_x000D_
    content: 'ON';_x000D_
    font: 12px/26px Arial, sans-serif;_x000D_
    color: #00bf00;_x000D_
    position: absolute;_x000D_
    left: 10px;_x000D_
    z-index: 0;_x000D_
    font-weight: bold;_x000D_
}_x000D_
_x000D_
.slideThree label {_x000D_
    display: block;_x000D_
    width: 34px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-transition: all .4s ease;_x000D_
    -moz-transition: all .4s ease;_x000D_
    -o-transition: all .4s ease;_x000D_
    -ms-transition: all .4s ease;_x000D_
    transition: all .4s ease;_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    top: 3px;_x000D_
    left: 3px;_x000D_
    z-index: 1;_x000D_
_x000D_
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.slideThree input[type=checkbox]:checked + label {_x000D_
    left: 43px;_x000D_
}_x000D_
_x000D_
/* ROUNDED ONE */_x000D_
.roundedOne {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.roundedOne label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.roundedOne label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
    background: #00bf00;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -moz-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -o-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -ms-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    top: 2px;_x000D_
    left: 2px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.roundedOne label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.roundedOne input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* ROUNDED TWO */_x000D_
.roundedTwo {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.roundedTwo label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
_x000D_
    -webkit-border-radius: 50px;_x000D_
    -moz-border-radius: 50px;_x000D_
    border-radius: 50px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.roundedTwo label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 5px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.roundedTwo label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.roundedTwo input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED ONE */_x000D_
.squaredOne {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredOne label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredOne label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 16px;_x000D_
    height: 16px;_x000D_
    background: #00bf00;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -moz-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -o-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: -ms-linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
    background: linear-gradient(top, #00bf00 0%, #009400 100%);_x000D_
_x000D_
    top: 2px;_x000D_
    left: 2px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.squaredOne label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredOne input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED TWO */_x000D_
.squaredTwo {_x000D_
    width: 28px;_x000D_
    height: 28px;_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
    margin: 20px auto;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredTwo label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    left: 4px;_x000D_
    top: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,1);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredTwo label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredTwo label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredTwo input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
_x000D_
/* SQUARED THREE */_x000D_
.squaredThree {_x000D_
    width: 20px;    _x000D_
    margin: 20px auto;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredThree label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    top: 0;_x000D_
    border-radius: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,.4);_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -moz-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -o-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: -ms-linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    background: linear-gradient(top, #222 0%, #45484d 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222', endColorstr='#45484d',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredThree label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #fcfff4;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredThree label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.squaredThree input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
/* SQUARED FOUR */_x000D_
.squaredFour {_x000D_
    width: 20px;    _x000D_
    margin: 20px auto;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.squaredFour label {_x000D_
    cursor: pointer;_x000D_
    position: absolute;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    top: 0;_x000D_
    border-radius: 4px;_x000D_
_x000D_
    -webkit-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    -moz-box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    box-shadow: inset 0px 1px 1px white, 0px 1px 3px rgba(0,0,0,0.5);_x000D_
    background: #fcfff4;_x000D_
_x000D_
    background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );_x000D_
}_x000D_
_x000D_
.squaredFour label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
    filter: alpha(opacity=0);_x000D_
    opacity: 0;_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width: 9px;_x000D_
    height: 5px;_x000D_
    background: transparent;_x000D_
    top: 4px;_x000D_
    left: 4px;_x000D_
    border: 3px solid #333;_x000D_
    border-top: none;_x000D_
    border-right: none;_x000D_
_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.squaredFour label:hover::after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";_x000D_
    filter: alpha(opacity=30);_x000D_
    opacity: 0.5;_x000D_
}_x000D_
_x000D_
.squaredFour input[type=checkbox]:checked + label:after {_x000D_
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";_x000D_
    filter: alpha(opacity=100);_x000D_
    opacity: 1;_x000D_
}
_x000D_
<h1>CSS3 Checkbox Styles</h1>_x000D_
_x000D_
<!-- Slide ONE -->_x000D_
<div class="slideOne">  _x000D_
    <input type="checkbox" value="None" id="slideOne" name="check" />_x000D_
    <label for="slideOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Slide TWO -->_x000D_
<div class="slideTwo">  _x000D_
    <input type="checkbox" value="None" id="slideTwo" name="check" />_x000D_
    <label for="slideTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Slide THREE -->_x000D_
<div class="slideThree">    _x000D_
    <input type="checkbox" value="None" id="slideThree" name="check" />_x000D_
    <label for="slideThree"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Rounded ONE -->_x000D_
<div class="roundedOne">_x000D_
    <input type="checkbox" value="None" id="roundedOne" name="check" />_x000D_
    <label for="roundedOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Rounded TWO -->_x000D_
<div class="roundedTwo">_x000D_
    <input type="checkbox" value="None" id="roundedTwo" name="check" />_x000D_
    <label for="roundedTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared ONE -->_x000D_
<div class="squaredOne">_x000D_
    <input type="checkbox" value="None" id="squaredOne" name="check" />_x000D_
    <label for="squaredOne"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared TWO -->_x000D_
<div class="squaredTwo">_x000D_
    <input type="checkbox" value="None" id="squaredTwo" name="check" />_x000D_
    <label for="squaredTwo"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared THREE -->_x000D_
<div class="squaredThree">_x000D_
    <input type="checkbox" value="None" id="squaredThree" name="check" />_x000D_
    <label for="squaredThree"></label>_x000D_
</div>_x000D_
_x000D_
<!-- Squared FOUR -->_x000D_
<div class="squaredFour">_x000D_
    <input type="checkbox" value="None" id="squaredFour" name="check" />_x000D_
    <label for="squaredFour"></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Equivalent of LIMIT for DB2

Using FETCH FIRST [n] ROWS ONLY:

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.perf/db2z_fetchfirstnrows.htm

SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY
  FROM EMP
  ORDER BY SALARY DESC
  FETCH FIRST 20 ROWS ONLY;

To get ranges, you'd have to use ROW_NUMBER() (since v5r4) and use that within the WHERE clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)

SELECT code, name, address
FROM ( 
  SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
  FROM contacts
  WHERE name LIKE '%Bob%' 
  ) AS t
WHERE t.rid BETWEEN 20 AND 25;

ToggleButton in C# WinForms

use if command to check status and let operate as a toggle button

private void Protection_ON_OFF_Button_Click(object sender, EventArgs e)
        {

            if (FolderAddButton.Enabled == true)
            {
                FolderAddButton.Enabled = false;
            }
            else
            {
                FolderAddButton.Enabled = true;
            }
        }

Reading Email using Pop3 in C#

I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

Perhaps this is happening because, even if Tesseract is correctly installed, you have not installed your language, as was my case. Fortunately this is very easy to fix, and I did not even need to mess with tesseract_cmd.

sudo apt-get install tesseract-ocr -y
sudo apt-get install tesseract-ocr-spa -y
tesseract --list-langs

Note that in the second line we have specified -spa for Spanish.

If installation has been successful, you should get a list of your available languages, like:

List of available languages (3):
eng
osd
spa

I found this at this blog post (Spanish). There is also a post for installation of Spanish language in Windows (not as easy apparently).

Note: since the question uses lang = 'eng', it is likely this is not the answer in that specific case. But the same error may happen in this other situation, which is why I posted the answer here.

CSS Flex Box Layout: full-width row and columns

You've almost done it. However setting flex: 0 0 <basis> declaration to the columns would prevent them from growing/shrinking; And the <basis> parameter would define the width of columns.

In addition, you could use CSS3 calc() expression to specify the height of columns with the respect to the height of the header.

#productShowcaseTitle {
  flex: 0 0 100%; /* Let it fill the entire space horizontally */
  height: 100px;
}

#productShowcaseDetail,
#productShowcaseThumbnailContainer {
  height: calc(100% - 100px); /* excluding the height of the header */
}

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 0 0 34%;  /* ~ 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
  <div id="productShowcaseDetail"></div>_x000D_
  <div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)


Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div> element, it would be achieved without using calc() as follows:

<div class="contentContainer"> <!-- Added wrapper -->
    <div id="productShowcaseDetail"></div>
    <div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
  display: flex;
  flex-direction: column;
  height: 600px; width: 580px;
}

.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 3;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
_x000D_
  <div class="contentContainer"> <!-- Added wrapper -->_x000D_
    <div id="productShowcaseDetail"></div>_x000D_
    <div id="productShowcaseThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)

Removing "bullets" from unordered list <ul>

In your css file add following.

ul{
 list-style-type: none;
}

Generating sql insert into for Oracle

You can do that in PL/SQL Developer v10.
1. Click on Table that you want to generate script for.
2. Click Export data.
3. Check if table is selected that you want to export data for.
4. Click on SQL inserts tab.
5. Add where clause if you don't need the whole table.
6. Select file where you will find your SQL script.
7. Click export.
enter image description here

How to read pickle file?

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break

Query to select data between two dates with the format m/d/yyyy

you have to split the datetime and then store it with your desired format like dd/MM/yyyy. then you can use this query with between but i have objection using this becasue it will search every single data on your database,so i suggest you can use datediff.

        Dim start = txtstartdate.Text.Trim()
        Dim endday = txtenddate.Text.Trim()
        Dim arr()
        arr = Split(start, "/")
        Dim dt As New DateTime
        dt = New Date(Val(arr(2).ToString), Val(arr(1).ToString), Val(arr(0).ToString))
        Dim arry()
        arry = Split(endday, "/")
        Dim dt2 As New DateTime
        dt2 = New Date(Val(arry(2).ToString), Val(arry(1).ToString), Val(arry(0).ToString))

        qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "

here i have used dd/MM/yyyy format.

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Change the URL in the browser without loading the new page using JavaScript

my code is:

//change address bar
function setLocation(curLoc){
    try {
        history.pushState(null, null, curLoc);
        return false;
    } catch(e) {}
        location.hash = '#' + curLoc;
}

and action:

setLocation('http://example.com/your-url-here');

and example

$(document).ready(function(){
    $('nav li a').on('click', function(){
        if($(this).hasClass('active')) {

        } else {
            setLocation($(this).attr('href'));
        }
            return false;
    });
});

That's all :)

Open File in Another Directory (Python)

Its a very old question but I think it will help newbies line me who are learning python. If you have Python 3.4 or above, the pathlib library comes with the default distribution.

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest. To indicate that the path is a raw string, put r in front of the string with your actual path.

For example,

from pathlib import Path

dataFolder = Path(r'D:\Desktop dump\example.txt')

Source: The easy way to deal with file paths on Windows, Mac and Linux

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

How to zoom in/out an UIImage object when user pinches screen?

Keep in mind that you're NEVER zooming in on a UIImage. EVER.

Instead, you're zooming in and out on the view that displays the UIImage.

In this particular case, you chould choose to create a custom UIView with custom drawing to display the image, a UIImageView which displays the image for you, or a UIWebView which will need some additional HTML to back it up.

In all cases, you'll need to implement touchesBegan, touchesMoved, and the like to determine what the user is trying to do (zoom, pan, etc.).

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

As said, JsonMappingException: out of START_ARRAY token exception is thrown by Jackson object mapper as it's expecting an Object {} whereas it found an Array [{}] in response.

A simpler solution could be replacing the method getLocations with:

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeReference<List<Location>> typeReference = new TypeReference<>() {};
        return objectMapper.readValue(inputStream, typeReference);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

On the other hand, if you don't have a pojo like Location, you could use:

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);

How to get index of an item in java.util.Set

How about add the strings to a hashtable where the value is an index:

  Hashtable<String, Integer> itemIndex = new Hashtable<>();
  itemIndex.put("First String",1);
  itemIndex.put("Second String",2);
  itemIndex.put("Third String",3);

  int indexOfThirdString = itemIndex.get("Third String");

How To Set A JS object property name from a variable

You'll have to use [] notation to set keys dynamically.

var jsonVariable = {};
for(i=1; i<3; i++) {        
 var jsonKey  = i+'name';
 jsonVariable[jsonKey] = 'name1';

}

Now in ES6 you can use object literal syntax to create object keys dynamically, just wrap the variable in []

var key  = i + 'name';
data = {
    [key] : 'name1',
}

Python String and Integer concatenation

If we want output like 'string0123456789' then we can use map function and join method of string.

>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'

If we want List of string values then use list comprehension method.

>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']

Note:

Use xrange() for Python 2.x

USe range() for Python 3.x

Take nth column in a text file

One more simple variant -

$ while read line
  do
      set $line          # assigns words in line to positional parameters
      echo "$3 $5"
  done < file

Pass data to layout that are common to all pages

instead of going through this you can always use another approach which is also fast

create a new partial view in the Shared Directory and call your partial view in your layout as

@Html.Partial("MyPartialView")

in your partial view you can call your db and perform what ever you want to do

@{
    IEnumerable<HOXAT.Models.CourseCategory> categories = new HOXAT.Models.HOXATEntities().CourseCategories;
}

<div>
//do what ever here
</div>

assuming you have added your Entity Framework Database

Why do we use __init__ in Python classes?

The __init__ function is setting up all the member variables in the class. So once your bicluster is created you can access the member and get a value back:

mycluster = bicluster(...actual values go here...)
mycluster.left # returns the value passed in as 'left'

Check out the Python Docs for some info. You'll want to pick up an book on OO concepts to continue learning.

How to access a mobile's camera from a web app?

AppMobi HTML5 SDK once promised access to native device functionality - including the camera - from an HTML5-based app, but is no longer Google-owned. Instead, try the HTML5-based answers in this post.

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

At a guess, you're initialising something before your initialize function: var directionsService = new google.maps.DirectionsService();

Move that into the function, so it won't try and execute it before the page is loaded.

var directionsDisplay, directionsService;
var map;
function initialize() {
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();

How can I clear or empty a StringBuilder?

You should use sb.delete(0, sb.length()) or sb.setLength(0) and NOT create a new StringBuilder().

See this related post for performance: Is it better to reuse a StringBuilder in a loop?

MySQL how to join tables on two fields

JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date)

Swift extract regex matches

My answer builds on top of given answers but makes regex matching more robust by adding additional support:

  • Returns not only matches but returns also all capturing groups for each match (see examples below)
  • Instead of returning an empty array, this solution supports optional matches
  • Avoids do/catch by not printing to the console and makes use of the guard construct
  • Adds matchingStrings as an extension to String

Swift 4.2

//: Playground - noun: a place where people can play

import Foundation

extension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = self as NSString
        let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map {
                result.range(at: $0).location != NSNotFound
                    ? nsString.substring(with: result.range(at: $0))
                    : ""
            }
        }
    }
}

"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")
// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]

"prefix12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["prefix12", "12"]]

"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here

// Safely accessing the capture of the first match (if any):
let number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]
// Prints: Optional("12")

Swift 3

//: Playground - noun: a place where people can play

import Foundation

extension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = self as NSString
        let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map {
                result.rangeAt($0).location != NSNotFound
                    ? nsString.substring(with: result.rangeAt($0))
                    : ""
            }
        }
    }
}

"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")
// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]

"prefix12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["prefix12", "12"]]

"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here

// Safely accessing the capture of the first match (if any):
let number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]
// Prints: Optional("12")

Swift 2

extension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = self as NSString
        let results  = regex.matchesInString(self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map {
                result.rangeAtIndex($0).location != NSNotFound
                    ? nsString.substringWithRange(result.rangeAtIndex($0))
                    : ""
            }
        }
    }
}

Can I install the "app store" in an IOS simulator?

You can install other builds but not Appstore build.

From Xcode 8.2,drag and drop the build to simulator for the installation.

https://stackoverflow.com/a/41671233/1522584

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.

I would suggest try using DBWeaver from here :

https://dbeaver.io/download/

I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.

ER Diagram using the Community Version Db Viewer

How to show code but hide output in RMarkdown?

As @ J_F answered in the comments, using {r echo = T, results = 'hide'}.

I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!

You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.

Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
                      results = "hide")
```

Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.

```{r analysis, results="markup"}
# code here
```

Find and Replace text in the entire table using a MySQL query

Running an SQL query in PHPmyadmin to find and replace text in all wordpress blog posts, such as finding mysite.com/wordpress and replacing that with mysite.com/news Table in this example is tj_posts

UPDATE `tj_posts`
SET `post_content` = replace(post_content, 'mysite.com/wordpress', 'mysite.com/news')

Difference between "git add -A" and "git add ."

The -A option adds, modifies, and removes index entries to match the working tree.

In Git 2 the -A option is now the default.

When a . is added that limits the scope of the update to the directory you are currently in, as per the Git documentation

If no <pathspec> is given when -A option is used, all files in the entire working tree are updated (old versions of Git used to limit the update to the current directory and its subdirectories).

One thing that I would add is that if the --interactive or -p mode is used then git add will behave as if the update (-u) flag was used and not add new files.

SQLiteDatabase.query method

tableColumns

  • null for all columns as in SELECT * FROM ...
  • new String[] { "column1", "column2", ... } for specific columns as in SELECT column1, column2 FROM ... - you can also put complex expressions here:
    new String[] { "(SELECT max(column1) FROM table1) AS max" } would give you a column named max holding the max value of column1

whereClause

  • the part you put after WHERE without that keyword, e.g. "column1 > 5"
  • should include ? for things that are dynamic, e.g. "column1=?" -> see whereArgs

whereArgs

  • specify the content that fills each ? in whereClause in the order they appear

the others

  • just like whereClause the statement after the keyword or null if you don't use it.

Example

String[] tableColumns = new String[] {
    "column1",
    "(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
    "value1",
    "value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
        null, null, orderBy);

// since we have a named column we can do
int idx = c.getColumnIndex("max");

is equivalent to the following raw query

String queryString =
    "SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
    "WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);

By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '.

Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";

because if value contains a ' your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--" might even drop your table since the statement would become two statements and a comment:

SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'

using the args version XYZ'; DROP TABLE table1;-- would be escaped to 'XYZ''; DROP TABLE table1;--' and would only be treated as a value. Even if the ' is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int and other primitives directly into whereClause though)

How to trigger a build only if changes happen on particular set of files

Basically, you need two jobs. One to check whether files changed and one to do the actual build:

Job #1

This should be triggered on changes in your Git repository. It then tests whether the path you specify ("src" here) has changes and then uses Jenkins' CLI to trigger a second job.

export JENKINS_CLI="java -jar /var/run/jenkins/war/WEB-INF/jenkins-cli.jar"
export JENKINS_URL=http://localhost:8080/
export GIT_REVISION=`git rev-parse HEAD`
export STATUSFILE=$WORKSPACE/status_$BUILD_ID.txt

# Figure out, whether "src" has changed in the last commit
git diff-tree --name-only HEAD | grep src

# Exit with success if it didn't
$? || exit 0

# Trigger second job
$JENKINS_CLI build job2 -p GIT_REVISION=$GIT_REVISION -s

Job #2

Configure this job to take a parameter GIT_REVISION like so, to make sure you're building exactly the revision the first job chose to build.

Parameterized build string parameter Parameterized build Git checkout

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

Best XML parser for Java

If you care less about performance, I'm a big fan of Apache Digester, since it essentially lets you map directly from XML to Java Beans.

Otherwise, you have to first parse, and then construct your objects.

Recommended website resolution (width and height)?

Try to target 1024 as the minimum width. Try how it looks at 800, but don't bother too much making that work. At 800x600 almost none of the major websites are going to work, so people working at that resolution are going to have problems all the time anyway.

If you're going to go for a liquid layout, make sure that text doesn't get too wide, because when lines are too long, they become hard to read. That's the main reason why most websites have a fixed width.

How to force child div to be 100% of parent div's height without specifying parent's height?

There is a bit of a contradiction in the question's title and the content. The title speaks of a parent div, but the question makes it sound like you want two sibling divs (navigation and content) to be the same height.

Do you (a) want both navigation and content to be 100% the height of main, or (b) want navigation and content to be be same height?

I'll assume (b)...if that is so, I don't think you will be able to do it given your current page structure (at least, not with pure CSS and no scripting). You would probably need to do something like:

<main div>
    <content div>
         <navigation div></div>
    </div>
</div>

and set the content div to have a left margin of whatever the width of the navigation pane is. That way, the content's content is to the right of the navigation and you can set the navigation div to be 100% of the content's height.

EDIT: I'm doing this completely in my head, but you would probably also need to set the navigation div's left margin to a negative value or set it's absolute left to 0 to shove it back to the far left. Problem is, there are many ways to pull this off but not all of them are going to be compatible with all browsers.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

One difference is that:

  • :map does nvo == normal + (visual + select) + operator pending
  • :map! does ic == insert + command-line mode

as stated on help map-modes tables.

So: map does not map to all modes.

To map to all modes you need both :map and :map!.

MySQL query to select events between start/end date

EDIT: I've squeezed the filter a lot. I couldn't wrap my head around it before how to make sure something really fit within the time period. It's this: Start date BEFORE the END of the time period, and End date AFTER the BEGINNING of the time period

With the help of someone in my office I think we've figured out how to include everyone in the filter. There are 5 scenarios where a student would be deemed active during the time period in question:

1) Student started and ended during the time period.

2) Student started before and ended during the time period.

3) Student started before and ended after the time period.

4) Student started during the time period and ended after the time period.

5) Student started during the time period and is still active (Doesn't have an end date yet)

Given these criteria, we can actually condense the statements into a few groups because a student can only end between the period dates, after the period date, or they don't have an end date:

1) Student ends during the time period AND [Student starts before OR during]

2) Student ends after the time period AND [Student starts before OR during]

3) Student hasn't finished yet AND [Student starts before OR during]

   (
        (
         student_programs.END_DATE  >=  '07/01/2017 00:0:0'
         OR
         student_programs.END_DATE  Is Null  
        )
        AND
        student_programs.START_DATE  <=  '06/30/2018 23:59:59'
   )

I think this finally covers all the bases and includes all scenarios where a student, or event, or anything is active during a time period when you only have start date and end date. Please, do not hesitate to tell me that I am missing something. I want this to be perfect so others can use this, as I don't believe the other answers have gotten everything right yet.

Scripting Language vs Programming Language

If we see logically programming language and scripting language so this is 99.09% same . because we use same concept like loop , control condition ,variable and all so we can say yes both are same but there is only one thing is different between them that is in C/C++ and other programming language we compile the code before execution . but in the PHP , JavaScript and other scripting language we don't need to compile we directly execute in the browser.

Thanks Nitish K. Jha

return SQL table as JSON in python

I would supplement The Demz answer with the psycopg2 version:

import psycopg2 
import psycopg2.extras
import json
connection = psycopg2.connect(dbname=_cdatabase, host=_chost, port=_cport , user=_cuser, password=_cpassword)
cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) # This line allows dictionary access.
#select some records into "rows"
jsonout= json.dumps([dict(ix) for ix in rows])

How can I extract all values from a dictionary in Python?

For nested dicts, lists of dicts, and dicts of listed dicts, ... you can use

def get_all_values(d):
    if isinstance(d, dict):
        for v in d.values():
            yield from get_all_values(v)
    elif isinstance(d, list):
        for v in d:
            yield from get_all_values(v)
    else:
        yield d 

An example:

d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': 6}]}

list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6]

PS: I love yield. ;-)

Bootstrap collapse animation not smooth

Do not set a height on the .collapse tag. It affects the animation, if the height is overridden with css; it will not animate correctly.

How to assign a select result to a variable?

Why do you need a cursor at all? Your entire segment of code can be replaced by this, which will run a lot faster on large numbers of rows.

UPDATE tarinvoice set confirmtocntctkey = PrimaryCntctKey 
FROM tarinvoice INNER JOIN tarcustomer ON tarinvoice.custkey = tarcustomer.custkey
WHERE confirmtocntctkey is null and tranno like '%115876'

Lock down Microsoft Excel macro

Just like you can password protect workbooks and worksheets, you can password protect a macro in Excel from being viewed (and executed).

Place a command button on your worksheet and add the following code lines:

  1. First, create a simple macro that you want to protect.

    Range("A1").Value = "This is secret code"

  2. Next, click Tools, Then VBAProject Properties...

enter image description here

Click Tools, VBAProject Properties...

  1. On the Protection tab, check "Lock project for viewing" and enter a password twice.

enter image description here

Enter a Password Twice

  1. Click OK.

  2. Save, close and reopen the Excel file. Try to view the code.

enter image description here

The following dialog box will appear:

Password Protected from being Viewed

You can still execute the code by clicking on the command button but you cannot view or edit the code anymore (unless you know the password). The password for the downloadable Excel file is "easy".

  1. If you want to password protect the macro from being executed, add the following code lines:
Dim password As Variant
password = Application.InputBox("Enter Password", "Password Protected")

Select Case password
    Case Is = False
        'do nothing
    Case Is = "easy"
        Range("A1").Value = "This is secret code"
    Case Else
        MsgBox "Incorrect Password"
End Select

Result when you click the command button on the sheet:

enter image description here

Password Protected from being Executed

Explanation: The macro uses the InputBox method of the Application object. If the users clicks Cancel, this method returns False and nothing happens (InputBox disappears). Only when the user knows the password ("easy" again), the secret code will be executed. If the entered password is incorrect, a MsgBox is displayed. Note that the user cannot take a look at the password in the Visual Basic Editor because the project is protected from being viewed

How can I copy the output of a command directly into my clipboard?

Linux & Windows (WSL)

When using the Windows Subsystem for Linux (e.g. Ubuntu/Debian on WSL) the xclip solution won't work. Instead you need to use clip.exe and powershell.exe to copy into and paste from the Windows clipboard.

.bashrc

This solution works on "real" Linux-based systems (i.e. Ubuntu, Debian) as well as on WSL systems. Just put the following code into your .bashrc:

if grep -q -i microsoft /proc/version; then
    # on WSL
    alias copy="clip.exe"
    alias paste="powershell.exe Get-Clipboard"
else
    # on "normal" linux
    alias copy="xclip -sel clip"
    alias paste="xclip -sel clip -o"
fi

How it works

The file /proc/version contains information about the currently running OS. When the system is running in WSL mode, then this file additionally contains the string Microsoft which is checked by grep.

Usage

To copy:

cat file | copy

And to paste:

paste > new_file

How do you remove all the options of a select box and then add one option and select it with jQuery?

You can do simply by replacing html

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');

How to See the Contents of Windows library (*.lib)

"dumpbin -exports" works for dll, but sometimes may not work for lib. For lib we can use "dumpbin -linkermember" or just "dumpbin -linkermember:1".

wp-admin shows blank page, how to fix it?

I faced the same problem and I tried many things such as trying to login through wp-login.php instead of /wp-admin and adding ob_start() in /wp-admin/index.php (if you hit the url /wp-admin it goes for /wp-admin). It showed login page but entering the username and password shows an error like "cookies are blocked due to unexpected output".

I finally got the solution: it happens because the theme or plugins that you installed are not supported.

How to check and fix:

  • Rename the plugin folder name and theme folder name. If opening /wp-admin and entering a valid username and password the dashboard is shown, then it worked.

  • Revert the folder name of plugin and theme, then activate the themes and plugins one by one, cross-checking with /wp-admin. You will find out the unsupported plugin or theme.

Opening a SQL Server .bak file (Not restoring!)

From SQL Server 2008 SSMS (SQL Server Management Studio), simply:

  1. Connect to your database instance (for example, "localhost\sqlexpress")
  2. Either:

    • a) Select the database you want to restore to; or, alternatively
    • b) Just create a new, empty database to restore to.
  3. Right-click, Tasks, Restore, Database

  4. Device, [...], Add, Browse to your .bak file
  5. Select the backup.
    Choose "overwrite=Y" under options.
    Restore the database
  6. It should say "100% complete", and your database should be on-line.

PS: Again, I emphasize: you can easily do this on a "scratch database" - you do not need to overwrite your current database. But you do need to RESTORE.

PPS: You can also accomplish the same thing with T-SQL commands, if you wished to script it.

What does the keyword Set actually do in VBA?

In your case, it will produce an error. :-)

Set assigns an object reference. For all other assignments the (implicit, optional, and little-used) Let statement is correct:

Set object = New SomeObject
Set object = FunctionReturningAnObjectRef(SomeArgument)

Let i = 0
Let i = FunctionReturningAValue(SomeArgument)

' or, more commonly '

i = 0
i = FunctionReturningAValue(SomeArgument)

Is there a way I can capture my iPhone screen as a video?

Short of using a video camera, no.

Many youtube videos for demonstrating iPhone applications are made with a screen grabber application (such as iShowU, ScreenFlow, or Snapz Pro) and the simulator. Be aware that the speed of response in the simulator can be dramatically different than a device - so it's possible to get effects (and miss) with the simulator you'll never see on a device. In particular, default animations can flash by in the simulator, where they just look quick on a device.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.