Programs & Examples On #Execute immediate

An Oracle statement to execute a dynamic query or anonymous PL/SQL block.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,

EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;

Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.

Creating custom function in React component

With React Functional way

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";

const App = () => {
  const saySomething = (something) => {
  useEffect(() => {
    saySomething("from useEffect");
  const handleClick = (e) => {
    saySomething("element clicked");
  return (
    <Button variant="contained" color="primary" onClick={handleClick}>
      Hello World

ReactDOM.render(<App />, document.querySelector("#app"));

How does java do modulus calculations with negative numbers?

In my version of Java JDK 1.8.0_05 -13%64=-13

you could try -13-(int(-13/64)) in other words do division cast to an integer to get rid of the fraction part then subtract from numerator So numerator-(int(numerator/denominator)) should give the correct remainder & sign

is there a function in lodash to replace matched item

Using lodash unionWith function, you can accomplish a simple upsert to an object. The documentation states that if there is a match, it will use the first array. Wrap your updated object in [ ] (array) and put it as the first array of the union function. Simply specify your matching logic and if found it will replace it and if not it will add it


let contacts = [
     {type: 'email', desc: 'work', primary: true, value: 'email prim'}, 
     {type: 'phone', desc: 'cell', primary: true, value:'phone prim'},
     {type: 'phone', desc: 'cell', primary: false,value:'phone secondary'},
     {type: 'email', desc: 'cell', primary: false,value:'email secondary'}

// Update contacts because found a match
_.unionWith([{type: 'email', desc: 'work', primary: true, value: 'email updated'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)

// Add to contacts - no match found
_.unionWith([{type: 'fax', desc: 'work', primary: true, value: 'fax added'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)

Rails: select unique values from a column

This code works as 'DISTINCT' (not as Array#uniq) since rails 3.2

Showing alert in angularjs when user leaves a page

The code for the confirmation dialogue can be written shorter this way:

$scope.$on('$locationChangeStart', function( event ) {
    var answer = confirm("Are you sure you want to leave this page?")
    if (!answer) {

How do I import .sql files into SQLite 3?

From a sqlite prompt:

sqlite> .read db.sql


cat db.sql | sqlite3 database.db

Also, your SQL is invalid - you need ; on the end of your statements:

create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);

How do you use NSAttributedString?

An easier solution with attributed string extension.

extension NSMutableAttributedString {

    // this function attaches color to string    
    func setColorForText(textToFind: String, withColor color: UIColor) {
        let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)


Try this and see (Tested in Swift 3 & 4)

let label = UILabel()
label.frame = CGRect(x: 120, y: 100, width: 200, height: 30)
let first = "first"
let second = "second"
let third = "third"
let stringValue = "\(first)\(second)\(third)"  // or direct assign single string value like "firstsecondthird"

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textToFind: first, withColor:   // use variable for string "first"
attributedString.setColorForText(textToFind: "second", withColor: // or direct string like this "second"
attributedString.setColorForText(textToFind: third, withColor:
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString

Here is expected result:

enter image description here

'tsc command not found' in compiling typescript

This answer is specific for iTermV2 on MAC

  1. First of all, I needed to instal as sudo (admin) during NPM install

    sudo npm install -g typescript

  2. NPM installs the libraries under /usr/local/Cellar/node/<your latest version>/lib/node_modules/typescript folder and symlinks at /usr/local/Cellar/node/<your latest version>/bin/tsc

hence I went ~/.zshrc ( .bashrc, if you use bash)and added /usr/local/Cellar/node/<your latest version>/bin to the $PATH.

  1. reload the shell profile via source ~/.zshrc (.bashrc in your case)

Focus Input Box On Load

If you can't add to the BODY tag for some reason, you can add this AFTER the Form:

<SCRIPT type="text/javascript">

Is there a 'box-shadow-color' property?

You can do this with CSS Variable

.box-shadow {
    --box-shadow-color: #000; /* Declaring the variable */
    width: 30px;                
    height: 30px;
    box-shadow: 1px 1px 25px var(--box-shadow-color); /* Calling the variable */


.box-shadow:hover  {
    --box-shadow-color: #ff0000; /* Changing the value of the variable */

Replace Div Content onclick

Try This:

I think that you want something like this.


<div id="1">
    My Content 1

<div id="2" style="display:none;">
    My Dynamic Content
<button id="btnClick">Click me!</button>


}else if($('#2').css('display')!='none'){

JsFiddle: <--- see this I hope You want something like this.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Are you running the application as a jar? ( java -jar xxxx.jar)

If so, do you have the stored in that jar ?

If no, try to figure out why :

  • To be automatically package in the jar, the files can be in : src/main/resources/
  • The maven plugin in the pom.xml can also be configured

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Select      Eventname, 
            count(Eventname) as 'Counts'
INTO        #TEMPTABLE                                                                                
FROM        tblevent
where       Eventname like 'A%'
Group by    Eventname
order by    count(Eventname)

Here by using the into clause the table is directly created

How to clear or stop timeInterval in angularjs?

    $scope.toggleRightDelayed = function(){
        var myInterval = $interval(function(){

How to concat string + i?

For versions prior to R2014a...

One easy non-loop approach would be to use genvarname to create a cell array of strings:

>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')

f = 

    'f1'    'f2'    'f3'    'f4'    'f5'

For newer versions...

The function genvarname has been deprecated, so matlab.lang.makeUniqueStrings can be used instead in the following way to get the same output:

>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')

 f =
   1×5 cell array

     'f1'    'f2'    'f3'    'f4'    'f5'

Cannot use a leading ../ to exit above the top directory

I had the problem occur on my system in a very strange way. In my system customers create products that sit inside a directory structure of product categories. So ProductA might sit in the folder CategoryInner inside the folder CategoryOuter. I had just added a feature where my URL would show the category nesting on the URL thusly:

Obviously the nesting on the URL was just for SEO purposes (and to show the user what category their product was sitting in. But when I used ResolveClientUrl on some URLs that used to work, it must've been confused by the extra fake pathing. The error message was popping up in the debugger on some line that was never the problem so it took me quite some time to figure out what was going on. I wnet through and removed all of my ResolveClientUrl calls that acted on anything that didn't start with a ~ and made the rest of the paths absolute paths.

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;

    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),

        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),

        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),

        // Private Implementation.

        protected override void Invoke(object parameter)
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(

            propertyInfo.SetValue(target, PropertyValue);

In this case I'm binding to a property called DialogResult on my viewmodel.


            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>


Logical operators ("and", "or") in DOS batch

Only the OR part is tricky, but with a general boolean expression containing NOT OR AND the only nice solution is this:

REM if A == B OR C == C then yes

(call :strequ A B || call :strequ C C) && echo yes
exit /b

if "%1" == "%2" exit /b 0
exit /b 1

How to properly overload the << operator for an ostream?

Just telling you about one other possibility: I like using friend definitions for that:

namespace Math
    class Matrix


        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {

The function will be automatically targeted into the surrounding namespace Math (even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>.

Check if process returns 0 with batch file

How to write a compound statement with if?

You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.

if %ERRORLEVEL% == 0 (
    echo ErrorLevel is zero
    echo A second statement
) else if %ERRORLEVEL% == 1 (
    echo ErrorLevel is one
    echo A second statement
) else (
   echo ErrorLevel is > 1
   echo A second statement

Explicit vs implicit SQL joins

The second syntax has the unwanted possibility of a cross join: you can add tables to the FROM part without corresponding WHERE clause. This is considered harmful.

How to Change Margin of TextView

TextView forgot_pswrd = (TextView) findViewById(;
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);

I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes {  
  width: 200px !important;

applies to div tags with the following two classes {  
  width: 200px !important;

If you wanted to modify this using jQuery

$(document).ready(function() {

How can I access getSupportFragmentManager() in a fragment?

in java you can replace with


in kotlin, make it simple by


hope it help :)

Inserting a PDF file in LaTeX

For putting a whole pdf in your file and not just 1 page, use:



How to unstash only certain files?

git checkout stash@{N} <File(s)/Folder(s) path> 

Eg. To restore only ./test.c file and ./include folder from last stashed,

git checkout stash@{0} ./test.c ./include

Take the content of a list and append it to another list

You probably want


instead of


Here's the difference:

>>> a = range(5)
>>> b = range(3)
>>> c = range(2)
>>> b.append(a)
>>> b
[0, 1, 2, [0, 1, 2, 3, 4]]
>>> c.extend(a)
>>> c
[0, 1, 0, 1, 2, 3, 4]

Since list.extend() accepts an arbitrary iterable, you can also replace

for line in mylog:



Root element is missing

Just in case anybody else lands here from Google, I was bitten by this error message when using XDocument.Load(Stream) method.

XDocument xDoc = XDocument.Load(xmlStream);  

Make sure the stream position is set to 0 (zero) before you try and load the Stream, its an easy mistake I always overlook!

if (xmlStream.Position > 0)
    xmlStream.Position = 0;
XDocument xDoc = XDocument.Load(xmlStream); 

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

Integrating CSS star rating into an HTML form

How about this? I needed the exact same thing, I had to create one from scratch. It's PURE CSS, and works in IE9+ Feel-free to improve upon it.


<ul class="form">
    <li class="rating">
        <input type="radio" name="rating" value="0" checked /><span class="hide"></span>
        <input type="radio" name="rating" value="1" /><span></span>
        <input type="radio" name="rating" value="2" /><span></span>
        <input type="radio" name="rating" value="3" /><span></span>
        <input type="radio" name="rating" value="4" /><span></span>
        <input type="radio" name="rating" value="5" /><span></span>


.form {

.form li {

.hide {

.rating input[type="radio"] {

.rating span {
    padding:1px 22px 1px 0; /* 1px FireFox fix */
    background:url(stars.png) no-repeat -22px 0;

.rating input[type="radio"]:checked + span {
    background-position:-22px 0;

.rating input[type="radio"]:checked + span ~ span {
    background-position:0 0;

Create an empty list in python with certain size

The accepted answer has some gotchas. For example:

>>> a = [{}] * 3
>>> a
[{}, {}, {}]
>>> a[0]['hello'] = 5
>>> a
[{'hello': 5}, {'hello': 5}, {'hello': 5}]

So each dictionary refers to the same object. Same holds true if you initialize with arrays or objects.

You could do this instead:

>>> b = [{} for i in range(0, 3)]
>>> b
[{}, {}, {}]
>>> b[0]['hello'] = 6
>>> b
[{'hello': 6}, {}, {}]

Replace words in a string - Ruby

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.

Moment get current date

Just call moment as a function without any arguments:


For timezone information with moment, look at the moment-timezone package:

Quickly create large file on a Windows system

I found a solution using DEBUG at, but I don't know an easy way to script it and it doesn't seem to be able to create files larger than 1 GB.

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>

Combining CSS Pseudo-elements, ":after" the ":last-child"

I do like this for list items in <menu> elements. Consider the following markup:

  <li><a href="/member/profile">Profile</a></li>
  <li><a href="/member/options">Options</a></li>
  <li><a href="/member/logout">Logout</a></li>

I style it with the following CSS:

menu > li {
  display: inline;

menu > li::after {
  content: ' | ';

menu > li:last-child::after {
  content: '';

This will display:

Profile | Options | Logout

And this is possible because of what Martin Atkins explained on his comment

Note that in CSS 2 you would use :after, not ::after. If you use CSS 3, use ::after (two semi-columns) because ::after is a pseudo-element (a single semi-column is for pseudo-classes).

How to randomly select an item from a list?

The following code demonstrates if you need to produce the same items. You can also specify how many samples you want to extract.
The sample method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.

import random as random
random.seed(0)  # don't use seed function, if you want different results in each run
print(random.sample(foo,3))  # 3 is the number of sample you want to retrieve

Output:['d', 'e', 'a']

How to set background color of an Activity to white programmatically?

View randview = new View(getBaseContext());
randview = (View)findViewById(;

worked for me. thank you.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Just for contrast, I like using the object_id function as shown below. It's a bit easier to read, and you don't have to worry about sys.objects vs. sysobjects vs. sys.all_objects vs. sys.tables. Basic form:

IF object_id('MyTable') is not null
    PRINT 'Present!'
    PRINT 'Not accounted for'

Of course this will show as "Present" if there is any object present with that name. If you want to check just tables, you'd need:

IF object_id('MyTable', 'U') is not null
    PRINT 'Present!'
    PRINT 'Not accounted for'

It works for temp tables as well:

IF object_id('tempdb.dbo.#MyTable') is not null
    PRINT 'Present!'
    PRINT 'Not accounted for'

How to find the path of Flutter SDK

The Flutter SDK path is certainly defined in a place where you can check it or change it, whether you created the project or not. Under Settings > Languages & Frameworks there should be a Flutter section. I found it by using the handy search bar in the Settings menu.

At the top of the Languages & Frameworks > Flutter is the Flutter SDK Path.

This is assuming that Flutter/Dart have already been installed under Plugins.

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

Remove duplicated rows

just isolate your data frame to the columns you need, then use the unique function :D

# in the above example, you only need the first three columns <- unique( yourdata[ , 1:3 ] )
# the fourth column no longer 'distinguishes' them, 
# so they're duplicates and thrown out.

C++ trying to swap values in a vector

after passing the vector by reference


will produce the expected result.

Iterating Through a Dictionary in Swift

Dictionaries in Swift (and other languages) are not ordered. When you iterate through the dictionary, there's no guarentee that the order will match the initialization order. In this example, Swift processes the "Square" key before the others. You can see this by adding a print statement to the loop. 25 is the 5th element of Square so largest would be set 5 times for the 5 elements in Square and then would stay at 25.

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25]
var largest = 0
for (kind, numbers) in interestingNumbers {
    println("kind: \(kind)")
    for number in numbers {
        if number > largest {
            largest = number

This prints:

kind: Square
kind: Prime
kind: Fibonacci

How to convert currentTimeMillis to a date in Java?

The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class.

SQL Current month/ year question

This should work in MySql


How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

     getUnits: function() {...}

Working fiddle:

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

What does enctype='multipart/form-data' mean?

when should we use it

Quentin's answer is right: use multipart/form-data if the form contains a file upload, and application/x-www-form-urlencoded otherwise, which is the default if you omit enctype.

I'm going to:

  • add some more HTML5 references
  • explain why he is right with a form submit example

HTML5 references

There are three possibilities for enctype:

How to generate the examples

Once you see an example of each method, it becomes obvious how they work, and when you should use each one.

You can produce examples using:

Save the form to a minimal .html file:

<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8"/>
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text1" value="text default">
  <p><input type="text" name="text2" value="a&#x03C9;b">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><input type="file" name="file3">
  <p><button type="submit">Submit</button>

We set the default text value to a&#x03C9;b, which means a?b because ? is U+03C9, which are the bytes 61 CF 89 62 in UTF-8.

Create files to upload:

echo 'Content of a.txt.' > a.txt

echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

# Binary file containing 4 bytes: 'a', 1, 2 and 'b'.
printf 'a\xCF\x89b' > binary

Run our little echo server:

while true; do printf '' | nc -l 8000 localhost; done

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received.

Tested on: Ubuntu 14.04.3, nc BSD 1.105, Firefox 40.


Firefox sent:

[[ Less interesting headers ... ]]
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
Content-Length: 834

Content-Disposition: form-data; name="text1"

text default
Content-Disposition: form-data; name="text2"

Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

Content-Disposition: form-data; name="file3"; filename="binary"
Content-Type: application/octet-stream


For the binary file and text field, the bytes 61 CF 89 62 (a?b in UTF-8) are sent literally. You could verify that with nc -l localhost 8000 | hd, which says that the bytes:

61 CF 89 62

were sent (61 == 'a' and 62 == 'b').

Therefore it is clear that:

  • Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150 sets the content type to multipart/form-data and says that the fields are separated by the given boundary string.

    But note that the:


    has two less dadhes -- than the actual barrier


    This is because the standard requires the boundary to start with two dashes --. The other dashes appear to be just how Firefox chose to implement the arbitrary boundary. RFC 7578 clearly mentions that those two leading dashes -- are required:

    4.1. "Boundary" Parameter of multipart/form-data

    As with other multipart types, the parts are delimited with a boundary delimiter, constructed using CRLF, "--", and the value of the "boundary" parameter.

  • every field gets some sub headers before its data: Content-Disposition: form-data;, the field name, the filename, followed by the data.

    The server reads the data until the next boundary string. The browser must choose a boundary that will not appear in any of the fields, so this is why the boundary may vary between requests.

    Because we have the unique boundary, no encoding of the data is necessary: binary data is sent as is.

    TODO: what is the optimal boundary size (log(N) I bet), and name / running time of the algorithm that finds it? Asked at:

  • Content-Type is automatically determined by the browser.

    How it is determined exactly was asked at: How is mime type of an uploaded file determined by browser?


Now change the enctype to application/x-www-form-urlencoded, reload the browser, and resubmit.

Firefox sent:

[[ Less interesting headers ... ]]
Content-Type: application/x-www-form-urlencoded
Content-Length: 51


Clearly the file data was not sent, only the basenames. So this cannot be used for files.

As for the text field, we see that usual printable characters like a and b were sent in one byte, while non-printable ones like 0xCF and 0x89 took up 3 bytes each: %CF%89!


File uploads often contain lots of non-printable characters (e.g. images), while text forms almost never do.

From the examples we have seen that:

  • multipart/form-data: adds a few bytes of boundary overhead to the message, and must spend some time calculating it, but sends each byte in one byte.

  • application/x-www-form-urlencoded: has a single byte boundary per field (&), but adds a linear overhead factor of 3x for every non-printable character.

Therefore, even if we could send files with application/x-www-form-urlencoded, we wouldn't want to, because it is so inefficient.

But for printable characters found in text fields, it does not matter and generates less overhead, so we just use it.

How do I automatically resize an image for a mobile site?

For me, it worked best to add this in image css: max-width:100%; and NOT specify image width and height in html parameters. This adjusted the width to fit in device screen while adjusting height automatically. Otherwise height might be distorted.

How to store a byte array in Javascript

I wanted a more exact and useful answer to this question. Here's the real answer (adjust accordingly if you want a byte array specifically; obviously the math will be off by a factor of 8 bits : 1 byte):

class BitArray {
  constructor(bits = 0) {
    this.uints = new Uint32Array(~~(bits / 32));

  getBit(bit) {
    return (this.uints[~~(bit / 32)] & (1 << (bit % 32))) != 0 ? 1 : 0;

  assignBit(bit, value) {
    if (value) {
      this.uints[~~(bit / 32)] |= (1 << (bit % 32));
    } else {
      this.uints[~~(bit / 32)] &= ~(1 << (bit % 32));

  get size() {
    return this.uints.length * 32;

  static bitsToUints(bits) {
    return ~~(bits / 32);


let bits = new BitArray(500);
for (let uint = 0; uint < bits.uints.length; ++uint) {
  bits.uints[uint] = 457345834;
for (let bit = 0; bit < 50; ++bit) {
  bits.assignBit(bit, 1);
str = '';
for (let bit = bits.size - 1; bit >= 0; --bit) {
  str += bits.getBit(bit);



Note: This class is really slow to e.g. assign bits (i.e. ~2s per 10 million assignments) if it's created as a global variable, at least in the Firefox 76.0 Console on Linux... If, on the other hand, it's created as a variable (i.e. let bits = new BitArray(1e7);), then it's blazingly fast (i.e. ~300ms per 10 million assignments)!

For more info, see here:

Note that I used Uint32Array because there's no way to directly have a bit/byte array (that you can interact with directly) and because even though there's a BigUint64Array, JS only supports 32 bits:

Bitwise operators treat their operands as a sequence of 32 bits


The operands of all bitwise operators are converted to...32-bit integers

Keras input explanation: input_shape, units, batch_size, dim, etc


The amount of "neurons", or "cells", or whatever the layer has inside it.

It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

  • Hidden layer 1: 4 units (4 neurons)
  • Hidden layer 2: 4 units
  • Last layer: 1 unit


Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

The input shape

What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

Each type of layer requires the input with a certain number of dimensions:

  • Dense layers require inputs as (batch_size, input_size)
    • or (batch_size, optional,...,optional, input_size)
  • 2D convolutional layers need inputs as:
    • if using channels_last: (batch_size, imageside1, imageside2, channels)
    • if using channels_first: (batch_size, channels, imageside1, imageside2)
  • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).


Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.


And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.

Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

Secure random token in Node.js

Simple function that gets you a token that is URL safe and has base64 encoding! It's a combination of 2 answers from above.

const randomToken = () => {

How do I setup a SSL certificate for an express.js server?

I was able to get SSL working with the following boilerplate code:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    express = require('express');

var port = 8000;

var options = {
    key: fs.readFileSync('./ssl/privatekey.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),

var app = express();

var server = https.createServer(options, app).listen(port, function(){
  console.log("Express server listening on port " + port);

app.get('/', function (req, res) {
    res.end("hello world\n");

Angular 4 HttpClient Query Parameters

You can pass it like this

let param: any = {'userId': 2};
this.http.get(`${ApiUrl}`, {params: param})

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

What is the difference between a data flow diagram and a flow chart?

The difference between a data flow diagram (DFD) and a flow chart (FC) are that a data flow diagram typically describes the data flow within a system and the flow chart usually describes the detailed logic of a business process.

How to check if an object is a list or tuple (but not string)?

H = "Hello"

if type(H) is list or type(H) is tuple:
    ## Do Something.
    ## Do Something.

error: use of deleted function

The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.

class X {
    const int x;

Since X::x is const, it must be initialized -- but a default ctor wouldn't normally initialize it (because it's a POD type). Therefore, to get a default ctor, you need to define one yourself (and it must initialize x). You can get the same kind of situation with a member that's a reference:

class X { 
    whatever &x;

It's probably worth noting that both of these will also disable implicit creation of an assignment operator as well, for essentially the same reason. The implicit assignment operator normally does members-wise assignment, but with a const member or reference member, it can't do that because the member can't be assigned. To make assignment work, you need to write your own assignment operator.

This is why a const member should typically be static -- when you do an assignment, you can't assign the const member anyway. In a typical case all your instances are going to have the same value so they might as well share access to a single variable instead of having lots of copies of a variable that will all have the same value.

It is possible, of course, to create instances with different values though -- you (for example) pass a value when you create the object, so two different objects can have two different values. If, however, you try to do something like swapping them, the const member will retain its original value instead of being swapped.

Escaping single quote in PHP when inserting into MySQL

I had the same problem and I solved it like this:

$text = str_replace("'", "\'", $YourContent);

There is probably a better way to do this, but it worked for me and it should work for you too.

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

depending on you application, i suggest using FLOAT(9,6)

spatial keys will give you more features, but in by production benchmarks the floats are much faster than the spatial keys. (0,01 VS 0,001 in AVG)

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

You can use myDict.has_key(keyname) as well to validate if the key exists.

Edit based on the comments -

This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1

Using if elif fi in shell scripts

I have a sample from your code. Try this:

echo "*Select Option:*"
echo "1 - script1"
echo "2 - script2"
echo "3 - script3 "
read option
echo "You have selected" $option"."
if [ $option="1" ]
    echo "1"
elif [ $option="2" ]
    echo "2"
    exit 0
elif [ $option="3" ]
    echo "3"
    exit 0
    echo "Please try again from given options only."

This should work. :)

Access maven properties defined in the pom

You can parse the pom file with JDOM (

Passing data to components in vue.js

-------------Following is applicable only to Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.

If you want to pass data from your html while you add a new component. That is done using props.

<my-component prop-name="value"></my-component>

This prop value will be available to your component only if you add the prop name prop-name to your props attribute.

When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:


And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event:

this.$dispatch('event_name', data);

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent:

    'event_name' : function(data){
        this.$broadcast('event_name', data);

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event:

events: {
    'event_name' : function(data){
        // Your code. 

The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.

Decide what type of data communication you want, and choose appropriately.

Convert Java Array to Iterable

I had the same problem and solved it like this:

final YourType[] yourArray = ...;
return new Iterable<YourType>() {
  public Iterator<YourType> iterator() {
     return Iterators.forArray(yourArray);   // Iterators is a Google guava utility

The iterator itself is a lazy UnmodifiableIterator but that's exactly what I needed.

How to get ERD diagram for an existing database?

ERBuilder can generate ER diagram from PostgreSQL databases (reverse engineer feature).

Below step to follow to generate an ER diagram:

• Click on Menu -> File -> reverse engineer

• Click on new connection

• Fill in PostgresSQL connection information

• Click on OK

• Click on next

• Select objects (tables, triggers, sequences…..) that you want to reverse engineer.

• Click on next.

  • If you are using trial version, your ERD will be displayed automatically.
  • If your are using the free edition you need to drag and drop the tables from the treeview placed in the left side of application

enter image description here

SQL Server Installation - What is the Installation Media Folder?

If you are using an executable,

  • just run the executable (for example: "en_sql_server_2012_express_edition_with_advanced_services_x64.exe")
  • Navigate to the "options" tab
  • Copy the "Installation Media Root Directory" (should look something like the below snipping)
  • Paste it into the open "Browse for SQL server Installation Media" window

enter image description here

Save yourself the hastle of renaming and unzipping etc.!

npm not working after clearing cache

Try npm cache clean --force if it doesn't work then manually delete %appdata%\npm-cache folder.

It worked for me.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

"Fatal error: Cannot redeclare <function>"

If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.

Cannot open include file with Visual Studio

I found this post because I was having the same error in Microsoft Visual C++. (Though it seems it's cause was a little different, than the above posted question.)

I had placed the file, I was trying to include, in the same directory, but it still could not be found.

My include looked like this: #include <ftdi.h>

But When I changed it to this: #include "ftdi.h" then it found it.

SyntaxError: "can't assign to function call"

You have done it backwards, it should be:

amount = invest(amount,top_company(5,year,year+1),year)

Sort hash by key, return hash in Ruby

Sort hash by key, return hash in Ruby

With destructuring and Hash#sort

hash.sort { |(ak, _), (bk, _)| ak <=> bk }.to_h


hash.sort_by { |k, v| k }.to_h

Hash#sort with default behaviour

h = { "b" => 2, "c" => 1, "a" => 3  }
h.sort         # e.g. ["a", 20] <=> ["b", 30]
hash.sort.to_h #=> { "a" => 3, "b" => 2, "c" => 1 }

Note: < Ruby 2.1

array = [["key", "value"]] 
hash  = Hash[array]
hash #=> {"key"=>"value"}

Note: > Ruby 2.1

[["key", "value"]].to_h #=> {"key"=>"value"}

Python: One Try Multiple Except

Yes, it is possible.

except FirstException:

except SecondException:

except (ThirdException, FourthException, FifthException) as e:

except Exception:


The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

#pragma once vs include guards?

From a software tester's perspective

#pragma once is shorter than an include guard, less error prone, supported by most compilers, and some say that it compiles faster (which is not true [any longer]).

But I still suggest you go with standard #ifndef include guards.

Why #ifndef?

Consider a contrived class hierarchy like this where each of the classes A, B, and C lives inside its own file:


#ifndef A_H
#define A_H

class A {
  // some virtual functions



#ifndef B_H
#define B_H

#include "a.h"

class B : public A {
  // some functions



#ifndef C_H
#define C_H

#include "b.h"

class C : public B {
  // some functions


Now let's assume you are writing tests for your classes and you need to simulate the behaviour of the really complex class B. One way to do this would be to write a mock class using for example google mock and put it inside a directory mocks/b.h. Note, that the class name hasn't changed but it's only stored inside a different directory. But what's most important is that the include guard is named exactly the same as in the original file b.h.


#ifndef B_H
#define B_H

#include "a.h"
#include "gmock/gmock.h"

class B : public A {
  // some mocks functions
  MOCK_METHOD0(SomeMethod, void());


What's the benefit?

With this approach you can mock the behaviour of class B without touching the original class or telling C about it. All you have to do is put the directory mocks/ in the include path of your complier.

Why can't this be done with #pragma once?

If you would have used #pragma once, you would get a name clash because it cannot protect you from defining the class B twice, once the original one and once the mocked version.

how to set start value as "0" in chartjs?

If you need use it as a default configuration, just place min: 0 inside the node defaults.scale.ticks, as follows:

defaults: {
  global: {...},
  scale: {
    ticks: { min: 0 },


Is there a code obfuscator for PHP?

You can try PHP protect which is a free PHP obfuscator to obfuscate your PHP code.
It is very nice, easy to use and also free.
EDIT: This service is not live anymore.

As for what others have written here about not using obfuscation because it can be broken etc:
I have only one thing to answer them - don't lock your house door because anyone can pick your lock.
This is exactly the case, obfuscation is not meant to prevent 100% code theft. It only needs to make it a time-consuming task so it will be cheaper to pay the original coder. Hope this helps.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.



How to execute a shell script in PHP?

Several possibilities:

  • You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
  • exec and shell_exec are disabled in php.ini
  • The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . '/');

Switch case in C# - a constant value is expected

You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ...

public static void Output<T>(IEnumerable<T> dataSource) where T : class
    dataSourceName = (typeof(T).Name);
    if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0)
        var t = 123;
    else if (/*case 2 conditional*/)
        //default case

I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString(). This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off.

How can I find the latitude and longitude from address?

The following code will work for google apiv2:

public void convertAddress() {
    if (address != null && !address.isEmpty()) {
        try {
            List<Address> addressList = geoCoder.getFromLocationName(address, 1);
            if (addressList != null && addressList.size() > 0) {
                double lat = addressList.get(0).getLatitude();
                double lng = addressList.get(0).getLongitude();
        } catch (Exception e) {
        } // end catch
    } // end if
} // end convertAddress

Where address is the String (123 Testing Rd City State zip) you want to convert to LatLng.

Class method decorator with self arguments?

You can't. There's no self in the class body, because no instance exists. You'd need to pass it, say, a str containing the attribute name to lookup on the instance, which the returned function can then do, or use a different method entirely.

Performing Breadth First Search recursively

Here's a python implementation:

graph = {'A': ['B', 'C'],
         'B': ['C', 'D'],
         'C': ['D'],
         'D': ['C'],
         'E': ['F'],
         'F': ['C']}

def bfs(paths, goal):
    if not paths:
        raise StopIteration

    new_paths = []
    for path in paths:
        if path[-1] == goal:
            yield path

        last = path[-1]
        for neighbor in graph[last]:
            if neighbor not in path:
                new_paths.append(path + [neighbor])
    yield from bfs(new_paths, goal)

for path in bfs([['A']], 'D'):

jQuery addClass onClick

It needs to be a jQuery element to use .addClass(), so it needs to be wrapped in $() like this:

function addClassByClick(button){

A better overall solution would be unobtrusive script, for example:

<asp:Button ID="Button" runat="server" class="clickable"/>

Then in jquery:

$(function() {                       //run when the DOM is ready
  $(".clickable").click(function() {  //use a class, since your ID gets mangled
    $(this).addClass("active");      //add the class to the clicked element

Evaluate a string with a switch in C++

what about just have the option number:

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

int main()
    string s;
    int op;

    cin >> s >> op;
    switch (op) {
    case 1: break;
    case 2: break;

    return 0;

How to install libusb in Ubuntu

This should work:

# apt-get install libusb-1.0-0-dev

Vim and Ctags tips and tricks

Another iteration on the SetCscope() function above. That sets cscope pre-path to get matches without being on the dir where "cscope.out" is:

function s:FindFile(file)
    let curdir = getcwd()
    let found = curdir
    while !filereadable(a:file) && found != "/"
        cd ..
        let found = getcwd()
    execute "cd " . curdir
    return found

if has('cscope')    
    let $CSCOPE_DIR=s:FindFile("cscope.out")
    let $CSCOPE_DB=$CSCOPE_DIR."/cscope.out"
    if filereadable($CSCOPE_DB)
        cscope add $CSCOPE_DB $CSCOPE_DIR

    command -nargs=0 Cscope !cscope -ub -R &

Redirection of standard and error output appending to the same log file

Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.

$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)

Can linux cat command be used for writing text to file?

cat > filename.txt

enter the text until EOF for save the text use : ctrl+d

if you want to read that .txt file use

cat filename.txt

and one thing .txt is not mandatory, its for your reference.

MySQL Where DateTime is greater than today

FROM customer 
WHERE joiningdate >= NOW();

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;

document.addEventListener('mousemove', function(e){

How do I make the method return type generic?

As the question is based in hypothetical data here is a good exemple returning a generic that extends Comparable interface.

public class MaximumTest {
    // find the max value using Comparable interface
    public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
        T max = x; // assume that x is initially the largest

        if (y.compareTo(max) > 0){
            max = y; // y is the large now
        if (z.compareTo(max) > 0){
            max = z; // z is the large now
        return max; // returns the maximum value

    //testing with an ordinary main method
    public static void main(String args[]) {
        System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5));
        System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7));
        System.out.printf("Maximum of %s, %s and %s is %s\n", "strawberry", "apple", "orange",
                maximum("strawberry", "apple", "orange"));

Stick button to right side of div

div {
 display: flex;
 flex-direction: row-reverse;

How do I open workbook programmatically as read-only?

Check out the language reference:

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Install gitk on Mac

I had the same issue. I installed gitx instead.

You can install gitx from here.

Download the package and install it. After that open the gitk from spotlight search, goto the top left corner. Click on GitX and enable the terminal usage.

Goto your repo and simply type:

$ gitx --all

It will open the Gui.

User manual:

How to recursively delete an entire directory with PowerShell 2.0?

To avoid the "The directory is not empty" errors of the accepted answer, simply use the good old DOS command as suggested before. The full PS syntax ready for copy-pasting is:

& cmd.exe /c rd /S /Q $folderToDelete

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

If you are using Spring MVC, then you need to declare default action servlet for static contents. Add the following entries in spring-action-servlet.xml. It worked for me.

NOTE: keep all the static contents outside WEB-INF.

<!-- Enable annotation-based controllers using @Controller annotations -->
<bean id="annotationUrlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="order" value="0" />

<bean id="controllerClassNameHandlerMapping" class="">
    <property name="order" value="1" />

<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

How can I find out which server hosts LDAP on my windows domain?

If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.

SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

How to get first record in each group using Linq

var res = (from element in list)
      .OrderBy(x => x.F2).AsEnumerable()
      .GroupBy(x => x.F1)

Use .AsEnumerable() after OrderBy()

How do I create ColorStateList programmatically?

if you use the resource the Colors.xml

int[] colors = new int[] {


ColorStateList csl = new ColorStateList(new int[][]{new int[0]}, new int[]{colors[0]}); 


How to pass an event object to a function in Javascript?

Although this is the accepted answer, toto_tico's answer below is better :)

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

Plotting with C#

ZedGraph is a good choice.

What is the difference between Google App Engine and Google Compute Engine?

In addition to the App Engine vs Compute Engine notes above the list here also includes a comparison with Google Kubernete Engine and some notes based on experience with a wide range of apps from small to very large. For more points see the Google Cloud Platform documentation high level description of features in App Engine Standard and Flex on the page Choosing an App Engine Environment. For another comparison of deployment of App Engine and Kubernetes see the post by Daz Wilkin App Engine Flex or Kubernetes Engine.

App Engine Standard


  • Very economical for low traffic apps in terms of direct costs and also the cost of maintaining the app.
  • Auto scaling is fast. Autoscaling in App Engine is based on lightweight instance classes F1-F4.
  • Version management and traffic splitting are fast and convenient. These features are built into App Engine (both Standard and Flex) natively.
  • Minimal management, developers need focus only on their app. Developers do not need to worry about managing VMs in a reliable, as in GCE, or learning about clusters, as with GKE.
  • Access to Datastore is fast. When App Engine was first released, the runtime was co-located with Datastore. Later Datastore was split out as the standalone product Cloud Datastore but the co-location of App Engine Standard serving with Datastore remains.
  • Access to Memcache is supported.
  • The App Engine sandbox is very secure. Compared with development on GCE or other virtual machines, where you need to do your own diligence to prevent the virtual machine from being taken over at the operating system level, the App Engine Standard sandbox is relatively secure by default.


  • Generally more constrained than other environments Instances are smaller. Although this is good for rapid autoscaling, many apps can benefit from larger instances, such as GCE instance sizes up to 96 cores.
  • Networking is not integrated with GCE
  • Cannot put App Engine behind a Google Cloud Load Balancer. Limited to supported runtimes: Python 2.7, Java 7 and 8, Go 1.6-1.9, and PHP 5.5. In Java, there is some support for Servlets but not the full J2EE standard.

App Engine Flex


  • Can use a custom runtime
  • Native integration with GCE networking
  • Version and traffic management is convenient, same as Standard
  • The larger instance sizes may be more suitable to to large complex applications, especially Java applications that can use a lot of memory


  • Network integration is not perfect - no integration with internal load balancers or Shared Virtual Private Clouds
  • Access to managed Memcache not generally available

Google Kubernetes Engine


  • Native integration with containers allows custom runtimes and greater control over cluster configuration.
  • Embodies many best practices working with virtual machines, such as immutable runtime environments and easy ability to roll back to previous versions
  • Provides a consistent and repeatable deployment framework
  • Based on open standards, notably Kubernetes, for portability between clouds and on-premises.
  • Version management can accomplished with Docker containers and the Google Container Registry


  • Traffic splitting and management is do-it-yourself, possibly leveraging Istio and Envoy
  • Some management overhead
  • Some time to ramp up on Kubernetes concepts, such as pods, deployments, services, ingress, and namespaces
  • Need to expose some public IPs unless using Private Clusters, now in beta, eliminate that need but you still need to provide access to locations where kubectl commands will be run from.
  • Monitoring integration not perfect
  • While L3 internal load balancing is supported natively on Kubernetes Engine, L7 internal load balancing is do-it-yourself, possibly leveraging Envoy

Compute Engine


  • Easy to ramp up - no need to ramp up on Kubernetes or App Engine, just reuse whatever you know from previous experience. This is probably the main reason for using Compute Engine directly.
  • Complete control - you can leverage many Compute Engine features directly and install the latest of all your favorite stuff to stay on the bleeding edge.
  • No need for public IPs. Some legacy software may be too hard to lock down if anything is exposed on public IPs.
  • You can leverage the Container-Optimized OS for running Docker containers


  • Mostly do-it-yourself, which can be challenging to do adequately for reliability and security, although you can reuse solutions from various places, including the Cloud Launcher.
  • More management overhead. There are many management tools for Compute Engine but they will not necessarily understand how you have deployed your application, like the App Engine and Kubernetes Engine monitoring tools do
  • Autoscaling is based on GCE instances, which can be slower than App Engine
  • Tendency is to install software on snowflake GCE instances, which can be some effort to maintain

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

Converting ArrayList to Array in java

This can be done using stream:

List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
    List<String[]> objects =
                                       .map(s -> s.split("#"))

The return value would be arrays of split string. This avoids converting the arraylist to an array and performing the operation.

Android Design Support Library expandable Floating Action Button(FAB) menu

  • First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.

  • Create the menu layouts as per your need and number.

  • Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.

Please check the below code for the reference and for more info checkout my project from github

Checkout project from Github


                app:srcCompat="@drawable/ic_add_black_24dp" />


                    android:typeface="normal" />

                    app:srcCompat="@drawable/ic_share_black_24dp" />



                    android:typeface="normal" />

                    app:srcCompat="@drawable/ic_create_black_24dp" />



These are the animations-

Opening animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android=""
    android:toYScale="1" />
    android:toAlpha="1.0" />


Closing animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android=""
    android:toYScale="0.0" />
    android:toAlpha="0.0" />

Then in my Activity I've simply used the animations above to show and hide the FAB menu :

Show Fab Menu:

  private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    isFabMenuOpen = true;


Close Fab Menu:

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    isFabMenuOpen = false;


Here is the the Activity class -


import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;


public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;

protected void onCreate(Bundle savedInstanceState) {

    binding = DataBindingUtil.setContentView(this,    R.layout.activity_main);
    binding.setFabHandler(new FabHandler());



private void getAnimations() {

    fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);

    fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);


private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    isFabMenuOpen = true;


private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    isFabMenuOpen = false;


public class FabHandler {

    public void onBaseFabClick(View view) {

        if (isFabMenuOpen)


    public void onCreateFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();


    public void onShareFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();



public void onBackPressed() {

    if (isFabMenuOpen)

Here are the screenshots

Floating Action Menu with Label Textview in new Cursive Font Family of Android

Floating Action Menu with Label Textview in new Roboto Font Family of Android

No tests found with test runner 'JUnit 4'

When I face this problem I just edit the file and save it... works like charm

What is the most appropriate way to store user settings in Android application

First of all I think User's data shouldn't be stored on phone, and if it is must to store data somewhere on the phone it should be encrypted with in the apps private data. Security of users credentials should be the priority of the application.

The sensitive data should be stored securely or not at all. In the event of a lost device or malware infection, data stored insecurely can be compromised.

Google Maps v2 - set both my location and zoom in

@CommonsWare's answer doesn't not actually work. I found that this is working properly :

map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

How to set gradle home while importing existing project in Android studio

If you are on a Windows machine, gradle home is located inside the installation folder of your Android Studio, usually at:

C:\Program Files\Android\Android Studio\gradle\gradle-5.1.1

Change the version if you have a different one.

What are the possible values of the Hibernate configuration and what do they do

validate: It validates the schema and makes no changes to the DB.
Assume you have added a new column in the mapping file and perform the insert operation, it will throw an Exception "missing the XYZ column" because the existing schema is different than the object you are going to insert. If you alter the table by adding that new column manually then perform the Insert operation then it will definitely insert all columns along with the new column to the Table. Means it doesn't make any changes/alters the existing schema/table.

update: it alters the existing table in the database when you perform operation. You can add or remove columns with this option of hbm2ddl. But if you are going to add a new column that is 'NOT NULL' then it will ignore adding that particular column to the DB. Because the Table must be empty if you want to add a 'NOT NULL' column to the existing table.

Add or change a value of JSON key with jquery or javascript

Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:

data.busNum = 12345;

Get class labels from Keras functional model

In addition to @Emilia Apostolova answer to get the ground truth labels, from

generator = train_datagen.flow_from_directory("train", batch_size=batch_size)

just call

y_true_labels = generator.classes

What's the main difference between int.Parse() and Convert.ToInt32

Have a look in reflector:


public static int Parse(string s)
    return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);

which is a call to:

internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
    byte* stackBuffer = stackalloc byte[1 * 0x72];
    NumberBuffer number = new NumberBuffer(stackBuffer);
    int num = 0;
    StringToNumber(s, style, ref number, info, false);
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
        if (!HexNumberToInt32(ref number, ref num))
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        return num;
    if (!NumberToInt32(ref number, ref num))
        throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
    return num;


public static int ToInt32(string value)
    if (value == null)
        return 0;
    return int.Parse(value, CultureInfo.CurrentCulture);

As the first (Dave M's) comment says.

#pragma pack effect

#pragma is used to send non-portable (as in this compiler only) messages to the compiler. Things like disabling certain warnings and packing structs are common reasons. Disabling specific warnings is particularly useful if you compile with the warnings as errors flag turned on.

#pragma pack specifically is used to indicate that the struct being packed should not have its members aligned. It's useful when you have a memory mapped interface to a piece of hardware and need to be able to control exactly where the different struct members point. It is notably not a good speed optimization, since most machines are much faster at dealing with aligned data.

Javascript seconds to minutes and seconds

You've done enough code to track minutes and seconds portions of time.

What you could do is add the hours factor in:

var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);

var mind = hrd % 60;
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

var moreminutes = minutes + hours * 60

This would give you what you need also.

How to add extra whitespace in PHP?

To render more than one whitespace on most web browsers use &nbsp; instead of normal white spaces.

echo "<p>Hello &nbsp;&nbsp;&nbsp; punt"; // This will render as Hello   Punt (with 4 white spaces)
echo "<p> Hello       punt"; // This will render as Hello punt (with one space)

For showing data in raw format (with exact number of spaces and "enters") use HTML <pre> tag.

echo "<pre>Hello        punt</pre>"; //Will render exactly as written here (8 white spaces)

Or you can use some CSS to style current block, not to break text or strip spaces (I don't know, but this one)

Any way you do the output will be the same but the browser itself strips double white spaces and renders as one.

How to change time in DateTime?

DateTime is an immutable type, so you can't change it.

However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.

Something like this:

var newDt = s.Date + TimeSpan.FromHours(2);

How to create an Oracle sequence starting with max value from a table?

Bear in mid, the MAX value will only be the maximum of committed values. It might return 1234, and you may need to consider that someone has already inserted 1235 but not committed.

How to fix C++ error: expected unqualified-id

Semicolon should be at the end of the class definition rather than after the name:

class WordGame

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

If you don't want to recompile (as Visual Leak Detector requires) I would recommend WinDbg, which is both powerful and fast (though it's not as easy to use as one could desire).

On the other hand, if you don't want to mess with WinDbg, you can take a look at UMDH, which is also developed by Microsoft and it's easier to learn.

Take a look at these links in order to learn more about WinDbg, memory leaks and memory management in general:

Android: Background Image Size (in Pixel) which Support All Devices

Android Devices Matrices

                            ldpi     mdpi     hdpi    xhdpi    xxhdpi      xxxhdpi
Launcher And Home           36*36    48*48   72*72    96*96    144*144     192*192
Toolbar And Tab             24*24    32*32   48*48    64*64    96*96       128*128
Notification                18*18    24*24   36*36    48*48    72*72       96*96 
Background                 240*320  320*480 480*800  768*1280  1080 *1920  1440*2560 

(For good approach minus Toolbar Size From total height of Background Screen and then Design Graphics of Screens )

For More Help (This link includes tablets also):

Android Native Icons (Recommended) You can change color of these icons programmatically.

What is __gxx_personality_v0 for?

Exception handling is included in free standing implementations.

The reason of this is that you possibly use gcc to compile your code. If you compile with the option -### you will notice it is missing the linker-option -lstdc++ when it invokes the linker process . Compiling with g++ will include that library, and thus the symbols defined in it.

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

Try this:

Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help

+extension name        Enable extension
-extension name        Disable extension

Javascript reduce on array of objects

I did it in ES6 with a little improvement:

arr.reduce((a, b) => ({x: a.x + b.x})).x

return number

Is there a cross-domain iframe height auto-resizer that works?

You have three alternatives:

1. Use iFrame-resizer

This is a simple library for keeping iFrames sized to their content. It uses the PostMessage and MutationObserver APIs, with fall backs for IE8-10. It also has options for the content page to request the containing iFrame is a certain size and can also close the iFrame when your done with it.

2. Use Easy XDM (PostMessage + Flash combo)

Easy XDM uses a collection of tricks for enabling cross-domain communication between different windows in a number of browsers, and there are examples for using it for iframe resizing:

Easy XDM works by using PostMessage on modern browsers and a Flash based solution as fallback for older browsers.

See also this thread on Stackoverflow (there are also others, this is a commonly asked question). Also, Facebook would seem to use a similar approach.

3. Communicate via a server

Another option would be to send the iframe height to your server and then poll from that server from the parent web page with JSONP (or use a long poll if possible).

Converting an OpenCV Image to Black and White

Specifying CV_THRESH_OTSU causes the threshold value to be ignored. From the documentation:

Also, the special value THRESH_OTSU may be combined with one of the above values. In this case, the function determines the optimal threshold value using the Otsu’s algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu’s method is implemented only for 8-bit images.

This code reads frames from the camera and performs the binary threshold at the value 20.

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;

int main(int argc, const char * argv[]) {

    VideoCapture cap; 
    if(argc > 1)[1])); 
    Mat frame; 
    namedWindow("video", 1); 
    for(;;) {
        cap >> frame; 
        cvtColor(frame, frame, CV_BGR2GRAY);
        threshold(frame, frame, 20, 255, THRESH_BINARY);
        imshow("video", frame); 
        if(waitKey(30) >= 0) 

    return 0;

TypeError : Unhashable type

... and so you should do something like this:

set(tuple ((a,b) for a in range(3)) for b in range(3))

... and if needed convert back to list

Reading all files in a directory, store them in objects, and send the object

For the code to work smoothy in different enviroments, path.resolve can be used in places where path is manipulated. Here is code which works better.

Reading part:

var fs = require('fs');

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
    filenames.forEach(function(filename) {
      fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
        if (err) {
        onFileContent(filename, content);

Storing part:

var data = {};
readFiles(path.resolve(__dirname, 'dirname/'), function(filename, content) {
  data[filename] = content;
}, function(error) {
  throw err;

ASP.NET email validator regex

Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET


By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator

How to rename JSON key

JSON.parse has two parameters. The second parameter, reviver, is a transform function that can be formatted output format we want. See ECMA specification here.

In reviver function:

  • if we return undefined, the original property will be deleted.
  • this is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function.
const json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}]';

const obj = JSON.parse(json, function(k, v) {
    if (k === "_id") { = v;
        return; # if return  undefined, orignal property will be removed
    return v;

const res = JSON.stringify(obj);


[{"email":"[email protected]","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"[email protected]","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}]

Why do Sublime Text 3 Themes not affect the sidebar?

I thought I would put a note here that explains a basic misconception for a lot of people who are using these Text Editors... Sublime Text in particular (or at least that's the one I use, so I don't know how it works for other editors):

There are "Themes" and there are "Color Schemes". They are similar but affect different things. "Themes" actively change the entire UI, and can include a Color Scheme if you set it up that way. This typically includes the sidebar, and can also include options for the file tabs, and some even include icons for the sidebar as well. And then we have "Color Schemes" which only change the coding windows and nothing else... not the Sidebar, nor the File tabs, etc.

The confusion happens because some people call Color Schemes "Themes" which makes folks think that their "Theme" is going to change everything.... when technically, it's just a color scheme.

And an additional note: Themes don't automatically install for all users. When I install a Theme, I have to open my User preferences (under "preferences > Settings - User"), and then you have to add the line which says something like:

"theme": "Theme-Name.sublime-theme" 

(where "Theme-Name" is the name of your theme).

This is different than just activating a color scheme. If you've chosen a color scheme via the dropdown menus in Sublime Text, you will see a line in there like this:

"color_scheme": "Packages/Color-Scheme-Name.tmTheme"

(where "Color-Scheme-Name" is the name of your color scheme).

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here

HTML form with two submit buttons and two "target" attributes

On each of your buttons you could have the following;

<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">

Then have a few small js functions;

<script type="text/javascript">
function frmSubmitSameWin() { = '';

function frmSubmitNewWin() { = '_blank';

That should do the trick.

Pass an array of integers to ASP.NET Web API?

As Filip W points out, you might have to resort to a custom model binder like this (modified to bind to actual type of param):

public IEnumerable<Category> GetCategories([ModelBinder(typeof(CommaDelimitedArrayModelBinder))]long[] categoryIds) 
    // do your thing

public class CommaDelimitedArrayModelBinder : IModelBinder
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        var key = bindingContext.ModelName;
        var val = bindingContext.ValueProvider.GetValue(key);
        if (val != null)
            var s = val.AttemptedValue;
            if (s != null)
                var elementType = bindingContext.ModelType.GetElementType();
                var converter = TypeDescriptor.GetConverter(elementType);
                var values = Array.ConvertAll(s.Split(new[] { ","},StringSplitOptions.RemoveEmptyEntries),
                    x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });

                var typedValues = Array.CreateInstance(elementType, values.Length);

                values.CopyTo(typedValues, 0);

                bindingContext.Model = typedValues;
                // change this line to null if you prefer nulls to empty arrays 
                bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);
            return true;
        return false;

And then you can say:

/Categories?categoryids=1,2,3,4 and ASP.NET Web API will correctly bind your categoryIds array.

How can I convert IPV6 address to IPV4 address?

Some googling led me to the following post:

The code provided in the post is in C, but it shouldn't be too hard to rewrite it to Java.

How do I timestamp every ping result?

Try this line.

while sleep 1;do echo "$(date +%d-%m-%y-%T) $(ping -c 1 | gawk 'FNR==2{print "Response from:",$4,$8}')" | tee -a /yourfolder/pingtest.log;done

You'll have to cancel it with ctrl-c tho.

How to check if a specified key exists in a given S3 bucket using Java

Alternatively you can use Minio-Java client library, its Open Source and compatible with AWS S3 API.

You can use Minio-Java examples for the same.

import io.minio.MinioClient;
import io.minio.errors.MinioException;


import org.xmlpull.v1.XmlPullParserException;

public class GetObject {
  public static void main(String[] args)
    throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException, MinioException {
    // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are
    // dummy values, please replace them with original values.
    // Set s3 endpoint, region is calculated automatically
    MinioClient s3Client = new MinioClient("", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY");
    InputStream stream = s3Client.getObject("my-bucketname", "my-objectname");

    byte[] buf = new byte[16384];
    int bytesRead;
    while ((bytesRead =, 0, buf.length)) >= 0) {
      System.out.println(new String(buf, 0, bytesRead));


I hope it helps.

Disclaimer : I work for Minio

How can I determine the current CPU utilization from the shell?

You can use top or ps commands to check the CPU usage.

using top : This will show you the cpu stats

top -b -n 1 |grep ^Cpu

using ps: This will show you the % cpu usage for each process.

ps -eo pcpu,pid,user,args | sort -r -k1 | less

Also, you can write a small script in bash or perl to read /proc/stat and calculate the CPU usage.

How can I check for an empty/undefined/null string in JavaScript?

You can easily add it to native String object in JavaScript and reuse it over and over...
Something simple like below code can do the job for you if you want to check '' empty strings:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);

Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);

and you can call it this way:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false

Where is the web server root directory in WAMP?

To check what is your root directory go to httpd.conf file of apache and search for "DocumentRoot".The location following it is your root directory

The default XML namespace of the project must be the MSBuild XML namespace

The projects you are trying to open are in the new .NET Core csproj format. This means you need to use Visual Studio 2017 which supports this new format.

For a little bit of history, initially .NET Core used project.json instead of *.csproj. However, after some considerable internal deliberation at Microsoft, they decided to go back to csproj but with a much cleaner and updated format. However, this new format is only supported in VS2017.

If you want to open the projects but don't want to wait until March 7th for the official VS2017 release, you could use Visual Studio Code instead.

How do you debug PHP scripts?

Manual debugging is generally quicker for me - var_dump() and debug_print_backtrace() are all the tools you need to arm your logic with.

How do we change the URL of a working GitLab install?

GitLab Omnibus

For an Omnibus install, it is a little different.

The correct place in an Omnibus install is:

    external_url ''

Finally, you'll need to execute sudo gitlab-ctl reconfigure and sudo gitlab-ctl restart so the changes apply.

I was making changes in the wrong places and they were getting blown away.

The incorrect paths are:


Pay attention to those warnings that read:

# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.

How to fully clean bin and obj folders within Visual Studio?

I can't add a comment yet (no minimal reputation reached)
so I leave this reply to underline that:

the "BeforeBuild" action with <RemoveDir Directories="$(BaseIntermediateOutputPath)" /> is great but, for me, is conflicting with an Entity Framework model included into the same project.

The error I receive is:

Error reading resource '{mymodel}.csdl' -- 'Could not find a part of the path '{myprojectpath}\obj\Release\edmxResourcesToEmbed\{mymodel}.csdl

I suppose, the "edmxResourcesToembed" is created before the "BeforeBuild" target action is executed.

How to set radio button selected value using jquery

for multiple dropdowns

$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");

here RBLExperienceApplicable is the matching part of the radio button groups input tag ids. and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable

PHP : send mail in localhost

It is configured to use localhost:25 for the mail server.

The error message says that it can't connect to localhost:25.

Therefore you have two options:

  1. Install / Properly configure an SMTP server on localhost port 25
  2. Change the configuration to point to some other SMTP server that you can connect to

JBoss AS 7: How to clean up tmp?

I do not have experience with version 7 of JBoss but with 5 I often had issues when redeploying apps which went away when I cleaned the work and tmp folder. I wrote a script for that which was executed everytime the server shut down. Maybe executing it before startup is better considering abnormal shutdowns (which weren't uncommon with Jboss 5 :))

Limit Decimal Places in Android EditText

Simpler solution without using regex:

import android.text.InputFilter;
import android.text.Spanned;

 * Input filter that limits the number of decimal digits that are allowed to be
 * entered.
public class DecimalDigitsInputFilter implements InputFilter {

  private final int decimalDigits;

   * Constructor.
   * @param decimalDigits maximum decimal digits
  public DecimalDigitsInputFilter(int decimalDigits) {
    this.decimalDigits = decimalDigits;

  public CharSequence filter(CharSequence source,
      int start,
      int end,
      Spanned dest,
      int dstart,
      int dend) {

    int dotPos = -1;
    int len = dest.length();
    for (int i = 0; i < len; i++) {
      char c = dest.charAt(i);
      if (c == '.' || c == ',') {
        dotPos = i;
    if (dotPos >= 0) {

      // protects against many dots
      if (source.equals(".") || source.equals(","))
          return "";
      // if the text is entered before the dot
      if (dend <= dotPos) {
        return null;
      if (len - dotPos > decimalDigits) {
        return "";

    return null;


To use:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(2)});

How to convert a Drawable to a Bitmap?

Maybe this will help someone...

From PictureDrawable to Bitmap, use:

private Bitmap pictureDrawableToBitmap(PictureDrawable pictureDrawable){ 
    Bitmap bmp = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(bmp); 
    return bmp; 

... implemented as such:

Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);

Cannot connect to local SQL Server with Management Studio

I was having this problem on a Windows 7 (64 bit) after a power outage. The SQLEXPRESS service was not started even though is status was set to 'Automatic' and the mahine had been rebooted several times. Had to start the service manually.

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

Passing by reference in C

In C, to pass by reference you use the address-of operator & which should be used against a variable, but in your case, since you have used the pointer variable p, you do not need to prefix it with the address-of operator. It would have been true if you used &i as the parameter: f(&i).

You can also add this, to dereference p and see how that value matches i:

printf("p=%d \n",*p);

When 1 px border is added to div, Div size increases, Don't want to do that

Just decrease the width and height by double of border-width

Execute Stored Procedure from a Function

Another option, in addition to using OPENQUERY and xp_cmdshell, is to use SQLCLR (SQL Server's "CLR Integration" feature). Not only is the SQLCLR option more secure than those other two methods, but there is also the potential benefit of being able to call the stored procedure in the current session such that it would have access to any session-based objects or settings, such as:

  • temporary tables
  • temporary stored procedures

This can be achieved by using "context connection = true;" as the ConnectionString. Just keep in mind that all other restrictions placed on T-SQL User-Defined Functions will be enforced (i.e. cannot have any side-effects).

If you use a regular connection (i.e. not using the context connection), then it will operate as an independent call, just like it does when using the OPENQUERY and xp_cmdshell methods.

HOWEVER, please keep in mind that if you will be using a function that calls a stored procedure (regardless of which of the 3 noted methods you use) in a statement that affects more than 1 row, then the behavior cannot be expected to run once per row. As @MartinSmith mentioned in a comment on @MatBailie's answer, the Query Optimizer does not guarantee either the timing or number of executions of functions. But if you are using it in a SET @Variable = function(); statement or SELECT * FROM function(); query, then it should be ok.

An example of using a .NET / C# SQLCLR user-defined function to execute a stored procedure is shown in the following article (which I wrote):

Stairway to SQLCLR Level 2: Sample Stored Procedure and Function

Setting Elastic search limit to "unlimited"

You can use the from and size parameters to page through all your data. This could be very slow depending on your data and how much is in the index.

Trying to Validate URL Using JavaScript

Here's a regular expression which might fit the bill (it's very long):


There are some caveats to its usage, namely it does not validate URIs which contain additional information after the user name (e.g. "username:password"). Also, only IPv6 addresses can be contained within the IP literal syntax and the "IPvFuture" syntax is currently ignored and will not validate against this regular expression. Port numbers are also constrained to be between 0 and 65,535. Also, only the file scheme can use triple slashes (e.g. "file:///etc/sysconfig") and can ignore both the query and fragment parts of a URI. Finally, it is geared towards regular URIs and not IRIs, hence the extensive focus on the ASCII character set.

This regular expression could be expanded upon, but it's already complex and long enough as it is. I also cannot guarantee it's going to be "100% accurate" or "bug free", but it should correctly validate URIs for all schemes.

You will need to do additional verification for any scheme-specific requirements or do URI normalization as this regular expression will validate a very broad range of URIs.

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
            std::thread([after, task]() {


void test1(void)

void test2(int a)
    printf("%i\n", a);

int main()
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;

Outputs after two seconds:


Google reCAPTCHA: How to get user response and validate in the server side?

Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.

      //  echo '<pre>'; print_r($_REQUEST); die('END');
        $post = [
            'secret' => 'Your Secret key',
            'response' => $_REQUEST['g-recaptcha-response'],
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec($ch);

        curl_close ($ch);
        echo '<pre>'; print_r($server_output); die('ss');
    <title>reCAPTCHA demo: Explicit render for multiple widgets</title>
    <script type="text/javascript">
      var site_key = 'Your Site key';
      var verifyCallback = function(response) {
      var widgetId1;
      var widgetId2;
      var onloadCallback = function() {
        // Renders the HTML element with id 'example1' as a reCAPTCHA widget.
        // The id of the reCAPTCHA widget is assigned to 'widgetId1'.
        widgetId1 = grecaptcha.render('example1', {
          'sitekey' : site_key,
          'theme' : 'light'
        widgetId2 = grecaptcha.render(document.getElementById('example2'), {
          'sitekey' : site_key
        grecaptcha.render('example3', {
          'sitekey' : site_key,
          'callback' : verifyCallback,
          'theme' : 'dark'
    <!-- The g-recaptcha-response string displays in an alert message upon submit. -->
    <form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
      <div id="example1"></div>
      <input type="submit" value="getResponse">
    <!-- Resets reCAPTCHA widgetId2 upon submit. -->
    <form action="javascript:grecaptcha.reset(widgetId2);">
      <div id="example2"></div>
      <input type="submit" value="reset">
    <!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
    <form action="?" method="POST">
      <div id="example3"></div>
      <input type="submit" value="Submit">
    <script src=""
        async defer>

YouTube embedded video: set different thumbnail

This tool gave me following results which helps me achieve the task as following code.

<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
    function play(){
        document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="" frameborder="0"></iframe>';

Align button at the bottom of div using CSS

CSS3 flexbox can also be used to align button at the bottom of parent element.

Required HTML:

<div class="container">
  <div class="btn-holder">
    <button type="button">Click</button>

Necessary CSS:

.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
.container .btn-holder {
  justify-content: flex-end;
  display: flex;


Output Image

Useful Resources:

* {box-sizing: border-box;}_x000D_
body {_x000D_
  background: linear-gradient(orange, yellow);_x000D_
  font: 14px/18px Arial, sans-serif;_x000D_
  margin: 0;_x000D_
.container {_x000D_
  justify-content: space-between;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  display: flex;_x000D_
  padding: 10px;_x000D_
.container .btn-holder {_x000D_
  justify-content: flex-end;_x000D_
  display: flex;_x000D_
.container .btn-holder button {_x000D_
  padding: 10px 25px;_x000D_
  background: blue;_x000D_
  font-size: 16px;_x000D_
  border: none;_x000D_
  color: #fff;_x000D_
<div class="container">_x000D_
  <p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>_x000D_
  <div class="btn-holder">_x000D_
    <button type="button">Click</button>_x000D_

Git - Ignore files during merge

You could start by using git merge --no-commit, and then edit the merge however you like i.e. by unstaging config.xml or any other file, then commit. I suspect you'd want to automate it further after that using hooks, but I think it'd be worth going through manually at least once.

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

It sometimes happens when you try to Insert/Update an entity while the foreign key that you are trying to Insert/Update actually does not exist. So, be sure that the foreign key exists and try again.

How do I trim whitespace?

For whitespace on both sides use str.strip:

s = "  \t a string example\t  "
s = s.strip()

For whitespace on the right side use rstrip:

s = s.rstrip()

For whitespace on the left side lstrip:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r')

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import re
print(re.sub('[\s+]', '', s))

That should print out:


@Nullable annotation usage

This annotation is commonly used to eliminate NullPointerExceptions. @Nullable says that this parameter might be null. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null. If you would try to pass null without an annotation the framework would refuse to do it's job.

What is more @Nullable might be used with @NotNull annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.

How to set tint for an image view programmatically in android?

After i tried all methods and they did not work for me.

I get the solution by using another PortDuff.MODE.


Stored procedure or function expects parameter which is not supplied

In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :

cmd.CommandType = System.Data.CommandType.StoredProcedure;

This is obviously not the case in the question above, but exception description is not very clear in this case, so I decided to specify that.

How to compare strings in an "if" statement?

You're looking for the function strcmp, or strncmp from string.h.

Since strings are just arrays, you need to compare each character, so this function will do that for you:

if (strcmp(favoriteDairyProduct, "cheese") == 0)
    printf("You like cheese too!");
    printf("I like cheese more.");

Further reading: strcmp at

What does the Java assert keyword do, and when should it be used?

To recap (and this is true of many languages not just Java):

"assert" is primarily used as a debugging aid by software developers during the debugging process. Assert-messages should never appear. Many languages provide a compile-time option that will cause all "asserts" to be ignored, for use in generating "production" code.

"exceptions" are a handy way to handle all kinds of error conditions, whether or not they represent logic errors, because, if you run into an error-condition such that you cannot continue, you can simply "throw them up into the air," from wherever you are, expecting someone else out there to be ready to "catch" them. Control is transferred in one step, straight from the code that threw the exception, straight to the catcher's mitt. (And the catcher can see the complete backtrace of calls that had taken place.)

Furthermore, callers of that subroutine don't have to check to see if the subroutine succeeded: "if we're here now, it must have succeeded, because otherwise it would have thrown an exception and we wouldn't be here now!" This simple strategy makes code-design and debugging much, much easier.

Exceptions conveniently allow fatal-error conditions to be what they are: "exceptions to the rule." And, for them to be handled by a code-path that is also "an exception to the rule ... "fly ball!"

How to sleep the thread in node.js without affecting other threads?

In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

   var startTimeout = function(timeout, i){
        setTimeout(function() {
        }, timeout);

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;

This examples waits 1 second after each request before sending the next one.

IF statement: how to leave cell blank if condition is false ("" does not work)

You could try this.

=IF(A1=1,B1,TRIM(" "))

If you put this formula in cell C1, then you could test if this cell is blank in another cells


You should see TRUE. I've tried on Microsoft Excel 2013. Hope this helps.

make html text input field grow as I type?

If you're allowed to use the ch measurement (monospaced) it completely solved what I was trying to do.

onChange(e => { = `${}ch`;

This was exactly what I needed but I'm not sure if it works for dynamic width font-families.

Where is android_sdk_root? and how do I set it.?

Open the terminal and run the command: nano $HOME/.bashrc aggregate the follow line:

export ANDROID_HOME=$HOME/Android/Sdk
export ANDROID_SDK_ROOT=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/platform-tools

Ctrl+o save and ctrl+x close.

And run the command:

source $HOME/.bashrc


Resizing SVG in html?

I have an SVG file in HTML [....] IS there any way to specify that you want an SVG image displayed smaller or larger than it actually is stored in the file system?

SVG graphics, like other creative works, are protected under copyright law in most countries. Depending on jurisdiction, license of the work or whether or not you are the copyright holder you may not be able to modify the SVG without violating copyright law, believe it or not.

But laws are tricky topics and sometimes you just want to get shit done. Therefore you may adjust the scale of the graphic without modifying the work itself using the img tag with width attribute within your HTML.

Using an external HTTP request to specify the size:

<img width="96" src="/path/to/image.svg">

Specifying size in markup using a Data URI:

<img width="96" src="data:image/svg+xml,...">

SVGs can be Optimized for Data URIs to create SVG Favicon images suitable for any size:

<link rel="icon" sizes="any" href="data:image/svg+xml,%3Csvg%20viewBox='0%200%2046%2045'%20xmlns=''%3E%3Ctitle%3EAfter%20Dark%3C/title%3E%3Cpath%20d='M.708%2045L23%20.416%2045.292%2045H.708zM35%2038L23%2019%2011%2038h24z'%20fill='%23000'/%3E%3C/svg%3E">

Nullable types: better way to check for null or zero in c#

Although I quite like the accepted answer, I think that, for completeness, this option should be mentioned as well:

if (item.Rate.GetValueOrDefault() == 0) { }

This solution

¹ This should not influence your decision, though, since these kinds of micro-optimization are unlikely to make any difference.

C# password TextBox in a website

@JohnHartsock: You can also write type="password". It's acceptable in aspx.

<asp:TextBox ID="txtBox" type="password" runat="server"/>

requestFeature() must be called before adding content

I know it's over a year old, but calling requestFeature() never solved my problem. In fact I don't call it at all.

It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.

AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog() to update that view.

Another alternative is to leverage AsyncTask for dialogs.

A final solution that I used is below:

public class CustomDialog extends AlertDialog {

   private View content;

   public CustomDialog(Context context) {

       LayoutInflater li = LayoutInflater.from(context);
       content = li.inflate(R.layout.custom_view, null);

       setUpAdditionalStuff(); // do more view cleanup

   private void setUpAdditionalStuff() {
       // ...

   // Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method  
   public void prepare() {
       setIcon( getIcon() );
       // ...

* Some Additional notes:

  1. Don't rely on hiding the title. There is often an empty space despite the title not being set.
  2. Don't try to build your own View with header footer and middle view. The header, as stated above, may not be entirely hidden despite requesting FEATURE_NO_TITLE.
  3. Don't heavily style your content view with color attributes or text size. Let the dialog handle that, other wise you risk putting black text on a dark blue dialog because the vendor inverted the colors.

How to select min and max values of a column in a datatable?

var answer = accountTable.Aggregate(new { Min = int.MinValue, Max = int.MaxValue }, 
                                        (a, b) => new { Min = Math.Min(a.Min, b.Field<int>("AccountLevel")),
                                                        Max = Math.Max(a.Max, b.Field<int>("AccountLevel")) });
int min = answer.Min;
int max = answer.Max;

1 iteration, linq style :)

How do you use the Immediate Window in Visual Studio?

One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.

For example, if you had a static method that returns the sum of two numbers such as:

private static int GetSum(int a, int b)
    return a + b;

Then in the Immediate Window you can type the following:

? GetSum(2, 4)

As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.

For example, let’s say this is what your class looks like:

private class Foo
    public string GetMessage()
        return "hello";

If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):

? foo.GetMessage(); // object ‘foo’ already exists

In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:

? Foo foo = new Foo(); // new instance of ‘Foo’
? foo.GetMessage()

You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:

? string msg = foo.GetMessage();
? msg + " there!"
"hello there!"

Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:

? new Foo().GetMessage()

A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.

Along with inspecting methods, you can do simple math equations:

? 5 * 6

or compare values:

? 5==6
? 6==6

The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.

Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.

Unfortunately, another drawback of the Immediate Window is that it does not support loops.


I solved my problem with adding these in build gradle:

   defaultConfig {
   multiDexEnabled true

 dependencies {
 compile ''

another solution can be removing unnecessary libraries

How to include view/partial specific styling in AngularJS

I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.

UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.

UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.

In case anyone in the future is interested, here's what I came up with:

1. Create a custom directive for the <head> element:

app.directive('head', ['$rootScope','$compile',
    function($rootScope, $compile){
        return {
            restrict: 'E',
            link: function(scope, elem){
                var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
                scope.routeStyles = {};
                $rootScope.$on('$routeChangeStart', function (e, next, current) {
                    if(current && current.$$route && current.$$route.css){
                            current.$$route.css = [current.$$route.css];
                        angular.forEach(current.$$route.css, function(sheet){
                            delete scope.routeStyles[sheet];
                    if(next && next.$$route && next.$$route.css){
                            next.$$route.css = [next.$$route.css];
                        angular.forEach(next.$$route.css, function(sheet){
                            scope.routeStyles[sheet] = sheet;

This directive does the following things:

  1. It compiles (using $compile) an html string that creates a set of <link /> tags for every item in the scope.routeStyles object using ng-repeat and ng-href.
  2. It appends that compiled set of <link /> elements to the <head> tag.
  3. It then uses the $rootScope to listen for '$routeChangeStart' events. For every '$routeChangeStart' event, it grabs the "current" $$route object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head> tag. It also grabs the "next" $$route object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head> tag.
  4. And the ng-repeat part of the compiled <link /> tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles object.

Note: this requires that your ng-app attribute is on the <html> element, not on <body> or anything inside of <html>.

2. Specify which stylesheets belong to which routes using the $routeProvider:

app.config(['$routeProvider', function($routeProvider){
        .when('/some/route/1', {
            templateUrl: 'partials/partial1.html', 
            controller: 'Partial1Ctrl',
            css: 'css/partial1.css'
        .when('/some/route/2', {
            templateUrl: 'partials/partial2.html',
            controller: 'Partial2Ctrl'
        .when('/some/route/3', {
            templateUrl: 'partials/partial3.html',
            controller: 'Partial3Ctrl',
            css: ['css/partial3_1.css','css/partial3_2.css']

This config adds a custom css property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart' event as .$$route. So when listening to the '$routeChangeStart' event, we can grab the css property that we specified and append/remove those <link /> tags as needed. Note that specifying a css property on the route is completely optional, as it was omitted from the '/some/route/2' example. If the route doesn't have a css property, the <head> directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3' example above, where the css property is an array of relative paths to the stylesheets needed for that route.

3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.

Hope that helps someone else who might be struggling with this issue as much as I was.

Using request.setAttribute in a JSP page

Correct me if wrong...I think request does persist between consecutive pages..

Think you traverse from page 1--> page 2-->page 3.

You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".

I mean something like this in page 2 fails:

Where as the same thing has worked in case of page 1 like:

So I think I would need to proceed with either of the two options suggested by Phill.

How to access html form input from code behind

What I'm guessing is that you need to set those input elements to runat="server".

So you won't be able to access the control

<input type="text" name="email" id="myTextBox" />

But you'll be able to work with

<input type="text" name="email" id="myTextBox" runat="server" />

And read from it by using

string myStringFromTheInput = myTextBox.Value;

Android: How to turn screen on and off programmatically?

Simply add


or call


on parent view.

C++: constructor initializer for arrays

This is my solution for your reference:

struct Foo
    Foo(){}//used to make compiler happy!
    Foo(int x){/*...*/}

struct Bar
    Foo foo[3];

        //initialize foo array here:
        for(int i=0;i<3;++i)

Darken background image on hover

try this


.image {
    background: url('');
    width: 58px;
    height: 58px;
filter:alpha(opacity=40); /* For IE8 and earlier */
    background: url('');
    width: 58px;
    height: 58px;




<div class="image"></div>