Programs & Examples On #Tfs power tools

Team foundation server power tools is a set of tools that allow you to manipulate the TFS server from the command line, it also allows you access to many features that cannot be accessed from the gui.

Android Webview - Completely Clear the Cache

The only solution that works for me

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();
} 

HTML img scaling

For an automatic letterbox/pillarbox in a fixed-size rectangle, use the object-fit CSS property. That is usually what I want, and it avoids using code to figure out which is the dominant dimension or — what I used to do — embedding an <SVG> element with an <image> child to wrap the content with its nice preserveAspectRatio options.

_x000D_
_x000D_
<!DOCTYPE html>
<html>
  <head>
    <style>
      :root
      {
        --box-side : min( 42vmin, 480px ) ;
      }
      body
      {
        align-items : center ;
        display : flex ; 
        flex-wrap : wrap ;
        justify-content : center ;
      }
      body,html
      {
        height : 100% ;
        width : 100% ;
      }
      img
      {
        background : grey ;
        border : 1px solid black ;
        height : var( --box-side ) ;
        object-fit : contain ;
        width : var( --box-side ) ;
      }
    </style>
    <title>object-fit</title>
  </head>
  <body>
    <img src="https://alesmith.com/wp-content/uploads/logos/ALESMITH-MasterLogoShadow01-MULTI-A.png" />
    <img src="https://ballastpoint.com/wp-content/themes/ballastpoint/assets/img/bp-logo-color.svg" />
    <img src="https://d2lchr2s24ssh5.cloudfront.net/wp-content/uploads/2014/01/GF19_PrimaryLogo_RGB.png" />
    <img src="https://s3-us-west-1.amazonaws.com/paradeigm-social/NeFAAJ7RlCreLCi9Uk9u_pizza-port-logo.svg">
    <img src="https://s3-us-west-2.amazonaws.com/lostabbey-prod/Logos/Logo_Port_SM_Circle_White.png" />
  </body>
</html>
_x000D_
_x000D_
_x000D_

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

PowerShell Alternative

This is an old post and I read through the answers. Still, I found it a bit too painful to output multi-line large text fields unaltered from SSMS. I ended up writing a small C# program for my needs, but got to thinking it could probably be done using the command line. Turns out, it is fairly easy to do so with PowerShell.

Start by installing the SqlServer module from an administrative PowerShell.

Install-Module -Name SqlServer

Use Invoke-Sqlcmd to run your query:

$Rows = Invoke-Sqlcmd -Query "select BigColumn from SomeTable where Id = 123" `
    -As DataRows -MaxCharLength 1000000 -ConnectionString $ConnectionString

This will return an array of rows that you can output to the console as follows:

$Rows[0].BigColumn

Or output to a file as follows:

$Rows[0].BigColumn | Out-File -FilePath .\output.txt -Encoding UTF8

The result is a beautiful un-truncated text written to a file for viewing/editing. I am sure there is a similar command to save back the text to SQL Server, although that seems like a different question.

EDIT: It turns out that there was an answer by @dvlsc that described this approach as a secondary solution. I think because it was listed as a secondary answer, is the reason I missed it in the first place. I am going to leave my answer which focuses on the PowerShell approach, but wanted to at least give credit where it was due.

Explicitly select items from a list or tuple

What about this:

from operator import itemgetter
itemgetter(0,2,3)(myList)
('foo', 'baz', 'quux')

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Java 1.7 makes our lives much easier thanks to the try-with-resources statement.

try (Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement()) {
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do stuff with the result set.
    }
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do more stuff with the second result set.
    }
}

This syntax is quite brief and elegant. And connection will indeed be closed even when the statement couldn't be created.

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

Difference between Big-O and Little-O Notation

In general

Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:

  • f(n) ? o(n) means: at some point, the more you zoom out, the more f(n) will be dominated by n (it will progressively diverge from it).
  • g(n) ? T(n) means: at some point, zooming out will not change how g(n) compare to n (if we remove ticks from the axis you couldn't tell the zoom level).

Finally h(n) ? O(n) means that function h can be in either of these two categories. It can either look a lot like n or it could be smaller and smaller than n when n increases. Basically, both f(n) and g(n) are also in O(n).

In computer science

In computer science, people will usually prove that a given algorithm admits both an upper O and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.

For example, if we prove that the complexity of an algorithm is both in O(n) and (n) it implies that its complexity is in T(n). That's the definition of T and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n). Again, roughly saying "this problem can't be solved in less than n steps".

An upper bound of O(n) simply means that even in the worse case, the algorithm will terminate in at most n steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n) means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n steps (again ignoring multiplicative and additive constants). The number of steps is at most n and at least n so this problem complexity is "exactly n". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n) for short.

What's the difference between 'git merge' and 'git rebase'?

For easy understand can see my figure.

Rebase will change commit hash, so that if you want to avoid much of conflict, just use rebase when that branch is done/complete as stable.

enter image description here

Find intersection of two nested lists?

You should flatten using this code ( taken from http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks ), the code is untested, but I'm pretty sure it works:


def flatten(x):
    """flatten(sequence) -> list

    Returns a single, flat list which contains all elements retrieved
    from the sequence and all recursively contained sub-sequences
    (iterables).

    Examples:
    >>> [1, 2, [3,4], (5,6)]
    [1, 2, [3, 4], (5, 6)]
    >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
    [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""

    result = []
    for el in x:
        #if isinstance(el, (list, tuple)):
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

After you had flattened the list, you perform the intersection in the usual way:


c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

def intersect(a, b):
     return list(set(a) & set(b))

print intersect(flatten(c1), flatten(c2))

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

You are using the --noImplicitAny and TypeScript doesn't know about the type of the Users object. In this case, you need to explicitly define the user type.

Change this line:

let user = Users.find(user => user.id === query);

to this:

let user = Users.find((user: any) => user.id === query); 
// use "any" or some other interface to type this argument

Or define the type of your Users object:

//...
interface User {
    id: number;
    name: string;
    aliases: string[];
    occupation: string;
    gender: string;
    height: {ft: number; in: number;}
    hair: string;
    eyes: string;
    powers: string[]
}
//...
const Users = <User[]>require('../data');
//...

Setting the Vim background colors

As vim's own help on set background says, "Setting this option does not change the background color, it tells Vim what the background color looks like. For changing the background color, see |:hi-normal|."

For example

:highlight Normal ctermfg=grey ctermbg=darkblue

will write in white on blue on your color terminal.

Python: Get the first character of the first string in a list?

Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.

If you have the following structure:

mylist = ['base', 'sample', 'test']

And want to get fist char for the first one string(item):

myList[0][0]
>>> b

If all first chars:

[x[0] for x in myList]
>>> ['b', 's', 't']    

If you have a text:

text = 'base sample test'
text.split()[0][0]
>>> b

How to iterate over array of objects in Handlebars?

I meant in the template() call..

You just need to pass the results as an object. So instead of calling

var html = template(data);

do

var html = template({apidata: data});

and use {{#each apidata}} in your template code

demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if code that crashed)

JBoss default password

The default credentials are:

login: admin
password: admin

But if you use EAP these credentials are turned off by default and there is no active user (security reasons :)). If you want to turn on these users, you have to edit the following file in your current profile: ./deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties. It should be enough to remove the # sign from the line with the user.

If you want to create a new user, don't forget to set up the correct groups in web-console-roles.properties file.

You can easily find information where these information are stored: just open the ./conf/login-config.xml file and find the proper security domain definition. In the case of the Web Console application, it will be web-console policy.

Also if you want to have access to JMX, you have unlock JMX Console. Just check the following files in the conf/props/ directory (in your profile): jmx-console-users.properties and jmx-console-roles.properties.

How can I regenerate ios folder in React Native project?

UPDATE 2020. React Native 0.63.3 no longer support this command react-native eject. Also react-native upgrade responsible for - Upgrade your app's template files to the specified or latest npm version using rn-diff-purge project.

Available options can be found thought this command react-native --help

How to convert JSON string into List of Java object?

use below simple code, no need to use any library

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);

Add/Delete table rows dynamically using JavaScript

Here Is full code with HTML,CSS and JS.

<style><style id='generate-style-inline-css' type='text/css'>
    body {
        background-color: #efefef;
        color: #3a3a3a;
    }

    a,
    a:visited {
        color: #1e73be;
    }

    a:hover,
    a:focus,
    a:active {
        color: #000000;
    }

    body .grid-container {
        max-width: 1200px;
    }

    body,
    button,
    input,
    select,
    textarea {
        font-family: "Open Sans", sans-serif;
    }

    .entry-content>[class*="wp-block-"]:not(:last-child) {
        margin-bottom: 1.5em;
    }

    .main-navigation .main-nav ul ul li a {
        font-size: 14px;
    }

    @media (max-width:768px) {
        .main-title {
            font-size: 30px;
        }
        h1 {
            font-size: 30px;
        }
        h2 {
            font-size: 25px;
        }
    }

    .top-bar {
        background-color: #636363;
        color: #ffffff;
    }

    .top-bar a,
    .top-bar a:visited {
        color: #ffffff;
    }

    .top-bar a:hover {
        color: #303030;
    }

    .site-header {
        background-color: #ffffff;
        color: #3a3a3a;
    }

    .site-header a,
    .site-header a:visited {
        color: #3a3a3a;
    }

    .main-title a,
    .main-title a:hover,
    .main-title a:visited {
        color: #222222;
    }

    .site-description {
        color: #757575;
    }

    .main-navigation,
    .main-navigation ul ul {
        background-color: #222222;
    }

    .main-navigation .main-nav ul li a,
    .menu-toggle {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li:hover>a,
    .main-navigation .main-nav ul li:focus>a,
    .main-navigation .main-nav ul li.sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    button.menu-toggle:hover,
    button.menu-toggle:focus,
    .main-navigation .mobile-bar-items a,
    .main-navigation .mobile-bar-items a:hover,
    .main-navigation .mobile-bar-items a:focus {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"],
    .navigation-search input[type="search"]:active {
        color: #3f3f3f;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"]:focus {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation ul ul {
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul ul li a {
        color: #ffffff;
    }

    .main-navigation .main-nav ul ul li:hover>a,
    .main-navigation .main-nav ul ul li:focus>a,
    .main-navigation .main-nav ul ul li.sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation . main-nav ul ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation .main-nav ul ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .separate-containers .inside-article,
    .separate-containers .comments-area,
    .separate-containers .page-header,
    .one-container .container,
    .separate-containers .paging-navigation,
    .inside-page-header {
        background-color: #ffffff;
    }

    .entry-meta {
        color: #595959;
    }

    .entry-meta a,
    .entry-meta a:visited {
        color: #595959;
    }

    .entry-meta a:hover {
        color: #1e73be;
    }

    .sidebar .widget {
        background-color: #ffffff;
    }

    .sidebar .widget .widget-title {
        color: #000000;
    }

    .footer-widgets {
        background-color: #ffffff;
    }

    .footer-widgets .widget-title {
        color: #000000;
    }

    .site-info {
        color: #ffffff;
        background-color: #222222;
    }

    .site-info a,
    .site-info a:visited {
        color: #ffffff;
    }

    .site-info a:hover {
        color: #606060;
    }

    .footer-bar .widget_nav_menu .current-menu-item a {
        color: #606060;
    }

    input[type="text"],
    input[type="email"],
    input[type="url"],
    input[type="password"],
    input[type="search"],
    input[type="tel"],
    input[type="number"],
    textarea,
    select {
        color: #666666;
        background-color: #fafafa;
        border-color: #cccccc;
    }

    input[type="text"]:focus,
    input[type="email"]:focus,
    input[type="url"]:focus,
    input[type="password"]:focus,
    input[type="search"]:focus,
    input[type="tel"]:focus,
    input[type="number"]:focus,
    textarea:focus,
    select:focus {
        color: #666666;
        background-color: #ffffff;
        border-color: #bfbfbf;
    }

    button,
    html input[type="button"],
    input[type="reset"],
    input[type="submit"],
    a.button,
    a.button:visited,
    a.wp-block-button__link:not(.has-background) {
        color: #ffffff;
        background-color: #666666;
    }

    button:hover,
    html input[type="button"]:hover,
    input[type="reset"]:hover,
    input[type="submit"]:hover,
    a.button:hover,
    button:focus,
    html input[type="button"]:focus,
    input[type="reset"]:focus,
    input[type="submit"]:focus,
    a.button:focus,
    a.wp-block-button__link:not(.has-background):active,
    a.wp-block-button__link:not(.has-background):focus,
    a.wp-block-button__link:not(.has-background):hover {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .generate-back-to-top,
    .generate-back-to-top:visited {
        background-color: rgba( 0, 0, 0, 0.4);
        color: #ffffff;
    }

    .generate-back-to-top:hover,
    .generate-back-to-top:focus {
        background-color: rgba( 0, 0, 0, 0.6);
        color: #ffffff;
    }

    .entry-content .alignwide,
    body:not(.no-sidebar) .entry-content .alignfull {
        margin-left: -40px;
        width: calc(100% + 80px);
        max-width: calc(100% + 80px);
    }

    @media (max-width:768px) {
        .separate-containers .inside-article,
        .separate-containers .comments-area,
        .separate-containers .page-header,
        .separate-containers .paging-navigation,
        .one-container .site-content,
        .inside-page-header {
            padding: 30px;
        }
        .entry-content .alignwide,
        body:not(.no-sidebar) .entry-content .alignfull {
            margin-left: -30px;
            width: calc(100% + 60px);
            max-width: calc(100% + 60px);
        }
    }

    .rtl .menu-item-has-children .dropdown-menu-toggle {
        padding-left: 20px;
    }

    .rtl .main-navigation .main-nav ul li.menu-item-has-children>a {
        padding-right: 20px;
    }

    .one-container .sidebar .widget {
        padding: 0px;
    }

    .append_row {
        color: black !important;
        background-color: #FFD6D6 !important;
        border: 1px #ccc solid !important;
    }

    .append_column {
        color: black !important;
        background-color: #D6FFD6 !important;
        border: 1px #ccc solid !important;
    }

    table#my-table td {
        width: 50px;
        height: 27px;
        border: 1px solid #D3D3D3;
        text-align: center;
        padding: 0;
    }

    div#my-container input {
        padding: 5px;
        font-size: 12px !important;
        width: 100px;
        margin: 2px;
    }

    .row {
        background-color: #FFD6D6 !important;
    }

    .col {
        background-color: #D6FFD6 !important;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.11.0.js"></script>
    <script>

    // append row to the HTML table
    function appendRow() {
        var tbl = document.getElementById('my-table'), // table reference
            row = tbl.insertRow(tbl.rows.length),      // append table row
            i;
        // insert table cells to the new row
        for (i = 0; i < tbl.rows[0].cells.length; i++) {
            createCell(row.insertCell(i), i, 'row');
        }
    }

    // create DIV element and append to the table cell
    function createCell(cell, text, style) {
        var div = document.createElement('div'), // create DIV element
            txt = document.createTextNode(text); // create text node
        div.appendChild(txt);                    // append text node to the DIV
        div.setAttribute('class', style);        // set DIV class attribute
        div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
        cell.appendChild(div);                   // append DIV to the table cell
    }

    // append column to the HTML table
    function appendColumn() {
        var tbl = document.getElementById('my-table'), // table reference
            i;
        // open loop for each row and append cell
        for (i = 0; i < tbl.rows.length; i++) {
            createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
        }
    }

    // delete table rows with index greater then 0
    function deleteRows() {
        var tbl = document.getElementById('my-table'), // table reference
            lastRow = tbl.rows.length - 1,             // set the last row index
            i;
        // delete rows with index greater then 0
        for (i = lastRow; i > 0; i--) {
            tbl.deleteRow(i);
        }
    }

    // delete table columns with index greater then 0
    function deleteColumns() {
        var tbl = document.getElementById('my-table'), // table reference
            lastCol = tbl.rows[0].cells.length - 1,    // set the last column index
            i, j;
        // delete cells with index greater then 0 (for each row)
        for (i = 0; i < tbl.rows.length; i++) {
            for (j = lastCol; j > 0; j--) {
                tbl.rows[i].deleteCell(j);
            }
        }
    }
    </script>
    <div id="my-container">
    <center><br>
    <input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"><br>
    <input type="button" value="Add column" onclick="javascript:appendColumn()" class="append_column"><br>
    <input type="button" value="Delete rows" onclick="javascript:deleteRows()" class="delete"><br>
    <input type="button" value="Delete columns" onclick="javascript:deleteColumns()" class="delete"><br>
    <input type="button" value="Delete both" onclick="javascript:deleteColumns();deleteRows()" class="delete"><p></p>
    <table id="my-table" align="center" cellspacing="0" cellpadding="0" border="0">
    <tbody><tr>
    <td>Small</td>
    </tr>
    </tbody></table>
    <p></p></center>
    </div>

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

An example cited from §15.26.2

[...] the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

In other words, your assumption is correct.

How to reverse a 'rails generate'

rails destroy controller Controller_name was returning a bunch of errors. To be able to destroy controller I had to remove related routes in routes.rb. P.S. I'm using rails 3.1

Filter Excel pivot table using VBA

Latest versions of Excel has a new tool called Slicers. Using slicers in VBA is actually more reliable that .CurrentPage (there have been reports of bugs while looping through numerous filter options). Here is a simple example of how you can select a slicer item (remember to deselect all the non-relevant slicer values):

Sub Step_Thru_SlicerItems2()
Dim slItem As SlicerItem
Dim i As Long
Dim searchName as string

Application.ScreenUpdating = False
searchName="Value1"

    For Each slItem In .VisibleSlicerItems
        If slItem.Name <> .SlicerItems(1).Name Then _
            slItem.Selected = False
        Else
            slItem.Selected = True
        End if
    Next slItem
End Sub

There are also services like SmartKato that would help you out with setting up your dashboards or reports and/or fix your code.

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

Create ul and li elements in javascript.

Here is my working code :

<!DOCTYPE html>
<html>
<head>
<style>
   ul#proList{list-style-position: inside}
   li.item{list-style:none; padding:5px;}
</style>
</head>
<body>
    <div id="renderList"></div>
</body>
<script>
    (function(){
        var ul = document.createElement('ul');
        ul.setAttribute('id','proList');

        productList = ['Electronics Watch','House wear Items','Kids wear','Women Fashion'];

        document.getElementById('renderList').appendChild(ul);
        productList.forEach(renderProductList);

        function renderProductList(element, index, arr) {
            var li = document.createElement('li');
            li.setAttribute('class','item');

            ul.appendChild(li);

            li.innerHTML=li.innerHTML + element;
        }
    })();
</script>
</html>

working jsfiddle example here

REST / SOAP endpoints for a WCF service

We must define the behavior configuration to REST endpoint

<endpointBehaviors>
  <behavior name="restfulBehavior">
   <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
  </behavior>
</endpointBehaviors>

and also to a service

<serviceBehaviors>
   <behavior>
     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
   </behavior>
</serviceBehaviors>

After the behaviors, next step is the bindings. For example basicHttpBinding to SOAP endpoint and webHttpBinding to REST.

<bindings>
   <basicHttpBinding>
     <binding name="soapService" />
   </basicHttpBinding>
   <webHttpBinding>
     <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
   </webHttpBinding>
</bindings>

Finally we must define the 2 endpoint in the service definition. Attention for the address="" of endpoint, where to REST service is not necessary nothing.

<services>
  <service name="ComposerWcf.ComposerService">
    <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
  </service>
</services>

In Interface of the service we define the operation with its attributes.

namespace ComposerWcf.Interface
{
    [ServiceContract]
    public interface IComposerService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/autenticationInfo/{app_id}/{access_token}", ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);
    }
}

Joining all parties, this will be our WCF system.serviceModel definition.

<system.serviceModel>

  <behaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <bindings>
    <basicHttpBinding>
      <binding name="soapService" />
    </basicHttpBinding>
    <webHttpBinding>
      <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
  </bindings>

  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  <services>
    <service name="ComposerWcf.ComposerService">
      <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
    </service>
  </services>

</system.serviceModel>

To test the both endpoint, we can use WCFClient to SOAP and PostMan to REST.

When should we use intern method of String on String literals

String s1 = "Anish";
        String s2 = "Anish";

        String s3 = new String("Anish");

        /*
         * When the intern method is invoked, if the pool already contains a
         * string equal to this String object as determined by the
         * method, then the string from the pool is
         * returned. Otherwise, this String object is added to the
         * pool and a reference to this String object is returned.
         */
        String s4 = new String("Anish").intern();
        if (s1 == s2) {
            System.out.println("s1 and s2 are same");
        }

        if (s1 == s3) {
            System.out.println("s1 and s3 are same");
        }

        if (s1 == s4) {
            System.out.println("s1 and s4 are same");
        }

OUTPUT

s1 and s2 are same
s1 and s4 are same

How do I set a variable to the output of a command in Bash?

If the command that you are trying to execute fails, it would write the output onto the error stream and would then be printed out to the console.

To avoid it, you must redirect the error stream:

result=$(ls -l something_that_does_not_exist 2>&1)

How do I see which version of Swift I'm using?

I am using Swift from Google Colab. Here's how to check it in Colab.

!/swift/toolchain/usr/bin/swift --version

The result is 5.0-dev

Programmatically go back to previous ViewController in Swift

I did it like this

func showAlert() {
    let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        self.dismissView()
    }))

    self.present(alert, animated: true)
}

func dismissView() {
    navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)
}

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).


On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

react-native :app:installDebug FAILED

As you add more modules to Android, there is an incredible demand placed on the Android build system, and the default memory settings will not work. To avoid OutOfMemory errors during Android builds, you should uncomment the alternate Gradle memory setting present in /android/gradle.properties:

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

Extract year from date

if all your dates are the same width, you can put the dates in a vector and use substring

Date
a <- c("01/01/2009", "01/01/2010" , "01/01/2011")
substring(a,7,10) #This takes string and only keeps the characters beginning in position 7 to position 10

output

[1] "2009" "2010" "2011"

How to change TextField's height and width?

To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.

Using request.setAttribute in a JSP page

Try

request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");

Oracle 'Partition By' and 'Row_Number' keyword

I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...

select a,b,rn 
  from (select a, b, row_number() over (partition by a,b order by a,b) as rn           
          from table) 
 where rn=1;

How to redirect to Index from another controller?

Complete answer (.Net Core 3.1)

Most answers here are correct but taken a bit out of context, so I will provide a full-fledged answer which works for Asp.Net Core 3.1. For completeness' sake:

[Route("health")]
[ApiController]
public class HealthController : Controller
{
    [HttpGet("some_health_url")]
    public ActionResult SomeHealthMethod() {}
}

[Route("v2")]
[ApiController]
public class V2Controller : Controller
{
    [HttpGet("some_url")]
    public ActionResult SomeV2Method()
    {
        return RedirectToAction("SomeHealthMethod", "Health"); // omit "Controller"
    }
}

If you try to use any of the url-specific strings, e.g. "some_health_url", it will not work!

For homebrew mysql installs, where's my.cnf?

You can find where the my.cnf file has been provided by the specific package, e.g.

brew list mysql # or: mariadb

In addition to verify if that file is read, you can run:

sudo fs_usage | grep my.cnf

which will show you filesystem activity in real-time related to that file.

onchange event on input type=range is not triggering in firefox while dragging

Yet another approach - just set a flag on an element signaling which type of event should be handled:

function setRangeValueChangeHandler(rangeElement, handler) {
    rangeElement.oninput = (event) => {
        handler(event);
        // Save flag that we are using onInput in current browser
        event.target.onInputHasBeenCalled = true;
    };

    rangeElement.onchange = (event) => {
        // Call only if we are not using onInput in current browser
        if (!event.target.onInputHasBeenCalled) {
            handler(event);
        }
    };
}

Do the parentheses after the type name make a difference with new?

Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • In C++1998 there are 2 types of initialization: zero and default
  • In C++2003 a 3rd type of initialization, value initialization was added.

Assume:

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

In a C++98 compiler, the following should occur:

  • new A - indeterminate value
  • new A() - zero-initialize

  • new B - default construct (B::m is uninitialized)

  • new B() - default construct (B::m is uninitialized)

  • new C - default construct (C::m is zero-initialized)

  • new C() - default construct (C::m is zero-initialized)

In a C++03 conformant compiler, things should work like so:

  • new A - indeterminate value
  • new A() - value-initialize A, which is zero-initialization since it's a POD.

  • new B - default-initializes (leaves B::m uninitialized)

  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

  • new C - default-initializes C, which calls the default ctor.

  • new C() - value-initializes C, which calls the default ctor.

So in all versions of C++ there's a difference between new A and new A() because A is a POD.

And there's a difference in behavior between C++98 and C++03 for the case new B().

This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.

NSString with \n or line break

try this ( stringWithFormat has to start with lowercase)

 [NSString stringWithFormat:@"%@\n%@",string1,string2];

How to compare values which may both be null in T-SQL

Equals comparison:

((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))

Not Equal To comparison: Just negate the Equals comparison above.

NOT ((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))

Is it verbose? Yes, it is. However it's efficient since it doesn't call any function. The idea is to use short circuit in predicates to make sure the equal operator (=) is used only with non-null values, otherwise null would propagate up in the expression tree.

How to change color of the back arrow in the new material theme?

Solution is very simple

Just put following line into your style named as AppTheme

<item name="colorControlNormal">@color/white</item>

Now your whole xml code will look like shown below (default style).

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="colorPrimary">#0F0F0F</item>
        <item name="android:statusBarColor">#EEEEF0</item>
        <item name="android:windowLightStatusBar">true</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowActivityTransitions">true</item>

        <item name="colorControlNormal">@color/white</item>
</style>

Understanding Matlab FFT example

The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.

Keras model.summary() result - Understanding the # of Parameters

The number of parameters is 7850 because with every hidden unit you have 784 input weights and one weight of connection with bias. This means that every hidden unit gives you 785 parameters. You have 10 units so it sums up to 7850.

The role of this additional bias term is really important. It significantly increases the capacity of your model. You can read details e.g. here Role of Bias in Neural Networks.

Substitute multiple whitespace with single whitespace in Python

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split())

The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).

define a List like List<int,string>?

With the new ValueTuple from C# 7 (VS 2017 and above), there is a new solution:

List<(int,string)> mylist= new List<(int,string)>();

Which creates a list of ValueTuple type. If you're targeting .Net Framework 4.7+ or .Net Core, it's native, otherwise you have to get the ValueTuple package from nuget.

It's a struct opposing to Tuple, which is a class. It also has the advantage over the Tuple class that you could create a named tuple, like this:

var mylist = new List<(int myInt, string myString)>();

That way you can access like mylist[0].myInt and mylist[0].myString

'LIKE ('%this%' OR '%that%') and something=else' not working

Try something like:

WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

If you're using mariadb, you have to modify the mariadb.cnf file located in /etc/mysql/conf.d/.

I supposed the stuff is the same for any other my-sql based solutions.

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

How to do the Recursive SELECT query in MySQL?

If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.

I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.

DELIMITER $$

CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC    
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;

WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
    SET lastParent = curParent;
    SELECT ParentId from `test` where id=curId limit 1 into curParent;

    IF curParent = pParentId THEN
        SET isChild = 1;
    END IF;
    SET curId = curParent;
END WHILE;

RETURN isChild;
END$$

Here, the table test has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.

Usage :

SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;

Result :

3   7   k
5   3   d
9   3   f
1   5   a

SQL for test creation :

CREATE TABLE IF NOT EXISTS `test` (
  `Id` int(11) NOT NULL,
  `ParentId` int(11) DEFAULT NULL,
  `Name` varchar(300) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');

EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.

How to use OpenCV SimpleBlobDetector

Python: Reads image blob.jpg and performs blob detection with different parameters.

#!/usr/bin/python

# Standard imports
import cv2
import numpy as np;

# Read image
im = cv2.imread("blob.jpg")

# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

# Change thresholds
params.minThreshold = 10
params.maxThreshold = 200


# Filter by Area.
params.filterByArea = True
params.minArea = 1500

# Filter by Circularity
params.filterByCircularity = True
params.minCircularity = 0.1

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.87

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.01

# Create a detector with the parameters
detector = cv2.SimpleBlobDetector(params)


# Detect blobs.
keypoints = detector.detect(im)

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures
# the size of the circle corresponds to the size of blob

im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show blobs
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)

C++: Reads image blob.jpg and performs blob detection with different parameters.

#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    // Read image
#if CV_MAJOR_VERSION < 3   // If you are using OpenCV 2
    Mat im = imread("blob.jpg", CV_LOAD_IMAGE_GRAYSCALE);
#else
    Mat im = imread("blob.jpg", IMREAD_GRAYSCALE);
#endif

    // Setup SimpleBlobDetector parameters.
    SimpleBlobDetector::Params params;

    // Change thresholds
    params.minThreshold = 10;
    params.maxThreshold = 200;

    // Filter by Area.
    params.filterByArea = true;
    params.minArea = 1500;

    // Filter by Circularity
    params.filterByCircularity = true;
    params.minCircularity = 0.1;

    // Filter by Convexity
    params.filterByConvexity = true;
    params.minConvexity = 0.87;

    // Filter by Inertia
    params.filterByInertia = true;
    params.minInertiaRatio = 0.01;

    // Storage for blobs
    std::vector<KeyPoint> keypoints;

#if CV_MAJOR_VERSION < 3   // If you are using OpenCV 2

    // Set up detector with params
    SimpleBlobDetector detector(params);

    // Detect blobs
    detector.detect(im, keypoints);
#else 

    // Set up detector with params
    Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params);

    // Detect blobs
    detector->detect(im, keypoints);
#endif 

    // Draw detected blobs as red circles.
    // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures
    // the size of the circle corresponds to the size of blob

    Mat im_with_keypoints;
    drawKeypoints(im, keypoints, im_with_keypoints, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);

    // Show blobs
    imshow("keypoints", im_with_keypoints);
    waitKey(0);
}

The answer has been copied from this tutorial I wrote at LearnOpenCV.com explaining various parameters of SimpleBlobDetector. You can find additional details about the parameters in the tutorial.

How to remove unused imports in Intellij IDEA on commit?

When you commit, tick the Optimize imports option on the right. This will become the default until you change it.

I prefer using the Reformat code option as well.

how does Array.prototype.slice.call() work?

Normally, calling

var b = a.slice();

will copy the array a into b. However, we can't do

var a = arguments.slice();

because arguments isn't a real array, and doesn't have slice as a method. Array.prototype.slice is the slice function for arrays, and call runs the function with this set to arguments.

Printing one character at a time from a string, using the while loop

   # make a list out of text - ['h','e','l','l','o']
   text = list('hello') 

   while text:
       print text.pop()

:)

In python empty object are evaluated as false. The .pop() removes and returns the last item on a list. And that's why it prints on reverse !

But can be fixed by using:

text.pop( 0 )

Drop rows containing empty cells from a pandas DataFrame

There's a situation where the cell has white space, you can't see it, use

df['col'].replace('  ', np.nan, inplace=True)

to replace white space as NaN, then

df= df.dropna(subset=['col'])

How to initialize an array's length in JavaScript?

(this was probably better as a comment, but got too long)

So, after reading this I was curious if pre-allocating was actually faster, because in theory it should be. However, this blog gave some tips advising against it http://www.html5rocks.com/en/tutorials/speed/v8/.

So still being unsure, I put it to the test. And as it turns out it seems to in fact be slower.

var time = Date.now();
var temp = [];
for(var i=0;i<100000;i++){
    temp[i]=i;
}
console.log(Date.now()-time);


var time = Date.now();
var temp2 = new Array(100000);
for(var i=0;i<100000;i++){
    temp2[i] = i;
}
console.log(Date.now()-time); 

This code yields the following after a few casual runs:

$ node main.js 
9
16
$ node main.js 
8
14
$ node main.js 
7
20
$ node main.js 
9
14
$ node main.js 
9
19

Database development mistakes made by application developers

1) Poor understanding of how to properly interact between Java and the database.

2) Over parsing, improper or no reuse of SQL

3) Failing to use BIND variables

4) Implementing procedural logic in Java when SQL set logic in the database would have worked (better).

5) Failing to do any reasonable performance or scalability testing prior to going into production

6) Using Crystal Reports and failing to set the schema name properly in the reports

7) Implementing SQL with Cartesian products due to ignorance of the execution plan (did you even look at the EXPLAIN PLAN?)

Get an object's class name at runtime

In Angular2, this can help to get components name:

    getName() {
        let comp:any = this.constructor;
        return comp.name;
    }

comp:any is needed because TypeScript compiler will issue errors since Function initially does not have property name.

Array of Matrices in MATLAB

Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);
    end
end

To use it:

myArray = createArrays(requiredNumberOfArrays, [500 800]);

And to access your elements:

myArray{1}(2,3) = 10;

If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:

myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end

How to list only the file names that changed between two commits?

To supplement @artfulrobot's answer, if you want to show changed files between two branches:

git diff --name-status mybranch..myotherbranch

Be careful on precedence. If you place the newer branch first then it would show files as deleted rather than added.

Adding a grep can refine things further:

git diff --name-status mybranch..myotherbranch | grep "A\t"

That will then show only files added in myotherbranch.

How can I find whitespace in a String?

For checking if a string contains whitespace use a Matcher and call it's find method.

Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();

If you want to check if it only consists of whitespace then you can use String.matches:

boolean isWhitespace = s.matches("^\\s*$");

Is putting a div inside an anchor ever correct?

You can't put <div> inside <a> - it's not valid (X)HTML.

Even though you style a span with display: block you still can't put block-level elements inside it: the (X)HTML still has to obey the (X)HTML DTD (whichever one you use), no matter how the CSS alters things.

The browser will probably display it as you want, but that doesn't make it right.

Error in setting JAVA_HOME

JAVA_HOME = C:\Program Files\Java\jdk(JDK version number)

Example: C:\Program Files\Java\jdk-10

And then restart you command prompt it works.

C# Foreach statement does not contain public definition for GetEnumerator

Your CarBootSaleList class is not a list. It is a class that contain a list.

You have three options:

Make your CarBootSaleList object implement IEnumerable

or

make your CarBootSaleList inherit from List<CarBootSale>

or

if you are lazy this could almost do the same thing without extra coding

List<List<CarBootSale>>

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Adding java.util.list will resolve your problem because List interface which you are trying to use is part of java.util.list package.

Pandas: Looking up the list of sheets in an excel file

You can still use the ExcelFile class (and the sheet_names attribute):

xl = pd.ExcelFile('foo.xls')

xl.sheet_names  # see all sheet names

xl.parse(sheet_name)  # read a specific sheet to DataFrame

see docs for parse for more options...

Is there any native DLL export functions viewer?

DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.

This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.

enter image description here

Returning an empty array

Both foo() and bar() may generate warnings in some IDEs. For example, IntelliJ IDEA will generate a Allocation of zero-length array warning.

An alternative approach is to use Apache Commons Lang 3 ArrayUtils.toArray() function with empty arguments:

public File[] bazz() {
    return ArrayUtils.toArray();
}

This approach is both performance and IDE friendly, yet requires a 3rd party dependency. However, if you already have commons-lang3 in your classpath, you could even use statically-defined empty arrays for primitive types:

public String[] bazz() {
    return ArrayUtils.EMPTY_STRING_ARRAY;
}

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Concatenate string with field value in MySQL

MySQL uses CONCAT() to concatenate strings

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

Trigger css hover with JS

I don't think what your asking is possible.

See: Hover Item with JQuery

Basically, adding a class is the only way to accomplish this that I am aware of.

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

You can do like

HTML in PHP :

<?php
     echo "<table>";
     echo "<tr>";
     echo "<td>Name</td>";
     echo "<td>".$name."</td>";
     echo "</tr>";
     echo "</table>";
?>

Or You can write like.

PHP in HTML :

<?php /*Do some PHP calculation or something*/ ?>
     <table>
         <tr>
             <td>Name</td>
             <td><?php echo $name;?></td>
         </tr>
     </table>


<?php /*Do some PHP calculation or something*/ ?> Means:
You can open a PHP tag with <?php, now add your PHP code, then close the tag with ?> and then write your html code. When needed to add more PHP, just open another PHP tag with <?php.

What does $ mean before a string?

$ is short-hand for String.Format and is used with string interpolations, which is a new feature of C# 6. As used in your case, it does nothing, just as string.Format() would do nothing.

It is comes into its own when used to build strings with reference to other values. What previously had to be written as:

var anInt = 1;
var aBool = true;
var aString = "3";
var formated = string.Format("{0},{1},{2}", anInt, aBool, aString);

Now becomes:

var anInt = 1;
var aBool = true;
var aString = "3";
var formated = $"{anInt},{aBool},{aString}";

There's also an alternative - less well known - form of string interpolation using $@ (the order of the two symbols is important). It allows the features of a @"" string to be mixed with $"" to support string interpolations without the need for \\ throughout your string. So the following two lines:

var someDir = "a";
Console.WriteLine($@"c:\{someDir}\b\c");

will output:

c:\a\b\c

Manifest Merger failed with multiple errors in Android Studio

Simple Answer Cross Check :

You might be defined Same Activity multiple times in the manifest.xml file.

OR

Activity or service or receiver you have defined in the manifest.xml file which is not in your project structure.

Maven dependency update on commandline

mvn clean install -U

-U means force update of dependencies.

Also, if you want to import the project into eclipse, I first run:

mvn eclipse:eclipse

then run

mvn eclipse:clean

Seems to work for me, but that's just my pennies worth.

Sending event when AngularJS finished loading

If you don't use ngRoute module, i.e. you don't have $viewContentLoaded event.

You can use another directive method:

    angular.module('someModule')
        .directive('someDirective', someDirective);

    someDirective.$inject = ['$rootScope', '$timeout']; //Inject services

    function someDirective($rootScope, $timeout){
        return {
            restrict: "A",
            priority: Number.MIN_SAFE_INTEGER, //Lowest priority
            link    : function(scope, element, attr){
                $timeout(
                    function(){
                        $rootScope.$emit("Some:event");
                    }
                );
            }
        };
    }

Accordingly to trusktr's answer it has lowest priority. Plus $timeout will cause Angular to run through an entire event loop before callback execution.

$rootScope used, because it allow to place directive in any scope of the application and notify only necessary listeners.

$rootScope.$emit will fire an event for all $rootScope.$on listeners only. The interesting part is that $rootScope.$broadcast will notify all $rootScope.$on as well as $scope.$on listeners Source

CSS Background image not loading

I had the same issue. The problem ended up being the path to the image file. Make sure the image path is relative to the location of the CSS file instead of the HTML.

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

Reasons for using the set.seed function

Fixing the seed is essential when we try to optimize a function that involves randomly generated numbers (e.g. in simulation based estimation). Loosely speaking, if we do not fix the seed, the variation due to drawing different random numbers will likely cause the optimization algorithm to fail.

Suppose that, for some reason, you want to estimate the standard deviation (sd) of a mean-zero normal distribution by simulation, given a sample. This can be achieved by running a numerical optimization around steps

  1. (Setting the seed)
  2. Given a value for sd, generate normally distributed data
  3. Evaluate the likelihood of your data given the simulated distributions

The following functions do this, once without step 1., once including it:

# without fixing the seed
simllh <- function(sd, y, Ns){
  simdist <- density(rnorm(Ns, mean = 0, sd = sd))
  llh <- sapply(y, function(x){ simdist$y[which.min((x - simdist$x)^2)] })
  return(-sum(log(llh)))
}
# same function with fixed seed
simllh.fix.seed <- function(sd,y,Ns){
  set.seed(48)
  simdist <- density(rnorm(Ns,mean=0,sd=sd))
  llh <- sapply(y,function(x){simdist$y[which.min((x-simdist$x)^2)]})
  return(-sum(log(llh)))
}

We can check the relative performance of the two functions in discovering the true parameter value with a short Monte Carlo study:

N <- 20; sd <- 2 # features of simulated data
est1 <- rep(NA,1000); est2 <- rep(NA,1000) # initialize the estimate stores
for (i in 1:1000) {
  as.numeric(Sys.time())-> t; set.seed((t - floor(t)) * 1e8 -> seed) # set the seed to random seed
  y <- rnorm(N, sd = sd) # generate the data
  est1[i] <- optim(1, simllh, y = y, Ns = 1000, lower = 0.01)$par
  est2[i] <- optim(1, simllh.fix.seed, y = y, Ns = 1000, lower = 0.01)$par
}
hist(est1)
hist(est2)

The resulting distributions of the parameter estimates are:

Histogram of parameter estimates without fixing the seed Histogram of parameter estimates fixing the seed

When we fix the seed, the numerical search ends up close to the true parameter value of 2 far more often.

How to delete a localStorage item when the browser window/tab is closed?

should be done like that and not with delete operator:

localStorage.removeItem(key);

Difference between application/x-javascript and text/javascript content types

Use type="application/javascript"

In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.

http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Use "application/javascript", because "text/javascript" is obsolete:

RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt

  1. Deployed Scripting Media Types and Compatibility

    Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:

    +-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+

Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.

x-javascript is experimental, don't use it.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

Annoyingly enough, if you want to use the default model binders, it looks like you will have to use numerical index values like a form POST.

See the following excerpt from this article http://msdn.microsoft.com/en-us/magazine/hh781022.aspx:

Though it’s somewhat counterintuitive, JSON requests have the same requirements—they, too, must adhere to the form post naming syntax. Take, for example, the JSON payload for the previous UnitPrice collection. The pure JSON array syntax for this data would be represented as:

[ 
  { "Code": "USD", "Amount": 100.00 },
  { "Code": "EUR", "Amount": 73.64 }
]

However, the default value providers and model binders require the data to be represented as a JSON form post:

{
  "UnitPrice[0].Code": "USD",
  "UnitPrice[0].Amount": 100.00,

  "UnitPrice[1].Code": "EUR",
  "UnitPrice[1].Amount": 73.64
}

The complex object collection scenario is perhaps one of the most widely problematic scenarios that developers run into because the syntax isn’t necessarily evident to all developers. However, once you learn the relatively simple syntax for posting complex collections, these scenarios become much easier to deal with.

How can I find matching values in two arrays?

I found a slight alteration on what @jota3 suggested worked perfectly for me.

var intersections = array1.filter(e => array2.indexOf(e) !== -1);

Hope this helps!

First letter capitalization for EditText

Earlier it used to be android:capitalize="words", which is now deprecated. The recommended alternative is to use android:inputType="textCapWords"

Please note that this will only work if your device keyboard Auto Capitalize Setting enabled.

To do this programatically, use the following method:

setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);

no suitable HttpMessageConverter found for response type

You could also simply tell your RestTemplate to accept all media types:

@Bean
public RestTemplate restTemplate() {
   final RestTemplate restTemplate = new RestTemplate();

   List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
   MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
   converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
   messageConverters.add(converter);
   restTemplate.setMessageConverters(messageConverters);

   return restTemplate;
}

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

For 2020.1.4 Ultimate edition, I had to do the following

View -> Maven -> Generate Sources and Update Folders For all Projects

The issue for me was the libraries were not getting populated with mvn -U clean install from the terminal.

enter image description here

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

How do I create a constant in Python?

A tuple technically qualifies as a constant, as a tuple will raise an error if you try to change one of its values. If you want to declare a tuple with one value, then place a comma after its only value, like this:

my_tuple = (0 """Or any other value""",)

To check this variable's value, use something similar to this:

if my_tuple[0] == 0:
    #Code goes here

If you attempt to change this value, an error will be raised.

How to insert a newline in front of a pattern?

This works in MAC for me

sed -i.bak -e 's/regex/xregex/g' input.txt sed -i.bak -e 's/qregex/\'$'\nregex/g' input.txt

Dono whether its perfect one...

Can't use WAMP , port 80 is used by IIS 7.5

This happens to me once: I uninstalled the IIS, and the port 80 still was used. Well the problem was that also I had the Report Service of the Sql Server 2012 installed, so I stopped that service and the problems solves.

See Stop Or Uninstall IIS for running Wamp Server (Apache) on default port (:80) question for more details.

Hope this helps some body, as it help to me.

How to get back Lost phpMyAdmin Password, XAMPP

There is a batch file called resetroot.bat located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin passwords. Then all you need to do is start the MySQL service in xamp and click the admin button.

How to pass parameters to a partial view in ASP.NET MVC?

make sure you add {} around Html.RenderPartial, as:

@{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});}

not

@Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});

CURL Command Line URL Parameters

The application/x-www-form-urlencoded Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:

curl -X DELETE "http://localhost:5000/locations?id=3"

or

curl -X GET "http://localhost:5000/locations?id=3"

What does -Xmn jvm option stands for

-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .

Good size is 33%

Source

PHP output showing little black diamonds with a question mark

You can also change the caracter set in your browser. Just for debug reasons.

Android sqlite how to check if a record exists

These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.

Additionally:
You can get an error when searching by String that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40". Those dashes (-) will cause an unrecognized token error. You can overcome this by putting the string in an array. So make it a habit to query like this:

public boolean hasObject(String id) {
    SQLiteDatabase db = getWritableDatabase();
    String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";

    // Add the String you are searching by here. 
    // Put it in an array to avoid an unrecognized token error 
    Cursor cursor = db.rawQuery(selectString, new String[] {id}); 

    boolean hasObject = false;
    if(cursor.moveToFirst()){
        hasObject = true;

        //region if you had multiple records to check for, use this region. 

        int count = 0;
        while(cursor.moveToNext()){
          count++;
        }
        //here, count is records found
        Log.d(TAG, String.format("%d records found", count));

        //endregion

    } 

    cursor.close();          // Dont forget to close your cursor
    db.close();              //AND your Database!
    return hasObject;
}

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

Squash the first two commits in Git?

Squashing the first and second commit would result in the first commit being rewritten. If you have more than one branch that is based off the first commit, you'd cut off that branch.

Consider the following example:

a---b---HEAD
 \
  \
   '---d

Squashing a and b into a new commit "ab" would result in two distinct trees which in most cases is not desirable since git-merge and git-rebase will no longer work across the two branches.

ab---HEAD

a---d

If you really want this, it can be done. Have a look at git-filter-branch for a powerful (and dangerous) tool for history rewriting.

Web colors in an Android color xml resource file

I specifically was looking for the XML representation for Android.Graphics.Color. I didn't find these, so here you are. More details are in the help document.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="sysBlack">#FF000000</color>
    <color name="sysBlue">#FF0000FF</color>
    <color name="sysCyan">#FF00FFFF</color>
    <color name="sysDkGray">#FF444444</color>
    <color name="sysGray">#FF888888</color>
    <color name="sysGreen">#FF00FF00</color>
    <color name="sysLtGray">#FFCCCCCC</color>
    <color name="sysMagenta">#FFFF00FF</color>
    <color name="sysRed">#FFFF0000</color>
    <color name="sysTransparent">#00000000</color>
    <color name="sysWhite">#FFFFFFFF</color>
    <color name="sysYellow">#FFFFFF00</color>
</resources>

Of course, this is used like this:

android:textColor="@color/sysGray"

How to initialize var?

This is the way how to intialize value to var variable

var _myVal = (dynamic)null; 

Remove carriage return from string

How about using a Regex?

var result = Regex.Replace(input, "\r\n", String.Empty)

If you just want to remove the new line at the very end use this

var result = Regex.Replace(input, "\r\n$", String.Empty)

How to solve javax.net.ssl.SSLHandshakeException Error?

I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..

ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...

Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )

In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..

I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...

P.S I cant get source code before the weekend since external SSH is disabled in my office :(

How does the communication between a browser and a web server take place?

There is a commercial product with an interesting logo which lets you see all kind of traffic between server and client named charles.

Another open source tools include: Live HttpHeaders, Wireshark or Firebug.

How do I get the value of a textbox using jQuery?

Per Jquery docs

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

In order to retrieve the value store in the text box with id txtEmail, you can use

$("#txtEmail").val()

HTML Text with tags to formatted text in an Excel cell

Nice! Very slick.

I was disappointed that Excel doesn't let us paste to a merged cell and also pastes results containing a break into successive rows below the "target" cell though, as that meant it simply doesn't work for me. I tried a few tweaks (unmerge/remerge, etc.) but then Excel dropped anything below a break, so that was a dead end.

Ultimately, I came up with a routine that'll handle simple tags and not use the "native" Unicode converter that is causing the issue with merged fields. Hope others find this useful:

Public Sub AddHTMLFormattedText(rngA As Range, strHTML As String, Optional blnShowBadHTMLWarning As Boolean = False)
    ' Adds converts text formatted with basic HTML tags to formatted text in an Excel cell
    ' NOTE: Font Sizes not handled perfectly per HTML standard, but I find this method more useful!

    Dim strActualText As String, intSrcPos As Integer, intDestPos As Integer, intDestSrcEquiv() As Integer
    Dim varyTags As Variant, varTag As Variant, varEndTag As Variant, blnTagMatch As Boolean
    Dim intCtr As Integer
    Dim intStartPos As Integer, intEndPos As Integer, intActualStartPos As Integer, intActualEndPos As Integer
    Dim intFontSizeStartPos As Integer, intFontSizeEndPos As Integer, intFontSize As Integer

    varyTags = Array("<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<sub>", "</sub>", "<sup>", "</sup>")

    ' Remove unhandled/unneeded tags, convert <br> and <p> tags to line feeds
    strHTML = Trim(strHTML)
    strHTML = Replace(strHTML, "<html>", "")
    strHTML = Replace(strHTML, "</html>", "")
    strHTML = Replace(strHTML, "<p>", "")
    While LCase(Right$(strHTML, 4)) = "</p>" Or LCase(Right$(strHTML, 4)) = "<br>"
        strHTML = Left$(strHTML, Len(strHTML) - 4)
        strHTML = Trim(strHTML)
    Wend
    strHTML = Replace(strHTML, "<br>", vbLf)
    strHTML = Replace(strHTML, "</p>", vbLf)

    strHTML = Trim(strHTML)

    ReDim intDestSrcEquiv(1 To Len(strHTML))
    strActualText = ""
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        blnTagMatch = False
        For Each varTag In varyTags
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intSrcPos = intSrcPos + Len(varTag)
                If intSrcPos > Len(strHTML) Then Exit Do
                Exit For
            End If
        Next
        If blnTagMatch = False Then
            varTag = "<font size"
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intEndPos = InStr(intSrcPos, strHTML, ">")
                intSrcPos = intEndPos + 1
                If intSrcPos > Len(strHTML) Then Exit Do
            Else
                varTag = "</font>"
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    blnTagMatch = True
                    intSrcPos = intSrcPos + Len(varTag)
                    If intSrcPos > Len(strHTML) Then Exit Do
                End If
            End If
        End If
        If blnTagMatch = False Then
            strActualText = strActualText & Mid$(strHTML, intSrcPos, 1)
            intDestSrcEquiv(intSrcPos) = intDestPos
            intDestPos = intDestPos + 1
            intSrcPos = intSrcPos + 1
        End If
    Loop

    ' Clear any bold/underline/italic/superscript/subscript formatting from cell
    rngA.Font.Bold = False
    rngA.Font.Underline = False
    rngA.Font.Italic = False
    rngA.Font.Subscript = False
    rngA.Font.Superscript = False

    rngA.Value = strActualText

    ' Now start applying Formats!"
    ' Start with Font Size first
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        varTag = "<font size"
        If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
            intFontSizeStartPos = InStr(intSrcPos, strHTML, """") + 1
            intFontSizeEndPos = InStr(intFontSizeStartPos, strHTML, """") - 1
            If intFontSizeEndPos - intFontSizeStartPos <= 3 And intFontSizeEndPos - intFontSizeStartPos > 0 Then
                Debug.Print Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                If Mid$(strHTML, intFontSizeStartPos, 1) = "+" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 + 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                ElseIf Mid$(strHTML, intFontSizeStartPos, 1) = "-" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 - 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                Else
                    intFontSize = Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                End If
            Else
                ' Error!
                GoTo HTML_Err
            End If
            intEndPos = InStr(intSrcPos, strHTML, ">")
            intSrcPos = intEndPos + 1
            intStartPos = intSrcPos
            If intSrcPos > Len(strHTML) Then Exit Do
            While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                intStartPos = intStartPos + 1
            Wend
            If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
            varEndTag = "</font>"
            intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
            If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
            While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                intEndPos = intEndPos - 1
            Wend
            If intEndPos > intSrcPos Then
                intActualStartPos = intDestSrcEquiv(intStartPos)
                intActualEndPos = intDestSrcEquiv(intEndPos)
                rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1) _
                    .Font.Size = intFontSize
            End If
        End If
        intSrcPos = intSrcPos + 1
    Loop

    'Now do remaining tags
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        If intDestSrcEquiv(intSrcPos) = 0 Then
            ' This must be a Tag!
            For intCtr = 0 To UBound(varyTags) Step 2
                varTag = varyTags(intCtr)
                intStartPos = intSrcPos + Len(varTag)
                While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                    intStartPos = intStartPos + 1
                Wend
                If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    varEndTag = varyTags(intCtr + 1)
                    intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
                    If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
                    While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                        intEndPos = intEndPos - 1
                    Wend
                    If intEndPos > intSrcPos Then
                        intActualStartPos = intDestSrcEquiv(intStartPos)
                        intActualEndPos = intDestSrcEquiv(intEndPos)
                        With rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1).Font
                            If varTag = "<b>" Then
                                .Bold = True
                            ElseIf varTag = "<i>" Then
                                .Italic = True
                            ElseIf varTag = "<u>" Then
                                .Underline = True
                            ElseIf varTag = "<sup>" Then
                                .Superscript = True
                            ElseIf varTag = "<sub>" Then
                                .Subscript = True
                            End If
                        End With
                    End If
                    intSrcPos = intSrcPos + Len(varTag) - 1
                    Exit For
                End If
            Next
        End If
        intSrcPos = intSrcPos + 1
        intDestPos = intDestPos + 1
    Loop
Exit_Sub:
    Exit Sub
HTML_Err:
    ' There was an error with the Tags. Show warning if requested.
    If blnShowBadHTMLWarning Then
        MsgBox "There was an error with the Tags in the HTML file. Could not apply formatting."
    End If
End Sub

Note this doesn't care about tag nesting, instead only requiring a close tag for every open tag, and assuming the close tag nearest the opening tag applies to the opening tag. Properly nested tags will work fine, while improperly nested tags will not be rejected and may or may not work.

How can I explicitly free memory in Python?

The del statement might be of use, but IIRC it isn't guaranteed to free the memory. The docs are here ... and a why it isn't released is here.

I have heard people on Linux and Unix-type systems forking a python process to do some work, getting results and then killing it.

This article has notes on the Python garbage collector, but I think lack of memory control is the downside to managed memory

Scaling an image to fit on canvas

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

Submit form and stay on same page?

When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.

Creating a list/array in excel using VBA to get a list of unique names in a column

I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.

Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes

How do I get the browser scroll position in jQuery?

It's better to use $(window).scroll() rather than $('#Eframe').on("mousewheel")

$('#Eframe').on("mousewheel") will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.

$(window).scroll(function(){
    var scrollPos = $(document).scrollTop();
    console.log(scrollPos);
});

If #Eframe is an element with overflow:scroll on it and you want it's scroll position. I think this should work (I haven't tested it though).

$('#Eframe').scroll(function(){
    var scrollPos = $('#Eframe').scrollTop();
    console.log(scrollPos);
});

Difference between WebStorm and PHPStorm

In my own experience, even though theoretically many JetBrains products share the same functionalities, the new features that get introduced in some apps don't get immediately introduced in the others. In particular, IntelliJ IDEA has a new version once per year, while WebStorm and PHPStorm get 2 to 3 per year I think. Keep that in mind when choosing an IDE. :)

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

This Works for me.

  1. Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
  2. In newly opened screen of Login Properties, go to the “User Mapping” tab.
  3. Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
  4. Click OK.

Read this blog.

http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/

LINQ: Select an object and change some properties without creating a new object

If you want to update items with a Where clause, using a .Where(...) will truncate your results if you do:

mylist = mylist.Where(n => n.Id == ID).Select(n => { n.Property = ""; return n; }).ToList();

You can do updates to specific item(s) in the list like so:

mylist = mylist.Select(n => { if (n.Id == ID) { n.Property = ""; } return n; }).ToList();

Always return item even if you don't make any changes. This way it will be kept in the list.

Determine the size of an InputStream

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

Initialising mock objects - MockIto

There is a neat way of doing this.

  • If it's an Unit Test you can do this:

    @RunWith(MockitoJUnitRunner.class)
    public class MyUnitTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Test
        public void testSomething() {
        }
    }
    
  • EDIT: If it's an Integration test you can do this(not intended to be used that way with Spring. Just showcase that you can initialize mocks with diferent Runners):

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("aplicationContext.xml")
    public class MyIntegrationTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Before
        public void setUp() throws Exception {
              MockitoAnnotations.initMocks(this);
        }
    
        @Test
        public void testSomething() {
        }
    }
    

What is the HTML5 equivalent to the align attribute in table cells?

Add this code into your StyleSheet:

margin-top:80px;

Create an array with same element repeated multiple times

If you need to repeat an array, use the following.

Array(3).fill(['a','b','c']).flat() 

will return

Array(9) [ "a", "b", "c", "a", "b", "c", "a", "b", "c" ]

Remove the last line from a file in Bash

For Mac Users :

On Mac, head -n -1 wont work. And, I was trying to find a simple solution [ without worrying about processing time ] to solve this problem only using "head" and/or "tail" commands.

I tried the following sequence of commands and was happy that I could solve it just using "tail" command [ with the options available on Mac ]. So, if you are on Mac, and want to use only "tail" to solve this problem, you can use this command :

cat file.txt | tail -r | tail -n +2 | tail -r

Explanation :

1> tail -r : simply reverses the order of lines in its input

2> tail -n +2 : this prints all the lines starting from the second line in its input

How can I jump to class/method definition in Atom text editor?

For Typescript users, the "atom-typescript" package adds a typescript aware symbols view, you can trigger it with Cmd+R, and it works great to jump to methods-

https://atom.io/packages/atom-typescript#alternative-to-symbols-view

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

Font Awesome & Unicode

You can also use the FontAwesome icon with the CSS3 pseudo selector as shown below. enter image description here

Ensure to set the font-family to FontAwesome as shown below:

table.dataTable thead th.sorting:after {font-family: FontAwesome;}

To get the above working, you must do the following:

  1. Download the FontAwesome css library here FontAwesome v4.7.0
  2. Extract from the zip file and include into your app root folder, the two folders as shown below: enter image description here
  3. Reference only the css folder in the <head></head> section of your app as shown below: enter image description here

jQuery Validation using the class instead of the name value

Here's the solution using jQuery:

    $().ready(function () {
        $(".formToValidate").validate();
        $(".checkBox").each(function (item) {
            $(this).rules("add", {
                required: true,
                minlength:3
            });
        });
    });

java.util.NoSuchElementException: No line found

For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:

Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How do I get the time of day in javascript/Node.js?

Both prior answers are definitely good solutions. If you're amenable to a library, I like moment.js - it does a lot more than just getting/formatting the date.

Click button copy to clipboard using jQuery

Both will works like a charm :),

JAVASCRIPT:

function CopyToClipboard(containerid) {
if (document.selection) { 
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select().createTextRange();
    document.execCommand("copy"); 

} else if (window.getSelection) {
    var range = document.createRange();
     range.selectNode(document.getElementById(containerid));
     window.getSelection().addRange(range);
     document.execCommand("copy");
     alert("text copied") 
}}

Also in html,

<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

<div id="div1" >Text To Copy </div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

JQUERY: https://paulund.co.uk/jquery-copy-clipboard

How to use an existing database with an Android application

You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.

shared global variables in C

In the header file

header file

#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef  MAIN_FILE
int global;
#else
extern int global;
#endif
#endif

In the file with the file you want the global to live:

#define MAIN_FILE
#include "share.h"

In the other files that need the extern version:

#include "share.h"

Sending credentials with cross-domain posts?

You can use the beforeSend callback to set additional parameters (The XMLHTTPRequest object is passed to it as its only parameter).

Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:

$.ajax({
    url: 'http://bar.other',
    data: { whatever:'cool' },
    type: 'GET',
    beforeSend: function(xhr){
       xhr.withCredentials = true;
    }
});

One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.

Is there any difference between "!=" and "<>" in Oracle Sql?

At university we were taught 'best practice' was to use != when working for employers, though all the operators above have the same functionality.

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

Trusting all certificates using HttpClient over HTTPS

Add this code before the HttpsURLConnection and it will be done. I got it.

private void trustEveryone() { 
    try { 
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){ 
                    public boolean verify(String hostname, SSLSession session) { 
                            return true; 
                    }}); 
            SSLContext context = SSLContext.getInstance("TLS"); 
            context.init(null, new X509TrustManager[]{new X509TrustManager(){ 
                    public void checkClientTrusted(X509Certificate[] chain, 
                                    String authType) throws CertificateException {} 
                    public void checkServerTrusted(X509Certificate[] chain, 
                                    String authType) throws CertificateException {} 
                    public X509Certificate[] getAcceptedIssuers() { 
                            return new X509Certificate[0]; 
                    }}}, new SecureRandom()); 
            HttpsURLConnection.setDefaultSSLSocketFactory( 
                            context.getSocketFactory()); 
    } catch (Exception e) { // should never happen 
            e.printStackTrace(); 
    } 
} 

I hope this helps you.

Sample random rows in dataframe

EDIT: This answer is now outdated, see the updated version.

In my R package I have enhanced sample so that it now behaves as expected also for data frames:

library(devtools); install_github('kimisc', 'krlmlr')

library(kimisc)
example(sample.data.frame)

smpl..> set.seed(42)

smpl..> sample(data.frame(a=c(1,2,3), b=c(4,5,6),
                           row.names=c('a', 'b', 'c')), 10, replace=TRUE)
    a b
c   3 6
c.1 3 6
a   1 4
c.2 3 6
b   2 5
b.1 2 5
c.3 3 6
a.1 1 4
b.2 2 5
c.4 3 6

This is achieved by making sample an S3 generic method and providing the necessary (trivial) functionality in a function. A call to setMethod fixes everything. The original implementation still can be accessed through base::sample.

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Well if you know the order of your words.. you can use:

SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'

Also you can use:

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'

React-Native: Module AppRegistry is not a registered callable module

I solved this issue just by adding

import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";  
AppRegistry.registerComponent(appName, () => App);

to my index.js

make sure this exists in your index.js

Have a div cling to top of screen if scrolled down past it

The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.

Derived from the code viixii.com uses I ended up using this:

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top)
        $('#sticky-element').addClass('sticky');
    else
        $('#sticky-element').removeClass('sticky');
}

$(function() {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.

Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.

Just place an empty div with a class acting like an anchor just above the element you want to have fixed.

Like so:

<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>

All credit for the code goes to viixii.com

Programmatically check Play Store for app updates

There's AppUpdater library. How to include:

  1. Add the repository to your project build.gradle:
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://jitpack.io"
        }
    }
}
  1. Add the library to your module build.gradle:
dependencies {
    compile 'com.github.javiersantos:AppUpdater:2.6.4'
}
  1. Add INTERNET and ACCESS_NETWORK_STATE permissions to your app's Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  1. Add this to your activity:
AppUpdater appUpdater = new AppUpdater(this); 
appUpdater.start();

xpath find if node exists

Try the following expression: boolean(path-to-node)

How to check if a Constraint exists in Sql server?

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))
 BEGIN 
ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
END 

How can I make robocopy silent in the command line except for progress?

robocopy also tends to print empty lines even if it does not do anything. I'm filtering empty lines away using command like this:

robocopy /NDL /NJH /NJS /NP /NS /NC %fromDir% %toDir% %filenames% | findstr /r /v "^$"

Sass - Converting Hex to RGBa for background opacity

The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

Get unique values from arraylist in java

you can use this for making a list Unique

ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");

ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());

What is the best way to repeatedly execute a function every x seconds?

I use Tkinter after() method, which doesn't "steal the game" (like the sched module that was presented earlier), i.e. it allows other things to run in parallel:

import Tkinter

def do_something1():
  global n1
  n1 += 1
  if n1 == 6: # (Optional condition)
    print "* do_something1() is done *"; return
  # Do your stuff here
  # ...
  print "do_something1() "+str(n1)
  tk.after(1000, do_something1)

def do_something2(): 
  global n2
  n2 += 1
  if n2 == 6: # (Optional condition)
    print "* do_something2() is done *"; return
  # Do your stuff here
  # ...
  print "do_something2() "+str(n2)
  tk.after(500, do_something2)

tk = Tkinter.Tk(); 
n1 = 0; n2 = 0
do_something1()
do_something2()
tk.mainloop()

do_something1() and do_something2() can run in parallel and in whatever interval speed. Here, the 2nd one will be executed twice as fast.Note also that I have used a simple counter as a condition to terminate either function. You can use whatever other contition you like or none if you what a function to run until the program terminates (e.g. a clock).

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

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%wild%';

What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

When should null values of Boolean be used?

There are many uses for the **null** value in the Boolean wrapper! :)

For example, you may have in a form a field named "newsletter" that indicate if the user want or doesn't want a newsletter from your site. If the user doesn't select a value in this field, you may want to implement a default behaviour to that situation (send? don't send?, question again?, etc) . Clearly, not set (or not selected or **null**), is not the same that true or false.

But, if "not set" doesn't apply to your model, don't change the boolean primitive ;)

Using switch statement with a range of value in each case?

Use a NavigableMap implementation, like TreeMap.

/* Setup */
NavigableMap<Integer, Optional<String>> messages = new TreeMap<>();
messages.put(Integer.MIN_VALUE, Optional.empty());
messages.put(1, Optional.of("testing case 1 to 5"));
messages.put(6, Optional.of("testing case 6 to 10"));
messages.put(11, Optional.empty());

/* Use */
messages.floorEntry(3).getValue().ifPresent(System.out::println);

How can I disable inherited css styles?

Simplest is to class-ify all of the divs:

div.rounded {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
}
div.rounded div.br {
    background: url('br.gif') no-repeat bottom right;
}
div.rounded div.br div.bl {
    background: url('bl.gif') no-repeat bottom left;
}
div.rounded div.br div.bl div.inner {
    padding: 10px;
}
.button {
    border: 1px solid #999;
     background:#eeeeee url('');
    text-align:center;
}
.button:hover {
    background-color:#c4e2f2;
}

And then use:

<div class='round'><div class='br'><div class='bl'><div class='inner'>
<div class='button'><a href='#'>Test</a></div>
</div></div></div></div>

Split a python list into other "sublists" i.e smaller lists

chunks = [data[100*i:100*(i+1)] for i in range(len(data)/100 + 1)]

This is equivalent to the accepted answer. For example, shortening to batches of 10 for readability:

data = range(35)
print [data[x:x+10] for x in xrange(0, len(data), 10)]
print [data[10*i:10*(i+1)] for i in range(len(data)/10 + 1)]

Outputs:

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]

How to decompile a whole Jar file?

Insert the following into decompile.jar.sh

# Usage: decompile.jar.sh some.jar [-d]

# clean target folders
function clean_target {
  rm -rf $unjar $src $jad_log
}

# clean all debug stuff
function clean_stuff {
  rm -rf $unjar $jad_log
}

# the main function
function work {
  jar=$1
  unjar=`basename $jar.unjar`
  src=`basename $jar.src`
  jad_log=jad.log

  clean_target

  unzip -q $jar -d $unjar
  jad -d $src -ff -r -lnc -o -s java $unjar/**/*.class > $jad_log 2>&1

  if [ ! $debug ]; then
    clean_stuff
  fi

  if [ -d $src ] 
    then
      echo "$jar has been decompiled to $src"
    else
      echo "Got some problems check output or run in debug mode"
  fi
}

function usage {
  echo "This script extract and decompile JAR file"
  echo "Usage: $0 some.jar [-d]"
  echo "    where: some.jar is the target to decompile"
  echo "    use -d for debug mode"
}

# check params
if [ -n "$1" ]
  then
    if [ "$2" == "-d" ]; then
      debug=true
      set -x
    fi
    work $1
  else
    usage
fi
  • chmod +x decomplie.jar.sh //executable
  • ln -s ./decomplie.jar.s /usr/bin/dj

Ready to use, just type dj your.jar and you will get your.jar.src folder with sources. Use -d option for debug mode.

xcode-select active developer directory error

Xcode > Preferences > Locations > Command Line Tools

screenshot

Select the option matching your version of Xcode.

How can I enter latitude and longitude in Google Maps?

for higher precision. this format:

45 11.735N,004 34.281E

and this

45 23.623, 5 38.77

How to change the color of a button?

For the text color add:

android:textColor="<hex color>"


For the background color add:

android:background="<hex color>"


From API 21 you can use:

android:backgroundTint="<hex color>"
android:backgroundTintMode="<mode>"

Note: If you're going to work with android/java you really should learn how to google ;)
How to customize different buttons in Android

Refused to load the script because it violates the following Content Security Policy directive

The probable reason why you get this error is likely because you've added the /build folder to your .gitignore file or generally haven't checked it into Git.

So when you Git push Heroku master, the build folder you're referencing don't get pushed to Heroku. And that's why it shows this error.

That's the reason it works properly locally, but not when you deployed to Heroku.

Get a UTC timestamp

You can use Date.UTC method to get the time stamp at the UTC timezone.

Usage:

var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , 
      now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());

Live demo here http://jsfiddle.net/naryad/uU7FH/1/

How to convert local time string to UTC?

This thread seems to be missing an option available since Python 3.6: datetime.astimezone(tz=None) can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.

from datetime import datetime, timezone
s = "2008-09-17 14:02:00"

# to datetime object:
dt = datetime.fromisoformat(s) # Python 3.7

# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
dt = dt.astimezone()
print(dt)
# 2008-09-17 14:02:00+02:00

# ...and to UTC:
dtutc = dt.astimezone(timezone.utc)
print(dtutc)
# 2008-09-17 12:02:00+00:00

There is one caveat though, see astimezone(None) gives aware datetime, unaware of DST.

Excel 2013 VBA Clear All Filters macro

Loop AutoFilter columns, if column is activated(on) then reset a column filter, you may insert a new criteria after a loop. This code does not remove AutoFilter banner.

Dim iCol as Long
Dim ws as Worksheet
...
For iCol = 1 To ws.AutoFilter.Filters.count
  If ws.AutoFilter.Filters(iCol).On Then ws.AutoFilter.Range.AutoFilter Field:=iCol
Next
...
ws.AutoFilter.Range.AutoFilter Field:=4, Criteria1:="AABBCC"

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

DateTime.ToString() format that can be used in a filename or extension?

You can use this:

DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

How can I fix MySQL error #1064?

TL;DR

Error #1064 means that MySQL can't understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this "syntax" of which you speak? Is it witchcraft?

      Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you'll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.

      I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE command. The very first thing on the page is the command's grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.

    I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn't intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

String.strip() in Python

strip does nothing but, removes the the whitespace in your string. If you want to remove the extra whitepace from front and back of your string, you can use strip.

The example string which can illustrate that is this:

In [2]: x = "something \t like     \t this"
In [4]: x.split('\t')
Out[4]: ['something ', ' like     ', ' this']

See, even after splitting with \t there is extra whitespace in first and second items which can be removed using strip in your code.

Laravel Blade html image

In Laravel 5.x you can use laravelcollective/html and the syntax:

{!! Html::image('img/logo.png') !!}

CSS last-child selector: select last-element of specific class, not last child inside of parent?

:last-child only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want :last-of-type

http://jsfiddle.net/C23g6/3/

As per @BoltClock's comment, this is only checking for the last article element, not the last element with the class of .comment.

_x000D_
_x000D_
body {_x000D_
  background: black;_x000D_
}_x000D_
_x000D_
.comment {_x000D_
  width: 470px;_x000D_
  border-bottom: 1px dotted #f0f0f0;_x000D_
  margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
.comment:last-of-type {_x000D_
  border-bottom: none;_x000D_
  margin-bottom: 0;_x000D_
}
_x000D_
<div class="commentList">_x000D_
  <article class="comment " id="com21"></article>_x000D_
_x000D_
  <article class="comment " id="com20"></article>_x000D_
_x000D_
  <article class="comment " id="com19"></article>_x000D_
_x000D_
  <div class="something"> hello </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Angular 4 - get input value

If you want to read only one field value, I think, using the template reference variables is the easiest way

Template

<input #phone placeholder="phone number" />

<input type="button" value="Call" (click)="callPhone(phone.value)" />

**Component** 
 
callPhone(phone): void 
{
  
console.log(phone);

}

If you have a number of fields, using the reactive form one of the best ways.

Differences in string compare methods in C#

Using .Equals is also a lot easier to read.

How to apply slide animation between two activities in Android?

Hopefully, it will work for you.

startActivityForResult( intent, 1 , ActivityOptions.makeCustomAnimation(getActivity(),R.anim.slide_out_bottom,R.anim.slide_in_bottom).toBundle());

ng serve not detecting file changes automatically

I was having this problem on a new Linux Ubuntu install and noticed I was getting an error about 'too many watchers for limit' in VSCode at the same time. I followed the instructions to fix it in VSCode and it also fixed the issue with ng watch. More info here https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-changes-in-this-large-workspace-error-enospc

I noticed people suggesting sudo to run watch. This is a dangerous game, you are giving npm packages root access to your system. If your permissions are correct, my issue could be your fix since the limit is per user, and by running as sudo, you are running as root instead of your current user that is past the limit (running a watch heavy ide like vscode or atom on ). If for some reason you have the wrong permissions, set them properly to your user / group with chown.

Insert Data Into Temp Table with Query

Fastest way to do this is using "SELECT INTO" command e.g.

SELECT * INTO #TempTableName
FROM....

This will create a new table, you don't have to create it in advance.

Google Maps API v3: InfoWindow not sizing correctly

Just to summarize all the solutions that worked for me in all browsers:

  • Don't use margins inside the infowindow, only padding.
  • Set a max-width for the infowindow:

    this.infowindow = new google.maps.InfoWindow({ maxWidth: 200 });

  • Wrap the contents of the infowindow with

    <div style="overflow:hidden;line-height:1.35;min-width:200px;">*CONTENT*</div>

    (change the min-width for the value you set on the infowindow maxWidth)

I have tested it and it worked on every browser, and I had over 400 markers...

How to make a char string from a C macro's value?

He who is Shy* gave you the germ of an answer, but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:

#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC

#include <stdio.h>
int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.

In section 6.10.3.2 of the C standard, 'The # operator', it says:

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.

The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.

So, to achieve the effect you are after, you most certainly have to do some extra work.

#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME  FUNCTION_NAME(test_func)

#include <stdio.h>

int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR_VALUE is an idiom that is necessary to get the desired result.

#define STR_VALUE(arg)      #arg
#define FUNCTION_NAME(name) STR_VALUE(name)

#define TEST_FUNC      test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)

#include <stdio.h>

static void TEST_FUNC(void)
{
    printf("In function %s\n", TEST_FUNC_NAME);
}

int main(void)
{
    puts(TEST_FUNC_NAME);
    TEST_FUNC();
    return(0);
}

* At the time when this answer was first written, shoosh's name used 'Shy' as part of the name.

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

What is an alternative to execfile in Python 3?

This one is better, since it takes the globals and locals from the caller:

import sys
def execfile(filename, globals=None, locals=None):
    if globals is None:
        globals = sys._getframe(1).f_globals
    if locals is None:
        locals = sys._getframe(1).f_locals
    with open(filename, "r") as fh:
        exec(fh.read()+"\n", globals, locals)

How to get the top position of an element?

Try: $('#mytable').attr('offsetTop')

Simple conversion between java.util.Date and XMLGregorianCalendar

I had to make some changes to make it work, as some things seem to have changed in the meantime:

  • xjc would complain that my adapter does not extend XmlAdapter
  • some bizarre and unneeded imports were drawn in (org.w3._2001.xmlschema)
  • the parsing methods must not be static when extending the XmlAdapter, obviously

Here's a working example, hope this helps (I'm using JodaTime but in this case SimpleDate would be sufficient):

import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;

public class DateAdapter extends XmlAdapter<Object, Object> {
    @Override
    public Object marshal(Object dt) throws Exception {
        return new DateTime((Date) dt).toString("YYYY-MM-dd");
    }

    @Override
        public Object unmarshal(Object s) throws Exception {
        return DatatypeConverter.parseDate((String) s).getTime();
    }
}

In the xsd, I have followed the excellent references given above, so I have included this xml annotation:

<xsd:appinfo>
    <jaxb:schemaBindings>
        <jaxb:package name="at.mycomp.xml" />
    </jaxb:schemaBindings>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:date"
              parseMethod="at.mycomp.xml.DateAdapter.unmarshal"
          printMethod="at.mycomp.xml.DateAdapter.marshal" />
    </jaxb:globalBindings>
</xsd:appinfo>

Get day of week using NSDate

There is an easier way. Just pass your string date to the following function, it will give you the day name :)

func getDayNameBy(stringDate: String) -> String
    {
        let df  = NSDateFormatter()
        df.dateFormat = "YYYY-MM-dd"
        let date = df.dateFromString(stringDate)!
        df.dateFormat = "EEEE"
        return df.stringFromDate(date);
    }

SQL Server: Database stuck in "Restoring" state

Here's how you do it:

  1. Stop the service (MSSQLSERVER);
  2. Rename or delete the Database and Log files (C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data...) or wherever you have the files;
  3. Start the service (MSSQLSERVER);
  4. Delete the database with problem;
  5. Restore the database again.

how to get date of yesterday using php?

If you define the timezone in your PHP app (as you should), which you can do this way:

date_default_timezone_set('Europe/Paris');

Then it's as simple as:

$yesterday = new DateTime('yesterday'); // will use our default timezone, Paris
echo $yesterday->format('Y-m-d'); // or whatever format you want

(You may want to define a constant or environment variable to store your default timezone.)

How do I close a tkinter window?

Of course you can assign the command to the button as follows, however, if you are making a UI, it is recommended to assign the same command to the "X" button:

def quit(self): # Your exit routine
   self.root.destroy()

self.root.protocol("WM_DELETE_WINDOW", self.quit) # Sets the command for the "X" button 

Button(text="Quit", command=self.quit) # No ()

Practical uses of git reset --soft?

Another potential use is as an alternative to stashing (which some people don't like, see e.g. https://codingkilledthecat.wordpress.com/2012/04/27/git-stash-pop-considered-harmful/).

For example, if I'm working on a branch and need to fix something urgently on master, I can just do:

git commit -am "In progress."

then checkout master and do the fix. When I'm done, I return to my branch and do

git reset --soft HEAD~1

to continue working where I left off.

PHP cURL HTTP CODE return 0

If you connect with the server, then you can get a return code from it, otherwise it will fail and you get a 0. So if you try to connect to "www.google.com/lksdfk" you will get a return code of 400, if you go directly to google.com, you will get 302 (and then 200 if you forward to the next page... well I do because it forwards to google.com.br, so you might not get that), and if you go to "googlecom" you will get a 0 (host no found), so with the last one, there is nobody to send a code back.

Tested using the code below.

<?php

$html_brand = "www.google.com";
$ch = curl_init();

$options = array(
    CURLOPT_URL            => $html_brand,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER         => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING       => "",
    CURLOPT_AUTOREFERER    => true,
    CURLOPT_CONNECTTIMEOUT => 120,
    CURLOPT_TIMEOUT        => 120,
    CURLOPT_MAXREDIRS      => 10,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch); 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ( $httpCode != 200 ){
    echo "Return code is {$httpCode} \n"
        .curl_error($ch);
} else {
    echo "<pre>".htmlspecialchars($response)."</pre>";
}

curl_close($ch);

How do I apply a diff patch on Windows?

EDIT: Looking at the replies so far, it seems that Tortoise will only do it right if it's a file that's already versioned. That's not the case here. I need to be able to apply a patch to a file that did not come out of an SVN repository. I just tried using Tortoise because I happen to know that SVN uses diffs and has to know how to both create them and apply them.

You can install Cygwin, then use the command-line patch tool to apply the patch. See also this Unix man page, which applies to patch.

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

How to assign pointer address manually in C programming language?

Like this:

void * p = (void *)0x28ff44;

Or if you want it as a char *:

char * p = (char *)0x28ff44;

...etc.

If you're pointing to something you really, really aren't meant to change, add a const:

const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;

...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.

How can I read command line parameters from an R script?

FYI: there is a function args(), which retrieves the arguments of R functions, not to be confused with a vector of arguments named args

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

NEW WAY SINCE VERSION 0.7.7

Since Version 0.7.7 there is a new way to create an aggregated report:

You create a separate 'report' project which collects all the necessary reports (Any goal in the aggregator project is executed before its modules therefore it can't be used).

aggregator pom
  |- parent pom
  |- module a
  |- module b
  |- report module 

The root pom looks like this (don't forget to add the new report module under modules):

<build>
<plugins>
  <plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.8</version>
    <executions>
      <execution>
        <id>prepare-agent</id>
        <goals>
          <goal>prepare-agent</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>

The poms from each sub module doesn't need to be changed at all. The pom from the report module looks like this:

<!-- Add all sub modules as dependencies here -->
<dependencies>
  <dependency>
    <module a>
  </dependency>
  <dependency>
    <module b>
  </dependency>
 ...

  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.7.8</version>
        <executions>
          <execution>
            <id>report-aggregate</id>
            <phase>verify</phase>
            <goals>
              <goal>report-aggregate</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

A full exmple can be found here.

Obtain smallest value from array in Javascript?

Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)

Code snippet:

_x000D_
_x000D_
const findMin = (arr, min, i) => arr.length === i ? min :_x000D_
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)_x000D_
  _x000D_
const arr = [5, 34, 2, 1, 6, 7, 9, 3];_x000D_
const min = findMin(arr, arr[0], 0)_x000D_
console.log(min);
_x000D_
_x000D_
_x000D_

Percentage Height HTML 5/CSS

Sometimes, you may want to conditionally set the height of a div, such as when the entire content is less than the height of the screen. Setting all parent elements to 100% will cut off content when it is longer than the screen size.

So, the way to get around this is to set the min-height:

Continue to let the parent elements automatically adjust their height Then in your main div, subtract the pixel sizes of the header and footer div from 100vh (viewport units). In css, something like:

min-height: calc(100vh - 246px);

100vh is full length of the screen, minus the surrounding divs. By setting min-height and not height, content longer than screen will continue to flow, instead of getting cut off.

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

Sorting dictionary keys in python

my_list = sorted(dict.items(), key=lambda x: x[1])

How to convert decimal to hexadecimal in JavaScript

If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code

_x000D_
_x000D_
const hugeNumber = "9007199254740991873839" // Make sure its in String_x000D_
const hexOfHugeNumber = BigInt(hugeNumber).toString(16);_x000D_
console.log(hexOfHugeNumber)
_x000D_
_x000D_
_x000D_

Rounded Corners Image in Flutter

You can also use CircleAvatar, which comes with flutter

CircleAvatar(
  radius: 20,
  backgroundImage: NetworkImage('https://via.placeholder.com/140x100')
)

Sqlite in chrome

You can use Web SQL API which is an ordinary SQLite database in your browser and you can open/modify it like any other SQLite databases for example with Lita.

Chrome locates databases automatically according to domain names or extension id. A few months ago I posted on my blog short article on how to delete Chrome's database because when you're testing some functionality it's quite useful.

Does C# have extension properties?

Because I recently needed this, I looked at the source of the answer in:

c# extend class by adding properties

and created a more dynamic version:

public static class ObjectExtenders
{
    static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();

    public static string GetFlags(this object objectItem, string key)
    {
        return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
    }

    public static void SetFlags(this object objectItem, string key, string value)
    {
        if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
        {
            Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
        }
        else
        {
            Flags.GetOrCreateValue(objectItem).Add(new stringObject()
            {
                Key = key,
                Value = value
            });
        }
    }

    class stringObject
    {
        public string Key;
        public string Value;
    }
}

It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)

Create a simple HTTP server with Java?

The easiest is Simple there is a tutorial, no WEB-INF not Servlet API no dependencies. Just a simple lightweight HTTP server in a single JAR.

Get Table and Index storage size in sql server

This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:

SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%'    -- filter out system tables for diagramming
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

If you want to separate table space from index space, you need to use AND i.index_id IN (0,1) for the table space (index_id = 0 is the heap space, index_id = 1 is the size of the clustered index = data pages) and AND i.index_id > 1 for the index-only space

How to get DropDownList SelectedValue in Controller in MVC

Model

Very basic model with Gender field. GetGenderSelectItems() returns select items needed to populate DropDownList.

public enum Gender 
{
    Male, Female
}

public class MyModel
{
    public Gender Gender { get; set; }

    public static IEnumerable<SelectListItem> GetGenderSelectItems()
    {
        yield return new SelectListItem { Text = "Male", Value = "Male" };
        yield return new SelectListItem { Text = "Female", Value = "Female" };
    }
}

View

Please make sure you wrapped your @Html.DropDownListFor in a form tag.

@model MyModel

@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
   @Html.DropDownListFor(m => m.Gender, MyModel.GetGenderSelectItems())
   <input type="submit" value="Send" />
}

Controller

Your .cshtml Razor view name should be the same as controller action name and folder name should match controller name e.g Views\MyController\MyAction.cshtml.

public class MyController : Controller 
{
    public ActionResult MyAction()
    {
        // shows your form when you load the page
        return View();
    }

    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        // the value is received in the controller.
        var selectedGender = model.Gender;
        return View(model);
    }
}

Going further

Now let's make it strongly-typed and enum independent:

var genderSelectItems = Enum.GetValues(typeof(Gender))
    .Cast<string>()
    .Select(genderString => new SelectListItem 
    {
        Text = genderString,
        Value = genderString,
    }).AsEnumerable();