Programs & Examples On #Integrity

The aspect of an object which describes it as unaltered since a reference time at which a description of its state was recorded, or a description of the continued functioning of a property of the object. An example of this is checking whether the MD5 hash of this file is the same as the MD5 hash that was calculated yesterday, to ensure the file was unaltered.

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

I faced same issue. Plus while I was trying to resolve from picking solutions from other devs, I faced few more issues like one listed here.

Angular 9 ng new myapp gives error The Schematic workflow failed

https://medium.com/@codewin/npm-warn-deprecated-request-2-88-2-b6da20766fd7

Finally after trying cache clean and verify and reinstall node of different versions and npm update, nvm and many other solution like set proxy and better internet connection, I still could not arrive to a resolve.

What worked for me is : I browsed a bit inside my C:\Users--- folder, I found package-lock.json and .npmrc files. I deleted those and reinstalled angular and tried. npm install and uninstall of different modules started working.

issue while creating using <code>ng new sample-app</code>

How to solve npm install throwing fsevents warning on non-MAC OS?

Yes, it works when with the command npm install --no-optional
Using environment:

  • iTerm2
  • macos login to my vm ubuntu16 LTS.

Search input with an icon Bootstrap 4

in ASPX bootstrap v4.0.0, no beta (dl 21-01-2018)

<div class="input-group">
<asp:TextBox ID="txt_Product" runat="server" CssClass="form-control" placeholder="Product"></asp:TextBox>
<div class="input-group-append">
    <asp:LinkButton ID="LinkButton3" runat="server" CssClass="btn btn-outline-primary">
        <i class="ICON-copyright"></i>
    </asp:LinkButton>
</div>

Bootstrap 4: Multilevel Dropdown Inside Navigation

This one works on Bootstrap 4.3.1.

Jsfiddle: https://jsfiddle.net/ko6L31w4/1/

The HTML code might be a little bit messy because I create a slightly complex dropdown menu for comprehensive test, otherwise everything is pretty straight forward.

Js includes fewer ways to collapse opened dropdowns and CSS only includes minimal styles for full functionalities.

_x000D_
_x000D_
$(function() {_x000D_
  $("ul.dropdown-menu [data-toggle='dropdown']").on("click", function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    _x000D_
    //method 1: remove show from sibilings and their children under your first parent_x000D_
    _x000D_
/*   if (!$(this).next().hasClass('show')) {_x000D_
        _x000D_
          $(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
       }  */     _x000D_
     _x000D_
     _x000D_
    //method 2: remove show from all siblings of all your parents_x000D_
    $(this).parents('.dropdown-submenu').siblings().find('.show').removeClass("show");_x000D_
    _x000D_
    $(this).siblings().toggleClass("show");_x000D_
    _x000D_
    _x000D_
    //collapse all after nav is closed_x000D_
    $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
      $('.dropdown-submenu .show').removeClass("show");_x000D_
    });_x000D_
_x000D_
  });_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu>.dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<nav class="navbar navbar-expand-md navbar-light bg-white py-3 shadow-sm">_x000D_
  <div class="container-fluid">_x000D_
    <a href="#" class="navbar-brand font-weight-bold">Multilevel Dropdown</a>_x000D_
    _x000D_
  <button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
_x000D_
  <div id="navbarContent" class="collapse navbar-collapse">_x000D_
      <ul class="navbar-nav mr-auto">_x000D_
      _x000D_
        <!-- nav dropdown -->_x000D_
        <li class="nav-item dropdown">_x000D_
        _x000D_
          <a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle">Dropdown</a>_x000D_
          <ul class="dropdown-menu">_x000D_
            _x000D_
            <li><a href="#" class="dropdown-item">Some action</a></li>_x000D_
            _x000D_
            <!-- lvl 1 dropdown -->_x000D_
            <li class="dropdown-submenu">_x000D_
              <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                _x000D_
                <!-- lvl 2 dropdown -->_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    _x000D_
                    <!-- lvl 3 dropdown --> _x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 3</a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#" class="dropdown-item">level 4</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                    _x000D_
                  </ul>_x000D_
                </li>_x000D_
_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            _x000D_
            <li><a href="#" class="dropdown-item">Some other action</a></li>_x000D_
            _x000D_
            <li class="dropdown-submenu">_x000D_
              <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
              <ul class="dropdown-menu">_x000D_
                _x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                _x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                _x000D_
                                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                _x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
              </ul>_x000D_
            </li>  _x000D_
          </ul>_x000D_
        </li>_x000D_
_x000D_
        <li class="nav-item"><a href="#" class="nav-link">About</a></li>_x000D_
        <li class="nav-item"><a href="#" class="nav-link">Services</a></li>_x000D_
        <li class="nav-item"><a href="#" class="nav-link">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Customize Bootstrap checkboxes

Since Bootstrap 3 doesn't have a style for checkboxes I found a custom made that goes really well with Bootstrap style.

Checkboxes

_x000D_
_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border: 1px solid #a9a9a9;_x000D_
  border-radius: .25em;_x000D_
  width: 1.3em;_x000D_
  height: 1.3em;_x000D_
  float: left;_x000D_
  margin-right: .5em;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon {_x000D_
  position: absolute;_x000D_
  font-size: .8em;_x000D_
  line-height: 0;_x000D_
  top: 50%;_x000D_
  left: 15%;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr {_x000D_
  opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default checkbox -->_x000D_
<div class="checkbox">_x000D_
  <label>_x000D_
   <input type="checkbox" value="">_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
   Option one_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked checkbox -->_x000D_
<div class="checkbox">_x000D_
  <label>_x000D_
   <input type="checkbox" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
   Option two is checked by default_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled checkbox -->_x000D_
<div class="checkbox disabled">_x000D_
  <label>_x000D_
   <input type="checkbox" value="" disabled>_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
   Option three is disabled_x000D_
   </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Radio

_x000D_
_x000D_
.checkbox label:after,_x000D_
.radio label:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border: 1px solid #a9a9a9;_x000D_
  border-radius: .25em;_x000D_
  width: 1.3em;_x000D_
  height: 1.3em;_x000D_
  float: left;_x000D_
  margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
  border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
  position: absolute;_x000D_
  font-size: .8em;_x000D_
  line-height: 0;_x000D_
  top: 50%;_x000D_
  left: 13%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
  margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
  opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default radio -->_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="">_x000D_
   <span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
   Option one_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked radio -->_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
   Option two is checked by default_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled radio -->_x000D_
<div class="radio disabled">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="" disabled>_x000D_
   <span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
   Option three is disabled_x000D_
   </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Custom icons

You can choose your own icon between the ones from Bootstrap or Font Awesome by changing [icon name] with your icon.

<span class="cr"><i class="cr-icon [icon name]"></i>

For example:

  • glyphicon glyphicon-remove for Bootstrap, or
  • fa fa-bullseye for Font Awesome

_x000D_
_x000D_
.checkbox label:after,_x000D_
.radio label:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border: 1px solid #a9a9a9;_x000D_
  border-radius: .25em;_x000D_
  width: 1.3em;_x000D_
  height: 1.3em;_x000D_
  float: left;_x000D_
  margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
  border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
  position: absolute;_x000D_
  font-size: .8em;_x000D_
  line-height: 0;_x000D_
  top: 50%;_x000D_
  left: 15%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
  margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
  opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<div class="checkbox">_x000D_
  <label>_x000D_
   <input type="checkbox" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-remove"></i></span>_x000D_
   Bootstrap - Custom icon checkbox_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
   Font Awesome - Custom icon radio checked by default_x000D_
   </label>_x000D_
</div>_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="">_x000D_
   <span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
   Font Awesome - Custom icon radio_x000D_
   </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Job for mysqld.service failed See "systemctl status mysqld.service"

This amazingly worked.

/etc/init.d/mysql stop
service mysql stop
killall -KILL mysql mysqld_safe mysqld
/etc/init.d/mysql start
service mysql start

Align button to the right

The bootstrap 4.0.0 file you are getting from cdn doesn't have a pull-right (or pull-left) class. The v4 is in alpha, so there are many issues like that.

There are 2 options:

1) Reverse to bootstrap 3.3.7

2) Write your own CSS.

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

If you want to apply an extra small class in Bootstrap 4,you need to use col-. important thing to know is that col-xs- is dropped in Bootstrap4

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

$(...).datepicker is not a function - JQuery - Bootstrap

Need to include jquery-ui too:

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

install python again:

brew install python

try it again:

sudo pip install scrapy

works for me, hope it can help

'NOT NULL constraint failed' after adding to models.py

@coldmind answer is correct but lacks details.

The 'NOT NULL constraint failed' occurs when something tries to set None to the 'zipcode' property, while it has not been explicitely allowed.

It usually happens when:

1) your field has Null=False by default, so that the value in the database cannot be None (i.e. undefined) when the object is created and saved in the database (this happens after a objects_set.create() call or setting the .zipcode property and doing a .save() call).

For instance, if somewhere in your code an assignement results in:

model.zipcode = None

this error is raised

2) When creating or updating the database, Django is constrained to find a default value to fill the field, because Null=False by default. It does not find any because you haven't defined any. So this error can not only happen during code execution but also when creating the database?

3) Note that the same error would be returned of you define default=None, or if your default value with an incorrect type, for instance default='00000' instead of 00000 for your field (maybe can there be automatic conversion between char and integers, but I would advise against relying on it. Besides, explicit is better than implicit). Most likely an error would also be raised if the default value violates the max_length property, e.g. 123456

So you'll have to define the field by one of the following:

models.IntegerField(_('zipcode'), max_length=5, Null=True,
   blank=True)

models.IntegerField(_('zipcode'), max_length=5, Null=False,
   blank=True, default=00000)

models.IntegerField(_('zipcode'), max_length=5, blank=True,
   default=00000)

and then make a migration (python3 manage.py makemigration ) and then migrate (python3 manage.py migrate).

For safety you can also delete the last failed migration files in <app_name>/migrations/, there are usually named after this pattern:

<NUMBER>_auto_<DATE>_<HOUR>.py

Finally, if you don't set Null=True, make sure that mode.zipcode = None is never done anywhere.

SSL Error: unable to get local issuer certificate

If you are a linux user Update node to a later version by running

sudo apt update

 sudo apt install build-essential checkinstall libssl-dev

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash

nvm --version

nvm ls

nvm ls-remote

nvm install [version.number]

this should solve your problem

Vagrant error : Failed to mount folders in Linux guest

(from my comment above)

Following the problem to it's roots: , specifically the part in the comments saying this:

wget https://www.virtualbox.org/download/testcase/VBoxGuestAdditions_4.3.11-93070.iso?? 
sudo cp VBoxGuestAdditions_4.3.11-93070.iso /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso

After doing that, I have business as usual with all my virtual machines (and their current Vagrantfiles, of course)

When you have to do something in a freshly created virtual machine, to make it work, something is wrong.

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Hibernate tries to insert data that violate underlying database integrity contraints.

There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).

Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering] part).

Android Studio: Unable to start the daemon process

I think it's wrong JAVA_HOME make this error. when i get error i try all the way,but it don't work for me. i try delete c:.gradle and Compiler Android studio but it's still don't work. i Re-install the system it work, when update system i get the error again. I try Compiler JAVA_HOME user environment and system environment: enter image description here

when i use cmd input java:

enter image description here

when cmd.exe show the masage it mean it's work, try to runing Android Studio, it will fix the error. enter image description here

How do I change Bootstrap 3 column order on mobile layout?

Updated 2018

For the original question based on Bootstrap 3, the solution was to use push-pull.

In Bootstrap 4 it's now possible to change the order, even when the columns are full-width stacked vertically, thanks to Bootstrap 4 flexbox. OFC, the push pull method will still work, but now there are other ways to change column order in Bootstrap 4, making it possible to re-order full-width columns.

Method 1 - Use flex-column-reverse for xs screens:

<div class="row flex-column-reverse flex-md-row">
    <div class="col-md-3">
        sidebar
    </div>
    <div class="col-md-9">
        main
    </div>
</div>

Method 2 - Use order-first for xs screens:

<div class="row">
    <div class="col-md-3">
        sidebar
    </div>
    <div class="col-md-9 order-first order-md-last">
        main
    </div>
</div>

Bootstrap 4(alpha 6): http://www.codeply.com/go/bBMOsvtJhD
Bootstrap 4.1: https://www.codeply.com/go/e0v77yGtcr


Original 3.x Answer

For the original question based on Bootstrap 3, the solution was to use push-pull for the larger widths, and then the columns will show is their natural order on smaller (xs) widths. (A-B reverse to B-A).

<div class="container">
    <div class="row">
        <div class="col-md-9 col-md-push-3">
            main
        </div>
        <div class="col-md-3 col-md-pull-9">
            sidebar
        </div>
    </div>
</div>

Bootstrap 3: http://www.codeply.com/go/wgzJXs3gel

@emre stated, "You cannot change the order of columns in smaller screens but you can do that in large screens". However, this should be clarified to state: "You cannot change the order of full-width "stacked" columns.." in Bootstrap 3.

The value violated the integrity constraints for the column

the point can be if you are not using valid login for linked server. Problem is on destination server side.

There are few steps to try:

  1. Align db user and login on destination server: alter user [DBUSER_of_linkedserverlogin] with login = [linkedserverlogin]

  2. recreate login on destination server used by linked server.

  3. Backup table and recreate it.

2nd resolved my issue with "The value violated the integrity constraints for the column.".

Foreign Key to non-primary key

Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

Center a column using Twitter Bootstrap 3

Use mx-auto in your div class using Bootstrap 4.

<div class="container">
  <div class="row">
    <div class="mx-auto">
      You content here
    </div>
  </div>
</div>

SHA-256 or MD5 for file integrity

Both SHA256 and MDA5 are hashing algorithms. They take your input data, in this case your file, and output a 256/128-bit number. This number is a checksum. There is no encryption taking place because an infinite number of inputs can result in the same hash value, although in reality collisions are rare.

SHA256 takes somewhat more time to calculate than MD5, according to this answer.

Offhand, I'd say that MD5 would be probably be suitable for what you need.

Integrity constraint violation: 1452 Cannot add or update a child row:

I just exported the table deleted and then imported it again and it worked for me. This was because i deleted the parent table(users) and then recreated it and child table(likes) has the foreign key to parent table(users).

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

your column value is already in database table it means your table column is Unique you should change your value and try again

oracle - what statements need to be committed?

And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

Is there a naming convention for MySQL?

Simple Answer: NO

Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.

By personal experience, I would recommed this:

  • Use lower case. This almost ensures interoperability when you migrate your databases from one server to another. Sometimes the lower_case_table_names is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).
  • Short names. Simple and clear. The most easy and fast is identify your table or columns, the better. Trust me, when you make a lot of different queries in a short amount of time is better having all simple to write (and read).
  • Avoid prefixes. Unless you are using the same database for tables of different applications, don't use prefixes. This only add more verbosity to your queries. There are situations when this could be useful, for example, when you want to indentify primary keys and foreign keys, that usually table names are used as prefix for id columns.
  • Use underscores for separating words. If you still want to use more than one word for naming a table, column, etc., so use underscores for separating_the_words, this helps for legibility (your eyes and your stressed brain are going to thank you).
  • Be consistent. Once you have your own standard, follow it. Don´t be the person that create the rules and is the first who breaking them, that is shameful.

And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.

How to remove carriage returns and new lines in Postgresql?

In the case you need to remove line breaks from the begin or end of the string, you may use this:

UPDATE table 
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );

Have in mind that the hat ^ means the begin of the string and the dollar sign $ means the end of the string.

Hope it help someone.

SQLite3 database or disk is full / the database disk image is malformed

I have seen this happen when the database gets corrupted, have you tried cloning it into a new one ?

Safley copy a s SQLite db

Safely copy a SQLite database

It's trivially easy to copy a SQLite database. It's less trivial to do this in a way that won't corrupt it. Here's how:

shell$ sqlite3 some.db
sqlite> begin immediate;
<press CTRL+Z>
shell$ cp some.db some.db.backup
shell$ exit
sqlite> rollback;

This will give you a nice clean backup that's sure to be in a proper state, since writing to the database half-way through your copying process is impossible.

Cannot add or update a child row: a foreign key constraint fails

If you use mysql index or relation between tables, firstly you delete the colums(for example:city_id) and create new colums with same name(for example:city_id).Then try again...

Postgres: INSERT if does not exist already

You can make use of VALUES - available in Postgres:

INSERT INTO person (name)
    SELECT name FROM person
    UNION 
    VALUES ('Bob')
    EXCEPT
    SELECT name FROM person;

Parsing JSON object in PHP using json_decode

While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like

echo $data[0]->weather[0]->weatherIconUrl[0]->value;

to make sure you are using the weatherIconUrl for the correct date instance.

MySQL foreign key constraints, cascade delete

I got confused by the answer to this question, so I created a test case in MySQL, hope this helps

-- Schema
CREATE TABLE T1 (
    `ID` int not null auto_increment,
    `Label` varchar(50),
    primary key (`ID`)
);

CREATE TABLE T2 (
    `ID` int not null auto_increment,
    `Label` varchar(50),
    primary key (`ID`)
);

CREATE TABLE TT (
    `IDT1` int not null,
    `IDT2` int not null,
    primary key (`IDT1`,`IDT2`)
);

ALTER TABLE `TT`
    ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
    ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;

-- Data
INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4),
(4,1),(4,2),(4,3),(4,4);

-- Delete
DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
TRUNCATE `T2`; -- Can't truncate a table with a referenced field
DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1

How can I select all rows with sqlalchemy?

You can easily import your model and run this:

from models import User

# User is the name of table that has a column name
users = User.query.all()

for user in users:
    print user.name

Can table columns with a Foreign Key be NULL?

The above works but this does not. Note the ON DELETE CASCADE

CREATE DATABASE t;
USE t;

CREATE TABLE parent (id INT NOT NULL,
                 PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (id INT NULL, 
                parent_id INT NULL,
                FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE

) ENGINE=INNODB;


INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)

What are database normal forms and can you give examples?

I've never had a good memory for exact wording, but in my database class I think the professor always said something like:

The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF].

What's wrong with foreign keys?

Foreign keys are essential to any relational database model.

Regex empty string or email

matching empty string or email

(^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

matching empty string or email but also matching any amount of whitespace

(^\s*$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)

see more about the email matching regex itself:

http://www.regular-expressions.info/email.html

How can I kill a process by name instead of PID?

If you run GNOME, you can use the system monitor (System->Administration->System Monitor) to kill processes as you would under Windows. KDE will have something similar.

Quick way to create a list of values in C#?

If you're looking to reduce clutter, consider

var lst = new List<string> { "foo", "bar" };

This uses two features of C# 3.0: type inference (the var keyword) and the collection initializer for lists.

Alternatively, if you can make do with an array, this is even shorter (by a small amount):

var arr = new [] { "foo", "bar" };

How do I get the last inserted ID of a MySQL table in PHP?

I tried

mysqli_insert_id($dbConnectionObj)

This returns the current connection's last inserted id, so if you are managing your connections properly this should work. Worked for me at least.

Spring Boot how to hide passwords in properties file

UPDATE: I noticed folks down-voting this, so I have to say that although this is not an ideal solution, but this works and acceptable in some use-cases. Cloudfoundry uses Environment variables to inject credentials when a Service is binded to an application. More info https://docs.cloudfoundry.org/devguide/services/application-binding.html

And also if your system is not shared, then for local development this is also acceptable. Of course, the more safe and secure way is explained in Answer by @J-Alex.

Answer:

If you want to hide your passwords then the easiest solution is to use Environment variables in application.properties file or directly in your code.

In application.properties:

mypassword=${password}

Then in your configuration class:

@Autowired
private Environment environment;

[...]//Inside a method
System.out.println(environment.getProperty("mypassword"));

In your configuration class:

@Value("${password}")
private String herokuPath;

[...]//Inside a method
System.out.println(herokuPath);

Note: You might have to restart after setting the environment variable. For windows:

In Windows

Refer this Documentation for more info.

"The page you are requesting cannot be served because of the extension configuration." error message

Use aspnet_regiis.exe to register version of .NET framework you are using.

This is a common issue and happens when IIS is installed after VS or .NET framework.

Note - for Windows 8/10 users, see the other answer by JohnOpincar below. And also the comment/tip from Kevin Brydon.

How to load data to hive from HDFS without removing the source file?

from your question I assume that you already have your data in hdfs. So you don't need to LOAD DATA, which moves the files to the default hive location /user/hive/warehouse. You can simply define the table using the externalkeyword, which leaves the files in place, but creates the table definition in the hive metastore. See here: Create Table DDL eg.:

create external table table_name (
  id int,
  myfields string
)
location '/my/location/in/hdfs';

Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:

row format delimited fields terminated by ','

How do I get the localhost name in PowerShell?

A slight tweak on @CPU-100's answer, for the local FQDN:

[System.Net.DNS]::GetHostByName($Null).HostName

How to pass parameters to $http in angularjs?

Build URL '/search' as string. Like

"/search?fname="+fname"+"&lname="+lname

Actually I didn't use

 `$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}})` 

but I'm sure "params" should be JSON.stringify like for POST

var jsonData = JSON.stringify(
    {
        fname: fname,
        lname: lname 
    }
);

After:

$http({
  method:'GET',
  url:'/search',
  params: jsonData
});

String Comparison in Java

The wording "comparison" is mildly misleading. You are not comparing for strict equality but for which string comes first in the dictionary (lexicon).

This is the feature that allows collections of strings to be sortable.

Note that this is very dependent on the active locale. For instance, here in Denmark we have a character "å" which used to be spelled as "aa" and is very distinct from two single a's (EDIT: If pronounced as "å"!). Hence Danish sorting rules treat two consequtive a's identically to an "å", which means that it goes after z. This also means that Danish dictionaries are sorted differently than English or Swedish ones.

Determine when a ViewPager changes pages

For ViewPager2,

viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
  override fun onPageSelected(position: Int) {
    super.onPageSelected(position)
  }
})

where OnPageChangeCallback is a static class with three methods:

onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position), 
onPageScrollStateChanged(@ScrollState int state)

How to check if number is divisible by a certain number?

package lecture3;

import java.util.Scanner;

public class divisibleBy2and5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter an integer number:");
        Scanner input = new Scanner(System.in);
        int x;
        x = input.nextInt();
         if (x % 2==0){
             System.out.println("The integer number you entered is divisible by 2");
         }
         else{
             System.out.println("The integer number you entered is not divisible by 2");
             if(x % 5==0){
                 System.out.println("The integer number you entered is divisible by 5");
             } 
             else{
                 System.out.println("The interger number you entered is not divisible by 5");
             }
        }

    }
}

Android: Internet connectivity change listener

ConnectivityAction is deprecated in api 28+. Instead you can use registerDefaultNetworkCallback as long as you support api 24+.

In Kotlin:

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
    it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            //take action when network connection is gained
        }
        override fun onLost(network: Network?) {
            //take action when network connection is lost
        }
    })
}

Passing ArrayList from servlet to JSP

<html>
    <%

        ArrayList<Actor> list = new ArrayList<Actor>();
        list = (ArrayList<Actor>) request.getAttribute("actors");
    %>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Actor</title>
</head>

<body>

    <h2>This is Actor Class</h2>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
            <% for(int i = 0; i < list.size(); i++) {
                Actor actor = new Actor();
                actor = list.get(i);
                //out.println(actor.getId());
                //out.println(actor.getFirstname());
                //out.println(actor.getLastname());
            %>


            <tr>
                <td><%=actor.getId()%></td>
                <td><%=actor.getFirstname()%></td>
                <td><%=actor.getLastname()%></td>
               </tr>
            <%
            };
            %>
        </tbody>
    </table>

</body>

Add views below toolbar in CoordinatorLayout

Take the attribute

app:layout_behavior="@string/appbar_scrolling_view_behavior"

off the RecyclerView and put it on the FrameLayout that you are trying to show under the Toolbar.

I've found that one important thing the scrolling view behavior does is to layout the component below the toolbar. Because the FrameLayout has a descendant that will scroll (RecyclerView), the CoordinatorLayout will get those scrolling events for moving the Toolbar.


One other thing to be aware of: That layout behavior will cause the FrameLayout height to be sized as if the Toolbar is already scrolled, and with the Toolbar fully displayed the entire view is simply pushed down so that the bottom of the view is below the bottom of the CoordinatorLayout.

This was a surprise to me. I was expecting the view to be dynamically resized as the toolbar is scrolled up and down. So if you have a scrolling component with a fixed component at the bottom of your view, you won't see that bottom component until you have fully scrolled the Toolbar.

So when I wanted to anchor a button at the bottom of the UI, I worked around this by putting the button at the bottom of the CoordinatorLayout (android:layout_gravity="bottom") and adding a bottom margin equal to the button's height to the view beneath the toolbar.

SSIS Convert Between Unicode and Non-Unicode Error

I have been having the same issue and tried everything written here but it was still giving me the same error. Turned out to be NULL value in the column which I was trying to convert.

Removing the NULL value solved my issue.

Cheers, Ahmed

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

Can I convert a C# string value to an escaped string literal

Code:

string someString1 = "\tHello\r\n\tWorld!\r\n";
string someString2 = @"\tHello\r\n\tWorld!\r\n";

Console.WriteLine(someString1);
Console.WriteLine(someString2);

Output:

    Hello
    World!

\tHello\r\n\tWorld!\r\n

Is this what you want?

Preferred way of loading resources in Java

I tried a lot of ways and functions that suggested above, but they didn't work in my project. Anyway I have found solution and here it is:

try {
    InputStream path = this.getClass().getClassLoader().getResourceAsStream("img/left-hand.png");
    img = ImageIO.read(path);
} catch (IOException e) {
    e.printStackTrace();
}

How to log out user from web site using BASIC authentication?

add this to your application :

@app.route('/logout')
def logout():
    return ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})

VBScript - How to make program wait until process has finished?

Probably something like this? (UNTESTED)

Sub Sample()
    Dim strWB4, strMyMacro
    strMyMacro = "Sheet1.my_macro_name"

    '
    '~~> Rest of Code
    '

    'loop through the folder and get the file names
    For Each Fil In FLD.Files
        Set x4WB = x1.Workbooks.Open(Fil)
        x4WB.Application.Visible = True

        x1.Run strMyMacro

        x4WB.Close

        Do Until IsWorkBookOpen(Fil) = False
            DoEvents
        Loop
    Next

    '
    '~~> Rest of Code
    '
End Sub

'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

This issue is occurring because we don't have Entity Framework installed. Please install Entity Framework using the below command.

Install-Package EntityFramework -IncludePrerelease

Once installed, choose the project in the package manger console default project drop down.

Make sure at least one class in your project inherits from data context, otherwise use the below class:

public class MyDbContext : DbContext
    {
        public MyDbContext()
        {
        }
    }

If we don't do this we will get another error:

No context type was found in the assembly

After completing these things you can run

enable-migrations

How to do a num_rows() on COUNT query in codeigniter?

As per CI Docs we can use the following,

$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();

If we want to get total rows in the table without any condition, simple use

echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table

How to remove elements from a generic list while iterating over it?

Copy the list you are iterating. Then remove from the copy and interate the original. Going backwards is confusing and doesn't work well when looping in parallel.

var ids = new List<int> { 1, 2, 3, 4 };
var iterableIds = ids.ToList();

Parallel.ForEach(iterableIds, id =>
{
    ids.Remove(id);
});

About "*.d.ts" in TypeScript

Like @takeshin said .d stands for declaration file for typescript (.ts).

Few points to be clarified before proceeding to answer this post -

  1. Typescript is syntactic superset of javascript.
  2. Typescript doesn't run on its own, it needs to be transpiled into javascript (typescript to javascript conversion)
  3. "Type definition" and "Type checking" are major add-on functionalities that typescript provides over javascript. (check difference between type script and javascript)

If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system

To Answer this post -

As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.

For ex -

If you install javascript library -

npm install --save mylib

and try importing it in typescript code -

import * from "mylib";

you will get error.

"Cannot find module 'mylib'."

As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.

In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.

Now when you try -

import * from "mylib";

mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Possible to view PHP code of a website?

By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).

Could not insert new outlet connection: Could not find any information for the class named

Simplest solution:- I used xCode 7 and iOS 9.

in your .m

delete #import "VC.h"

save .m and link your outlet again it work fine.

ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

The located assembly's manifest definition does not match the assembly reference

I got stumped with this for a while. I could build and run in release, couldn't in debug due to a reference that didn't match match the manifest. I must have checked the references a hundred times, and deleted all dll's. I noticed that the generated manifest in debug and release were different.

I deleted the app.manifest in my project/properties and it fixed the problem. This didn't include mention of the offending referenced dll's - so I don't know why this was causing a problem.

Listing only directories using ls in Bash?

Four (more) Reliable Options.

An unquoted asterisk * will be interpreted as a pattern (glob) by the shell. The shell will use it in pathname expansion. It will then generate a list of filenames that match the pattern.

A simple asterisk will match all filenames in the PWD (present working directory). A more complex pattern as */ will match all filenames that end in /. Thus, all directories. That is why the command:

1.- echo.

echo */
echo ./*/              ### Avoid misinterpreting filenames like "-e dir"

will be expanded (by the shell) to echo all directories in the PWD.


To test this: Create a directory (mkdir) named like test-dir, and cd into it:

mkdir test-dir; cd test-dir

Create some directories:

mkdir {cs,files,masters,draft,static}   # Safe directories.
mkdir {*,-,--,-v\ var,-h,-n,dir\ with\ spaces}  # Some a bit less secure.
touch -- 'file with spaces' '-a' '-l' 'filename'    # And some files:

The command echo ./*/ will remain reliable even with odd named files:

./--/ ./-/ ./*/ ./cs/ ./dir with spaces/ ./draft/ ./files/ ./-h/
./masters/ ./-n/ ./static/ ./-v var/

But the spaces in filenames make reading a bit confusing.


If instead of echo, we use ls. The shell is still what is expanding the list of filenames. The shell is the reason to get a list of directories in the PWD. The -d option to ls makes it list the present directory entry instead of the contents of each directory (as presented by default).

ls -d */

However, this command is (somewhat) less reliable. It will fail with the odd named files listed above. It will choke with several names. You need to erase one by one till you find the ones with problems.

2.- ls

The GNU ls will accept the "end of options" (--) key.

ls -d ./*/                     ### More reliable BSD ls
ls -d -- */                    ### More reliable GNU ls

3.-printf

To list each directory in its own line (in one column, similar to ls -1), use:

$ printf "%s\n" */        ### Correct even with "-", spaces or newlines.

And, even better, we could remove the trailing /:

$ set -- */; printf "%s\n" "${@%/}"        ### Correct with spaces and newlines.

An attempt like

$ for i in $(ls -d */); do echo ${i%%/}; done

will fail on:

  • some names (ls -d */) as already shown above.
  • will be affected by the value of IFS.
  • will split names on spaces and tabs (with default IFS).
  • each newline in the name will start a new echo command.

4.- Function

Finally, using the argument list inside a function will not affect the arguments list of the present running shell. Simply

$ listdirs(){ set -- */; printf "%s\n" "${@%/}"; }
$ listdirs

presents this list:

--
-
*
cs
dir with spaces
draft
files
-h
masters
-n
static
-v var

These options are safe with several types of odd filenames.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

BAT file to open CMD in current directory

Another solution is to use a shortcut file to cmd.exe instead of a batch file.

Edit the shortcut's start in property to %~dp0.

You achieve the same thing, except it has the Cmd icon (and you can change this).

Some people don't like clicking on batch files without knowing what's in them, and some corporate network drives have a ban on .bat files...

Read next word in java

You already get the next line in this line of your code:

 String line = sc.nextLine();  

To get the words of a line, I would recommend to use:

String[] words = line.split(" ");

Create a file if it doesn't exist

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in (over)write mode
    [it overwrites the file if it already exists]
r+  open an existing file in read+write mode
a+  create file if it doesn't exist and open it in append mode
'''

example:

file_name = 'my_file.txt'
f = open(file_name, 'a+')  # open file in append mode
f.write('python rules')
f.close()

I hope this helps. [FYI am using python version 3.6.2]

How to center a subview of UIView

You can use

yourView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds))

And In Swift 3.0

yourView.center = CGPoint(x: superview.bounds.midX, y: superview.bounds.midY)

expected assignment or function call: no-unused-expressions ReactJS

import React from 'react';

class Counter extends React.Component{
    state = {
        count: 0,
    };

    formatCount() {
        const {count} = this.state;
        // use a return statement here, it is a importent,
        return count === 0 ? 'Zero' : count;
    }
    render() {
        return(
          <React.Fragment>
              <span>{this.formatCount()}</span>
              <button type="button" className="btn btn-primary">Increment</button>
          </React.Fragment>
        );
    }
}

export default Counter;

Java : Accessing a class within a package, which is the better way?

As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang package is automatically imported, as is everything in the current package.

The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.

By the way, if you are using lots of static methods (from Math, for example), you could also write

import static java.lang.Math.*;

and then use

sqrt(x)

directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)

Could not locate Gemfile

I had the same problem and got it solved by using a different directory.

bash-4.2$ bundle install
Could not locate Gemfile
bash-4.2$ pwd
/home/amit/redmine/redmine-2.2.2-0/apps/redmine
bash-4.2$ cd htdocs/
bash-4.2$ ls
app  config db   extra  Gemfile   lib  plugins  Rakefile     script  tmp
bin  config.ru  doc  files  Gemfile.lock  log  public   README.rdoc  test    vendor
bash-4.2$ cd plugins/
bash-4.2$ bundle install
Using rake (0.9.2.2) 
Using i18n (0.6.0) 
Using multi_json (1.3.6) 
Using activesupport (3.2.11) 
Using builder (3.0.0) 
Using activemodel (3.2.11) 
Using erubis (2.7.0) 
Using journey (1.0.4) 
Using rack (1.4.1) 
Using rack-cache (1.2) 
Using rack-test (0.6.1) 
Using hike (1.2.1) 
Using tilt (1.3.3) 
Using sprockets (2.2.1) 
Using actionpack (3.2.11) 
Using mime-types (1.19) 
Using polyglot (0.3.3) 
Using treetop (1.4.10) 
Using mail (2.4.4) 
Using actionmailer (3.2.11) 
Using arel (3.0.2) 
Using tzinfo (0.3.33) 
Using activerecord (3.2.11) 
Using activeresource (3.2.11) 
Using coderay (1.0.6) 
Using rack-ssl (1.3.2) 
Using json (1.7.5) 
Using rdoc (3.12) 
Using thor (0.15.4) 
Using railties (3.2.11) 
Using jquery-rails (2.0.3) 
Using mysql2 (0.3.11) 
Using net-ldap (0.3.1) 
Using ruby-openid (2.1.8) 
Using rack-openid (1.3.1) 
Using bundler (1.2.3) 
Using rails (3.2.11) 
Using rmagick (2.13.1) 
Your bundle i

Accidentally committed .idea directory files into git

Add .idea directory to the list of ignored files

First, add it to .gitignore, so it is not accidentally committed by you (or someone else) again:

.idea

Remove it from repository

Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:

Remove a file from a Git repository without deleting it from the local filesystem

Send the change to others

Third, commit the .gitignore file and the removal of .idea from the repository. After that push it to the remote(s).

Summary

The full process would look like this:

$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push

(optionally you can replace last line with git push some_remote, where some_remote is the name of the remote you want to push to)

In Powershell what is the idiomatic way of converting a string to an int?

I'd probably do something like that :

[int]::Parse("35")

But I'm not really a Powershell guy. It uses the static Parse method from System.Int32. It should throw an exception if the string can't be parsed.

How to get the hostname of the docker host from inside a docker container on that host without env vars

I'm adding this because it's not mentioned in any of the other answers. You can give a container a specific hostname at runtime with the -h directive.

docker run -h=my.docker.container.example.com ubuntu:latest

You can use backticks (or whatever equivalent your shell uses) to get the output of hosthame into the -h argument.

docker run -h=`hostname` ubuntu:latest

There is a caveat, the value of hostname will be taken from the host you run the command from, so if you want the hostname of a virtual machine that's running your docker container then using hostname as an argument may not be correct if you are using the host machine to execute docker commands on the virtual machine.

Install GD library and freetype on Linux

For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd

Get child node index

Could you do something like this:

var index = Array.prototype.slice.call(element.parentElement.children).indexOf(element);

https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement

What is the fastest factorial function in JavaScript?

Here is one solution:

function factorial(number) {
  total = 1
  while (number > 0) {
    total *= number
    number = number - 1
  }
  return total
}

tsc is not recognized as internal or external command

tsc is not recognized as internal or external command

As mentioned in another answer this is because tsc is not present in path.

1. Install as global package

To make TypeScript compiler available to all directories for this user, run the below command:

npm install -g typescript

You will see something similar to

C:\Users\username\AppData\Roaming\npm\tsserver -> C:\Users\username\AppData\Roaming\npm\node_modules\typescript\bin\tsserver C:\Users\username\AppData\Roaming\npm\tsc -> C:\Users\username\AppData\Roaming\npm\node_modules\typescript\bin\tsc + [email protected] added 1 package from 1 contributor in 4.769s

2. Set the environment variable

  • Add the npm installation folder to your "user variables" AND "environment variables".

  • In windows you can add environment variable PATH with value

    C:\Users\username\AppData\Roaming\npm\

i.e. wherever the npm installation folder is present.

Note: If multiple Paths are present separate them with a ;(semicolon)

If the below command gives the version then you have successfully installed

tsc --version

C# : Passing a Generic Object

In your generic method, T is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var member.

The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest):

public void PrintGeneric<T>(T test) where T : ITest

Then, the members of that interface would be directly available inside the method. However, your ITest is currently empty, you need to declare common stuff there in order to enable its usage within the method.

AngularJS Uploading An Image With ng-upload

You can try ng-file-upload angularjs plugin (instead of ng-upload).

It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.

html

<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script> 
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script> 

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', //upload.php script, node.js route, or servlet url
        data: {myObj: $scope.myModelObj},
        file: file,
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).then(function(response) {
        var data = response.data;
        // file is uploaded successfully
        console.log(data);
      });
    }
  };
}];

Creating a timer in python

import time 

...

def stopwatch(mins):
   # complete this whole code in some mins.
   time.sleep(60*mins)

...

SMTP error 554

SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.

We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

How to specify "does not contain" in dplyr filter

Note that %in% returns a logical vector of TRUE and FALSE. To negate it, you can use ! in front of the logical statement:

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
 !where_case_travelled_1 %in% 
   c('Outside Canada','Outside province/territory of residence but within Canada'))

Regarding your original approach with -c(...), - is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -.

How to use Java property files?

1) It is good to have your property file in classpath but you can place it anywhere in project.

Below is how you load property file from classpath and read all properties.

Properties prop = new Properties();
InputStream input = null;

try {

    String filename = "path to property file";
    input = getClass().getClassLoader().getResourceAsStream(filename);
    if (input == null) {
        System.out.println("Sorry, unable to find " + filename);
        return;
    }

    prop.load(input);

    Enumeration<?> e = prop.propertyNames();
    while (e.hasMoreElements()) {
        String key = (String) e.nextElement();
        String value = prop.getProperty(key);
        System.out.println("Key : " + key + ", Value : " + value);
    }

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2) Property files have the extension as .properties

Rails: Using greater than/less than with a where statement

I often have this problem with date fields (where comparison operators are very common).

To elaborate further on Mihai's answer, which I believe is a solid approach.

To the models you can add scopes like this:

scope :updated_at_less_than, -> (date_param) { 
  where(arel_table[:updated_at].lt(date_param)) }

... and then in your controller, or wherever you are using your model:

result = MyModel.updated_at_less_than('01/01/2017')

... a more complex example with joins looks like this:

result = MyParentModel.joins(:my_model).
  merge(MyModel.updated_at_less_than('01/01/2017'))

A huge advantage of this approach is (a) it lets you compose your queries from different scopes and (b) avoids alias collisions when you join to the same table twice since arel_table will handle that part of the query generation.

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

initializing a boolean array in java

public static Boolean freq[] = new Boolean[Global.iParameter[2]];

Global.iParameter[2]:

It should be const value

Hashing with SHA1 Algorithm in C#

public string Hash(byte [] temp)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        var hash = sha1.ComputeHash(temp);
        return Convert.ToBase64String(hash);
    }
}

EDIT:

You could also specify the encoding when converting the byte array to string as follows:

return System.Text.Encoding.UTF8.GetString(hash);

or

return System.Text.Encoding.Unicode.GetString(hash);

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Personally, I add the following line to my app/build.gradle:

implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"

With this syntax, version is dynamical.

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

Make sure you have created angular App using below command, then running ng serve in created Project folder.

ng new Project_Name

Why I can't change directories using "cd"?

You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.

You can run the script in your current process with the "dot" command:

. proj

But I'd prefer Greg's suggestion to use an alias in this simple case.

Insert array into MySQL database with PHP

most easiest way

for ($i=0; $i < count($tableData); $i++) { 

        $cost     =$tableData[$i]['cost'];
        $quantity =$tableData[$i]['quantity'];
        $price    =$tableData[$i]['price'];
        $p_id     =$tableData[$i]['p_id'];

        mysqli_query($conn,"INSERT INTO bill_details (bill_id, price, bill_date, p_id, quantity, cost) VALUES ($bill_id[bill_id],$price,$date,$p_id,$quantity,$cost)");
    }

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.name will stay there until the window is closed.

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider.

window.name has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that window.name can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

How do I insert datetime value into a SQLite database?

The format you need is:

'2007-01-01 10:00:00'

i.e. yyyy-MM-dd HH:mm:ss

If possible, however, use a parameterised query as this frees you from worrying about the formatting details.

How to get file size in Java

Try this:

long length = f.length();

Excel VBA Run-time error '13' Type mismatch

I had the same problem as you mentioned here above and my code was doing great all day yesterday.

I kept on programming this morning and when I opened my application (my file with an Auto_Open sub), I got the Run-time error '13' Type mismatch, I went on the web to find answers, I tried a lot of things, modifications and at one point I remembered that I read somewhere about "Ghost" data that stays in a cell even if we don't see it.

My code do only data transfer from one file I opened previously to another and Sum it. My code stopped at the third SheetTab (So it went right for the 2 previous SheetTab where the same code went without stopping) with the Type mismatch message. And it does that every time at the same SheetTab when I restart my code.

So I selected the cell where it stopped, manually entered 0,00 (Because the Type mismatch comes from a Summation variables declared in a DIM as Double) and copied that cell in all the subsequent cells where the same problem occurred. It solved the problem. Never had the message again. Nothing to do with my code but the "Ghost" or data from the past. It is like when you want to use the Control+End and Excel takes you where you had data once and deleted it. Had to "Save" and close the file when you wanted to use the Control+End to make sure Excel pointed you to the right cell.

What is the point of "final class" in Java?

Let's say you have an Employee class that has a method greet. When the greet method is called it simply prints Hello everyone!. So that is the expected behavior of greet method

public class Employee {

    void greet() {
        System.out.println("Hello everyone!");
    }
}

Now, let GrumpyEmployee subclass Employee and override greet method as shown below.

public class GrumpyEmployee extends Employee {

    @Override
    void greet() {
        System.out.println("Get lost!");
    }
}

Now in the below code have a look at the sayHello method. It takes Employee instance as a parameter and calls the greet method hoping that it would say Hello everyone! But what we get is Get lost!. This change in behavior is because of Employee grumpyEmployee = new GrumpyEmployee();

public class TestFinal {
    static Employee grumpyEmployee = new GrumpyEmployee();

    public static void main(String[] args) {
        TestFinal testFinal = new TestFinal();
        testFinal.sayHello(grumpyEmployee);
    }

    private void sayHello(Employee employee) {
        employee.greet(); //Here you would expect a warm greeting, but what you get is "Get lost!"
    }
}

This situation can be avoided if the Employee class was made final. Just imagine the amount of chaos a cheeky programmer could cause if String Class was not declared as final.

index.php not loading by default

Apache needs to be configured to recognize index.php as an index file.

The simplest way to accomplish this..

  1. Create a .htaccess file in your web root.

  2. Add the line...

DirectoryIndex index.php

Here is a resource regarding the matter...
http://www.twsc.biz/twsc_hosting_htaccess.php

Edit: I'm assuming apache is configured to allow .htaccess files. If it isn't, you'll have to modify the setting in apache's configuration file (httpd.conf)

Where is my m2 folder on Mac OS X Mavericks

If you search directly it won't appear so please follow as below steps to see .M2 repository path.

Go-> Find folder ->  type this "~/.m2" and click go

If Maven is already installed and used, the .m2 will be listed.

Source

How do I do a simple 'Find and Replace" in MsSQL?

The following will find and replace a string in every database (excluding system databases) on every table on the instance you are connected to:

Simply change 'Search String' to whatever you seek and 'Replace String' with whatever you want to replace it with.

--Getting all the databases and making a cursor
DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

DECLARE @databaseName nvarchar(1000)
--opening the cursor to move over the databases in this instance
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @databaseName   

WHILE @@FETCH_STATUS = 0   
BEGIN
    PRINT @databaseName
    --Setting up temp table for the results of our search
    DECLARE @Results TABLE(TableName nvarchar(370), RealColumnName nvarchar(370), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @SearchStr nvarchar(100), @ReplaceStr nvarchar(100), @SearchStr2 nvarchar(110)
    SET @SearchStr = 'Search String'
    SET @ReplaceStr = 'Replace String'
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128)
    SET  @TableName = ''

    --Looping over all the tables in the database
    WHILE @TableName IS NOT NULL
    BEGIN
        DECLARE @SQL nvarchar(2000)
        SET @ColumnName = ''
        DECLARE @result NVARCHAR(256)
        SET @SQL = 'USE ' + @databaseName + '
            SELECT @result = MIN(QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME))
            FROM    [' + @databaseName + '].INFORMATION_SCHEMA.TABLES
            WHERE       TABLE_TYPE = ''BASE TABLE'' AND TABLE_CATALOG = ''' + @databaseName + '''
                AND QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) > ''' + @TableName + '''
                AND OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME)
                                ), ''IsMSShipped''
                                ) = 0'
        EXEC master..sp_executesql @SQL, N'@result nvarchar(256) out', @result out

        SET @TableName = @result
        PRINT @TableName

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            DECLARE @ColumnResult NVARCHAR(256)
            SET @SQL = '
                SELECT @ColumnResult = MIN(QUOTENAME(COLUMN_NAME))
                FROM    [' + @databaseName + '].INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 2)
                    AND TABLE_NAME  = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 1)
                    AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')
                    AND TABLE_CATALOG = ''' + @databaseName + '''
                    AND QUOTENAME(COLUMN_NAME) > ''' + @ColumnName + ''''
            PRINT @SQL
            EXEC master..sp_executesql @SQL, N'@ColumnResult nvarchar(256) out', @ColumnResult out
            SET @ColumnName = @ColumnResult 

            PRINT @ColumnName

            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO @Results
                EXEC
                (
                    'USE ' + @databaseName + '
                    SELECT ''' + @TableName + ''',''' + @ColumnName + ''',''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END
    END

    --Declaring another temporary table
    DECLARE @time_to_update TABLE(TableName nvarchar(370), RealColumnName nvarchar(370))

    INSERT INTO @time_to_update
    SELECT TableName, RealColumnName FROM @Results GROUP BY TableName, RealColumnName

    DECLARE @MyCursor CURSOR;
    BEGIN
        DECLARE @t nvarchar(370)
        DECLARE @c nvarchar(370)
        --Looping over the search results   
        SET @MyCursor = CURSOR FOR
        SELECT TableName, RealColumnName FROM @time_to_update GROUP BY TableName, RealColumnName

        --Getting my variables from the first item
        OPEN @MyCursor 
        FETCH NEXT FROM @MyCursor 
        INTO @t, @c

        WHILE @@FETCH_STATUS = 0
        BEGIN
            -- Updating the old values with the new value
            DECLARE @sqlCommand varchar(1000)
            SET @sqlCommand = '
                USE ' + @databaseName + '
                UPDATE [' + @databaseName + '].' + @t + ' SET ' + @c + ' = REPLACE(' + @c + ', ''' + @SearchStr + ''', ''' + @ReplaceStr + ''') 
                WHERE ' + @c + ' LIKE ''' + @SearchStr2 + ''''
            PRINT @sqlCommand
            BEGIN TRY
                EXEC (@sqlCommand)
            END TRY
            BEGIN CATCH
                PRINT ERROR_MESSAGE()
            END CATCH

            --Getting next row values
            FETCH NEXT FROM @MyCursor 
            INTO @t, @c 
        END;

        CLOSE @MyCursor ;
        DEALLOCATE @MyCursor;
    END;

    DELETE FROM @time_to_update
    DELETE FROM @Results

    FETCH NEXT FROM db_cursor INTO @databaseName
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

Note: this isn't ideal, nor is it optimized

Align text to the bottom of a div

You now can do this with Flexbox justify-content: flex-end now:

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
  align-items: flex-end;_x000D_
  width: 150px;_x000D_
  height: 150px;_x000D_
  border: solid 1px red;_x000D_
}_x000D_
  
_x000D_
<div>_x000D_
  Something to align_x000D_
</div>
_x000D_
_x000D_
_x000D_

Consult your Caniuse to see if Flexbox is right for you.

Mocking Logger and LoggerFactory with PowerMock and Mockito

In answer to your first question, it should be as simple as replacing:

   when(LoggerFactory.getLogger(GoodbyeController.class)).thenReturn(loggerMock);

with

   when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);

Regarding your second question (and possibly the puzzling behavior with the first), I think the problem is that logger is static. So,

private static Logger logger = LoggerFactory.getLogger(GoodbyeController.class);

is executed when the class is initialized, not the when the object is instantiated. Sometimes this can be at about the same time, so you'll be OK, but it's hard to guarantee that. So you set up LoggerFactory.getLogger to return your mock, but the logger variable may have already been set with a real Logger object by the time your mocks are set up.

You may be able to set the logger explicitly using something like ReflectionTestUtils (I don't know if that works with static fields) or change it from a static field to an instance field. Either way, you don't need to mock LoggerFactory.getLogger because you'll be directly injecting the mock Logger instance.

In Python, how do I convert all of the items in a list to floats?

This is how I would do it.

my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', 
    '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', 
    '0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>

Docker command can't connect to Docker daemon

Had the same issue and what worked for me was:
Checking the ownership of /var/run/docker.sock

ls -l /var/run/docker.sock

If you're not the owner then change ownership with the command

sudo chown *your-username* /var/run/docker.sock

Then you can go ahead and try executing the docker commands hassle-free :D

Add a fragment to the URL without causing a redirect?

Try this

var URL = "scratch.mit.edu/projects";
var mainURL = window.location.pathname;

if (mainURL == URL) {
    mainURL += ( mainURL.match( /[\?]/g ) ? '&' : '#' ) + '_bypasssharerestrictions_';
    console.log(mainURL)
}

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

Adding the right repository in Project build.gradle solved the issue. In my case Google Maven Repository was needed and was added as below in the build.gradle

repositories {
google()
}

refer to this link for declaring repositories: https://docs.gradle.org/current/userguide/declaring_repositories.html

Fastest way to check a string contain another substring in JavaScript?

It's easy way to use .match() method to string.

var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));

Wish you a nice day, sir!

How to trim a string after a specific character in java

you can use StringTokenizer:

StringTokenizer st = new StringTokenizer("34.1 -118.33\n<!--ABCDEFG-->", "\n");
System.out.println(st.nextToken());

output:

34.1 -118.33

CS0234: Mvc does not exist in the System.Web namespace

Check your runtime tag inside the web.config, and verify you have something like this declared:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
.....
</runtime>

PHP: HTML: send HTML select option attribute in POST

just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:

<form name='add'>
Age: <select name='age'>
     <option value='1_sre'>23</option>
     <option value='2_sam>24</option>
     <option value='5_john>25</option>
     </select>
<input type='submit' name='submit'/>
</form>

Draggable div without jQuery UI

No Jquery Solution - Basic

The most basic draggable code would be :

Element.prototype.drag = function(){

   var mousemove = function(e){ // document mousemove

       this.style.left = ( e.clientX - this.dragStartX ) + 'px';
       this.style.top  = ( e.clientY - this.dragStartY ) + 'px';

   }.bind(this);

   var mouseup = function(e){ // document mouseup

       document.removeEventListener('mousemove',mousemove);
       document.removeEventListener('mouseup',mouseup);

   }.bind(this);

   this.addEventListener('mousedown',function(e){ // element mousedown

       this.dragStartX = e.offsetX;
       this.dragStartY = e.offsetY;

       document.addEventListener('mousemove',mousemove);
       document.addEventListener('mouseup',mouseup);

   }.bind(this));

   this.style.position = 'absolute' // fixed might work as well

}

and then usage (non-jquery) :

document.querySelector('.target').drag();

or in jquery :

$('.target')[0].drag();

Notice : the dragged element should have a position:absolute or position:fixed applied to it for the left,top movement to work...

the codepen below has some more "advanced" features : dragStart, dragStop callbacks, css classes appending to remove text selection of other elements while dragging, and a drop feature also...

checkout the following codepen :

http://codepen.io/anon/pen/VPPaEK

its basically setting a 'mousedown' event on the element which needs to be dragged, and then binding and unbinding the document mousemove to handle the movement.

Draggable Handle

in order to set a draggable handle for the element

Element.prototype.drag = function( setup ){

   var setup = setup || {};

   var mousemove = function(e){ // document mousemove

       this.style.left = ( e.clientX - this.dragStartX ) + 'px';
       this.style.top  = ( e.clientY - this.dragStartY ) + 'px';

   }.bind(this);

   var mouseup = function(e){ // document mouseup

       document.removeEventListener('mousemove',mousemove);
       document.removeEventListener('mouseup',mouseup);

   }.bind(this);

   var handle = setup.handle || this;

   handle.addEventListener('mousedown',function(e){ // element mousedown

       this.dragStartX = e.offsetX;
       this.dragStartY = e.offsetY;

       document.addEventListener('mousemove',mousemove);
       document.addEventListener('mouseup',mouseup);

       handle.classList.add('dragging');

   }.bind(this)); 

   handle.classList.add('draggable');

   this.style.position = 'absolute' // fixed might work as well

}

The above code is used like so :

var setup = {
   handle : document.querySelector('.handle')
};

document.querySelector('.box').drag(setup);

Adding CSS to eliminate selectable text

The problem now, is that when dragging, the text within the draggable element is annoyingly being selected with no use...

This is why we have added the draggable and dragging classes to the element. which will cancel out this unwanted behavior, and also add a move cursor, to display that this element is draggable

.draggable{
    cursor: move;
    position: fixed;
}

.draggable.dragging{
    user-select: none;
}

Adding Events

So now that we have our draggable element, we sometimes need to call various events.

setup.ondraginit  // this is called when setting up the draggable
setup.ondragstart // this is called when mouse is down on the element
setup.ondragend   // this is called when mouse is released (after dragging)
setup.ondrag      // this is called while the element is being dragged

Each will pass the original mouse event to the specific handler

Finally, this is what we get...

Element.prototype.drag = function( setup ){

    var setup = setup || {};

    var mousemove = function(e){ // document mousemove

        this.style.left = ( e.clientX - this.dragStartX ) + 'px';
        this.style.top  = ( e.clientY - this.dragStartY ) + 'px';

        setup.ondrag && setup.ondrag(e); // ondrag event

    }.bind(this);

    var mouseup = function(e){ // document mouseup

        document.removeEventListener('mousemove',mousemove);
        document.removeEventListener('mouseup',mouseup);

        handle.classList.remove('dragging');

        setup.ondragend && setup.ondragend(e); // ondragend event

    }.bind(this);

    var handle = setup.handle || this;

    handle.addEventListener('mousedown',function(e){ // element mousedown

        this.dragStartX = e.offsetX;
        this.dragStartY = e.offsetY;

        document.addEventListener('mousemove',mousemove);
        document.addEventListener('mouseup',mouseup);

        handle.classList.add('dragging');

        setup.ondragstart && setup.ondragstart(e); // ondragstart event

    }.bind(this)); 

    handle.classList.add('draggable');

    setup.ondraginit && setup.ondraginit(e); // ondraginit event

}

And to use this :

var setup = {
   handle      : document.querySelector('.handle'),
   ondragstart : e => { console.log('drag has started!'); },
   ondrag      : e => { console.log('drag!'); },
   ondragend   : e => { console.log('drag has ended!'); }
};

document.querySelector('.box').drag(setup);

note that e.target is a reference back to our draggable element

Java logical operator short-circuiting

boolean a = (x < z) && (x == x);

This kind will short-circuit, meaning if (x < z) evaluates to false then the latter is not evaluated, a will be false, otherwise && will also evaluate (x == x).

& is a bitwise operator, but also a boolean AND operator which does not short-circuit.

You can test them by something as follows (see how many times the method is called in each case):

public static boolean getFalse() {
    System.out.println("Method");
    return false;
}

public static void main(String[] args) {
    if(getFalse() && getFalse()) { }        
    System.out.println("=============================");        
    if(getFalse() & getFalse()) { }
}

C++ int float casting

When doing integer division, the result will always be a integer unless one or more of the operands are a float. Just type cast one/both of the operands to a float and the compiler will do the conversion. Type casting is used when you want the arithmetic to perform as it should so the result will be the correct data type.

float m = static_cast<float>(a.y - b.y) / (a.x - b.x);

Swift apply .uppercaseString to only the first letter of a string

From Swift 3 you can easily use textField.autocapitalizationType = UITextAutocapitalizationType.sentences

How can I set an SQL Server connection string?

They are a number of things to worry about when connecting to SQL Server on another machine.

  • Host/IP address of the machine
  • Initial catalog (database name)
  • Valid username/password

Very often SQL Server may be running as a default instance which means you can simply specify the hostname/IP address, but you may encounter a scenario where it is running as a named instance (SQL Server Express Edition for instance). In this scenario you'll have to specify the hostname/instance name.

Random alpha-numeric string in JavaScript?

When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid.toUpperCase();
}

Fiddle: http://jsfiddle.net/nlviands/fNPvf/11227/

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

What is cardinality in Databases?

Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set

How to append something to an array?

Append Single Element

//Append to the end
arrName.push('newName1');

//Prepend to the start
arrName.unshift('newName1');

//Insert at index 1
arrName.splice(1, 0,'newName1');
//1: index number, 0: number of element to remove, newName1: new element


// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';

Append Multiple Elements

//Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
//1: index number from where insert starts, 
//0: number of element to remove, 
//newElemenet1,2,3: new elements

Append array

//join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Make WPF Application Fullscreen (Cover startmenu)

<Window x:Class="HTA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    mc:Ignorable="d" 
    ResizeMode="NoResize"
    WindowStartupLocation="CenterScreen" 
    Width="1024" Height="768"
    WindowState="Maximized" WindowStyle="None">

Window state to Maximized and window style to None

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Python csv string to array

Simple - the csv module works with lists, too:

>>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]

Localhost not working in chrome and firefox

I faced the same issue and the complete solution is to set to false(uncheck) the "Automatically detect settings" checkbox from Lan Area Network( the same window as for Bypass proxy server for local address )

Best Timer for using in a Windows service

Don't use a service for this. Create a normal application and create a scheduled task to run it.

This is the commonly held best practice. Jon Galloway agrees with me. Or maybe its the other way around. Either way, the fact is that it is not best practices to create a windows service to perform an intermittent task run off a timer.

"If you're writing a Windows Service that runs a timer, you should re-evaluate your solution."

–Jon Galloway, ASP.NET MVC community program manager, author, part time superhero

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Modulo operator in Python

In addition to the other answers, the fmod documentation has some interesting things to say on the subject:

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

Should a RESTful 'PUT' operation return something

As opposed to most of the answers here, I actually think that PUT should return the updated resource (in addition to the HTTP code of course).

The reason why you would want to return the resource as a response for PUT operation is because when you send a resource representation to the server, the server can also apply some processing to this resource, so the client would like to know how does this resource look like after the request completed successfully. (otherwise it will have to issue another GET request).

Request format is unrecognized for URL unexpectedly ending in

For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
   at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
   at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
   at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
   at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)

In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:

  <system.webServer>
    <handlers>
      <remove name="ScriptHandlerFactory" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>

Why it worked without these lines on one web server and not the other I don't know.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.

add modify this line in

m2.conf

set maven.home C:\Users\me\.m2

How to test an Internet connection with bash?

The top voted answer does not work for MacOS so for those on a mac, I've successfully tested this:

GATEWAY=`route -n get default | grep gateway`
if [ -z "$GATEWAY" ]
  then
    echo error
else
  ping -q -t 1 -c 1 `echo $GATEWAY | cut -d ':' -f 2` > /dev/null && echo ok || echo error
fi

tested on MacOS High Sierra 10.12.6

Gather multiple sets of columns

This could be done using reshape. It is possible with dplyr though.

  colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))
  colnames(df)[2] <- "Date"
  res <- reshape(df, idvar=c("id", "Date"), varying=3:8, direction="long", sep="_")
  row.names(res) <- 1:nrow(res)
  
   head(res)
  #  id       Date time       Q3.2       Q3.3
  #1  1 2009-01-01    1  1.3709584  0.4554501
  #2  2 2009-01-02    1 -0.5646982  0.7048373
  #3  3 2009-01-03    1  0.3631284  1.0351035
  #4  4 2009-01-04    1  0.6328626 -0.6089264
  #5  5 2009-01-05    1  0.4042683  0.5049551
  #6  6 2009-01-06    1 -0.1061245 -1.7170087

Or using dplyr

  library(tidyr)
  library(dplyr)
  colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))

  df %>%
     gather(loop_number, "Q3", starts_with("Q3")) %>% 
     separate(loop_number,c("L1", "L2"), sep="_") %>% 
     spread(L1, Q3) %>%
     select(-L2) %>%
     head()
  #  id       time       Q3.2       Q3.3
  #1  1 2009-01-01  1.3709584  0.4554501
  #2  1 2009-01-01  1.3048697  0.2059986
  #3  1 2009-01-01 -0.3066386  0.3219253
  #4  2 2009-01-02 -0.5646982  0.7048373
  #5  2 2009-01-02  2.2866454 -0.3610573
  #6  2 2009-01-02 -1.7813084 -0.7838389

Update

With new version of tidyr, we can use pivot_longer to reshape multiple columns. (Using the changed column names from gsub above)

library(dplyr)
library(tidyr)
df %>% 
    pivot_longer(cols = starts_with("Q3"), 
          names_to = c(".value", "Q3"), names_sep = "_") %>% 
    select(-Q3)
# A tibble: 30 x 4
#      id time         Q3.2    Q3.3
#   <int> <date>      <dbl>   <dbl>
# 1     1 2009-01-01  0.974  1.47  
# 2     1 2009-01-01 -0.849 -0.513 
# 3     1 2009-01-01  0.894  0.0442
# 4     2 2009-01-02  2.04  -0.553 
# 5     2 2009-01-02  0.694  0.0972
# 6     2 2009-01-02 -1.11   1.85  
# 7     3 2009-01-03  0.413  0.733 
# 8     3 2009-01-03 -0.896 -0.271 
#9     3 2009-01-03  0.509 -0.0512
#10     4 2009-01-04  1.81   0.668 
# … with 20 more rows

NOTE: Values are different because there was no set seed in creating the input dataset

How to make Twitter Bootstrap tooltips have multiple lines?

If you are using Angular UI Bootstrap, you can use tooltip with html syntax: tooltip-html-unsafe

e.g. update to angular 1.2.10 & angular-ui-bootstrap 0.11: http://jsfiddle.net/aX2vR/1/

old one: http://jsfiddle.net/8LMwz/1/

How to delete Certain Characters in a excel 2010 cell

Replace [ with nothing, then ] with nothing.

How can I list all foreign keys referencing a given table in SQL Server?

Some good answers above. But I prefer to have the answer with one query. This piece of code is taken from sys.sp_helpconstraint (sys proc)

That's the way Microsoft looks up if there are foreign keys associated to the tbl.

--setup variables. Just change 'Customer' to tbl you want
declare @objid int,
    @objname nvarchar(776)
select @objname = 'Customer'    
select @objid = object_id(@objname)

if exists (select * from sys.foreign_keys where referenced_object_id = @objid)
    select 'Table is referenced by foreign key' =
        db_name() + '.'
        + rtrim(schema_name(ObjectProperty(parent_object_id,'schemaid')))
        + '.' + object_name(parent_object_id)
        + ': ' + object_name(object_id)
    from sys.foreign_keys 
    where referenced_object_id = @objid 
    order by 1

The answer will look like this: test_db_name.dbo.Account: FK_Account_Customer

Node.js spawn child process and get terminal output live

child:

setInterval(function() {
    process.stdout.write("hi");
}, 1000); // or however else you want to run a timer

parent:

require('child_process').fork('./childfile.js');
// fork'd children use the parent's stdio

Disable cross domain web security in Firefox

I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.

The steps are:

  1. Open fiddler.

  2. If on https go to menu Tools -> Options -> Https and tick the Capture & Decrypt https options

  3. Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:

     static function OnBeforeResponse(oSession: Session) {
        //....
        oSession.oResponse.headers.Remove("Access-Control-Allow-Origin");
        oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
        //...
     }
    

    This will make every web response to have the Access-Control-Allow-Origin: * header.

  4. This still won't work as the OPTIONS preflight will pass through and cause the request to block before our above rule gets the chance to modify the headers. So to fix this, in the fiddler main window, on the right hand side there's an AutoResponder tab. Add a new rule and response: METHOD:OPTIONS https://yoursite.com/ with auto response: *CORSPreflightAllow and tick the boxes: "Enable Rules" and "Unmatched requests passthrough".

See picture below for reference:

enter image description here

Embedding SVG into ReactJS

You can import svg and it use it like a image

import chatSVG from '../assets/images/undraw_typing_jie3.svg'

And ise it in img tag

<img src={chatSVG} className='iconChat' alt="Icon chat"/>

How to avoid scientific notation for large numbers in JavaScript?

I know this is an older question, but shows recently active. MDN toLocaleString

const myNumb = 1000000000000000000000;
console.log( myNumb ); // 1e+21
console.log( myNumb.toLocaleString() ); // "1,000,000,000,000,000,000,000"
console.log( myNumb.toLocaleString('fullwide', {useGrouping:false}) ); // "1000000000000000000000"

you can use options to format the output.

Note:

Number.toLocaleString() rounds after 16 decimal places, so that...

const myNumb = 586084736227728377283728272309128120398;
console.log( myNumb.toLocaleString('fullwide', { useGrouping: false }) );

...returns...

586084736227728400000000000000000000000

This is perhaps undesirable if accuracy is important in the intended result.

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

How to Create a real one-to-one relationship in SQL Server

What about this ?

create table dbo.[Address]
(
Id int identity not null,
City nvarchar(255) not null,
Street nvarchar(255) not null,
CONSTRAINT PK_Address PRIMARY KEY (Id)
)

create table dbo.[Person]
(
Id int identity not null,
AddressId int not null,
FirstName nvarchar(255) not null,
LastName nvarchar(255) not null,
CONSTRAINT PK_Person PRIMARY KEY (Id),
CONSTRAINT FK_Person_Address FOREIGN KEY (AddressId) REFERENCES dbo.[Address] (Id)
)

Extract digits from string - StringUtils Java

Just one line:

int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));

How to get all options of a select using jQuery?

    var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +'  value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
            });
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);

Mythical man month 10 lines per developer day - how close on large projects?

One suspects this perennial bit of manager-candy was coined when everything was a sys app written in C because if nothing else the magic number would vary by orders of magnitude depending on the language, scale and nature of the application. And then you have to discount comments and attributes. And ultimately who cares about the number of lines of code written? Are you supposed to be finished when you've reach 10K lines? 100K? So arbitrary.

It's useless.

How to extract hours and minutes from a datetime.datetime object?

Don't know how you want to format it, but you can do:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

select the TOP N rows from a table

select * from table_name LIMIT 100

remember this only works with MYSQL

Connecting to Microsoft SQL server using Python

In data source connections between a client and server there are two general types: ODBC which uses a DRIVER and OLEDB which uses a PROVIDER. And in the programming world, it is a regular debate as to which route to go in connecting to data sources.

You are using a provider, SQLOLEDB, but specifying it as a driver. As far as I know, neither the pyodbc nor pypyodbc modules support Window OLEDB connections. However, the adodbapi does which uses the Microsoft ADO as an underlying component.

Below are both approaches for your connection parameters. Also, I string format your variables as your concatenation did not properly break quotes within string. You'll notice I double the curly braces since it is needed in connection string and string.format() also uses it.

# PROVIDER
import adodbapi
conn = adodbapi.connect("PROVIDER=SQLOLEDB;Data Source={0};Database={1}; \
       trusted_connection=yes;UID={2};PWD={3};".format(ServerName,MSQLDatabase,username,password))
cursor = conn.cursor()

# DRIVER
import pyodbc
conn = pyodbc.connect("DRIVER={{SQL Server}};SERVER={0}; database={1}; \
       trusted_connection=yes;UID={2};PWD={3}".format(ServerName,MSQLDatabase,username,password))
cursor = conn.cursor()

How can I make all images of different height and width the same via CSS?

Updated answer (No IE11 support)

_x000D_
_x000D_
img {_x000D_
    float: left;_x000D_
    width:  100px;_x000D_
    height: 100px;_x000D_
    object-fit: cover;_x000D_
}
_x000D_
<img src="http://i.imgur.com/tI5jq2c.jpg">_x000D_
<img src="http://i.imgur.com/37w80TG.jpg">_x000D_
<img src="http://i.imgur.com/B1MCOtx.jpg">
_x000D_
_x000D_
_x000D_

Original answer

_x000D_
_x000D_
.img {_x000D_
    float: left;_x000D_
    width:  100px;_x000D_
    height: 100px;_x000D_
    background-size: cover;_x000D_
}
_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/tI5jq2c.jpg');"></div>_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/37w80TG.jpg');"></div>_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/B1MCOtx.jpg');"></div>
_x000D_
_x000D_
_x000D_

I would like to see a hash_map example in C++

#include <tr1/unordered_map> will get you next-standard C++ unique hash container. Usage:

std::tr1::unordered_map<std::string,int> my_map;
my_map["answer"] = 42;
printf( "The answer to life and everything is: %d\n", my_map["answer"] );

How to display tables on mobile using Bootstrap?

You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:

http://elvery.net/demo/responsive-tables/

I'm partial to 'No More Tables' but that obviously depends on your application.

CSS fixed width in a span

People span in this case cant be a block element because rest of the text in between li elements will go down. Also using float is very bad idea because you will need to set width for whole li element and this width will need to be the same as width of whole ul element or other container.

Try something like this in html:

<li><span></span><strong>The</strong> lazy dog.</li>
<li><span>AND</span> <strong>The</strong> lazy cat.</li>
<li><span>OR</span>  <strong>The</strong> active goldfish.</li>

and in the css

li {position:relative;padding-left:80px;} // 80px or something else
li span {position:absolute;top:0;left:0;}
li strong {color:red;} // red or else

so, when the li element is relative you format the span element to be as absolute and at the top:0;left:0; so it stays upper left and you set the padding-left (or: padding:0px 0px 0px 80px;) to set this free space for span element.

It should work better for simple cases.

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

We can add "AwaitTerminationSeconds" property for both taskExecutor and taskScheduler as below,

<property name="awaitTerminationSeconds" value="${taskExecutor .awaitTerminationSeconds}" />

<property name="awaitTerminationSeconds" value="${taskScheduler .awaitTerminationSeconds}" />

Documentation for "waitForTasksToCompleteOnShutdown" property says, when shutdown is called

"Spring's container shutdown continues while ongoing tasks are being completed. If you want this executor to block and wait for the termination of tasks before the rest of the container continues to shut down - e.g. in order to keep up other resources that your tasks may need -, set the "awaitTerminationSeconds" property instead of or in addition to this property."

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.html#setWaitForTasksToCompleteOnShutdown-boolean-

So it is always advised to use waitForTasksToCompleteOnShutdown and awaitTerminationSeconds properties together. Value of awaitTerminationSeconds depends on our application.

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

to

"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

IE11 does implement String.prototype.includes so why not using the official Polyfill?

  if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
      if (typeof start !== 'number') {
        start = 0;
      }

      if (start + search.length > this.length) {
        return false;
      } else {
        return this.indexOf(search, start) !== -1;
      }
    };
  }

Source: polyfill source

javascript unexpected identifier

I recommend using http://jsbeautifier.org/ - if you paste your code snippet into it and press beautify, the error is immediately visible.

Only variables should be passed by reference

PHP complains because end() expects a reference to something that it wants to change (which can be a variable only). You however pass the result of explode() directly to end() without saving it to a variable first. At the moment when explode() returns your value, it exists only in memory and no variable points to it. You cannot create a reference to something (or to something unknown in the memory), that does not exists.

Or in other words: PHP does not know, if the value you give him is the direct value or just a pointer to the value (a pointer is also a variable (integer), which stores the offset of the memory, where the actual value resides). So PHP expects here a pointer (reference) always.

But since this is still just a notice (not even deprecated) in PHP 7, you can savely ignore notices and use the ignore-operator instead of completely deactivating error reporting for notices:

$file_extension = @end(explode('.', $file_name));

Apply multiple functions to multiple groupby columns

As an alternative (mostly on aesthetics) to Ted Petrou's answer, I found I preferred a slightly more compact listing. Please don't consider accepting it, it's just a much-more-detailed comment on Ted's answer, plus code/data. Python/pandas is not my first/best, but I found this to read well:

df.groupby('group') \
  .apply(lambda x: pd.Series({
      'a_sum'       : x['a'].sum(),
      'a_max'       : x['a'].max(),
      'b_mean'      : x['b'].mean(),
      'c_d_prodsum' : (x['c'] * x['d']).sum()
  })
)

          a_sum     a_max    b_mean  c_d_prodsum
group                                           
0      0.530559  0.374540  0.553354     0.488525
1      1.433558  0.832443  0.460206     0.053313

I find it more reminiscent of dplyr pipes and data.table chained commands. Not to say they're better, just more familiar to me. (I certainly recognize the power and, for many, the preference of using more formalized def functions for these types of operations. This is just an alternative, not necessarily better.)


I generated data in the same manner as Ted, I'll add a seed for reproducibility.

import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df

          a         b         c         d  group
0  0.374540  0.950714  0.731994  0.598658      0
1  0.156019  0.155995  0.058084  0.866176      0
2  0.601115  0.708073  0.020584  0.969910      1
3  0.832443  0.212339  0.181825  0.183405      1

Change default timeout for mocha

In current versions of Mocha, the timeout can be changed globally like this:

mocha.timeout(5000);

Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.


In older versions, and only in a browser, you could change the global configuration using mocha.setup.

mocha.setup({ timeout: 5000 });

The documentation does not cover the global timeout setting, but offers a few examples on how to change the timeout in other common scenarios.

SQL: Insert all records from one table to another table without specific the columns

All the answers above, for some reason or another, did not work for me on SQL Server 2012. My situation was I accidently deleted all rows instead of just one row. After our DBA restored the table to dbo.foo_bak, I used the below to restore. NOTE: This only works if the backup table (represented by dbo.foo_bak) and the table that you are writing to (dbo.foo) have the exact same column names.

This is what worked for me using a hybrid of a bunch of different answers:

USE [database_name];
GO
SET IDENTITY_INSERT dbo.foo ON;
GO
INSERT INTO [dbo].[foo]
           ([rown0]
           ,[row1]
           ,[row2]
           ,[row3]
           ,...
           ,[rown])
     SELECT * FROM [dbo].[foo_bak];
GO
SET IDENTITY_INSERT dbo.foo OFF;
GO

This version of my answer is helpful if you have primary and foreign keys.

How do you debug PHP scripts?

I use Netbeans with XDebug and the Easy XDebug FireFox Add-on

The add-on is essential when you debug MVC projects, because the normal way XDebug runs in Netbeans is to register the dbug session via the url. With the add-on installed in FireFox, you would set your Netbeans project properties -> Run Configuratuion -> Advanced and select "Do Not Open Web Browser" You can now set your break points and start the debugging session with Ctrl-F5 as usual. Open FireFox and right-click the Add-on icon in the right bottom corner to start monitoring for breakpoints. When the code reaches the breakpoint it will stop and you can inspect your variable states and call-stack.

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

Some simpler example code for using globalAlpha:

ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore();

If you need img to be loaded:

var img = new Image();
img.onload = function() {
    ctx.save();
    ctx.globalAlpha = 0.4;
    ctx.drawImage(img, x, y);
    ctx.restore()
};
img.src = "http://...";

Notes:

  • Set the 'src' last, to guarantee that your onload handler is called on all platforms, even if the image is already in the cache.

  • Wrap changes to stuff like globalAlpha between a save and restore (in fact use them lots), to make sure you don't clobber settings from elsewhere, particularly when bits of drawing code are going to be called from events.

removeEventListener on anonymous functions in JavaScript

I just experienced similiar problem with copy-protection wordpress plugin. The code was:

function disableSelection(target){
 if (typeof target.onselectstart!="undefined") //For IE 
  target.onselectstart=function(){return false}
 else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
  target.style.MozUserSelect="none"
 else //All other route (For Opera)
  target.onmousedown=function(){return false}
target.style.cursor = "default"
}

And then it was initiated by loosely put

<script type="text/javascript">disableSelection(document.body)</script>.

I came around this simply by attaching other annonymous function to this event:

document.body.onselectstart = function() { return true; };

Wrap a text within only two lines inside div

Another simple and quick solution

.giveMeEllipsis {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: N; /* number of lines to show */
   line-height: X;        /* fallback */
   max-height: X*N;       /* fallback */
}

The reference to the original question and answer is here

jQuery .val change doesn't change input value

Use attr instead.
$('#link').attr('value', 'new value');

demo

Removing the password from a VBA project

This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you'd have to continue on using SendKeys to figure out a way to remove the password protection: http://www.pcreview.co.uk/forums/thread-989191.php

And here's one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you. http://www.ozgrid.com/forum/showthread.php?t=13006&page=2

I haven't tried either method, but this may save you some time if it's what you need to do...

Using CSS how to change only the 2nd column of a table

on this web http://quirksmode.org/css/css2/columns.html i found that easy way

<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..

How to fire a button click event from JavaScript in ASP.NET

You can just place this line in a JavaScript function:

__doPostBack('btnSubmit','OnClick');

Or do something like this:

$('#btnSubmit').trigger('click');

Run text file as commands in Bash

You can use something like this:

for i in `cat foo.txt`
do
    sudo $i
done

Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo as a command. But it gives you an idea on how to start.

How to remove a directory from git repository?

To remove folder/directory only from git repository and not from the local try 3 simple commands.


Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root folder (main project directory where the git is initialized) named .gitignore and put that folder name into it. You can ignore as many files/folders as you want

.gitignore file will look like this

/FolderName

remove directory

How to see the changes between two commits without commits in-between?

Asking for the difference /between/ two commits without including the commits in-between makes little sense. Commits are just snapshots of the contents of the repository; asking for the difference between two necessarily includes them. So the question then is, what are you really looking for?

As William suggested, cherry-picking can give you the delta of a single commit rebased on top of another. That is:

$ git checkout 012345
$ git cherry-pick -n abcdef
$ git diff --cached

This takes commit 'abcdef', compares it to its immediate ancestor, then applies that difference on top of '012345'. This new difference is then shown - the only change is the context comes from '012345' rather than 'abcdef's immediate ancestor. Of course, you may get conflicts and etc, so it's not a very useful process in most cases.

If you're just interested in abcdef itself, you can do:

$ git log -u -1 abcdef

This compares abcdef to its immediate ancestor, alone, and is usually what you want.

And of course

$ git diff 012345..abcdef

gives you all differences between those two commits.

It would help to get a better idea of what you're trying to achieve - as I mentioned, asking for the difference between two commits without what's in between doesn't actually make sense.

Download a file by jQuery.Ajax

Ok so here is the working code when Using MVC and you are getting your file from a controller

lets say you have your byte array declare and populate, the only thing you need to do is to use the File function (using System.Web.Mvc)

byte[] bytes = .... insert your bytes in the array
return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "nameoffile.exe");

and then, in the same controller, add thoses 2 functions

protected override void OnResultExecuting(ResultExecutingContext context)
    {
        CheckAndHandleFileResult(context);

        base.OnResultExecuting(context);
    }

    private const string FILE_DOWNLOAD_COOKIE_NAME = "fileDownload";

    /// <summary>
    /// If the current response is a FileResult (an MVC base class for files) then write a
    /// cookie to inform jquery.fileDownload that a successful file download has occured
    /// </summary>
    /// <param name="context"></param>
    private void CheckAndHandleFileResult(ResultExecutingContext context)
    {
        if (context.Result is FileResult)
            //jquery.fileDownload uses this cookie to determine that a file download has completed successfully
            Response.SetCookie(new HttpCookie(FILE_DOWNLOAD_COOKIE_NAME, "true") { Path = "/" });
        else
            //ensure that the cookie is removed in case someone did a file download without using jquery.fileDownload
            if (Request.Cookies[FILE_DOWNLOAD_COOKIE_NAME] != null)
                Response.Cookies[FILE_DOWNLOAD_COOKIE_NAME].Expires = DateTime.Now.AddYears(-1);
    }

and then you will be able to call your controller to download and get the "success" or "failure" callback

$.fileDownload(mvcUrl('name of the controller'), {
            httpMethod: 'POST',
            successCallback: function (url) {
            //insert success code

            },
            failCallback: function (html, url) {
            //insert fail code
            }
        });

What's the difference between nohup and ampersand

There are many cases when small differences between environments can bite you. This is one into which I have ran recently. What is the difference between these two commands?

1 ~ $ nohup myprocess.out &
2 ~ $ myprocess.out &

The answer is the same as usual - it depends.

nohup catches the hangup signal while the ampersand does not.

What is the hangup signal?

SIGHUP - hangup detected on controlling terminal or death of controlling process (value: 1).

Normally, when running a command using & and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (like kill -SIGHUP $PID). This can be prevented using nohup, as it catches the signal and ignores it so that it never reaches the actual application.

Fine, but like in this case there are always ‘buts’. There is no difference between these launching methods when the shell is configured in a way where it does not send SIGHUP at all.

In case you are using bash, you can use the command specified below to find out whether your shell sends SIGHUP to its child processes or not:

~ $ shopt | grep hupon

And moreover - there are cases where nohup does not work. For example, when the process you start reconnects the NOHUP signal (it is done inside, on the application code level).

In the described case, lack of differences bit me when inside a custom service launching script there was a call to a second script which sets up and launches the proper application without a nohup command.

On one Linux environment everything worked smoothly, on a second one the application quit as soon as the second script exited (detecting that case, of course took me much more time then you might think :stuck_out_tongue:).

After adding nohup as a launching method to second script, application keeps running even if the scripts will exit and this behavior became consistent on both environments.

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

Best way to reverse a string

This is the code used for reverse string

public Static void main(){
    string text = "Test Text";
    Console.Writeline(RevestString(text))
}

public Static string RevestString(string text){
    char[] textToChar = text.ToCharArray();
    string result= string.Empty;
    int length = textToChar .Length;
    for (int i = length; i > 0; --i)
    result += textToChar[i - 1];
    return result;
}

How to run Ruby code from terminal?

You can run ruby commands in one line with the -e flag:

ruby -e "puts 'hi'"

Check the man page for more information.

How to URL encode a string in Ruby

Code:

str = "http://localhost/with spaces and spaces"
encoded = URI::encode(str)
puts encoded

Result:

http://localhost/with%20spaces%20and%20spaces

What is the JavaScript equivalent of var_dump or print_r in PHP?

You could also try this function. Can't remember the original author, but all credits goes to him/her.

Works like a charm - 100% the same as var_dump in PHP.

Check it out.

_x000D_
_x000D_
function dump(arr,level) {_x000D_
 var dumped_text = "";_x000D_
 if(!level) level = 0;_x000D_
_x000D_
 //The padding given at the beginning of the line._x000D_
 var level_padding = "";_x000D_
 for(var j=0;j<level+1;j++) level_padding += "    ";_x000D_
_x000D_
 if(typeof(arr) == 'object') { //Array/Hashes/Objects_x000D_
  for(var item in arr) {_x000D_
   var value = arr[item];_x000D_
_x000D_
   if(typeof(value) == 'object') { //If it is an array,_x000D_
    dumped_text += level_padding + "'" + item + "' ...\n";_x000D_
    dumped_text += dump(value,level+1);_x000D_
   } else {_x000D_
    dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";_x000D_
   }_x000D_
  }_x000D_
 } else { //Stings/Chars/Numbers etc._x000D_
  dumped_text = "===>"+arr+"<===("+typeof(arr)+")";_x000D_
 }_x000D_
 return dumped_text;_x000D_
}_x000D_
_x000D_
_x000D_
// Example:_x000D_
_x000D_
var employees = [_x000D_
    { id: '1', sex: 'm', city: 'Paris' }, _x000D_
    { id: '2', sex: 'f', city: 'London' },_x000D_
    { id: '3', sex: 'f', city: 'New York' },_x000D_
    { id: '4', sex: 'm', city: 'Moscow' },_x000D_
    { id: '5', sex: 'm', city: 'Berlin' }_x000D_
]_x000D_
_x000D_
_x000D_
// Open dev console (F12) to see results:_x000D_
_x000D_
console.log(dump(employees));
_x000D_
_x000D_
_x000D_

Is it possible to use Java 8 for Android development?

Follow this link for new updates. Use Java 8 language features

Old Answer

As of Android N preview release Android support limited features of Java 8 see Java 8 Language Features

To start using these features, you need to download and set up Android Studio 2.1 and the Android N Preview SDK, which includes the required Jack toolchain and updated Android Plugin for Gradle. If you haven't yet installed the Android N Preview SDK, see Set Up to Develop for Android N.

Supported Java 8 Language Features and APIs

Android does not currently support all Java 8 language features. However, the following features are now available when developing apps targeting the Android N Preview:

Default and static interface methods

Lambda expressions (also available on API level 23 and lower)

Repeatable annotations

Method References (also available on API level 23 and lower)

There are some additional Java 8 features which Android support, you can see complete detail from Java 8 Language Features

Update

Note: The Android N bases its implementation of lambda expressions on anonymous classes. This approach allows them to be backwards compatible and executable on earlier versions of Android. To test lambda expressions on earlier versions, remember to go to your build.gradle file, and set compileSdkVersion and targetSdkVersion to 23 or lower.

Update 2

Now Android studio 3.0 stable release support Java 8 libraries and Java 8 language features (without the Jack compiler).

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

HRESULT: 0x800A03EC on Worksheet.range

I also faced the same issue, when I was developing a application which exports project contents into excel file.

I could not found the resolution in forums for my problem, then I check the maximum capacity of excel and found below link which says

"Worksheet size 1,048,576 rows by 16,384 columns" and this was the issue in my case, I was exporting more than that rows. Refer below link for details

http://answers.microsoft.com/en-us/office/forum/office_2013_release-excel/with-excel-2013how-many-rows-will-this-contain/271264fb-3ab8-4c5b-aa0d-7095c5ac6108

Regards Prashant Neve

How do I handle ImeOptions' done button click?

I know this question is old, but I want to point out what worked for me.

I tried using the sample code from the Android Developers website (shown below), but it didn't work. So I checked the EditorInfo class, and I realized that the IME_ACTION_SEND integer value was specified as 0x00000004.

Sample code from Android Developers:

editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextEmail
        .setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    /* handle action here */
                    handled = true;
                }
                return handled;
            }
        });

So, I added the integer value to my res/values/integers.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="send">0x00000004</integer>
</resources>

Then, I edited my layout file res/layouts/activity_home.xml as follows

<EditText android:id="@+id/editTextEmail"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:imeActionId="@integer/send"
  android:imeActionLabel="@+string/send_label"
  android:imeOptions="actionSend"
  android:inputType="textEmailAddress"/>

And then, the sample code worked.

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

Enable remote connections for SQL Server Express 2012

One more thing to check is that you have spelled the named instance correctly!

This article is very helpful in troubleshooting connection problems: How to Troubleshoot Connecting to the SQL Server Database Engine

How to count the occurrence of certain item in an ndarray?

using numpy.count

$ a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]

$ np.count(a, 1)

Get all parameters from JSP page

<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
    if(parameter.toLowerCase().startsWith("question")) {
        String[] values = parameters.get(parameter);
        //your code here
    }
}

How to get character for a given ascii value

This works in my code.

string asciichar = (Convert.ToChar(65)).ToString();

Return: asciichar = 'A';

How to calculate time difference in java?

The painful way is to convert to millis and do the subtraction and then back to whatever seconds or so you want. The better way is to use JodaTime.

How to get label of select option with jQuery?

To get the label of a specific option in a dropdown yo can ty this --

$('.class_of_dropdown > option[value='value_to_be_searched']').html();

or

$('#id_of_dropdown > option[value='value_to_be_Searched']').html();

The remote certificate is invalid according to the validation procedure

You must check the certificate hash code.

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain,
    errors) =>
        {
            var hashString = certificate.GetCertHashString();
            if (hashString != null)
            {
                var certHashString = hashString.ToLower();
                return certHashString == "dec2b525ddeemma8ccfaa8df174455d6e38248c5";
            }
            return false;
        };

Showing the same file in both columns of a Sublime Text window

I regularly work on the same file in 2 different positions. I solved this in Sublime Text 3 using origami and chain with some additional config.

My workflow is Ctrl + k + 2 splits the view of the file in two (horizontal) panes with the lower one active. Use Ctrl + k + o to toggle between the panes. When done ensure the lower pane is the active and press Ctrl + F4 to close the duplicated view and the pane.

In sublime global settings (not origami settings!) add

"origami_auto_close_empty_panes": true,

Add the following shortcuts

  { "keys": ["ctrl+k", "2"], 
    "command": "chain", 
    "args": {
      "commands": [
        ["create_pane", {"direction": "down"}],
        ["clone_file_to_pane", {"direction": "down"}],
      ],
    }
  },

  { "keys": ["ctrl+k", "o"], "command": "focus_neighboring_group" },

HTML input fields does not get focus when clicked

iPhone6 chrome

Problem for me was placing the input field inside <label> and <p>

like this :

<label>
  <p>
     <input/>
  </p>
</label>

I changed them to

<div>
  <div>
     <input/>
  </div>
</div>

And it works for me .

After check this answer, Please check other answers in this page, this issue may have different reasons

Getting the IP Address of a Remote Socket Endpoint

string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();

What is the difference between & and && in Java?

Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100

How to implement private method in ES6 class with Traceur

Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time. Thus, you have private properties and methods :)

Here is an example (in test.js file)

function tryMe1(a) {
  console.log(a + 2);
}

var tryMe2 = 1234;

class myModule {
  tryMe3(a) {
    console.log(a + 100);
  }

  getTryMe1(a) {
    tryMe1(a);
  }

  getTryMe2() {
    return tryMe2;
  }
}

// Exports just myModule class. Not anything outside of it.
export default myModule; 

In another file

import MyModule from './test';

let bar = new MyModule();

tryMe1(1); // ReferenceError: tryMe1 is not defined
tryMe2; // ReferenceError: tryMe2 is not defined
bar.tryMe1(1); // TypeError: bar.tryMe1 is not a function
bar.tryMe2; // undefined

bar.tryMe3(1); // 101
bar.getTryMe1(1); // 3
bar.getTryMe2(); // 1234

How to allocate aligned memory only using the standard library?

For the solution i used a concept of padding which aligns the memory and do not waste the memory of a single byte .

If there are constraints that, you cannot waste a single byte. All pointers allocated with malloc are 16 bytes aligned.

C11 is supported, so you can just call aligned_alloc (16, size).

void *mem = malloc(1024+16);
void *ptr = ((char *)mem+16) & ~ 0x0F;
memset_16aligned(ptr, 0, 1024);
free(mem);

Homebrew refusing to link OpenSSL

The solution might be updating some tools.

Here's my scenario from 2020 with Ruby and Python:

I needed to install Python 3 on Mac and things escalated. In the end, updating homebrew, node and python lead to the problem with openssl. I did not have openssl 1.0 anymore, so I couldn't "brew switch" to it.
So what was still trying to use that old 1.0 version?

It tuned out it was Ruby 2.5.5.
So I just installed Ruby 2.5.8 and removed the old one.

Other things you can try if this is not enough: Use rbenv and pyenv. Clean up gems and formulas. Update homebrew, node, yarn. Upgrade bundler. Make sure your .bash_profile (or equivalent) is set up according to each tool's instructions. Reopen the terminal.

PHPExcel Make first row bold

Try this

    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                 ->setLastModifiedBy("Maarten Balliauw")
                                 ->setTitle("Office 2007 XLSX Test Document")
                                 ->setSubject("Office 2007 XLSX Test Document")
                                 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                 ->setKeywords("office 2007 openxml php")
                                 ->setCategory("Test result file");
    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValue('A1', 'No');
    $sheet->setCellValue('B1', 'Job ID');
    $sheet->setCellValue('C1', 'Job completed Date');
    $sheet->setCellValue('D1', 'Job Archived Date');
    $styleArray = array(
        'font' => array(
        'bold' => true
        )
    );
    $sheet->getStyle('A1')->applyFromArray($styleArray);
    $sheet->getStyle('B1')->applyFromArray($styleArray);
    $sheet->getStyle('C1')->applyFromArray($styleArray);
    $sheet->getStyle('D1')->applyFromArray($styleArray);
    $sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
    

This is give me output like below link.(https://www.screencast.com/t/ZkKFHbDq1le)

What's the difference between '$(this)' and 'this'?

this is the element, $(this) is the jQuery object constructed with that element

$(".class").each(function(){
 //the iterations current html element 
 //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
 var HTMLElement = this;

 //the current HTML element is passed to the jQuery constructor
 //the jQuery API is exposed here (such as .html() and .append())
 var jQueryObject = $(this);
});

A deeper look

thisMDN is contained in an execution context

The scope refers to the current Execution ContextECMA. In order to understand this, it is important to understand the way execution contexts operate in JavaScript.

execution contexts bind this

When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this occurs.

jQuery binds this

Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using applyMDN.

callback.apply( obj[ i ] )//where obj[i] is the current element

The result of calling apply is that inside of jQuery callback functions, this refers to the current element being used by the callback function.

For example, in .each, the callback function commonly used allows for .each(function(index,element){/*scope*/}). In that scope, this == element is true.

jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.

$(selector) calls the jQuery function (remember that $ is a reference to jQuery, code: window.jQuery = window.$ = jQuery;). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $() internally uses new jQuery(). Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this).

Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this to the current element. This call can be seen in the code snippet above where obj is the array-like structure, and i is the iterator used for the position in the array of the current element.

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

How to sort a Collection<T>?

I came across a similar problem. Had to sort a list of 3rd party class (objects).

List<ThirdPartyClass> tpc = getTpcList(...);

ThirdPartyClass does not implement the Java Comparable interface. I found an excellent illustration from mkyong on how to approach this problem. I had to use the Comparator approach to sorting.

//Sort ThirdPartyClass based on the value of some attribute/function
Collections.sort(tpc, Compare3rdPartyObjects.tpcComp);

where the Comparator is:

public abstract class Compare3rdPartyObjects {

public static Comparator<ThirdPartyClass> tpcComp = new Comparator<ThirdPartyClass>() {

    public int compare(ThirdPartyClass tpc1, ThirdPartyClass tpc2) {

        Integer tpc1Offset = compareUsing(tpc1);
        Integer tpc2Offset = compareUsing(tpc2);

        //ascending order
        return tpc1Offset.compareTo(tpc2Offset);

    }
};

//Fetch the attribute value that you would like to use to compare the ThirdPartyClass instances 
public static Integer compareUsing(ThirdPartyClass tpc) {

    Integer value = tpc.getValueUsingSomeFunction();
    return value;
}
}

SQL query to get the deadlocks in SQL SERVER 2008

You can use a deadlock graph and gather the information you require from the log file.

The only other way I could suggest is digging through the information by using EXEC SP_LOCK (Soon to be deprecated), EXEC SP_WHO2 or the sys.dm_tran_locks table.

SELECT  L.request_session_id AS SPID, 
    DB_NAME(L.resource_database_id) AS DatabaseName,
    O.Name AS LockedObjectName, 
    P.object_id AS LockedObjectId, 
    L.resource_type AS LockedResource, 
    L.request_mode AS LockType,
    ST.text AS SqlStatementText,        
    ES.login_name AS LoginName,
    ES.host_name AS HostName,
    TST.is_user_transaction as IsUserTransaction,
    AT.name as TransactionName,
    CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
    JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
    JOIN sys.objects O ON O.object_id = P.object_id
    JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
    JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
    JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
    JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
    CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph

http://weblogs.sqlteam.com/mladenp/archive/2008/04/29/SQL-Server-2005-Get-full-information-about-transaction-locks.aspx

What is the shortcut to Auto import all in Android Studio?

Note that in my Android Studio 1.4, Auto Import now under General

(Android Studio --> Preferences --> Editors --> General --> Auto Import)

enter image description here

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

Center-align a HTML table

Try this -

<table align="center" style="margin: 0px auto;"></table>

How to set xampp open localhost:8080 instead of just localhost

I agree and found this file under xammp-control the type of file is configuration. When I changed it to 8080 it worked automagically!

How to SELECT a dropdown list item by value programmatically

If you know that the dropdownlist contains the value you're looking to select, use:

ddl.SelectedValue = "2";

If you're not sure if the value exists, use (or you'll get a null reference exception):

ListItem selectedListItem = ddl.Items.FindByValue("2");

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
}

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

change your code to this

$start_date = new DateTime( "@" . $dbResult->db_timestamp );

and it will work fine

Find Item in ObservableCollection without using a loop

Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

Get DataKey values in GridView RowCommand

I managed to get the value of the DataKeys using this code:

In the GridView I added:

DataKeyNames="ID" OnRowCommand="myRowCommand"

Then in my row command function:

protected void myRowCommand(object sender, GridViewCommandEventArgs e) 
{
    LinkButton lnkBtn = (LinkButton)e.CommandSource;    // the button
    GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;  // the row
    GridView myGrid = (GridView)sender; // the gridview
    string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey 

    switch (e.CommandName)
    {
      case "cmd1":
      // do something using the ID
      break;
      case "cmd2":
      // do something else using the ID
      break;
    }
 }

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

Connecting an input stream to an outputstream

Asynchronous way to achieve it.

void inputStreamToOutputStream(final InputStream inputStream, final OutputStream out) {
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                int d;
                while ((d = inputStream.read()) != -1) {
                    out.write(d);
                }
            } catch (IOException ex) {
                //TODO make a callback on exception.
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

As per the documentation: FROM (Transact-SQL):

<join_type> ::= 
    [ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ]
    JOIN

The keyword OUTER is marked as optional (enclosed in square brackets). In this specific case, whether you specify OUTER or not makes no difference. Note that while the other elements of the join clause is also marked as optional, leaving them out will make a difference.

For instance, the entire type-part of the JOIN clause is optional, in which case the default is INNER if you just specify JOIN. In other words, this is legal:

SELECT *
FROM A JOIN B ON A.X = B.Y

Here's a list of equivalent syntaxes:

A LEFT JOIN B            A LEFT OUTER JOIN B
A RIGHT JOIN B           A RIGHT OUTER JOIN B
A FULL JOIN B            A FULL OUTER JOIN B
A INNER JOIN B           A JOIN B

Also take a look at the answer I left on this other SO question: SQL left join vs multiple tables on FROM line?.

enter image description here

Send cookies with curl

You can use -b to specify a cookie file to read the cookies from as well.

In many situations using -c and -b to the same file is what you want:

curl -b cookies.txt -c cookies.txt http://example.com

Further

Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.

The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.

See Also

The cookies chapter in the Everything curl book.

How to find the maximum value in an array?

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}

How to percent-encode URL parameters in Python?

It is better to use urlencode here. Not much difference for single parameter but IMHO makes the code clearer. (It looks confusing to see a function quote_plus! especially those coming from other languates)

In [21]: query='lskdfj/sdfkjdf/ksdfj skfj'

In [22]: val=34

In [23]: from urllib.parse import urlencode

In [24]: encoded = urlencode(dict(p=query,val=val))

In [25]: print(f"http://example.com?{encoded}")
http://example.com?p=lskdfj%2Fsdfkjdf%2Fksdfj+skfj&val=34

Docs

urlencode: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode

quote_plus: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus

Make the image go behind the text and keep it in center using CSS

Start at 0 and go up from there, rather than using -1. For instance, set the div containing your inputs and labels to a z-index of 100, and give the image you want to place behind it a z-index of 50.

Alternatively just set the image as the background-image of the div containing the inputs and labels. Since the image is probably illustrative and therefore presentational, it doesn't really need to be an actual img element.

Replacing .NET WebBrowser control with a better browser, like Chrome?

You can use registry to set IE version for webbrowser control. Go to: HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add "yourApplicationName.exe" with value of browser_emulation To see value of browser_emulation, refer link: http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation

.Net System.Mail.Message adding multiple "To" addresses

I wasn't able to replicate your bug:

var message = new MailMessage();

message.To.Add("[email protected]");
message.To.Add("[email protected]");

message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";

var client = new SmtpClient("localhost", 25);
client.Send(message);

Dumping the contents of the To: MailAddressCollection:

MailAddressCollection (2 items)
DisplayName User Host Address

user example.com [email protected]
user2 example.com [email protected]

And the resulting e-mail as caught by smtp4dev:

Received: from mycomputername (mycomputername [127.0.0.1])
     by localhost (Eric Daugherty's C# Email Server)
     3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Test

Are you sure there's not some other issue going on with your code or SMTP server?

Sleep Command in T-SQL?

You can also "WAITFOR" a "TIME":

    RAISERROR('Im about to wait for a certain time...', 0, 1) WITH NOWAIT
    WAITFOR TIME '16:43:30.000'
    RAISERROR('I waited!', 0, 1) WITH NOWAIT

Not able to access adb in OS X through Terminal, "command not found"

I couldn't get the stupid path working so I created an alias for abd

alias abd ="~/Library/Android/sdk/platform-tools/adb"

works fine.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

Rails does not use the stdlib's ERB by default, it uses erubis. Sources: this dev's comment, ActionView's gemspec, accepted merge request I did while writing this.

There are behavior differences between them, in particular on how the hyphen operators %- and -% work.

Documentation is scarce, Where is Ruby's ERB format "officially" defined? so what follows are empirical conclusions.

All tests suppose:

require 'erb'
require 'erubis'

When you can use -

  • ERB: you must pass - to trim_mode option of ERB.new to use it.
  • erubis: enabled by default.

Examples:

begin ERB.new("<%= 'a' -%>\nb").result; rescue SyntaxError ; else raise; end
ERB.new("<%= 'a' -%>\nb"  , nil, '-') .result == 'ab'  or raise
Erubis::Eruby.new("<%= 'a' -%>  \n b").result == 'a b' or raise

What -% does:

  • ERB: remove the next character if it is a newline.

  • erubis:

    • in <% %> (without =), - is useless because <% %> and <% -%> are the same. <% %> removes the current line if it only contains whitespaces, and does nothing otherwise.

    • in <%= -%> (with =):

      • remove the entire line if it only contains whitespaces
      • else, if there is a non-space before the tag, and only whitesapces after, remove the whitespces that come after
      • else, there is a non-space after the tag: do nothing

Examples:

# Remove
ERB.new("a \nb <% 0 -%>\n c", nil, '-').result == "a \nb  c" or raise

# Don't do anything: not followed by newline, but by space:
ERB.new("a\n<% 0 -%> \nc", nil, '-').result == "a\nb \nc" or raise

# Remove the current line because only whitesapaces:
Erubis::Eruby.new(" <% 0 %> \nb").result == 'b' or raise

# Same as above, thus useless because longer.
Erubis::Eruby.new(" <% 0 -%> \nb").result == 'b' or raise

# Don't do anything because line not empty.
Erubis::Eruby.new("a <% 0 %> \nb").result == "a  \nb" or raise
Erubis::Eruby.new(" <% 0 %> a\nb").result == "  a\nb" or raise
Erubis::Eruby.new(" <% 0 -%> a\nb").result == "  a\nb" or raise

# Don't remove the current line because of `=`:
Erubis::Eruby.new(" <%= 0 %> \nb").result == " 0 \nb" or raise

# Remove the current line even with `=`:
Erubis::Eruby.new(" <%= 0 -%> \nb").result == " 0b"   or raise

# Remove forward only because of `-` and non space before:
Erubis::Eruby.new("a <%= 0 -%> \nb").result == "a 0b"   or raise

# Don't do anything because non-whitespace forward:
Erubis::Eruby.new(" <%= 0 -%> a\nb").result == " 0 a\nb"   or raise

What %- does:

  • ERB: remove whitespaces before tag and after previous newlines, but only if there are only whitespaces before.

  • erubis: useless because <%- %> is the same as <% %> (without =), and this cannot be used with = which is the only case where -% can be useful. So never use this.

Examples:

# Remove
ERB.new("a \n  <%- 0 %> b\n c", nil, '-').result == "a \n b\n c" or raise

# b is not whitespace: do nothing:
ERB.new("a \nb  <%- 0 %> c\n d", nil, '-').result == "a \nb   c\n d" or raise

What %- and -% do together

The exact combination of both effects separately.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Follow the steps below in Oracle VM VirtualBox Manager:

  1. Select the Virtual device and choose Settings
  2. Navigate to System and click the Processor tab
  3. Tick the check-box, Enable PAE/NX
  4. Click OK and you are done

To verify, start the Virtual device from Oracle VM VirtualBox. If all has gone well, the device boots up.

Close this device and open it from Genymotion.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

This error is usually caused by the missing Visual C++ Redistributable file, which is a required dependency for most of the application on Windows Computer.

Download Visual C++ Redistributable from here and install it. After installing this, Reboot the system.

Link: Visual C++ Redistributable

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.

I had no luck with any of the above methods.

I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.

This is working very well for me.

(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf

How to add text to JFrame?

You can add a multi-line label with the following:

JLabel label = new JLabel("My label");

label.setText("<html>This is a<br>multline label!<br> Try it yourself!</html>");

From here, simply add the label to the frame using the add() method, and you're all set!