Programs & Examples On #Innertext

the innerText is used to set or retrieve the text between the start and end tags of the object.

Javascript .querySelector find <div> by innerTEXT

Here's the XPath approach but with a minimum of XPath jargon.

Regular selection based on element attribute values (for comparison):

// for matching <element class="foo bar baz">...</element> by 'bar'
var things = document.querySelectorAll('[class*="bar"]');
for (var i = 0; i < things.length; i++) {
    things[i].style.outline = '1px solid red';
}

XPath selection based on text within element.

// for matching <element>foo bar baz</element> by 'bar'
var things = document.evaluate('//*[contains(text(),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
    things.snapshotItem(i).style.outline = '1px solid red';
}

And here's with case-insensitivity since text is more volatile:

// for matching <element>foo bar baz</element> by 'bar' case-insensitively
var things = document.evaluate('//*[contains(translate(text(),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
    things.snapshotItem(i).style.outline = '1px solid red';
}

How to get element by innerText

Simply pass your substring into the following line:

Outer HTML

document.documentElement.outerHTML.includes('substring')

Inner HTML

document.documentElement.innerHTML.includes('substring')

You can use these to search through the entire document and retrieve the tags that contain your search term:

function get_elements_by_inner(word) {
    res = []
    elems = [...document.getElementsByTagName('a')];
    elems.forEach((elem) => { 
        if(elem.outerHTML.includes(word)) {
            res.push(elem)
        }
    })
    return(res)
}

Usage:

How many times is the user "T3rm1" mentioned on this page?

get_elements_by_inner("T3rm1").length

1

How many times is jQuery mentioned?

get_elements_by_inner("jQuery").length

3

Get all elements containing the word "Cybernetic":

get_elements_by_inner("Cybernetic")

enter image description here

pyplot axes labels for subplots

plt.setp() will do the job:

# plot something
fig, axs = plt.subplots(3,3, figsize=(15, 8), sharex=True, sharey=True)
for i, ax in enumerate(axs.flat):
    ax.scatter(*np.random.normal(size=(2,200)))
    ax.set_title(f'Title {i}')

# set labels
plt.setp(axs[-1, :], xlabel='x axis label')
plt.setp(axs[:, 0], ylabel='y axis label')

enter image description here

Passing parameter to controller action from a Html.ActionLink

You are using the incorrect overload of ActionLink. Try this

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

How do I debug jquery AJAX calls?

you can use success function, once see this jquery.ajax settings

 $('#ChangePermission').click(function(){
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
        'user': document.GetElementById("user").value,
        'perm': document.GetElementById("perm").value
        }
       success:function(result)//we got the response
       {
        //you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
       }
    })
})

we can also have error() function

hope this helps you

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

VBA Check if variable is empty

I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.

At first I just used a boolean var and IF statement:

Dim i as integer, bol as boolean
   If bol = false then
      i = ValueIWantToAssign
      bol = True
   End If

In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.

Like so:

Dim i as integer
ForLoopStart
   If ConditionIsMet Then
      i = ValueIWantToAssign
   Exit For
   End If
ForLoopEnd

Redirect Windows cmd stdout and stderr to a single file

Anders Lindahl's answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.

REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt

How to create a dump with Oracle PL/SQL Developer?

Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?

Creating executable files in Linux

Make file executable:

chmod +x file

Find location of perl:

which perl

This should return something like

/bin/perl sometimes /usr/local/bin

Then in the first line of your script add:

#!"path"/perl with path from above e.g.

#!/bin/perl

Then you can execute the file

./file

There may be some issues with the PATH, so you may want to change that as well ...

AttributeError: 'module' object has no attribute 'model'

As the error message says in the last line: the module models in the file c:\projects\mysite..\mysite\polls\models.py contains no class model. This error occurs in the definition of the Poll class:

class Poll(models.model):

Either the class model is misspelled in the definition of the class Poll or it is misspelled in the module models. Another possibility is that it is completely missing from the module models. Maybe it is in another module or it is not yet implemented in models.

Vue equivalent of setTimeout?

Arrow Function

The best and simplest way to solve this problem is by using an arrow function () => {}:

    addToBasket() {
        var item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        // now 'this' is referencing the Vue object and not the 'setTimeout' scope
        setTimeout(() => this.basketAddSuccess = false, 2000);
    }

This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

Argument Passing

Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Add scope argument to func, pass this after delay in setTimeout
        setTimeout(function(scope) {
             scope.basketAddSuccess = false;
        }, 2000, this);
    }

(It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

Local Variable

Another possible, but less eloquent and less encouraged, way is to bind this to a var outside of setTimeout:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Declare self, which is accessible inside setTimeout func
        var self = this;
        setTimeout(function() {
             self.basketAddSuccess = false;
        }, 2000);
    }

Using an arrow function would eliminate the need for this extra variable entirely however, and really should be used unless something else is preventing its use.

How to compare only date components from DateTime in EF?

Just always compare the Date property of DateTime, instead of the full date time.

When you make your LINQ query, use date.Date in the query, ie:

var results = from c in collection
              where c.Date == myDateTime.Date
              select c;

Identify if a string is a number

If you want to catch a broader spectrum of numbers, à la PHP's is_numeric, you can use the following:

// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)

// Finds whether the given variable is numeric.

// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.

// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
    new Regex(  "^(" +
                /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                /*Bin*/ @"0b[01]+"      + "|" + 
                /*Oct*/ @"0[0-7]*"      + "|" +
                /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                ")$" );
static bool IsNumeric( string value )
{
    return _isNumericRegex.IsMatch( value );
}

Unit Test:

static void IsNumericTest()
{
    string[] l_unitTests = new string[] { 
        "123",      /* TRUE */
        "abc",      /* FALSE */
        "12.3",     /* TRUE */
        "+12.3",    /* TRUE */
        "-12.3",    /* TRUE */
        "1.23e2",   /* TRUE */
        "-1e23",    /* TRUE */
        "1.2ef",    /* FALSE */
        "0x0",      /* TRUE */
        "0xfff",    /* TRUE */
        "0xf1f",    /* TRUE */
        "0xf1g",    /* FALSE */
        "0123",     /* TRUE */
        "0999",     /* FALSE (not octal) */
        "+0999",    /* TRUE (forced decimal) */
        "0b0101",   /* TRUE */
        "0b0102"    /* FALSE */
    };

    foreach ( string l_unitTest in l_unitTests )
        Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );

    Console.ReadKey( true );
}

Keep in mind that just because a value is numeric doesn't mean it can be converted to a numeric type. For example, "999999999999999999999999999999.9999999999" is a perfeclty valid numeric value, but it won't fit into a .NET numeric type (not one defined in the standard library, that is).

Make a simple fade in animation in Swift?

Swift only solution

Similar to Luca's anwer, I use a UIView extension. Compared to his solution I use DispatchQueue.main.async to make sure animations are done on the main thread, alpha parameter for fading to a specific value and optional duration parameters for cleaner code.

extension UIView {
  func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
    DispatchQueue.main.async {
      UIView.animate(withDuration: duration) {
        self.alpha = alpha
      }
    }
  }

  func fadeIn(_ duration: TimeInterval = 0.3) {
    fadeTo(1.0, duration: duration)
  }

  func fadeOut(_ duration: TimeInterval = 0.3) {
    fadeTo(0.0, duration: duration)
  }
}

How to use it:

// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn()     // uses default duration of 0.3
yourView.fadeIn(1.0)  // uses custom duration (1.0 in this example)

// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut()    // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)

// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5)  // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)

How do I select last 5 rows in a table without sorting?

In SQL Server 2012 you can do this :

Declare @Count1 int ;

Select @Count1 = Count(*)
FROM    [Log] AS L

SELECT  
   *
FROM    [Log] AS L
ORDER BY L.id
OFFSET @Count - 5 ROWS
FETCH NEXT 5 ROWS ONLY;

How do I escape ampersands in batch files?

explorer "http://www.google.com/search?client=opera&rls=...."

How to find out what type of a Mat object is with Mat::type() in OpenCV

In OpenCV header "types_c.h" there are a set of defines which generate these, the format is CV_bits{U|S|F}C<number_of_channels>
So for example CV_8UC3 means 8 bit unsigned chars, 3 colour channels - each of these names map onto an arbitrary integer with the macros in that file.

Edit: See "types_c.h" for example:

#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))

eg.
depth = CV_8U = 0
cn = 3
CV_CN_SHIFT = 3

CV_MAT_DEPTH(0) = 0
(((cn)-1) << CV_CN_SHIFT) = (3-1) << 3 = 2<<3 = 16

So CV_8UC3 = 16 but you aren't supposed to use this number, just check type() == CV_8UC3 if you need to know what type an internal OpenCV array is.
Remember OpenCV will convert the jpeg into BGR (or grey scale if you pass '0' to imread) - so it doesn't tell you anything about the original file.

How to remove html special chars?

A plain vanilla strings way to do it without engaging the preg regex engine:

function remEntities($str) {
  if(substr_count($str, '&') && substr_count($str, ';')) {
    // Find amper
    $amp_pos = strpos($str, '&');
    //Find the ;
    $semi_pos = strpos($str, ';');
    // Only if the ; is after the &
    if($semi_pos > $amp_pos) {
      //is a HTML entity, try to remove
      $tmp = substr($str, 0, $amp_pos);
      $tmp = $tmp. substr($str, $semi_pos + 1, strlen($str));
      $str = $tmp;
      //Has another entity in it?
      if(substr_count($str, '&') && substr_count($str, ';'))
        $str = remEntities($tmp);
    }
  }
  return $str;
}

Best HTML5 markup for sidebar

First of all ASIDE is to be used only to denote related content to main content, not for a generic sidebar. Second, one aside for each sidebar only

You will have only one aside for each sidebar. Elements of a sidebar are divs or sections inside a aside.

I would go with Option 1: Aside with sections

<aside id="sidebar">
    <section id="widget_1"></section>
    <section id="widget_2"></section>
    <section id="widget_3"></section>
</aside>

Here is the spec https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside

Again use section only if they have a header or footer in them, otherwise use a plain div.

how to parse JSON file with GSON

You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.

private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() {
}.getType();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list
data.toScreen(); // prints to screen some values

Can you disable tabs in Bootstrap?

No Need Any Jquery, Just One Line CSS

.nav-tabs li.disabled a {
    pointer-events: none;
}

Why is using onClick() in HTML a bad practice?

It's not good for several reasons:

  • it mixes code and markup
  • code written this way goes through eval
  • and runs in the global scope

The simplest thing would be to add a name attribute to your <a> element, then you could do:

document.myelement.onclick = function() {
    window.popup('/map/', 300, 300, 'map');
    return false;
};

although modern best practise would be to use an id instead of a name, and use addEventListener() instead of using onclick since that allows you to bind multiple functions to a single event.

Element-wise addition of 2 lists?

Perhaps "the most pythonic way" should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.

Example:

import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)

Which result might you want if this were in a function in your problem?

How to open this .DB file?

I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

If it is a SQLite database, it will start with "SQLite format 3"

Reverse order of foreach list items

If you don't mind destroying the array (or a temp copy of it) you can do:

$stack = array("orange", "banana", "apple", "raspberry");

while ($fruit = array_pop($stack)){
    echo $fruit . "\n<br>"; 
}

produces:

raspberry 
apple 
banana 
orange 

I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:

$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
    echo $stack[$index] ." is in position ". $index . "\n<br>";
    $index--;
} 

But as you can see, you have to be very careful with the index...

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/)

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

How to change symbol for decimal point in double.ToString()?

If you have an Asp.Net web application, you can also set it in the web.config so that it is the same throughout the whole web application

<system.web>
    ...
    <globalization 
        requestEncoding="utf-8" 
        responseEncoding="utf-8" 
        culture="en-GB" 
        uiCulture="en-GB" 
        enableClientBasedCulture="false"/>
    ...
</system.web>

UIButton Image + Text IOS

swift version:

var button = UIButton()

newGameButton.setTitle("????? ????", for: .normal)
newGameButton.setImage(UIImage(named: "energi"), for: .normal)
newGameButton.backgroundColor = .blue
newGameButton.imageEdgeInsets.left = -50

enter image description here

How to set image on QPushButton?

This is old but it is still useful, Fully tested with QT5.3.

Be carreful, example concerning the ressources path :

In my case I created a ressources directory named "Ressources" in the source directory project.

The folder "ressources" contain pictures and icons.Then I added a prefix "Images" in Qt So the pixmap path become:

QPixmap pixmap(":/images/Ressources/icone_pdf.png");

JF

how to count the total number of lines in a text file using python

You can use sum() with a generator expression here. The generator expression will be [1, 1, ...] up to the length of the file. Then we call sum() to add them all together, to get the total count.

with open('text.txt') as myfile:
    count = sum(1 for line in myfile)

It seems by what you have tried that you don't want to include empty lines. You can then do:

with open('text.txt') as myfile:
    count = sum(1 for line in myfile if line.rstrip('\n'))

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

jQuery .scrollTop(); + animation

you must see this

$(function () {
        $('a[href*="#"]:not([href="#"])').click(function () {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });

or try them

$(function () {$('a').click(function () {
$('body,html').animate({
    scrollTop: 0
}, 600);
return false;});});

java how to use classes in other package?

Given your example, you need to add the following import in your main.main class:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

it's well documented here:

https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

Standard Implementation -> address

"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

jQuery Mobile Page refresh mechanism

I solved this problem by using the the data-cache="false" attribute in the page div on the pages I wanted refreshed.

<div data-role="page" data-cache="false">
/*content goes here*/

</div>

In my case it was my shopping cart. If a customer added an item to their cart and then continued shopping and then added another item to their cart the cart page would not show the new item. Unless they refreshed the page. Setting data-cache to false instructs JQM not to cache that page as far as I understand.

Hope this helps others in the future.

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

Setting PATH environment variable in OSX permanently

You can open any of the following files:

/etc/profile
~/.bash_profile
~/.bash_login   (if .bash_profile does not exist)
~/.profile      (if .bash_login does not exist)

And add:

export PATH="$PATH:your/new/path/here"

What is the difference between signed and unsigned int

In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.

MySQL Error 1264: out of range value for column

You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.

SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10

"Proxy server connection failed" in google chrome

  1. Open Google Chrome.
  2. Click Menu on the upper right side. Beside the STAR symbol (Bookmark).
  3. Click Show Advanced Settings.
  4. Scroll down and find Network.
  5. Click Change proxy settings.
  6. On the Connections tab, click LAN settings.
  7. Uncheck "Use a proxy server for your LAN."
  8. Then click OK.

Hope it helps .

JPA entity without id

See the Java Persistence book: Identity and Sequencing

The relevant part for your question is the No Primary Key section:

Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object's row, so all of the matching rows will be updated or deleted.

If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Scroll / Jump to id without jQuery

below code might help you

var objControl=document.getElementById("divid");
objControl.scrollTop = objControl.offsetTop;

laravel Eloquent ORM delete() method

At first,

You should know that destroy() is correct method for removing an entity directly via object or model and delete() can only be called in query builder.

In your case, You have not checked if record exists in database or not. Record can only be deleted if exists.

So, You can do it like follows.

$user = User::find($id);
    if($user){
        $destroy = User::destroy(2);
    }

The value or $destroy above will be 0 or 1 on fail or success respectively. So, you can alter the $data array like:

if ($destroy){

    $data=[
        'status'=>'1',
        'msg'=>'success'
    ];

}else{

    $data=[
        'status'=>'0',
        'msg'=>'fail'
    ];

}

Hope, you understand.

internal/modules/cjs/loader.js:582 throw err

For me "npm install" again from command prompt worked. Command Prompt must be "Run as Administrator"

How can you use optional parameters in C#?

In C#, I would normally use multiple forms of the method:

void GetFooBar(int a) { int defaultBValue;  GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
 // whatever here
}

UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:

public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender, 
                                   EDIVanInfo receiver, 
                                   EDIDocumentInfo info,
                                   EDIDocumentType type 
                                     = new EDIDocumentType(EDIDocTypes.X12_814),
                                   bool Production = false)
{
   // My code is here
}

Pandas dataframe fillna() only some columns in place

using the top answer produces a warning about making changes to a copy of a df slice. Assuming that you have other columns, a better way to do this is to pass a dictionary:
df.fillna({'A': 'NA', 'B': 'NA'}, inplace=True)

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Using a .php file to generate a MySQL dump

Please reffer to the following link which contains a scriptlet that will help you: http://davidwalsh.name/backup-mysql-database-php

Note: This script may contain bugs with NULL data types

How to enable/disable bluetooth programmatically in android

Android BluetoothAdapter docs say it has been available since API Level 5. API Level 5 is Android 2.0.

You can try using a backport of the Bluetooth API (have not tried it personally): http://code.google.com/p/backport-android-bluetooth/

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Click handlers on anchor tags are a special case in jQuery.

I think you might be getting confused between the anchor's onclick event (known by the browser) and the click event of the jQuery object which wraps the DOM's notion of the anchor tag.

You can download the jQuery 1.3.2 source here.

The relevant sections of the source are lines 2643-2645 (I have split this out to multiple lines to make it easier to comprehend):

// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if (
     (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && 
       elem["on"+type] && 
       elem["on"+type].apply( elem, data ) === false
   )
     event.result = false;

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

How can I create and style a div using JavaScript?

You can just use the method below:

document.write()

It is very simple, in the doc below I explain

_x000D_
_x000D_
document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
_x000D_
.div {
  background-color: red;
  padding: 5px;
  color: #fff;
  font-family: Arial;
  cursor: pointer;
}

.div:hover {
  background-color: blue;
  padding: 10px;
}

.div:hover:before {
  content: 'Hover! ';
}

.div:active {
  background-color: green;
  padding: 15px;
}

.div:active:after {
  content: ' Active! or clicked...';
}
_x000D_
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>
_x000D_
_x000D_
_x000D_

When to use RDLC over RDL reports?

While I currently lean toward RDL because it seems more flexible and easier to manage, RDLC has an advantage in that it seems to simplify your licensing. Because RDLC doesn’t need a Reporting Services instance, you won't need a Reporting Services License to use it.

I’m not sure if this still applies with the newer versions of SQL Server, but at one time if you chose to put the SQL Server Database and Reporting Services instances on two separate machines, you were required to have two separate SQL Server licenses:
http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/82dd5acd-9427-4f64-aea6-511f09aac406/

You can Bing for other similar blogs and posts regarding Reporting Services licensing.

Use jQuery to get the file input's selected filename without the path

Get path work with all OS

var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');

Example

C:\fakepath\filename.doc 
/var/fakepath/filename.doc

Both return

filename.doc
filename.doc

How to display a pdf in a modal window?

You can do this using with jQuery UI dialog, you can download JQuery ui from here Download JQueryUI

Include these scripts first inside <head> tag

<link href="css/smoothness/jquery-ui-1.9.0.custom.css" rel="stylesheet">
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script src="js/jquery-ui-1.9.0.custom.js"></script>

JQuery code

<script language="javascript" type="text/javascript">
  $(document).ready(function() {
    $('#trigger').click(function(){
      $("#dialog").dialog();
    }); 
  });                  
</script>

HTML code within <body> tag. Use an iframe to load the pdf file inside

<a href="#" id="trigger">this link</a>
<div id="dialog" style="display:none">
    <div>
    <iframe src="yourpdffile.pdf"></iframe>
    </div>
</div> 

newline in <td title="">

This should now work with Internet Explorer, Firefox v12+ and Chrome 28+

<img src="'../images/foo.gif'" 
  alt="line 1&#013;line 2" title="line 1&#013;line 2">

Try a JavaScript tooltip library for a better result, something like OverLib.

Create a new cmd.exe window from within another cmd.exe prompt

start cmd.exe 

opens a separate window

start file.cmd 

opens the batch file and executes it in another command prompt

Multi-dimensional arrays in Bash

Expanding on Paul's answer - here's my version of working with associative sub-arrays in bash:

declare -A SUB_1=(["name1key"]="name1val" ["name2key"]="name2val")
declare -A SUB_2=(["name3key"]="name3val" ["name4key"]="name4val")
STRING_1="string1val"
STRING_2="string2val"
MAIN_ARRAY=(
  "${SUB_1[*]}"
  "${SUB_2[*]}"
  "${STRING_1}"
  "${STRING_2}"
)
echo "COUNT: " ${#MAIN_ARRAY[@]}
for key in ${!MAIN_ARRAY[@]}; do
    IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}
    echo "VALUE: " ${val[@]}
    if [[ ${#val[@]} -gt 1 ]]; then
        for subkey in ${!val[@]}; do
            subval=${val[$subkey]}
            echo "SUBVALUE: " ${subval}
        done
    fi
done

It works with mixed values in the main array - strings/arrays/assoc. arrays

The key here is to wrap the subarrays in single quotes and use * instead of @ when storing a subarray inside the main array so it would get stored as a single, space separated string: "${SUB_1[*]}"

Then it makes it easy to parse an array out of that when looping through values with IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}

The code above outputs:

COUNT:  4
VALUE:  name1val name2val
SUBVALUE:  name1val
SUBVALUE:  name2val
VALUE:  name4val name3val
SUBVALUE:  name4val
SUBVALUE:  name3val
VALUE:  string1val
VALUE:  string2val

Java split string to array

This is expected. Refer to Javadocs for split.

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Resize to fit image in div, and center horizontally and vertically

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

No connection could be made because the target machine actively refused it?

Well, I've received this error today on Windows 8 64-bit out of the blue, for the first time, and it turns out my my.ini had been reset, and the bin/mysqld file had been deleted, among other items in the "Program Files/MySQL/MySQL Server 5.6" folder.

To fix it, I had to run the MySQL installer again, installing only the server, and copy a recent version of the my.ini file from "ProgramData/MySQL/MySQL Server 5.6", named my_2014-03-28T15-51-20.ini in my case (don't know how or why that got copied there so recently) back into "Program Files/MySQL/MySQL Server 5.6".

The only change to the system since MySQL worked was the installation of Native Instruments' Traktor 2 and a Traktor Audio 2 sound card, which really shouldn't have caused this problem, and no one else has used the system besides me. If anyone has a clue, it would be kind of you to comment to prevent this for me and anyone else who has encountered this.

How to create a printable Twitter-Bootstrap page

Replace every col-md- with col-xs-

eg: replace every col-md-6 to col-xs-6.

This is the thing that worked for me to get me rid of this problem you can see what you have to replace.

How to save and extract session data in codeigniter

In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';

and create a ci_session table in the database

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

For more details and reference, click here

How do I declare a 2d array in C++ using new?

A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.

Here N is row and M is column.

dynamic allocation

int** ary = new int*[N];
  for(int i = 0; i < N; i++)
      ary[i] = new int[M];

fill

for(int i = 0; i < N; i++)
    for(int j = 0; j < M; j++)
      ary[i][j] = i;

print

for(int i = 0; i < N; i++)
    for(int j = 0; j < M; j++)
      std::cout << ary[i][j] << "\n";

free

for(int i = 0; i < N; i++)
    delete [] ary[i];
delete [] ary;

Platform.runLater and Task in JavaFX

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

Code using Platform.runLater(...):

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();

it suffers from none of the flaws exhibited in the previous code

Reference : Worker Threading in JavaFX 2.0

Trigger event on body load complete js/jquery

$(document).ready( function() { YOUR CODE HERE } )

How to iterate over each string in a list of strings and operate on it's elements

c=0
words = ['challa','reddy','challa']

for idx, word in enumerate(words):
    if idx==0:
        firstword=word
        print(firstword)
    elif idx == len(words)-1:
        lastword=word
        print(lastword)
        if firstword==lastword:
            c=c+1
            print(c)

The number of method references in a .dex file cannot exceed 64k API 17

When your app references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

Multidex support for Android 5.0 and higher

Android 5.0 (API level 21) and higher uses a runtime called ART which natively supports loading multiple DEX files from APK files. Therefore, if your minSdkVersion is 21 or higher, you do not need the multidex support library.

Avoid the 64K limit

  • Remove unused code with ProGuard - Enable code shrinking

Configure multidex in app for

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file

android {
defaultConfig {
    ...
    minSdkVersion 21 
    targetSdkVersion 28
    multiDexEnabled true
  }
 ...
}

if your minSdkVersion is set to 20 or lower, then you must use the multidex support library

android {
defaultConfig {
    ...
    minSdkVersion 15 
    targetSdkVersion 28
    multiDexEnabled true
   }
   ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.3'
}

Override the Application class, change it to extend MultiDexApplication (if possible) as follows:

public class MyApplication extends MultiDexApplication { ... }

add to the manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="MyApplication" >
        ...
    </application>
</manifest>

Jquery get form field value

You can get any input field value by $('input[fieldAttribute=value]').val()

here is an example

_x000D_
_x000D_
displayValue = () => {_x000D_
_x000D_
  // you can get the value by name attribute like this_x000D_
  _x000D_
  console.log('value of firstname : ' + $('input[name=firstName]').val());_x000D_
  _x000D_
  // if there is the id as lastname_x000D_
  _x000D_
  console.log('value of lastname by id : ' + $('#lastName').val());_x000D_
  _x000D_
  // get value of carType from placeholder  _x000D_
  console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());_x000D_
_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="formdiv">_x000D_
    <form name="inpForm">_x000D_
        <input type="text" name="firstName" placeholder='first name'/>_x000D_
        <input type="text" name="lastName" id='lastName' placeholder='last name'/>_x000D_
        _x000D_
        <input type="text" placeholder="carType" />_x000D_
        <input type="button" value="display value" onclick='displayValue()'/>_x000D_
        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between PUT, POST and PATCH?

Quite logical the difference between PUT & PATCH w.r.t sending full & partial data for replacing/updating respectively. However, just couple of points as below

  1. Sometimes POST is considered as for updates w.r.t PUT for create
  2. Does HTTP mandates/checks for sending full vs partial data in PATCH? Otherwise, PATCH may be quite same as update as in PUT/POST

Swift - Integer conversion to Hours/Minutes/Seconds

Answer of @r3dm4n was great. However, I needed also hour in it. Just in case someone else needed too here it is:

func formatSecondsToString(_ seconds: TimeInterval) -> String {
    if seconds.isNaN {
        return "00:00:00"
    }
    let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
    let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
    let hour = Int(seconds / 3600)
    return String(format: "%02d:%02d:%02d", hour, min, sec)
}

Two Decimal places using c#

The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use

yournumber.ToString("0.00");

View JSON file in Browser

json-ie.reg. for IE

try this url

http://www.jsonviewer.com/

How to calculate a Mod b in Casio fx-991ES calculator

This calculator does not have any modulo function. However there is quite simple way how to compute modulo using display mode ab/c (instead of traditional d/c).

How to switch display mode to ab/c:

  • Go to settings (Shift + Mode).
  • Press arrow down (to view more settings).
  • Select ab/c (number 1).

Now do your calculation (in comp mode), like 50 / 3 and you will see 16 2/3, thus, mod is 2. Or try 54 / 7 which is 7 5/7 (mod is 5). If you don't see any fraction then the mod is 0 like 50 / 5 = 10 (mod is 0).

The remainder fraction is shown in reduced form, so 60 / 8 will result in 7 1/2. Remainder is 1/2 which is 4/8 so mod is 4.

EDIT: As @lawal correctly pointed out, this method is a little bit tricky for negative numbers because the sign of the result would be negative.

For example -121 / 26 = -4 17/26, thus, mod is -17 which is +9 in mod 26. Alternatively you can add the modulo base to the computation for negative numbers: -121 / 26 + 26 = 21 9/26 (mod is 9).

EDIT2: As @simpatico pointed out, this method will not work for numbers that are out of calculator's precision. If you want to compute say 200^5 mod 391 then some tricks from algebra are needed. For example, using rule (A * B) mod C = ((A mod C) * B) mod C we can write:

200^5 mod 391 = (200^3 * 200^2) mod 391 = ((200^3 mod 391) * 200^2) mod 391 = 98

What is the C# equivalent of NaN or IsNumeric?

Maybe this is a C# 3 feature, but you could use double.NaN.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

Ok, so the answer was derived from some other posts about this problem and it is:

If your ViewData contains a SelectList with the same name as your DropDownList i.e. "submarket_0", the Html helper will automatically populate your DropDownList with that data if you don't specify the 2nd parameter which in this case is the source SelectList.

What happened with my error was:

Because the table containing the drop down lists was in a partial view and the ViewData had been changed and no longer contained the SelectList I had referenced, the HtmlHelper (instead of throwing an error) tried to find the SelectList called "submarket_0" in the ViewData (GRRRR!!!) which it STILL couldnt find, and then threw an error on that :)

Please correct me if im wrong

Python: How exactly can you take a string, split it, reverse it and join it back together again?

You mean this?

from string import punctuation, digits

takeout = punctuation + digits

turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis

How to add anchor tags dynamically to a div in Javascript?

I recommend that you use jQuery for this, as it makes the process much easier. Here are some examples using jQuery:

$("div#id").append('<a href="' + url + '">' + text + '</a>');

If you need a list though, as in a <ul>, you can do this:

$("div#id").append('<ul>');
var ul = $("div#id > ul");

ul.append('<li><a href="' + url + '">' + text + '</a></li>');

how to remove the bold from a headline?

for "THIS IS" not to be bold - add <span></span> around the text

<h1>><span>THIS IS</span> A HEADLINE</h1>

and in style

h1 span{font-weight:normal}

Call a global variable inside module

Download the bootbox typings

Then add a reference to it inside your .ts file.

how to split the ng-repeat data with three columns using bootstrap

m59's answer is pretty good. The one thing I don't like about it is that it uses divs for what could potentially be data for a table.

So in conjunction with m59's filter (answer somewhere above), here is how to display it in a table.

<table>
    <tr class="" ng-repeat="rows in foos | chunk:2">
        <td ng-repeat="item in rows">{{item}}</td>
    </tr>
</table>

Can I scale a div's height proportionally to its width using CSS?

One way usefull when you work with images, but can be used as workaround otherwise:

<html>
<head>
</head>
<style>
    #someContainer {
        width:50%;
        position: relative;
    }
    #par {
        width: 100%;
        background-color:red;
    }
    #image {
        width: 100%;
        visibility: hidden;
    }
    #myContent {
        position:absolute;
    }
</style>
<div id="someContainer">
    <div id="par">
        <div id="myContent">
            <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </p>    
        </div>
        <img src="yourImage" id="image"/>
    </div>
</div>
</html>

To use replace yourImage with your image url. You use image with width / height ratio you desire.

div id="myContent" is here as example of workaround where myContent will overlay over image.

This works like: Parent div will adopt to the height of image, image height will adopt to width of parent. However image is hidden.

Is there a JavaScript / jQuery DOM change listener?

Many sites use AJAX/XHR/fetch to add, show, modify content dynamically and window.history API instead of in-site navigation so current URL is changed programmatically. Such sites are called SPA, short for Single Page Application.


Usual JS methods of detecting page changes

  • MutationObserver (docs) to literally detect DOM changes:

  • Event listener for sites that signal content change by sending a DOM event:

  • Periodic checking of DOM via setInterval:
    Obviously this will work only in cases when you wait for a specific element identified by its id/selector to appear, and it won't let you universally detect new dynamically added content unless you invent some kind of fingerprinting the existing contents.

  • Cloaking History API:

    let _pushState = History.prototype.pushState;
    History.prototype.pushState = function (state, title, url) {
      _pushState.call(this, state, title, url);
      console.log('URL changed', url)
    };
    
  • Listening to hashchange, popstate events:

    window.addEventListener('hashchange', e => {
      console.log('URL hash changed', e);
      doSomething();
    });
    window.addEventListener('popstate', e => {
      console.log('State changed', e);
      doSomething();
    });
    


Extensions-specific methods

All above-mentioned methods can be used in a content script. Note that content scripts aren't automatically executed by the browser in case of programmatic navigation via window.history in the web page because only the URL was changed but the page itself remained the same (the content scripts run automatically only once in page lifetime).

Now let's look at the background script.

Detect URL changes in a background / event page.

There are advanced API to work with navigation: webNavigation, webRequest, but we'll use simple chrome.tabs.onUpdated event listener that sends a message to the content script:

  • manifest.json:
    declare background/event page
    declare content script
    add "tabs" permission.

  • background.js

    var rxLookfor = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
    chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
      if (rxLookfor.test(changeInfo.url)) {
        chrome.tabs.sendMessage(tabId, 'url-update');
      }
    });
    
  • content.js

    chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
      if (msg === 'url-update') {
        // doSomething();
      }
    });
    

Installing a plain plugin jar in Eclipse 3.5

For Eclipse Mars (I've just verified that) you to do this (assuming that C:\eclipseMarsEE is root folder of your Eclipse):

  1. Add plugins folder to C:\eclipseMarsEE\dropins so that it looks like: C:\eclipseMarsEE\dropins\plugins
  2. Then add plugin you want to install into that folder: C:\eclipseMarsEE\dropins\plugins\someplugin.jar
  3. Start Eclipse with clean option.
  4. If you are using shortcut on desktop then just right click on Eclipse icon > Properties and in Target field add: -clean like this: C:\eclipseMarsEE\eclipse.exe -clean

enter image description here

  1. Start Eclipse and verify that your plugin works.
  2. Remove -clean option from Target field.

Git push error: "origin does not appear to be a git repository"

Your config file does not include any references to "origin" remote. That section looks like this:

[remote "origin"]
    url = [email protected]:repository.git
    fetch = +refs/heads/*:refs/remotes/origin/*

You need to add the remote using git remote add before you can use it.

Git submodule head 'reference is not a tree' error

To sync the git repo with the submodule's head, in case that is really what you want, I found that removing the submodule and then readding it avoids the tinkering with the history. Unfortunately removing a submodule requires hacking rather than being a single git command, but doable.

Steps I followed to remove the submodule, inspired by https://gist.github.com/kyleturner/1563153:

  1. Run git rm --cached
  2. Delete the relevant lines from the .gitmodules file.
  3. Delete the relevant section from .git/config.
  4. Delete the now untracked submodule files.
  5. Remove directory .git/modules/

Again, this can be useful if all you want is to point at the submodule's head again, and you haven't complicated things by needing to keep the local copy of the submodule intact. It assumes you have the submodule "right" as its own repo, wherever the origin of it is, and you just want to get back to properly including it as a submodule.

Note: always make a full copy of your project before engaging in these kinds of manipulation or any git command beyond simple commit or push. I'd advise that with all other answers as well, and as a general git guideline.

Duplicate and rename Xcode project & associated folders

For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.

Next, check that your current module is the correct renamed module and not the old one.

Truncate with condition

The short answer is no: MySQL does not allow you to add a WHERE clause to the TRUNCATE statement. Here's MySQL's documentation about the TRUNCATE statement.

But the good news is that you can (somewhat) work around this limitation.

Simple, safe, clean but slow solution using DELETE

First of all, if the table is small enough, simply use the DELETE statement (it had to be mentioned):

1. LOCK TABLE my_table WRITE;
2. DELETE FROM my_table WHERE my_date<DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. UNLOCK TABLES;

The LOCK and UNLOCK statements are not compulsory, but they will speed things up and avoid potential deadlocks.

Unfortunately, this will be very slow if your table is large... and since you are considering using the TRUNCATE statement, I suppose it's because your table is large.

So here's one way to solve your problem using the TRUNCATE statement:

Simple, fast, but unsafe solution using TRUNCATE

1. CREATE TABLE my_table_backup AS
      SELECT * FROM my_table WHERE my_date>=DATE_SUB(NOW(), INTERVAL 1 MONTH);
2. TRUNCATE my_table;
3. LOCK TABLE my_table WRITE, my_table_backup WRITE;
4. INSERT INTO my_table SELECT * FROM my_table_backup;
5. UNLOCK TABLES;
6. DROP TABLE my_table_backup;

Unfortunately, this solution is a bit unsafe if other processes are inserting records in the table at the same time:

  • any record inserted between steps 1 and 2 will be lost
  • the TRUNCATE statement resets the AUTO-INCREMENT counter to zero. So any record inserted between steps 2 and 3 will have an ID that will be lower than older IDs and that might even conflict with IDs inserted at step 4 (note that the AUTO-INCREMENT counter will be back to it's proper value after step 4).

Unfortunately, it is not possible to lock the table and truncate it. But we can (somehow) work around that limitation using RENAME.

Half-simple, fast, safe but noisy solution using TRUNCATE

1. RENAME TABLE my_table TO my_table_work;
2. CREATE TABLE my_table_backup AS
     SELECT * FROM my_table_work WHERE my_date>DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. TRUNCATE my_table_work;
4. LOCK TABLE my_table_work WRITE, my_table_backup WRITE;
5. INSERT INTO my_table_work SELECT * FROM my_table_backup;
6. UNLOCK TABLES;
7. RENAME TABLE my_table_work TO my_table;
8. DROP TABLE my_table_backup;

This should be completely safe and quite fast. The only problem is that other processes will see table my_table disappear for a few seconds. This might lead to errors being displayed in logs everywhere. So it's a safe solution, but it's "noisy".

Disclaimer: I am not a MySQL expert, so these solutions might actually be crappy. The only guarantee I can offer is that they work fine for me. If some expert can comment on these solutions, I would be grateful.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

If you are in a MySQL shell, exit it by typing exit, which will return you to the command prompt.

Now start MySQL by using exactly the following command:

sudo mysql -u root -p

If your username is something other than root, replace 'root' in the above command with your username:

sudo mysql -u <your-user-name> -p

It will then ask you the MySQL account/password, and your MySQL won't show any access privilege issue then on.

How to align the checkbox and label in same line in html?

Use below css to align Label with Checkbox

    .chkbox label
            {
                position: relative;
                top: -2px;
            }

<div class="chkbox">
<asp:CheckBox ID="Ckbox" runat="server" Text="Check Box Alignment"/>
</div>

How to get first and last element in an array in java?

If you have a double array named numbers, you can use:

firstNum = numbers[0];
lastNum = numbers[numbers.length-1];

or with ArrayList

firstNum = numbers.get(0);
lastNum = numbers.get(numbers.size() - 1); 

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

Why do we use __init__ in Python classes?

Classes are objects with attributes (state, characteristic) and methods (functions, capacities) that are specific for that object (like the white color and fly powers, respectively, for a duck).

When you create an instance of a class, you can give it some initial personality (state or character like the name and the color of her dress for a newborn). You do this with __init__.

Basically __init__ sets the instance characteristics automatically when you call instance = MyClass(some_individual_traits).

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Is there an alternative sleep function in C to milliseconds?

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

SQL query for a carriage return in a string and ultimately removing carriage return

If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

    DECLARE @NewLine Table
    (ColumnName Varchar(100)
    ,Location Int
    ,ColumnValue Varchar(8000)
    )

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'

    DECLARE looper CURSOR FAST_FORWARD for
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'
    OPEN looper
    FETCH NEXT FROM looper INTO @ColName

    WHILE @@fetch_status = 0
    BEGIN
    SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
    PRINT @cmd
    INSERT @NewLine ( ColumnName, Location, ColumnValue )
    EXEC sp_executesql @cmd
    FETCH NEXT FROM looper INTO @ColName
    end
    CLOSE looper
    DEALLOCATE looper


    SELECT * FROM  @NewLine

How do I monitor the computer's CPU, memory, and disk usage in Java?

For disk space, if you have Java 6, you can use the getTotalSpace and getFreeSpace methods on File. If you're not on Java 6, I believe you can use Apache Commons IO to get some of the way there.

I don't know of any cross platform way to get CPU usage or Memory usage I'm afraid.

100% height minus header?

For "100% of the browser window", if you mean this literally, you should use fixed positioning. The top, bottom, right, and left properties are then used to offset the divs edges from the respective edges of the viewport:

#nav, #content{position:fixed;top:0px;bottom:0px;}
#nav{left:0px;right:235px;}
#content{left:235px;right:0px}

This will set up a screen with the left 235 pixels devoted to the nav, and the right rest of the screen to content.

Note, however, you won't be able to scroll the whole screen at once. Though you can set it to scroll either pane individually, by applying overflow:auto to either div.

Note also: fixed positioning is not supported in IE6 or earlier.

Android findViewById() in Custom View

Try this in your constructor

MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);

How to search a string in String array

Each class implementing IList has a method Contains(Object value). And so does System.Array.

Remove spaces from a string in VB.NET

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

C# Call a method in a new thread

If you actually start a new thread, that thread will terminate when the method finishes:

Thread thread = new Thread(SecondFoo);
thread.Start();

Now SecondFoo will be called in the new thread, and the thread will terminate when it completes.

Did you actually mean that you wanted the thread to terminate when the method in the calling thread completes?

EDIT: Note that starting a thread is a reasonably expensive operation. Do you definitely need a brand new thread rather than using a threadpool thread? Consider using ThreadPool.QueueUserWorkItem or (preferrably, if you're using .NET 4) TaskFactory.StartNew.

vuetify center items into v-flex

<v-layout justify-center>
  <v-card-actions>
    <v-btn primary>
     <span>SignUp</span>
    </v-btn>`enter code here`
  </v-card-actions>
</v-layout>

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

There is no difference at all!

1) git checkout -b branch origin/branch

If there is no --track and no --no-track, --track is assumed as default. The default can be changed with the setting branch.autosetupmerge.

In effect, 1) behaves like git checkout -b branch --track origin/branch.

2) git checkout --track origin/branch

“As a convenience”, --track without -b implies -b and the argument to -b is guessed to be “branch”. The guessing is driven by the configuration variable remote.origin.fetch.

In effect, 2) behaves like git checkout -b branch --track origin/branch.

As you can see: no difference.

But it gets even better:

3) git checkout branch

is also equivalent to git checkout -b branch --track origin/branch if “branch” does not exist yet but “origin/branch” does1.


All three commands set the “upstream” of “branch” to be “origin/branch” (or they fail).

Upstream is used as reference point of argument-less git status, git push, git merge and thus git pull (if configured like that (which is the default or almost the default)).

E.g. git status tells you how far behind or ahead you are of upstream, if one is configured.

git push is configured to push the current branch upstream by default2 since git 2.0.

1 ...and if “origin” is the only remote having “branch”
2 the default (named “simple”) also enforces for both branch names to be equal

Handling ExecuteScalar() when no results are returned

SQL NULL value

  • equivalent in C# is DBNull.Value
  • if a NULLABLE column has no value, this is what is returned
  • comparison in SQL: IF ( value IS NULL )
  • comparison in C#: if (obj == DBNull.Value)
  • visually represented in C# Quick-Watch as {}

Best practice when reading from a data reader:

var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());

In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be

select MAX(ID) from <table name> where <impossible condition>

The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)

var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

How to have multiple colors in a Windows batch file?

Windows 10 ((Version 1511, build 10586, release 2015-11-10)) supports ANSI colors.
You can use the escape key to trigger the color codes.

In the Command Prompt:

echo ^[[32m HI ^[[0m

echo Ctrl+[[32m HI Ctrl+[[0mEnter

When using a text editor, you can use ALT key codes.
The ESC key code can be created using ALT and NUMPAD numbers : Alt+027

[32m  HI  [0m

Sending files using POST with HttpURLConnection

I tried the solutions above and none worked for me out of the box.

However http://www.baeldung.com/httpclient-post-http-request. Line 6 POST Multipart Request worked within seconds

public void whenSendMultipartRequestUsingHttpClient_thenCorrect() 
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://www.example.com");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("username", "John");
    builder.addTextBody("password", "pass");
    builder.addBinaryBody("file", new File("test.txt"),
      ContentType.APPLICATION_OCTET_STREAM, "file.ext");

    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);

    CloseableHttpResponse response = client.execute(httpPost);
    client.close();
}

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

Unsetting array values in a foreach loop

Try that:

foreach ($images[1] as $key => &$image) {
    if (yourConditionGoesHere) {
        unset($images[1][$key])
    }
}
unset($image); // detach reference after loop  

Normally, foreach operates on a copy of your array so any changes you make, are made to that copy and don't affect the actual array.

So you need to unset the values via $images[$key];

The reference on &$image prevents the loop from creating a copy of the array which would waste memory.

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

Both of the following work (as discussed here).

exec sp_rename 'ENG_TEst.[[ENG_Test_A/C_TYPE]]]' , 
                'ENG_Test_A/C_TYPE', 'COLUMN'


exec sp_rename 'ENG_TEst."[ENG_Test_A/C_TYPE]"' , 
                'ENG_Test_A/C_TYPE', 'COLUMN'

Is there a RegExp.escape function in JavaScript?

Mozilla Developer Network's Guide to Regular Expressions provides this escaping function:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Set background image according to screen resolution

Delete your "body background image code" then paste this code:

html { 
    background: url(../img/background.jpg) no-repeat center center fixed #000; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

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

AFAIK, you don't need to map the UNC path to a drive letter in order to establish credentials for a server. I regularly used batch scripts like:

net use \\myserver /user:username password

:: do something with \\myserver\the\file\i\want.xml

net use /delete \\my.server.com

However, any program running on the same account as your program would still be able to access everything that username:password has access to. A possible solution could be to isolate your program in its own local user account (the UNC access is local to the account that called NET USE).

Note: Using SMB accross domains is not quite a good use of the technology, IMO. If security is that important, the fact that SMB lacks encryption is a bit of a damper all by itself.

String.Format for Hex

You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

Enable PHP Apache2

If anyone gets

ERROR: Module phpX.X does not exist!

just install the module for your current php version:

apt-get install libapache2-mod-phpX.X

What is LDAP used for?

LDAP stands for Lightweight Directory Access Protocol. As the name suggests, it is a lightweight protocol for accessing directory services, specifically X.500-based directory services. LDAP runs over TCP/IP or other connection oriented transfer services. The nitty-gritty details of LDAP are defined in RFC2251 "The Lightweight Directory Access Protocol (v3)" and other documents comprising the technical specification RFC3377. This section gives an overview of LDAP from a user's perspective.

What kind of information can be stored in the directory? The LDAP information model is based on entries. An entry is a collection of attributes that has a globally-unique Distinguished Name (DN). The DN is used to refer to the entry unambiguously. Each of the entry's attributes has a type and one or more values. The types are typically mnemonic strings, like cn for common name, or mail for email address. The syntax of values depend on the attribute type. For example, a cn attribute might contain the value Babs Jensen. A mail attribute might contain the value [email protected]. A jpegPhoto attribute would contain a photograph in the JPEG (binary) format.

How is the information arranged? In LDAP, directory entries are arranged in a hierarchical tree-like structure.

enter image description here

hidden field in php

Can I use a field of the type ... and retrieve it after the GET / POST method ...

Yes (haven't you tried?)

Are there any other ways of using hidden fields in PHP?

You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.


Btw. input fiels have no end tag. So write either just <input ...> or as self-closing tag <input .../>.

SQL select statements with multiple tables

You need to join the two tables:

select p.id, p.first, p.middle, p.last, p.age,
       a.id as address_id, a.street, a.city, a.state, a.zip
from Person p inner join Address a on p.id = a.person_id
where a.zip = '97229';

This will select all of the columns from both tables. You could of course limit that by choosing different columns in the select clause.

Spring Boot + JPA : Column name annotation ignored

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

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

Change:

@Column(name="testName")
private String testName;

To:

@Column(name="testname")
private String testName;

Inherit CSS class

As others have already mentioned, there is no concept of OOP inheritance in CSS. But, i have always used a work around for this.

Let's say i have two buttons, and except the background image URL, all other attributes are common. This is how i did it.

/*button specific attributes*/
.button1 {
    background-image: url("../Images/button1.gif");
}
/*button specific attributes*/
.button2 {
    background-image: url("../Images/button2.gif");
}

/*These are the shared attributes */
.button1, .button2 {
    cursor: pointer;
    background-repeat: no-repeat;
    width: 25px;
    height: 20px;
    border: 0;
}

Hope this helps somebody.

One-liner if statements, how to convert this if-else-statement

All you'd need in your case is:

return expression;

The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

How do I fix "Expected to return a value at the end of arrow function" warning?

The easiest way only if you don't need return something it'ts just return null

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

How to make an element width: 100% minus padding?

Just understand the difference between width:auto; and width:100%; Width:auto; will (AUTO)MATICALLY calculate the width in order to fit the exact given with of the wrapping div including the padding. Width 100% expands the width and adds the padding.

How do I check whether a checkbox is checked in jQuery?

I believe you could do this:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

init-param and context-param

<context-param> 
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:/META-INF/PersistenceContext.xml
    </param-value>
</context-param>

I have initialized my PersistenceContext.xml within <context-param> because all my servlets will be interacting with database in MVC framework.

Howerver,

<servlet>
    <servlet-name>jersey-servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:ApplicationContext.xml
        </param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.organisation.project.rest</param-value>
    </init-param>
</servlet>

in the aforementioned code, I am configuring jersey and the ApplicationContext.xml only to rest layer. For the same I am using </init-param>

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:

$("#focus_point").attr("tabindex",-1).focus();

In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)
       .focus();

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

How can jQuery deferred be used?

1) Use it to ensure an ordered execution of callbacks:

var step1 = new Deferred();
var step2 = new Deferred().done(function() { return step1 });
var step3 = new Deferred().done(function() { return step2 });

step1.done(function() { alert("Step 1") });
step2.done(function() { alert("Step 2") });
step3.done(function() { alert("All done") });
//now the 3 alerts will also be fired in order of 1,2,3
//no matter which Deferred gets resolved first.

step2.resolve();
step3.resolve();
step1.resolve();

2) Use it to verify the status of the app:

var loggedIn = logUserInNow(); //deferred
var databaseReady = openDatabaseNow(); //deferred

jQuery.when(loggedIn, databaseReady).then(function() {
  //do something
});

How to do if-else in Thymeleaf?

In simpler case (when html tags is the same):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>

MySQL Error: #1142 - SELECT command denied to user

You need to give privileges to the particular user by giving the command mysql> GRANT ALL PRIVILEGES . To 'username'@'localhost'; and then give FLUSH PRIVILEGES; command. Then it won't give this error.., hope it helps thank you..!

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

In case of CORS request all modern browsers respond with an OPTION verb, and then the actual request follows through. This is supposed to be used to prompt the user for confirmation in case of a CORS request. But in case of an API if you would want to skip this verification process add the following snippet to Global.asax

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Here we are just by passing the check by checking for OPTIONS verb.

What is the use of static synchronized method in java?

static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.lang.class class object is there. That object's lock is needed for.static synchronized methods. So when you have a static field which should be restricted to be accessed by multiple threads at once you can set those fields private and create public static synchronized setters or getters to access those fields.

java - path to trustStore - set property doesn't work?

Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.

System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");

should be:

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

How to get file's last modified date on Windows command line?

To get the last modification date/time of a file in a locale-independent manner you could use the wmic command with the DataFile alias:

wmic DataFile where "Name='D:\\Path\\To\\myfile.txt'" get LastModified /VALUE

Regard that the full path to the file must be provided and that all path separators (backslashes \) must be doubled herein.

This returns a standardised date/time value like this (meaning 12th of August 2019, 13:00:00, UTC + 120'):

LastModified=20190812130000.000000+120

To capture the date/time value use for /F, then you can assign it to a variable using set:

for /F "delims=" %%I in ('
    wmic DataFile where "Name='D:\\Path\\To\\myfile.txt'" get LastModified /VALUE
') do for /F "tokens=1* delims==" %%J in ("%%I") do set "DateTime=%%K"

The second for /F loop avoids artefacts (like orphaned carriage-return characters) from conversion of the Unicode output of wmic to ASCII/ANSI text by the first for /F loop (see also this answer).

You can then use sub-string expansion to extract the pure date or the time from this:

set "DateOnly=%DateTime:~0,8%"
set "TimeOnly=%DateTime:~8,6%"

To get the creation date/time or the last access date/time, just replace the property LastModified by CreationDate or LastAccessed, respectively. To get information about a directory rather than a file, use the alias FSDir instead of DataFile.

For specifying file (or directory) paths/names containing both , and ), which are usually not accepted by wmic, take a look at this question.

Check out also this post as well as this one about how to get file and directory date/time stamps.

How to find all the tables in MySQL with specific column names in them?

If you want "To get all tables only", Then use this query:

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME like '%'
and TABLE_SCHEMA = 'tresbu_lk'

If you want "To get all tables with Columns", Then use this query:

SELECT DISTINCT TABLE_NAME, COLUMN_NAME  
FROM INFORMATION_SCHEMA.COLUMNS  
WHERE column_name LIKE '%'  
AND TABLE_SCHEMA='tresbu_lk'

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

How to remove time portion of date in C# in DateTime object only?

Have a look at the DateTime.Date property.

Gets the date component of this instance.

Chrome:The website uses HSTS. Network errors...this page will probably work later

I see there are so many useful answers here but still, I come across a handy and useful article out there. https://www.thesslstore.com/blog/clear-hsts-settings-chrome-firefox/

I ran into the same issue and that article helped me to what exactly it is and how to deal with that HTH :-)

How to submit a form when the return key is pressed?

I use this method:

<form name='test' method=post action='sendme.php'>
    <input type=text name='test1'>
    <input type=button value='send' onClick='document.test.submit()'>
    <input type=image src='spacer.gif'>  <!-- <<<< this is the secret! -->
</form>

Basically, I just add an invisible input of type image (where "spacer.gif" is a 1x1 transparent gif).

In this way, I can submit this form either with the 'send' button or simply by pressing enter on the keyboard.

This is the trick!

How do you easily create empty matrices javascript?

You can add functionality to an Array by extending its prototype object.

Array.prototype.nullify = function( n ) {
    n = n >>> 0;
    for( var i = 0; i < n; ++i ) {
        this[ i ] = null;
    }
    return this;
};

Then:

var arr = [].nullify(9);

or:

var arr = [].nullify(9).map(function() { return [].nullify(9); });

How to show current time in JavaScript in the format HH:MM:SS?

This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.

var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55

Number format in excel: Showing % value without multiplying with 100

Be aware that a value of 1 equals 100% in Excel's interpretation. If you enter 5.66 and you want to show 5.66%, then AxGryndr's hack with the formatting will work, but it is a display format only and does not represent the true numeric value. If you want to use that percentage in further calculations, these calculations will return the wrong result unless you divide by 100 at calculation time.

The consistent and less error-prone way is to enter 0.0566 and format the number with the built-in percentage format. That way, you can easily calculate 5.6% of A1 by just multiplying A1 with the value.

The good news is that you don't need to go through the rigmarole of entering 0.0566 and then formatting as percent. You can simply type

5.66%

into the cell, including the percentage symbol, and Excel will take care of the rest and store the number correctly as 0.0566 if formatted as General.

Understanding the Rails Authenticity Token

What happens

When the user views a form to create, update, or destroy a resource, the Rails app creates a random authenticity_token, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for the authenticity_token, compares it to the one stored in the session, and if they match the request is allowed to continue.

Why it happens

Since the authenticity token is stored in the session, the client cannot know its value. This prevents people from submitting forms to a Rails app without viewing the form within that app itself. Imagine that you are using service A, you logged into the service and everything is ok. Now imagine that you went to use service B, and you saw a picture you like, and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to http://serviceA.com/close_account. This is what is known as CSRF (Cross Site Request Forgery).

If service A is using authenticity tokens, this attack vector is no longer applicable, since the request from service B would not contain the correct authenticity token, and will not be allowed to continue.

API docs describes details about meta tag:

CSRF protection is turned on with the protect_from_forgery method, which checks the token and resets the session if it doesn't match what was expected. A call to this method is generated for new Rails applications by default. The token parameter is named authenticity_token by default. The name and value of this token must be added to every layout that renders forms by including csrf_meta_tags in the HTML head.

Notes

Keep in mind, Rails only verifies not idempotent methods (POST, PUT/PATCH and DELETE). GET request are not checked for authenticity token. Why? because the HTTP specification states that GET requests is idempotent and should not create, alter, or destroy resources at the server, and the request should be idempotent (if you run the same command multiple times, you should get the same result every time).

Also the real implementation is a bit more complicated as defined in the beginning, ensuring better security. Rails does not issue the same stored token with every form. Neither does it generate and store a different token every time. It generates and stores a cryptographic hash in a session and issues new cryptographic tokens, which can be matched against the stored one, every time a page is rendered. See request_forgery_protection.rb.

Lessons

Use authenticity_token to protect your not idempotent methods (POST, PUT/PATCH, and DELETE). Also make sure not to allow any GET requests that could potentially modify resources on the server.


EDIT: Check the comment by @erturne regarding GET requests being idempotent. He explains it in a better way than I have done here.

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

how to set the background color of the whole page in css

I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white to the HTML element. I overwrote that and everything was easy to handle from there.

must appear in the GROUP BY clause or be used in an aggregate function

For me, it is not about a "common aggregation problem", but just about an incorrect SQL query. The single correct answer for "select the maximum avg for each cname..." is

SELECT cname, MAX(avg) FROM makerar GROUP BY cname;

The result will be:

 cname  |      MAX(avg)
--------+---------------------
 canada | 2.0000000000000000
 spain  | 5.0000000000000000

This result in general answers the question "What is the best result for each group?". We see that the best result for spain is 5 and for canada the best result is 2. It is true, and there is no error. If we need to display wmname also, we have to answer the question: "What is the RULE to choose wmname from resulting set?" Let's change the input data a bit to clarify the mistake:

  cname | wmname |        avg           
--------+--------+-----------------------
 spain  | zoro   |  1.0000000000000000
 spain  | luffy  |  5.0000000000000000
 spain  | usopp  |  5.0000000000000000

Which result do you expect on runnig this query: SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;? Should it be spain+luffy or spain+usopp? Why? It is not determined in the query how to choose "better" wmname if several are suitable, so the result is also not determined. That's why SQL interpreter returns an error - the query is not correct.

In the other word, there is no correct answer to the question "Who is the best in spain group?". Luffy is not better than usopp, because usopp has the same "score".

How do you make a deep copy of an object?

A few people have mentioned using or overriding Object.clone(). Don't do it. Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.

The schemes that rely on serialization (XML or otherwise) are kludgy.

There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. Strings) do not need to be copied. As an aside, you should favor immutability for this reason.

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

Bootstrap carousel width and height

If you use bootstrap 4 Alpha and you have an error with the height of the images in chrome, I have a solution: The documentation of bootstrap 4 says this:

<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="..." alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Third slide">
    </div>
  </div>
</div>

Solution:

The solution is to put "div" around the image, with the class ".container", like this:

<div class="carousel-item active">
  <div class="container">
    <img src="images/proyecto_0.png" alt="First slide" class="d-block img-fluid">
  </div>
</div>

How do I use reflection to call a generic method?

Inspired by Enigmativity's answer - let's assume you have two (or more) classes, like

public class Bar { }
public class Square { }

and you want to call the method Foo<T> with Bar and Square, which is declared as

public class myClass
{
    public void Foo<T>(T item)
    {
        Console.WriteLine(typeof(T).Name);
    }
}

Then you can implement an Extension method like:

public static class Extension
{
    public static void InvokeFoo<T>(this T t)
    {
        var fooMethod = typeof(myClass).GetMethod("Foo");
        var tType = typeof(T);
        var fooTMethod = fooMethod.MakeGenericMethod(new[] { tType });
        fooTMethod.Invoke(new myClass(), new object[] { t });
    }
}

With this, you can simply invoke Foo like:

var objSquare = new Square();
objSquare.InvokeFoo();

var objBar = new Bar();
objBar.InvokeFoo();

which works for every class. In this case, it will output:

Square
Bar

`col-xs-*` not working in Bootstrap 4

col-xs-* have been dropped in Bootstrap 4 in favor of col-*.

Replace col-xs-12 with col-12 and it will work as expected.

Also note col-xs-offset-{n} were replaced by offset-{n} in v4.

No function matches the given name and argument types

Your function has a couple of smallint parameters.
But in the call, you are using numeric literals that are presumed to be type integer.

A string literal or string constant ('123') is not typed immediately. It remains type "unknown" until assigned or cast explicitly.

However, a numeric literal or numeric constant is typed immediately. Per documentation:

A numeric constant that contains neither a decimal point nor an exponent is initially presumed to be type integer if its value fits in type integer (32 bits); otherwise it is presumed to be type bigint if its value fits in type bigint (64 bits); otherwise it is taken to be type numeric. Constants that contain decimal points and/or exponents are always initially presumed to be type numeric.

More explanation and links in this related answer:

Solution

Add explicit casts for the smallint parameters or quote them.

Demo

CREATE OR REPLACE FUNCTION f_typetest(smallint)
  RETURNS bool AS 'SELECT TRUE' LANGUAGE sql;

Incorrect call:

SELECT * FROM f_typetest(1);

Correct calls:

SELECT * FROM f_typetest('1');
SELECT * FROM f_typetest(smallint '1');
SELECT * FROM f_typetest(1::int2);
SELECT * FROM f_typetest('1'::int2);

db<>fiddle here
Old sqlfiddle.

SQL string value spanning multiple lines in query

SQL Server allows the following (be careful to use single quotes instead of double)

UPDATE User
SET UserId = 12345
   , Name = 'J Doe'
   , Location = 'USA'
   , Bio='my bio
spans 
multiple
lines!'
WHERE UserId = 12345

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Player.cpp require the definition of Ball class. So simply add #include "Ball.h"

Player.cpp:

#include "Player.h"
#include "Ball.h"

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

An extension to what GenericTypeTea says - Here is a concrete example:

<form onsubmit="return false">

The above form will not submit, whereas...

<form onsubmit="false">

...does nothing, i.e. the form will submit.

Without the return, onsubmit doesn't receive a value and the event is executed just like without any handler at all.

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Use this,

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%?=*&]).{8,20})

It will validate for at least one lowercase, one upper case, one number and the special charecters of (!,@,#,$,%,?,=,*,&).

Minimum length is 8 and maximum length is 20

QtCreator: No valid kits found

I had a similar problems after installing Qt in Windows.

This could be because only the Qt creator was installed and not any of the Qt libraries during initial installation. When installing from scratch use the online installer and select the following to install:

  1. For starting, select at least one version of Qt libs (ex Qt 5.15.1) and the c++ compiler of choice (ex MinGW 8.1.0 64-bit).

  2. Select Developer and Designer Tools. I kept the selected defaults.

Note: The choice of the Qt libs and Tools can also be changed post initial installation using MaintenanceTool.exe under Qt installation dir C:\Qt. See here.

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */
</div>

Best practices to test protected methods with PHPUnit

I think troelskn is close. I would do this instead:

class ClassToTest
{
   protected function testThisMethod()
   {
     // Implement stuff here
   }
}

Then, implement something like this:

class TestClassToTest extends ClassToTest
{
  public function testThisMethod()
  {
    return parent::testThisMethod();
  }
}

You then run your tests against TestClassToTest.

It should be possible to automatically generate such extension classes by parsing the code. I wouldn't be surprised if PHPUnit already offers such a mechanism (though I haven't checked).

Eclipse Bug: Unhandled event loop exception No more handles

in short: check out if the bold sections below may save your day :-)

(This answer may help but the source problem is still not found. I'll update my findings if satisfyingly solved.)

<updates...>

update: It just happened again and occurred on dragging/positioning of one XML file (Tomcats content.xml) underneath all other files. (Opened by "XML Editor": Provider: Eclipse Web Tools Platform, Plug-in Name: XML editor, Version: 1.0.700.v201005192212, Plug-in Id: org.eclipse.wst.xmleditor.doc.user)

update2: On further looking into it the error disappears when I move the editor back to the other files (all open editors in one area). Furthermore it appears only when entering or leaving this XML editor, not on e.g. making changes to it and saving it via CRTL+S. Other than that the JBoss-related exception from below occurs on the CTRL+S event, but independent of this issue (so it may not be related at all).

update3: Getting even closer: since some time there has been a new editor positioning feature around. (Initially I was a bit confused, but now I am getting the point and even visually can see what is meant and what makes the difference...). So there are two ways to position editors vertically or horizontally next to other editors:

  1. positioning it inside the same "panel" (indicated by a global and two inner panels/borders/rectangles around the editors) and
  2. positing it next to the old "panel" (indicated by a rectangle frame around the old panel and the new one.

So putting an editor in a new "global" panel (2.) works fine, putting it in a new "local" panel (1.) causes the issue (that's actually very helpful because I can still continue to work quite efficiently) (maybe somebody else could report this bug appropriately) (it also seems not related to the XML editor mentioned above since it also happens e.g. on property files)

update 4: I am using Windows 7 in hibernate mode. Meaning I don't start my Eclipse too often. Now I realized that Eclipse itself had been started (looking at the Task Manager) 2 times (visually and using ALT+TAB for open windows navigation this was not obvious). After (stopping/killing all open instances and) restarting the problem does not occur anymore.

update 5: In this duplicate question somebody stated it would have been solved by the latest windows update: https://stackoverflow.com/a/19316804/1915920 . I'll check this out for myself, but currently I cannot reproduce the problem anyways.

update 6: In another situation I had this and it seemed related to some property window (in this case Jasper Reports) that updated its content automatically, based on the current editor (like an outline view). So it could be a good idea to close and re-open (all) outline and/or property windows.

</...updates>

The error in general indicates, that some program(s) have (propably) unusually many (probably thousands?) of operating system file handles open. So one should check if outside or inside of Eclipse a lot of files are opened at the same time or opened over a short period of time, but not properly closed (they could be visually closed, but the operating system still thinks they are beeing used because the application did not properly free the file handles somehow).

Now I have this issue currently as well. If I look in the Error Log (Window->Show View->General->Error Log) I can see a lot of the following org.jboss.ide.eclipse.archives.core.* exceptions immediately before. Since I don't use the installed JBoss Developer Studio Plugin (that is likely related to this one) right now and no associated window or editor is opened (only some toolbar "JBoss Central" and perspective "JBoss" buttons) I'll have a look if disabling these will help on this sporadic problem. Also I closed all open editors, restarted Eclipse and open them and can't see this issue right now again.

Problems occurred when invoking code from plug-in: "org.eclipse.core.resources".

...

java.lang.NullPointerException
    at org.jboss.ide.eclipse.archives.core.WorkspaceChangeListener$2.visit(WorkspaceChangeListener.java:74)
    at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:69)
    at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:49)
    at org.jboss.ide.eclipse.archives.core.WorkspaceChangeListener.resourceChanged(WorkspaceChangeListener.java:70)
    at org.eclipse.core.internal.events.NotificationManager$1.run(NotificationManager.java:291)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:285)
    at org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:149)
    at org.eclipse.core.internal.resources.Workspace.broadcastPostChange(Workspace.java:396)
    at org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:1531)
    at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2354)
    at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:118)
    at org.eclipse.ui.internal.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:75)
    at org.eclipse.ui.internal.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:65)
    at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation(TextFileDocumentProvider.java:456)
    at org.eclipse.ui.editors.text.TextFileDocumentProvider.saveDocument(TextFileDocumentProvider.java:772)
    at org.eclipse.ui.texteditor.AbstractTextEditor.performSave(AbstractTextEditor.java:5068)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.tools.common.editor.ObjectMultiPageEditor.saveX(ObjectMultiPageEditor.java:403)
    at org.jboss.tools.common.editor.ObjectMultiPageEditor.doSave(ObjectMultiPageEditor.java:385)
    at org.eclipse.ui.internal.SaveableHelper$2.run(SaveableHelper.java:150)
    at org.eclipse.ui.internal.SaveableHelper$5.run(SaveableHelper.java:276)
    at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:464)
    at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:372)
    at org.eclipse.ui.internal.WorkbenchWindow$13.run(WorkbenchWindow.java:1812)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:1809)
    at org.eclipse.ui.internal.SaveableHelper.runProgressMonitorOperation(SaveableHelper.java:284)
    at org.eclipse.ui.internal.SaveableHelper.runProgressMonitorOperation(SaveableHelper.java:263)
    at org.eclipse.ui.internal.SaveableHelper.savePart(SaveableHelper.java:155)
    at org.eclipse.ui.internal.WorkbenchPage.saveSaveable(WorkbenchPage.java:3777)
    at org.eclipse.ui.internal.WorkbenchPage.saveEditor(WorkbenchPage.java:3790)
    at org.jboss.tools.common.model.ui.texteditors.SaveAction3.run(PropertiesTextEditorComponent.java:357)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:499)
    at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:119)
    at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90)
    at sun.reflect.GeneratedMethodAccessor58.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56)
    at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:243)
    at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:224)
    at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
    at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:167)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
    at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:285)
    at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:504)
    at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:555)
    at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:376)
    at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:322)
    at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:84)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1262)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1056)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1081)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1066)
    at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1108)
    at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1104)
    at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1525)
    at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4723)
    at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:344)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4611)
    at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:340)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:4977)
    at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method)
    at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2549)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1113)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:997)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:138)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:610)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:567)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1450)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1426)

...

eclipse.buildId=4.3.0.I20130605-2000
java.version=1.7.0_25
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=de_DE
Framework arguments:  -product org.eclipse.epp.package.reporting.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.reporting.product

installed plugins (Help->About Eclipse->Installation Details->Installed Software: mark all + CTRL+C): (Eclipse Kepler Java EE and BIRT edition as base install)

  Apache Directory Studio LDAP Browser  2.0.0.v20130628 org.apache.directory.studio.ldapbrowser.feature.feature.group   Apache Software Foundation
  DevUtilsFeature   1.0.9.201209201734  DevUtilsFeature.feature.group   null
  Eclipse IDE for Java and Report Developers    2.0.0.20130613-0530 epp.package.reporting   null
  GlassFish Tools   6.2.0.201307232054  oracle.eclipse.tools.glassfish.feature.group    Oracle
  JarPlug   0.6.1   com.simontuffs.eclipse.jarplug.feature.feature.group    simontuffs.com
  Jaspersoft Studio feature 5.2.0   com.jaspersoft.studio.feature.feature.group Jaspersoft Corporation
  Java EE 5 Documentation   6.2.0.201307232054  oracle.eclipse.tools.javaee.doc.v5.feature.group    Oracle
  Java EE 6 Documentation   6.2.0.201307232054  oracle.eclipse.tools.javaee.doc.v6.feature.group    Oracle
  Java EE 7 Documentation   6.2.0.201307232054  oracle.eclipse.tools.javaee.doc.v7.feature.group    Oracle
  JBoss Developer Studio (Core Features)    7.0.0.GA-v20130720-0044-B364    com.jboss.jbds.product.feature.feature.group    JBoss by Red Hat
  Log Viewer Feature    0.9.8.8 de.anbos.eclipse.logviewer.feature.feature.group    Andre Bossert
  MercurialEclipse  2.1.0.201304290948  mercurialeclipse.feature.group  MercurialEclipse project
  MyLV  1.0.4   mylv_feature.feature.group  null
  Oracle ADF Documentation (11.1.1.4)   6.2.0.201307232054  oracle.eclipse.tools.adf.doc.v11114.feature.group   Oracle
  Oracle ADF Documentation (11.1.1.5)   6.2.0.201307232054  oracle.eclipse.tools.adf.doc.v11115.feature.group   Oracle
  Oracle ADF Documentation (11.1.1.6)   6.2.0.201307232054  oracle.eclipse.tools.adf.doc.v11116.feature.group   Oracle
  Oracle ADF Documentation (11.1.1.7)   6.2.0.201307232054  oracle.eclipse.tools.adf.doc.v11117.feature.group   Oracle
  Oracle ADF Documentation (12.1.2) 6.2.0.201307232054  oracle.eclipse.tools.adf.doc.v1212.feature.group    Oracle
  Oracle ADF Tools  6.2.0.201307232054  oracle.eclipse.tools.adf.feature.group  Oracle
  Oracle Cloud Tools    6.2.0.201307232054  oracle.eclipse.tools.cloud.feature.group    Oracle
  Oracle Coherence Tools    6.2.0.201307232054  oracle.eclipse.tools.coherence.feature.group    Oracle
  Oracle Database Tools 6.2.0.201307232054  oracle.eclipse.tools.database.feature.group Oracle
  Oracle Java EE Tools  6.2.0.201307232054  oracle.eclipse.tools.javaee.feature.group   Oracle
  Oracle Maven Tools    6.2.0.201307232054  oracle.eclipse.tools.maven.feature.group    Oracle
  Oracle Spring Tools   6.2.0.201307232054  oracle.eclipse.tools.spring.feature.group   Oracle
  Oracle WebLogic Scripting Tools   6.2.0.201307232054  oracle.eclipse.tools.weblogic.scripting.feature.group   Oracle
  Oracle WebLogic Server Tools  6.2.0.201307232054  oracle.eclipse.tools.weblogic.feature.group Oracle
  Toad® Extension for Eclipse - Community Edition - Core Plugin 1.8.3.201308140922  com.quest.toadext.core.feature.feature.group    Quest Software, Inc.
  Toad® Extension for Eclipse - Community Edition - MySQL DB Plugin 1.8.3.201308140922  com.quest.toadext.mysql.feature.feature.group   Quest Software, Inc.
  Toad® Extension for Eclipse - Community Edition - Oracle Database Plugin  1.8.3.201308140922  com.quest.toadext.feature.feature.group Quest Software, Inc.
  Toad® Extension for Eclipse - Community Edition - PostgreSQL Plugin   1.8.3.201308140922  com.quest.toadext.postgre.feature.feature.group Quest Software, Inc.                

Eclipse error: R cannot be resolved to a variable

Try to delete the import line import com.your.package.name.app.R, then, any resource calls such as mView= (View) mView.findViewById(R.id.resource_name); will highlight the 'R' with an error, a 'Quick fix' will prompt you to import R, and there will be at least two options:

  • android.R
  • your.package.name.R

Select the R corresponding to your package name, and you should be good to go. Hope that helps.

How to add and remove classes in Javascript without jQuery

When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().

function removeClass(classString, toRemove) {
    classes = classString.split(' ');
    var out = Array();
    for (var i=0; i<classes.length; i++) {
        if (classes[i].length == 0) // double spaces can create empty elements
            continue;
        if (classes[i] == toRemove) // don't include this one
            continue;
        out.push(classes[i])
    }
    return out.join(' ');
}

This method is a lot bigger than a simple replace() but at least it can be used on older browsers. And in case the browser doesn't even support the split() command it's relatively easy to add it using prototype.

How to vertically align <li> elements in <ul>?

Here's a good one:

Set line-height equal to whatever the height is; works like a charm!

E.g:

li {
    height: 30px;
    line-height: 30px;
}

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

Late to the party, but may help for coming users -

I got this issue when i select a record using getsession() and again update another record with same identifier using same session causes the issue. Added code below.

Customer existingCustomer=getSession().get(Customer.class,1);
Customer customerFromUi;// This customer details comiong from UI with identifer 1

getSession().update(customerFromUi);// Here the issue comes

This should never be done . Solution is either evict session before update or change business logic.

What's the most appropriate HTTP status code for an "item not found" error page

204:

No Content.” This code means that the server has successfully processed the request, but is not going to return any content

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204

How can I view the Git history in Visual Studio Code?

I recommend you this repository, https://github.com/DonJayamanne/gitHistoryVSCode

Git History Git History

It does exactly what you need and has these features:

  • View the details of a commit, such as author name, email, date, committer name, email, date and comments.
  • View a previous copy of the file or compare it against the local workspace version or a previous version.
  • View the changes to the active line in the editor (Git Blame).
  • Configure the information displayed in the list
  • Use keyboard shortcuts to view history of a file or line
  • View the Git log (along with details of a commit, such as author name, email, comments and file changes).

Changing the width of Bootstrap popover

With the help of what @EML has described above regarding popover on modal windows and also the code shown by @2called-chaos, this is how I solved the problem.

I have a icon on the modal which when clicked should the popup

My HTML

<i title="" class="glyphicon glyphicon-info-sign" rel="popover" data-title="Several Lines" data-content="A - First line<br />B - Second line - Long line <br />C - Third Line - Long Long Long Line"></i>

My Script

    $('[rel=popover]').popover({
        placement: 'bottom',
        html: 'true',
        container: '#name-of-modal-window .modal-body'
    }).on("show.bs.popover", function () { $(this).data("bs.popover").tip().css("max-width", "600px"); });

Change route params without reloading in Angular 2

For me it was actually a mix of both with Angular 4.4.5.

Using router.navigate kept destroying my url by not respecting the realtiveTo: activatedRoute part.

I've ended up with:

this._location.go(this._router.createUrlTree([this._router.url], { queryParams: { profile: value.id } }).toString())

Why is Visual Studio 2010 not able to find/open PDB files?

I'm having the same warnings. I'm not sure it's a matter of 32 vs 64 bits. Just loaded the new symbols and some problems were solved, but the ones regarding OpenCV still persist. This is an extract of the output with solved vs unsolved issue:

'OpenCV_helloworld.exe': Loaded 'C:\OpenCV2.2\bin\opencv_imgproc220d.dll', Cannot find or open the PDB file

'OpenCV_helloworld.exe': Loaded 'C:\WINDOWS\system32\imm32.dll', Symbols loaded (source information stripped).

The code is exiting 0 in case someone will ask.

The program '[4424] OpenCV_helloworld.exe: Native' has exited with code 0 (0x0).

Make browser window blink in task Bar

function blinkTab() {
        const browserTitle = document.title;
        let timeoutId;
        let message = 'My New Title';

        const stopBlinking = () => {
            document.title = browserTitle;
            clearInterval(timeoutId);
        };

        const startBlinking = () => {
            document.title = document.title  === message ? browserTitle : message;
        };

        function registerEvents() {
            window.addEventListener("focus", function(event) { 
                stopBlinking();
            });

            window.addEventListener("blur", function(event) {
                const timeoutId = setInterval(startBlinking, 500);
            });
        };

        registerEvents();
    };


    blinkTab();

What is a good naming convention for vars, methods, etc in C++?

consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.

one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.

as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.

as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):

/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_

/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */

namespace NamespaceName {

/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
    /* private types */
    class t_thing {
        /*...*/
    };
public:
    /* public types */
    typedef uint64_t t_nanosecond;

    /* factory initializers -- UpperCamel */
    t_nanotimer* WithFloat(const float& arg);
    /* public/protected class interface -- UpperCamel */
    static float Uptime();
protected:
    /* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
    static const t_spoke Spoke;
public:
    /* enums in interface are labeled as static class data */
    enum { Granularity = 4 };
public:
    /* construction/destruction -- always use proper initialization list */
    explicit t_nanotimer(t_init);
    explicit t_nanotimer(const float& arg);

    virtual ~t_nanotimer();

    /*
       public and protected instance methods -- lowercaseCamel()
       - booleans prefer is/has
       - accessors use the form: getVariable() setVariable().
       const-correctness is important
     */
    const void* address() const;
    virtual uint64_t hashCode() const;
protected:
    /* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
    virtual bool hasExpired() const;
private:
    /* private methods and private static data */
    void invalidate();
private:
    /*
       instance variables
       - i tend to use underscore suffix, but d_ (for example) is another good alternative
       - note redundancy in visibility
     */
    t_thing ivar_;
private:
    /* prohibited stuff */
    explicit t_nanotimer();
    explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */    
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is my personal goto for this topic:

Gist here, (pull requests welcome!): https://gist.github.com/thorsummoner/b5b1dfcff7e7fdd334ec

import multiprocessing
import sys

THREADS = 3

# Used to prevent multiple threads from mixing thier output
GLOBALLOCK = multiprocessing.Lock()


def func_worker(args):
    """This function will be called by each thread.
    This function can not be a class method.
    """
    # Expand list of args into named args.
    str1, str2 = args
    del args

    # Work
    # ...



    # Serial-only Portion
    GLOBALLOCK.acquire()
    print(str1)
    print(str2)
    GLOBALLOCK.release()


def main(argp=None):
    """Multiprocessing Spawn Example
    """
    # Create the number of threads you want
    pool = multiprocessing.Pool(THREADS)

    # Define two jobs, each with two args.
    func_args = [
        ('Hello', 'World',), 
        ('Goodbye', 'World',), 
    ]


    try:
        # Spawn up to 9999999 jobs, I think this is the maximum possible.
        # I do not know what happens if you exceed this.
        pool.map_async(func_worker, func_args).get(9999999)
    except KeyboardInterrupt:
        # Allow ^C to interrupt from any thread.
        sys.stdout.write('\033[0m')
        sys.stdout.write('User Interupt\n')
    pool.close()

if __name__ == '__main__':
    main()

How to concatenate string and int in C?

Strings are hard work in C.

#include <stdio.h>

int main()
{
   int i;
   char buf[12];

   for (i = 0; i < 100; i++) {
      snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
      printf("%s\n", buf); // outputs so you can see it
   }
}

The 12 is enough bytes to store the text "pre_", the text "_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.

This will tell you how to use snprintf, but I suggest a good C book!

Yes or No confirm box using jQuery

_x000D_
_x000D_
ConfirmDialog('Are you sure');_x000D_
_x000D_
function ConfirmDialog(message) {_x000D_
  $('<div></div>').appendTo('body')_x000D_
    .html('<div><h6>' + message + '?</h6></div>')_x000D_
    .dialog({_x000D_
      modal: true,_x000D_
      title: 'Delete message',_x000D_
      zIndex: 10000,_x000D_
      autoOpen: true,_x000D_
      width: 'auto',_x000D_
      resizable: false,_x000D_
      buttons: {_x000D_
        Yes: function() {_x000D_
          // $(obj).removeAttr('onclick');                                _x000D_
          // $(obj).parents('.Parent').remove();_x000D_
_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        },_x000D_
        No: function() {_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        }_x000D_
      },_x000D_
      close: function(event, ui) {_x000D_
        $(this).remove();_x000D_
      }_x000D_
    });_x000D_
};
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
_x000D_
_x000D_
_x000D_

Grep only the first match and stop

You can pipe grep result to head in conjunction with stdbuf.

Note, that in order to ensure stopping after Nth match, you need to using stdbuf to make sure grep don't buffer its output:

stdbuf -oL grep -rl 'pattern' * | head -n1
stdbuf -oL grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -n1
stdbuf -oL grep -nH -m 1 -R "django.conf.urls.defaults" * | head -n1

As soon as head consumes 1 line, it terminated and grep will receive SIGPIPE because it still output something to pipe while head was gone.

This assumed that no file names contain newline.

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Use "javascript.validate.enable": false in your VS Code settings, It doesn't disable ESLINT. I use both ESLINT & Flow. Simply follow the instructions Flow For Vs Code Setup

Adding this line in settings.json. Helps "javascript.validate.enable": false

Composer could not find a composer.json

You are in wrong directory. cd to your project directory then run composer update.

C++ equivalent of java's instanceof

Depending on what you want to do you could do this:

template<typename Base, typename T>
inline bool instanceof(const T*) {
    return std::is_base_of<Base, T>::value;
}

Use:

if (instanceof<BaseClass>(ptr)) { ... }

However, this purely operates on the types as known by the compiler.

Edit:

This code should work for polymorphic pointers:

template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
    return dynamic_cast<const Base*>(ptr) != nullptr;
}

Example: http://cpp.sh/6qir

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;

Java Byte Array to String to Byte Array

Use the below code API to convert bytecode as string to Byte array.

 byte[] byteArray = DatatypeConverter.parseBase64Binary("JVBERi0xLjQKMyAwIG9iago8P...");

How to center buttons in Twitter Bootstrap 3?

Wrap the Button in div with "text-center" class.

Just change this:

<!-- wrong -->
<div class="col-md-4 center-block">
    <button id="singlebutton" name="singlebutton" class="btn btn-primary center-block">Next Step!</button>
</div>

To this:

<!-- correct -->
<div class="col-md-4 text-center"> 
    <button id="singlebutton" name="singlebutton" class="btn btn-primary">Next Step!</button> 
</div>

Edit

As of BootstrapV4, center-block was dropped #19102 in favor of m-*-auto

ReactJS - How to use comments?

This is how.

Valid:

...
render() {

  return (
    <p>
       {/* This is a comment, one line */}

       {// This is a block 
        // yoohoo
        // ...
       }

       {/* This is a block 
         yoohoo
         ...
         */
       }
    </p>
  )

}
...

Invalid:

...
render() {

  return (
    <p>
       {// This is not a comment! oops! }

       {//
        Invalid comment
       //}
    </p>
  )

}
...

Flutter - Layout a Grid

There are few named constructors in GridView for different scenarios,

Constructors

  1. GridView
  2. GridView.builder
  3. GridView.count
  4. GridView.custom
  5. GridView.extent

Below is a example of GridView constructor:

import 'package:flutter/material.dart';

void main() => runApp(
  MaterialApp(
    home: ExampleGrid(),
  ),
);

class ExampleGrid extends StatelessWidget {
  List<String> images = [
    "https://uae.microless.com/cdn/no_image.jpg",
    "https://images-na.ssl-images-amazon.com/images/I/81aF3Ob-2KL._UX679_.jpg",
    "https://www.boostmobile.com/content/dam/boostmobile/en/products/phones/apple/iphone-7/silver/device-front.png.transform/pdpCarousel/image.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgUgs8_kmuhScsx-J01d8fA1mhlCR5-1jyvMYxqCB8h3LCqcgl9Q",
    "https://ae01.alicdn.com/kf/HTB11tA5aiAKL1JjSZFoq6ygCFXaw/Unlocked-Samsung-GALAXY-S2-I9100-Mobile-Phone-Android-Wi-Fi-GPS-8-0MP-camera-Core-4.jpg_640x640.jpg",
    "https://media.ed.edmunds-media.com/gmc/sierra-3500hd/2018/td/2018_gmc_sierra-3500hd_f34_td_411183_1600.jpg",
    "https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/images/16q1/665019/2016-chevrolet-silverado-2500hd-high-country-diesel-test-review-car-and-driver-photo-665520-s-original.jpg",
    "https://www.galeanasvandykedodge.net/assets/stock/ColorMatched_01/White/640/cc_2018DOV170002_01_640/cc_2018DOV170002_01_640_PSC.jpg",
    "https://media.onthemarket.com/properties/6191869/797156548/composite.jpg",
    "https://media.onthemarket.com/properties/6191840/797152761/composite.jpg",
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView(
        physics: BouncingScrollPhysics(), // if you want IOS bouncing effect, otherwise remove this line
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),//change the number as you want
        children: images.map((url) {
          return Card(child: Image.network(url));
        }).toList(),
      ),
    );
  }
}

If you want your GridView items to be dynamic according to the content, you can few lines to do that but the simplest way to use StaggeredGridView package. I have provided an answer with example here.

Below is an example for a GridView.count:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 4,
        children: List.generate(40, (index) {
          return Card(
            child: Image.network("https://robohash.org/$index"),
          ); //robohash.org api provide you different images for any number you are giving
        }),
      ),
    );
  }
}

Screenshot for above snippet:

Flutter gridview example by blasanka using card widget and robohash api

Example for a SliverGridView:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        primary: false,
        slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.all(20.0),
            sliver: SliverGrid.count(
              crossAxisSpacing: 10.0,
              crossAxisCount: 2,
              children: List.generate(20, (index) {
                return Card(child: Image.network("https://robohash.org/$index"));
              }),
            ),
          ),
        ],
      )
    );
  }
}

How do I check if a type is a subtype OR the type of an object?

If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom gives an error:

Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

because IsAssignableFrom asks for a TypeInfo object. You can use the GetTypeInfo() method from System.Reflection:

typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())

How to print a linebreak in a python function?

The newline character is actually '\n'.

Nested ifelse statement

If you are using any spreadsheet application there is a basic function if() with syntax:

if(<condition>, <yes>, <no>)

Syntax is exactly the same for ifelse() in R:

ifelse(<condition>, <yes>, <no>)

The only difference to if() in spreadsheet application is that R ifelse() is vectorized (takes vectors as input and return vector on output). Consider the following comparison of formulas in spreadsheet application and in R for an example where we would like to compare if a > b and return 1 if yes and 0 if not.

In spreadsheet:

  A  B C
1 3  1 =if(A1 > B1, 1, 0)
2 2  2 =if(A2 > B2, 1, 0)
3 1  3 =if(A3 > B3, 1, 0)

In R:

> a <- 3:1; b <- 1:3
> ifelse(a > b, 1, 0)
[1] 1 0 0

ifelse() can be nested in many ways:

ifelse(<condition>, <yes>, ifelse(<condition>, <yes>, <no>))

ifelse(<condition>, ifelse(<condition>, <yes>, <no>), <no>)

ifelse(<condition>, 
       ifelse(<condition>, <yes>, <no>), 
       ifelse(<condition>, <yes>, <no>)
      )

ifelse(<condition>, <yes>, 
       ifelse(<condition>, <yes>, 
              ifelse(<condition>, <yes>, <no>)
             )
       )

To calculate column idnat2 you can:

df <- read.table(header=TRUE, text="
idnat idbp idnat2
french mainland mainland
french colony overseas
french overseas overseas
foreign foreign foreign"
)

with(df, 
     ifelse(idnat=="french",
       ifelse(idbp %in% c("overseas","colony"),"overseas","mainland"),"foreign")
     )

R Documentation

What is the condition has length > 1 and only the first element will be used? Let's see:

> # What is first condition really testing?
> with(df, idnat=="french")
[1]  TRUE  TRUE  TRUE FALSE
> # This is result of vectorized function - equality of all elements in idnat and 
> # string "french" is tested.
> # Vector of logical values is returned (has the same length as idnat)
> df$idnat2 <- with(df,
+   if(idnat=="french"){
+   idnat2 <- "xxx"
+   }
+   )
Warning message:
In if (idnat == "french") { :
  the condition has length > 1 and only the first element will be used
> # Note that the first element of comparison is TRUE and that's whay we get:
> df
    idnat     idbp idnat2
1  french mainland    xxx
2  french   colony    xxx
3  french overseas    xxx
4 foreign  foreign    xxx
> # There is really logic in it, you have to get used to it

Can I still use if()? Yes, you can, but the syntax is not so cool :)

test <- function(x) {
  if(x=="french") {
    "french"
  } else{
    "not really french"
  }
}

apply(array(df[["idnat"]]),MARGIN=1, FUN=test)

If you are familiar with SQL, you can also use CASE statement in sqldf package.

What is the difference between persist() and merge() in JPA and Hibernate?

This is coming from JPA. In a very simple way:

  • persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

  • merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

Convert any object to a byte[]

Using Encoding.UTF8.GetBytes is faster than using MemoryStream. Here, I am using NewtonsoftJson to convert input object to JSON string and then getting bytes from JSON string.

byte[] SerializeObject(object value) =>Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));

Benchmark for @Daniel DiPaolo's version with this version

Method                    |     Mean |     Error |    StdDev |   Median |  Gen 0 | Allocated |
--------------------------|----------|-----------|-----------|----------|--------|-----------| 
ObjectToByteArray         | 4.983 us | 0.1183 us | 0.2622 us | 4.887 us | 0.9460 |    3.9 KB |
ObjectToByteArrayWithJson | 1.548 us | 0.0309 us | 0.0690 us | 1.528 us | 0.3090 |   1.27 KB |

Printing to the console in Google Apps Script?

Updated for 2020

In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:

  1. Logger.log()
  2. console.log()

Happy coding!

Difference between Select Unique and Select Distinct

Only In Oracle =>

SELECT DISTINCT and SELECT UNIQUE behave the same way. While DISTINCT is ANSI SQL standard, UNIQUE is an Oracle specific statement.

In other databases (like sql-server in your case) =>

SELECT UNIQUE is invalid syntax. UNIQUE is keyword for adding unique constraint on the column.

SELECT DISTINCT

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

Sorry to revive a dead thread but i solved this on VS2017 by deleting the project template cache and item template cache folders in

%localappdata%\Microsoft\VisualStudio\[BUILD]

Then resetting the visual studio settings via

Tools>Import and export settings>reset all settings

Also ive heard turning off "Lightweight solution load for all projects" can help.