Programs & Examples On #Cppunit

CppUnit is a macro-based unit testing framework for C++.

Comparison of C++ unit test frameworks

See this question for some discussion.

They recommend the articles: Exploring the C++ Unit Testing Framework Jungle, By Noel Llopis. And the more recent: C++ Test Unit Frameworks

I have not found an article that compares googletest to the other frameworks yet.

How to automatically start a service when running a docker container?

Simple! Add at the end of dockerfile:

ENTRYPOINT service mysql start && /bin/bash

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

In my case I got the error simply because I had changed the Listen 80 to listen 443 in the file

/etc/httpd/conf/httpd.conf 

Since I had installed mod_ssl using the yum commands

yum -y install mod_ssl  

there was a duplicate listen 443 directive in the file ssl.conf created during mod_ssl installation.

You can verify this if you have duplicate listen 80 or 443 by running the below command in linux centos (My linux)

grep  '443' /etc/httpd/conf.d/*

below is sample output

/etc/httpd/conf.d/ssl.conf:Listen 443 https
/etc/httpd/conf.d/ssl.conf:<VirtualHost _default_:443>
/etc/httpd/conf.d/ssl.conf:#ServerName www.example.com:443

Simply reverting the listen 443 in httd.conf to listen 80 fixed my issue.

Speed tradeoff of Java's -Xms and -Xmx options

It depends on the GC your java is using. Parallel GCs might work better on larger memory settings - I'm no expert on that though.

In general, if you have larger memory the less frequent it needs to be GC-ed - there is lots of room for garbage. However, when it comes to a GC, the GC has to work on more memory - which in turn might be slower.

How to access JSON Object name/value?

Try this code..

function (data) {


var json = jQuery.parseJSON(data);
alert( json.name );


}

Logout button php

Instead of a button, put a link and navigate it to another page

<a href="logout.php">Logout</a>

Then in logout.php page, use

session_start();
session_destroy();
header('Location: login.php');
exit;

How to remove close button on the jQuery UI dialog?

Once you have called .dialog() on an element, you can locate the close button (and other dialog markup) at any convenient time without using event handlers:

$("#div2").dialog({                    // call .dialog method to create the dialog markup
    autoOpen: false
});
$("#div2").dialog("widget")            // get the dialog widget element
    .find(".ui-dialog-titlebar-close") // find the close button for this dialog
    .hide();                           // hide it

Alternate method:

Inside dialog event handlers, this refers to the element being "dialogged" and $(this).parent() refers to the dialog markup container, so:

$("#div3").dialog({
    open: function() {                         // open event handler
        $(this)                                // the element being dialogged
            .parent()                          // get the dialog widget element
            .find(".ui-dialog-titlebar-close") // find the close button for this dialog
            .hide();                           // hide it
    }
});

FYI, dialog markup looks like this:

<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
    <!-- ^--- this is the dialog widget -->
    <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
        <span class="ui-dialog-title" id="ui-dialog-title-dialog">Dialog title</span>
        <a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
    </div>
    <div id="div2" style="height: 200px; min-height: 200px; width: auto;" class="ui-dialog-content ui-widget-content">
        <!-- ^--- this is the element upon which .dialog() was called -->
    </div>
</div>

Demos here

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

Multiple ways to delete Key in Hash. you can use any Method from below

hash = {a: 1, b: 2, c: 3}
hash.except!(:a) # Will remove *a* and return HASH
hash # Output :- {b: 2, c: 3}

hash = {a: 1, b: 2, c: 3}
hash.delete(:a) # will remove *a* and return 1 if *a* not present than return nil

So many ways is there, you can look on Ruby doc of Hash here.

Thank you

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

Using set_facts and with_items together in Ansible

Looks like this behavior is how Ansible currently works, although there is a lot of interest in fixing it to work as desired. There's currently a pull request with the desired functionality so hopefully this will get incorporated into Ansible eventually.

How do I get the path of the current executed file in Python?

You have simply called:

path = os.path.abspath(os.path.dirname(sys.argv[0]))

instead of:

path = os.path.dirname(os.path.abspath(sys.argv[0]))

abspath() gives you the absolute path of sys.argv[0] (the filename your code is in) and dirname() returns the directory path without the filename.

How to Apply Corner Radius to LinearLayout

You would use a Shape Drawable as the layout's background and set its cornerRadius. Check this blog for a detailed tutorial

Problems when trying to load a package in R due to rJava

If you have this issue with macOS, there is no easy way here: ( Especially, when you want to use R3.4. I have been there already.

R 3.4, rJava, macOS and even more mess

For R3.3 it's a little bit easier (R3.3 was compiled using different compiler).

R, Java, rJava and macOS adventures

How to add a class with React.js?

It is simple. take a look at this

https://codepen.io/anon/pen/mepogj?editors=001

basically you want to deal with states of your component so you check the currently active one. you will need to include

getInitialState: function(){}
//and 
isActive: function(){}

check out the code on the link

How can I convert an HTML element to a canvas element?

You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:

var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');

var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;

domtoimage.toPng(node).then(function (pngDataUrl) {
    var img = new Image();
    img.onload = function () {
        var context = canvas.getContext('2d');

        context.translate(canvas.width, 0);
        context.scale(-1, 1);
        context.drawImage(img, 0, 0);

        parent.removeChild(node);
        parent.appendChild(canvas);
    };

    img.src = pngDataUrl;
});

And here is jsfiddle

rename the columns name after cbind the data

It's easy just add the name which you want to use in quotes before adding vector

a_matrix <- cbind(b_matrix,'Name-Change'= c_vector)

Mongoose: Find, modify, save

If you want to use find, like I would for any validation you want to do on the client side.

find returns an ARRAY of objects

findOne returns only an object

Adding user = user[0] made the save method work for me.

Here is where you put it.

User.find({username: oldUsername}, function (err, user) {
    user = user[0];
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

C# adding a character in a string

Remember a string is immutable so you will need to create a new string.

Strings are IEnumerable so you should be able to run a for loop over it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string alpha = "abcdefghijklmnopqrstuvwxyz";
            var builder = new StringBuilder();
            int count = 0;
            foreach (var c in alpha)
            {
                builder.Append(c);
                if ((++count % 5) == 0)
                {
                    builder.Append('-');
                }
            }
            Console.WriteLine("Before: {0}", alpha);
            alpha = builder.ToString();
            Console.WriteLine("After: {0}", alpha);
        }
    }
}

Produces this:

Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z

Get my phone number in android

Robi Code is work for me, just put if !null so that if phone number is null, user can fill the phone number by him/her self.

editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
TelephonyManager tMgr;
tMgr= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
if (mPhoneNumber != null){
editTextPhoneNumber.setText(mPhoneNumber);
}

How can I get the last 7 characters of a PHP string?

for last 7 characters

$newstring = substr($dynamicstring, -7);

$newstring : 5409els

for first 7 characters

$newstring = substr($dynamicstring, 0, 7);

$newstring : 2490slk

C# - Create SQL Server table programmatically

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
    try
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
        cmd.ExecuteNonQuery();
        lblAlert.Text = "SucessFully Connected";
        cn.Close();
    }
    catch (Exception eq)
    {
        lblAlert.Text = eq.ToString();
    }
}

React Error: Target Container is not a DOM Element

I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.

Iterating through populated rows

It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:

Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  RowCount = RowCount + 1

Next rw

MsgBox (RowCount)

The import android.support cannot be resolved

This is very easy step to import any 3rd party lib or jar file into your project

  1. Copy android-support-v4.jar file from your_drive\android-sdks\extras\android\support\v4\android-support-v4.jar
    or copy from your existing project's bin folder.
    or any third party .jar file
  2. paste copied jar file into lib folder

  3. right click on this jar file and then click on build Path->Add to Build Path enter image description here

  4. even still you are getting error in your project then Clean the Project and Build it.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Difference between nVidia Quadro and Geforce cards?

Hardware wise the Quadro and GeForce cards are often idential. Indeed it is sometimes possible to convert some models from GeForce into Quadro by simply uploading new firmware and changing a couple resistor jumpers.

The difference is in the intended market and hence cost.

Quadro cards are intended for CAD. High end CAD software still uses OpenGL, whereas games and lower end CAD software use Direct3D (aka DirectX).

Quadro cards simply have firmware that is optimised for OpenGL. In the early days OpenGL was better and faster than Direct3D but now there is little difference. Gaming cards only support a very limited set of OpenGL, hence they don't run it very well.

CAD companies, e.g. Dassault with SolidWorks actively push high end cards by offering no support for DirectX with any level of performance.

Other CAD companies such as Altium, with Altium Designer, made the decision that forcing their customers to buy more expensive cards is not worthwhile when Direct3D is as good (if not better these days) than OpenGL.

Because of the cost, there are often other differences in the hardware, such as less use of overclocking, more memory etc, but these have relatively minor effects compared with the firmware support.

Selecting only first-level elements in jquery

You might want to try this if results still flows down to children, in many cases JQuery will still apply to children.

$("ul.rootlist > li > a")

Using this method: E > F Matches any F element that is a child of an element E.

Tells JQuery to look only for explicit children. http://www.w3.org/TR/CSS2/selector.html

SQLite error 'attempt to write a readonly database' during insert?

This can be caused by SELinux. If you don't want to disable SELinux completely, you need to set the db directory fcontext to httpd_sys_rw_content_t.

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/railsapp/db(/.*)?"
restorecon -v /var/www/railsapp/db

Firing events on CSS class changes in jQuery

if you know a what event changed the class in the first place you may use a slight delay on the same event and the check the for the class. example

//this is not the code you control
$('input').on('blur', function(){
    $(this).addClass('error');
    $(this).before("<div class='someClass'>Warning Error</div>");
});

//this is your code
$('input').on('blur', function(){
    var el= $(this);
    setTimeout(function(){
        if ($(el).hasClass('error')){ 
            $(el).removeClass('error');
            $(el).prev('.someClass').hide();
        }
    },1000);
});

http://jsfiddle.net/GuDCp/3/

how to implement Pagination in reactJs

I recently created this Pagination component that implements paging logic like Google's search results:

import React, { PropTypes } from 'react';
 
const propTypes = {
    items: PropTypes.array.isRequired,
    onChangePage: PropTypes.func.isRequired,
    initialPage: PropTypes.number   
}
 
const defaultProps = {
    initialPage: 1
}
 
class Pagination extends React.Component {
    constructor(props) {
        super(props);
        this.state = { pager: {} };
    }
 
    componentWillMount() {
        this.setPage(this.props.initialPage);
    }
 
    setPage(page) {
        var items = this.props.items;
        var pager = this.state.pager;
 
        if (page < 1 || page > pager.totalPages) {
            return;
        }
 
        // get new pager object for specified page
        pager = this.getPager(items.length, page);
 
        // get new page of items from items array
        var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);
 
        // update state
        this.setState({ pager: pager });
 
        // call change page function in parent component
        this.props.onChangePage(pageOfItems);
    }
 
    getPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;
 
        // default page size is 10
        pageSize = pageSize || 10;
 
        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);
 
        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }
 
        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
 
        // create an array of pages to ng-repeat in the pager control
        var pages = _.range(startPage, endPage + 1);
 
        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }
 
    render() {
        var pager = this.state.pager;
 
        return (
            <ul className="pagination">
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(1)}>First</a>
                </li>
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
                </li>
                {pager.pages.map((page, index) =>
                    <li key={index} className={pager.currentPage === page ? 'active' : ''}>
                        <a onClick={() => this.setPage(page)}>{page}</a>
                    </li>
                )}
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
                </li>
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.totalPages)}>Last</a>
                </li>
            </ul>
        );
    }
}
 
Pagination.propTypes = propTypes;
Pagination.defaultProps
export default Pagination;

And here's an example App component that uses the Pagination component to paginate a list of 150 example items:

import React from 'react';
import Pagination from './Pagination';
 
class App extends React.Component {
    constructor() {
        super();
 
        // an example array of items to be paged
        var exampleItems = _.range(1, 151).map(i => { return { id: i, name: 'Item ' + i }; });
 
        this.state = {
            exampleItems: exampleItems,
            pageOfItems: []
        };
 
        // bind function in constructor instead of render (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)
        this.onChangePage = this.onChangePage.bind(this);
    }
 
    onChangePage(pageOfItems) {
        // update state with new page of items
        this.setState({ pageOfItems: pageOfItems });
    }
 
    render() {
        return (
            <div>
                <div className="container">
                    <div className="text-center">
                        <h1>React - Pagination Example with logic like Google</h1>
                        {this.state.pageOfItems.map(item =>
                            <div key={item.id}>{item.name}</div>
                        )}
                        <Pagination items={this.state.exampleItems} onChangePage={this.onChangePage} />
                    </div>
                </div>
                <hr />
                <div className="credits text-center">
                    <p>
                        <a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
                    </p>
                </div>
            </div>
        );
    }
}
 
export default App;

For more details and a live demo you can check out this post

How to get GET (query string) variables in Express.js on Node.js?

You should be able to do something like this:

var http = require('http');
var url  = require('url');

http.createServer(function(req,res){
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    console.log(query); //{Object}

    res.end("End")
})

How to convert R Markdown to PDF?

For an option that looks more like what you get when you print from a browser, wkhtmltopdf provides one option.

On Ubuntu

sudo apt-get install wkhtmltopdf

And then the same command as for the pandoc example to get to the HTML:

RMDFILE=example-r-markdown  
Rscript -e "require(knitr); require(markdown); knit('$RMDFILE.rmd', '$RMDFILE.md'); markdownToHTML('$RMDFILE.md', '$RMDFILE.html', options=c('use_xhml'))"

and then

wkhtmltopdf example-r-markdown.html example-r-markdown.pdf

The resulting file looked like this. It did not seem to handle the MathJax (this issue is discussed here), and the page breaks are ugly. However, in some cases, such a style might be preferred over a more LaTeX style presentation.

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Note- position really matters add google() before jcenter()

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

How can I present a file for download from an MVC controller?

Use .ashx file type and use the same code

Custom Authentication in ASP.Net-Core

I would like to add something to brilliant @AmiNadimi answer for everyone who going implement his solution in .NET Core 3:

First of all, you should change signature of SignIn method in UserManager class from:

public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

to:

public async Task SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

It's because you should never use async void, especially if you work with HttpContext. Source: Microsoft Docs

The last, but not least, your Configure() method in Startup.cs should contains app.UseAuthorization and app.UseAuthentication in proper order:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Chrome: Uncaught SyntaxError: Unexpected end of input

Try Firebug for Mozilla - it will show the position of the missing }.

http://getfirebug.com/

Direct casting vs 'as' operator?

When trying to get the string representation of anything (of any type) that could potentially be null, I prefer the below line of code. It's compact, it invokes ToString(), and it correctly handles nulls. If o is null, s will contain String.Empty.

String s = String.Concat(o);

Can not get a simple bootstrap modal to work

You must call your Bootstrap jQuery plugin so that it will trigger.

oracle plsql: how to parse XML and insert into table

You can load an XML document into an XMLType, then query it, e.g.:

DECLARE
  x XMLType := XMLType(
    '<?xml version="1.0" ?> 
<person>
   <row>
       <name>Tom</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
   <row>
       <name>Jim</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
</person>');
BEGIN
  FOR r IN (
    SELECT ExtractValue(Value(p),'/row/name/text()') as name
          ,ExtractValue(Value(p),'/row/Address/State/text()') as state
          ,ExtractValue(Value(p),'/row/Address/City/text()') as city
    FROM   TABLE(XMLSequence(Extract(x,'/person/row'))) p
    ) LOOP
    -- do whatever you want with r.name, r.state, r.city
  END LOOP;
END;

View more than one project/solution in Visual Studio

Don't know whether this is useful but if you want to work with multiple projects without navigating through projects tree {like multi window} you can try opening VS in another virtual desktop (at least it's possible for Windows 10) by holding Ctrl+win+D. Then open another VS studio and open your other project there. You can switch between projects by Ctrl+win+arrow key {left/right}.

What is a reasonable code coverage % for unit tests (and why)?

Generally speaking, from the several engineering excellence best practices papers that I have read, 80% for new code in unit tests is the point that yields the best return. Going above that CC% yields a lower amount of defects for the amount of effort exerted. This is a best practice that is used by many major corporations.

Unfortunately, most of these results are internal to companies, so there are no public literatures that I can point you to.

Hibernate: "Field 'id' doesn't have a default value"

What about this:

<set name="fieldName" cascade="all"> 
   <key column="id" not-null="true" />
   <one-to-many class="com.yourClass"/>
</set>

I hope it helps you.

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

Excel 2013 VBA Clear All Filters macro

That is brilliant, the only answer I found that met my particular need, thanks SO much for putting it up!

I made just a minor addition to it so that the screen didn't flash and it removes and subsequently reapplies the password on each sheet as it cycles through [I have the same password for all sheets in the workbook]. In the spirit of your submission, I add this to assist anyone else....

Sub ClearFilters()
    Application.ScreenUpdating = False

    On Error Resume Next
    For Each wrksheet In ActiveWorkbook.Worksheets
        'Change the password to whatever is required
        wrksheet.Unprotect Password:="Albuterol1"
        wrksheet.ShowAllData 'This works for filtered data not in a table

        For Each lstobj In wrksheet.ListObjects
            If lstobj.ShowAutoFilter Then
                lstobj.Range.AutoFilter 'Clear filters from a table
                lstobj.Range.AutoFilter 'Add the filters back to the table
            End If

        'Change the password to whatever is required
        wrksheet.Protect Password:="Albuterol1", _
              DrawingObjects:=True, _
              Contents:=True, _
              Scenarios:=True, _
              AllowFiltering:=True
        Next 'Check next worksheet in the workbook
    Next

    Application.ScreenUpdating = True
End Sub

I know this is a relatively old post and don't really like being a necromancer... But since I had the same issue and tried a few of the options in this thread without success I combined some of the answers to get a working macro..

Hopefully this helps someone out there :)

Sub ResetFilters()
    On Error Resume Next
    For Each wrksheet In ActiveWorkbook.Worksheets
        wrksheet.ShowAllData 'This works for filtered data not in a table
        For Each lstobj In wrksheet.ListObjects
            If lstobj.ShowAutoFilter Then
                lstobj.Range.AutoFilter 'Clear filters from a table
                lstobj.Range.AutoFilter 'Add the filters back to the table
            End If
        Next 'Check next worksheet in the workbook
    Next
End Sub

How to use pip with Python 3.x alongside Python 2.x

This worked for me on OS X: (I say this because sometimes is a pain that mac has "its own" version of every open source tool, and you cannot remove it because "its improvements" make it unique for other apple stuff to work, and if you remove it things start falling appart)

I followed the steps provided by @Lennart Regebro to get pip for python 3, nevertheless pip for python 2 was still first on the path, so... what I did is to create a symbolic link to python 3 inside /usr/bin (in deed I did the same to have my 2 pythons running in peace):

ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/pip /usr/bin/pip3

Notice that I added a 3 at the end, so basically what you have to do is to use pip3 instead of just pip.

The post is old but I hope this helps someone someday. this should theoretically work for any LINUX system.

Two column div layout with fluid left and fixed right column

Here's a solution (and it has some quirks, but let me know if you notice them and that they're a concern):

<div>
    <div style="width:200px;float:left;display:inline-block;">
        Hello world
    </div>
    <div style="margin-left:200px;">
        Hello world
    </div>
</div>

How can I get last characters of a string

Don't use .substr(). Use the .slice() method instead because it is cross browser compatible (see IE).

_x000D_
_x000D_
const id = "ctl03_Tabs1";_x000D_
console.log(id.slice(id.length - 5)); //Outputs: Tabs1_x000D_
console.log(id.slice(id.length - 1)); //Outputs: 1
_x000D_
_x000D_
_x000D_

substr() with negative value not working in IE

Maximum length for MySQL type text

TINYTEXT 256 bytes
TEXT 65,535 bytes ~64kb
MEDIUMTEXT 16,777,215 bytes ~16MB
LONGTEXT 4,294,967,295 bytes ~4GB

TINYTEXT is a string data type that can store up to to 255 characters.

TEXT is a string data type that can store up to 65,535 characters. TEXT is commonly used for brief articles.

LONGTEXT is a string data type with a maximum length of 4,294,967,295 characters. Use LONGTEXT if you need to store large text, such as a chapter of a novel.

Calculate business days

This is another solution, it is nearly 25% faster than checking holidays with in_array:

/**
 * Function to calculate the working days between two days, considering holidays.
 * @param string $startDate -- Start date of the range (included), formatted as Y-m-d.
 * @param string $endDate -- End date of the range (included), formatted as Y-m-d.
 * @param array(string) $holidayDates -- OPTIONAL. Array of holidays dates, formatted as Y-m-d. (e.g. array("2016-08-15", "2016-12-25"))
 * @return int -- Number of working days.
 */
function getWorkingDays($startDate, $endDate, $holidayDates=array()){
    $dateRange = new DatePeriod(new DateTime($startDate), new DateInterval('P1D'), (new DateTime($endDate))->modify("+1day"));
    foreach ($dateRange as $dr) { if($dr->format("N")<6){$workingDays[]=$dr->format("Y-m-d");} }
    return count(array_diff($workingDays, $holidayDates));
}

How can we run a test method with multiple parameters in MSTest?

EDIT 4: Looks like this is completed in MSTest V2 June 17, 2016: https://blogs.msdn.microsoft.com/visualstudioalm/2016/06/17/taking-the-mstest-framework-forward-with-mstest-v2/

Original Answer:

As of about a week ago in Visual Studio 2012 Update 1 something similar is now possible:

[DataTestMethod]
[DataRow(12,3,4)]
[DataRow(12,2,6)]
[DataRow(12,4,3)]
public void DivideTest(int n, int d, int q)
{
  Assert.AreEqual( q, n / d );
}

EDIT: It appears this is only available within the unit testing project for WinRT/Metro. Bummer

EDIT 2: The following is the metadata found using "Go To Definition" within Visual Studio:

#region Assembly Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll, v11.0.0.0
// C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\MSTestFramework\11.0\References\CommonConfiguration\neutral\Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll
#endregion

using System;

namespace Microsoft.VisualStudio.TestPlatform.UnitTestFramework
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class DataTestMethodAttribute : TestMethodAttribute
    {
        public DataTestMethodAttribute();

        public override TestResult[] Execute(ITestMethod testMethod);
    }
}

EDIT 3: This issue was brought up in Visual Studio's UserVoice forums. Last Update states:

STARTED · Visual Studio Team ADMIN Visual Studio Team (Product Team, Microsoft Visual Studio) responded · April 25, 2016 Thank you for the feedback. We have started working on this.

Pratap Lakshman Visual Studio

https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/3865310-allow-use-of-datatestmethod-datarow-in-all-unit

Print <div id="printarea"></div> only?

hm ... use the type of a stylsheet for printing ... eg:

<link rel="stylesheet" type="text/css" href="print.css" media="print" />

print.css:

div { display: none; }
#yourdiv { display: block; }

adb doesn't show nexus 5 device

Solution for Windows 7 and Nexus 5 (should be applicable for any Nexus device):

I figured out that my system was installing the Nexus 5 default driver for windows automatically the moment I was connecting my Nexus 5 to my system through USB. So uninstalling the default driver was in vain and it gets installed automatically anyways.Moreover if you uninstall the default driver, you won't be able to locate Nexus 5 under Devices in Computer Management. So here is what i did and worked for me!

  1. Computer-->right Click-->Manage-->Device Manager-->Portable Device-->Nexus 5-->Update Driver Software
  2. Choose 'Browse my computer for driver software' 1.Make sure to give this location: %APPDATA%\Local\Android\sdk\extras\google\usb_driver
  3. Click Next and you are done.

Add Custom Headers using HttpWebRequest

IMHO it is considered as malformed header data.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

The second way is true.

Split a large dataframe into a list of data frames based on common value in column

From version 0.8.0, dplyr offers a handy function called group_split():

# On sample data from @Aus_10

df %>%
  group_split(g)

[[1]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     2.04      0.627 A    
 2     0.530    -0.703 A    
 3    -0.475     0.541 A    
 4     1.20     -0.565 A    
 5    -0.380    -0.126 A    
 6     1.25     -1.69  A    
 7    -0.153    -1.02  A    
 8     1.52     -0.520 A    
 9     0.905    -0.976 A    
10     0.517    -0.535 A    
# … with 15 more rows

[[2]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     1.61      0.858 B    
 2     1.05     -1.25  B    
 3    -0.440    -0.506 B    
 4    -1.17      1.81  B    
 5     1.47     -1.60  B    
 6    -0.682    -0.726 B    
 7    -2.21      0.282 B    
 8    -0.499     0.591 B    
 9     0.711    -1.21  B    
10     0.705     0.960 B    
# … with 15 more rows

To not include the grouping column:

df %>%
 group_split(g, keep = FALSE)

How to watch for array changes?

From reading all the answers here, I have assembled a simplified solution that does not require any external libraries.

It also illustrates much better the general idea for the approach:

function processQ() {
   // ... this will be called on each .push
}

var myEventsQ = [];
myEventsQ.push = function() { Array.prototype.push.apply(this, arguments);  processQ();};

No module named MySQLdb

mysqldb is a module for Python that doesn't come pre-installed or with Django. You can download mysqldb here.

Webpack.config how to just copy the index.html to the dist folder

You can add the index directly to your entry config and using a file-loader to load it

module.exports = {

  entry: [
    __dirname + "/index.html",
    .. other js files here
  ],

  module: {
    rules: [
      {
        test: /\.html/, 
        loader: 'file-loader?name=[name].[ext]', 
      },
      .. other loaders
    ]
  }

}

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

C# Parsing JSON array of objects

I believe this is much simpler;

dynamic obj = JObject.Parse(jsonString);
string results  = obj.results;
foreach(string result in result.Split('))
{
//Todo
}

nodejs - How to read and output jpg image?

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

[Edit] You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');

Could not load type from assembly error

If you have one project referencing another project (such as a 'Windows Application' type referencing a 'Class Library') and both have the same Assembly name, you'll get this error. You can either strongly name the referenced project or (even better) rename the assembly of the referencing project (under the 'Application' tab of project properties in VS).

Google Maps v3 - limit viewable area and zoom level

To limit the zoom on v.3+. in your map setting add default zoom level and minZoom or maxZoom (or both if required) zoom levels are 0 to 19. You must declare deafult zoom level if limitation is required. all are case sensitive!

function initialize() {
   var mapOptions = {
      maxZoom:17,
      minZoom:15,
      zoom:15,
      ....

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes

.abc.xyz {  
  width: 200px !important;
}

applies to div tags with the following two classes

div.abc.xyz {  
  width: 200px !important;
}

If you wanted to modify this using jQuery

$(document).ready(function() {
  $("div.abc.xyz").width("200px");
});

How do I change the text of a span element using JavaScript?

Like in other answer, innerHTML and innerText are not recommended, it's better use textContent. This attribute is well supported, you can check it this: http://caniuse.com/#search=textContent

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

How to check if anonymous object has a method?

typeof myObj.prop2 === 'function'; will let you know if the function is defined.

if(typeof myObj.prop2 === 'function') {
    alert("It's a function");
} else if (typeof myObj.prop2 === 'undefined') {
    alert("It's undefined");
} else {
    alert("It's neither undefined nor a function. It's a " + typeof myObj.prop2);
}

Why shouldn't `&apos;` be used to escape single quotes?

&apos; is not part of the HTML 4 standard.

&quot; is, though, so is fine to use.

String.equals versus ==

a==b

Compares references, not values. The use of == with object references is generally limited to the following:

  1. Comparing to see if a reference is null.

  2. Comparing two enum values. This works because there is only one object for each enum constant.

  3. You want to know if two references are to the same object

"a".equals("b")

Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

C# "as" cast vs classic cast

I suppose it is useful if the result of the cast will be passed to a method that you know will handle null references without throwing and ArgumentNullException or suchlike.

I tend to find very little use for as, since:

obj as T

Is slower than:

if (obj is T)
    ...(T)obj...

The use of as is very much an edge-case scenario for me, so I can't think of any general rules for when I would use it over just casting and handling the (more informative) casting exception further up the stack.

How do I download a tarball from GitHub using cURL?

with a specific dir:

cd your_dir && curl -L https://download.calibre-ebook.com/3.19.0/calibre-3.19.0-x86_64.txz | tar zx

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

First check your Internet conection..

or try with

Tools -> Android -> Sync

or Try

File -> Settings -> Gradle -> Check Offline Work

enter image description here

Xcode : Adding a project as a build dependency

To add it as a dependency do the following:

  • Highlight the added project in your file explorer within xcode. In the directory browser window to the right it should show a file with a .a extension. There is a checkbox under the target column (target icon), check it.
  • Right-Click on your Target (under the targets item in the file explorer) and choose Get Info
  • On the general tab is a Direct Dependencies section. Hit the plus button
  • Choose the project and click Add Target

"Untrusted App Developer" message when installing enterprise iOS Application

You absolutely can avoid this issue if you manage the device with MDM or have access to Apple Configurator.

The solution is to push either the Developer or iOS Distribution certificate to the device via MDM or Apple Configurator. Once you do that, any application signed by that cert will be trusted.

When you click on "Do you trust this developer", you're essentially adding that certificate manually on a per-app basis.

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

How do I export an Android Studio project?

It seems as if Android Studio is missing some features Eclipse has (which is surprising considering the choice to make Android Studio official IDE).

Eclipse had the ability to export zip files which could be sent over email for example. If you zip the folder from your workspace, and try to send it over Gmail for example, Gmail will refuse because the folder contains executable. Obviously you can delete files but that is inefficient if you do that frequently going back and forth from work.

Here's a solution though: You can use source control. Android Studio supports that. Your code will be stored online. A git will do the trick. Look under "VCS" in the top menu in Android Studio. It has many other benefits as well. One of the downsides though, is that if you use GitHub for free, your code is open source and everyone can see it.

How to convert upper case letters to lower case

To convert a string to lower case in Python, use something like this.

list.append(sentence.lower())

I found this in the first result after searching for "python upper to lower case".

Submit button doesn't work

I ran into this on a friend's HTML code and in his case, he was missing quotes.

For example:

<form action="formHandler.php" name="yourForm" id="theForm" method="post">    
<input type="text" name="fname" id="fname" style="width:90;font-size:10>     
<input type="submit" value="submit"/>
</form>

In this example, a missing quote on the input text fname will simply render the submit button un-usable and the form will not submit.

Of course, this is a bad example because I should be using CSS in the first place ;) but anyways, check all your single and double quotes to see that they are closing properly.

Also, if you have any tags like center, move them out of the form.

<form action="formHandler.php" name="yourForm" id="theForm" method="post">  
<center> <-- bad

As strange it may seems, it can have an impact.

[Vue warn]: Property or method is not defined on the instance but referenced during render

Although some answers here maybe great, none helped my case (which is very similar to OP's error message).

This error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data).

To fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did:

_x000D_
_x000D_
// pulled data in this life cycle hook, saving it to my store
created() {
  FetchData.getProfile()
    .then(myProfile => {
      const mp = myProfile.data;
      console.log(mp)
      this.$store.dispatch('dispatchMyProfile', mp)
      this.propsToPass = mp;
    })
    .catch(error => {
      console.log('There was an error:', error.response)
    })
}
// called my store here
computed: {
    menu() {
        return this.$store.state['myProfile'].profile
    }
},

// then in my template, I pass this "menu" method in child component
 <LeftPanel :data="menu" />
_x000D_
_x000D_
_x000D_

This cleared that error away. I deployed it again to firebase hosting, and viola!

Hope this bit helps you.

How does the class_weight parameter in scikit-learn work?

The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.

SUMMARY

  • for moderately imbalanced data WITHOUT noise, there is not much of a difference in applying class weights
  • for moderately imbalanced data WITH noise and strongly imbalanced, it is better to apply class weights
  • param class_weight="balanced" works decent in the absence of you wanting to optimize manually
  • with class_weight="balanced" you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
    • as a result, the total % TRUE might be higher than actual because of all the false positives
    • AUC might misguide you here if the false alarms are an issue
  • no need to change decision threshold to the imbalance %, even for strong imbalance, ok to keep 0.5 (or somewhere around that depending on what you need)

NB

The result might differ when using RF or GBM. sklearn does not have class_weight="balanced" for GBM but lightgbm has LGBMClassifier(is_unbalance=False)

CODE

# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd

# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same

# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last

print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%

print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE

Xampp MySQL not starting - "Attempting to start MySQL service..."

Had this problem today, on a Windows 10 machine. Opened C:\xampp\data\mysql_error.log and looked for lines containing [ERROR].

Last error line was:

... [ERROR] InnoDB: File (unknown): 'close' returned OS error 206. Cannot continue operation

Important note: if your error is different, google it (you'll likely find a fix).

Searching for the above error, found this thread on Apache Friends Support Forum, which led me to the fix:

  1. Open C:\xampp\mysql\bin\my.ini and add the following line towards the end of [mysqld] section (above the line containing ## UTF 8 Settings):
innodb_flush_method=normal
  1. Restart MySQL service. Should run just fine.

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

How to stop text from taking up more than 1 line?

You can use CSS white-space Property to achieve this.

white-space: nowrap

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

How to split an integer into an array of digits?

I'd rather not turn an integer into a string, so here's the function I use for this:

def digitize(n, base=10):
    if n == 0:
        yield 0
    while n:
        n, d = divmod(n, base)
        yield d

Examples:

tuple(digitize(123456789)) == (9, 8, 7, 6, 5, 4, 3, 2, 1)
tuple(digitize(0b1101110, 2)) == (0, 1, 1, 1, 0, 1, 1)
tuple(digitize(0x123456789ABCDEF, 16)) == (15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

As you can see, this will yield digits from right to left. If you'd like the digits from left to right, you'll need to create a sequence out of it, then reverse it:

reversed(tuple(digitize(x)))

You can also use this function for base conversion as you split the integer. The following example splits a hexadecimal number into binary nibbles as tuples:

import itertools as it
tuple(it.zip_longest(*[digitize(0x123456789ABCDEF, 2)]*4, fillvalue=0)) == ((1, 1, 1, 1), (0, 1, 1, 1), (1, 0, 1, 1), (0, 0, 1, 1), (1, 1, 0, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 0, 0, 1), (1, 1, 1, 0), (0, 1, 1, 0), (1, 0, 1, 0), (0, 0, 1, 0), (1, 1, 0, 0), (0, 1, 0, 0), (1, 0, 0, 0))

Note that this method doesn't handle decimals, but could be adapted to.

NTFS performance and large volumes of files and directories

I am building a File-Structure to host up to 2 billion (2^32) files and performed the following tests that show a sharp drop in Navigate + Read Performance at about 250 Files or 120 Directories per NTFS Directory on a Solid State Drive (SSD):

  • The File Performance drops by 50% between 250 and 1000 Files.
  • The Directory Performance drops by 60% between 120 and 1000 Directories.
  • Values for Numbers > 1000 remain relatively stable

Interestingly the Number of Directories and Files do NOT significantly interfere.

So the Lessons are:

  • File Numbers above 250 cost a Factor of 2
  • Directories above 120 cost a Factor of 2.5
  • The File-Explorer in Windows 7 can handle large #Files or #Dirs, but Usability is still bad.
  • Introducing Sub-Directories is not expensive

This is the Data (2 Measurements for each File and Directory):

(FOPS = File Operations per Second)
(DOPS = Directory Operations per Second)

#Files  lg(#)   FOPS    FOPS2   DOPS    DOPS2
   10   1.00    16692   16692   16421   16312
  100   2.00    16425   15943   15738   16031
  120   2.08    15716   16024   15878   16122
  130   2.11    15883   16124   14328   14347
  160   2.20    15978   16184   11325   11128
  200   2.30    16364   16052   9866    9678
  210   2.32    16143   15977   9348    9547
  220   2.34    16290   15909   9094    9038
  230   2.36    16048   15930   9010    9094
  240   2.38    15096   15725   8654    9143
  250   2.40    15453   15548   8872    8472
  260   2.41    14454   15053   8577    8720
  300   2.48    12565   13245   8368    8361
  400   2.60    11159   11462   7671    7574
  500   2.70    10536   10560   7149    7331
 1000   3.00    9092    9509    6569    6693
 2000   3.30    8797    8810    6375    6292
10000   4.00    8084    8228    6210    6194
20000   4.30    8049    8343    5536    6100
50000   4.70    7468    7607    5364    5365

And this is the Test Code:

[TestCase(50000, false, Result = 50000)]
[TestCase(50000, true, Result = 50000)]
public static int TestDirPerformance(int numFilesInDir, bool testDirs) {
    var files = new List<string>();
    var dir = Path.GetTempPath() + "\\Sub\\" + Guid.NewGuid() + "\\";
    Directory.CreateDirectory(dir);
    Console.WriteLine("prepare...");
    const string FILE_NAME = "\\file.txt";
    for (int i = 0; i < numFilesInDir; i++) {
        string filename = dir + Guid.NewGuid();
        if (testDirs) {
            var dirName = filename + "D";
            Directory.CreateDirectory(dirName);
            using (File.Create(dirName + FILE_NAME)) { }
        } else {
            using (File.Create(filename)) { }
        }
        files.Add(filename);
    }
    //Adding 1000 Directories didn't change File Performance
    /*for (int i = 0; i < 1000; i++) {
        string filename = dir + Guid.NewGuid();
        Directory.CreateDirectory(filename + "D");
    }*/
    Console.WriteLine("measure...");
    var r = new Random();
    var sw = new Stopwatch();
    sw.Start();
    int len = 0;
    int count = 0;
    while (sw.ElapsedMilliseconds < 5000) {
        string filename = files[r.Next(files.Count)];
        string text = File.ReadAllText(testDirs ? filename + "D" + FILE_NAME : filename);
        len += text.Length;
        count++;
    }
    Console.WriteLine("{0} File Ops/sec ", count / 5);
    return numFilesInDir; 
}

Finding multiple occurrences of a string within a string in Python

Using regular expressions, you can use re.finditer to find all (non-overlapping) occurences:

>>> import re
>>> text = 'Allowed Hello Hollow'
>>> for m in re.finditer('ll', text):
         print('ll found', m.start(), m.end())

ll found 1 3
ll found 10 12
ll found 16 18

Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use str.find to get the next index:

>>> text = 'Allowed Hello Hollow'
>>> index = 0
>>> while index < len(text):
        index = text.find('ll', index)
        if index == -1:
            break
        print('ll found at', index)
        index += 2 # +2 because len('ll') == 2

ll found at  1
ll found at  10
ll found at  16

This also works for lists and other sequences.

How can I align YouTube embedded video in the center in bootstrap

make iframe with align="middle" and put it in paragraph with style="text-aling:center":

<p style="text-align:center;">
<iframe width="420" height="315" align="middle" src="https://www.youtube.com/embed/YOURVIDEO">
</iframe>
</p>

Local package.json exists, but node_modules missing

This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.

please check on it and run npm install first and then npm start.

CSS3 background image transition

If you can use jQuery, you can try BgSwitcher plugin to switch the background-image with effects, it's very easy to use.

For example :

$('.bgSwitch').bgswitcher({
        images: ["style/img/bg0.jpg","style/img/bg1.jpg","style/img/bg2.jpg"],
        effect: "fade",
        interval: 10000
});

And add your own effect, see adding an effect types

MVC Calling a view from a different controller

You can move you read.aspx view to Shared folder. It is standard way in such circumstances

show icon in actionbar/toolbar with AppCompat-v7 21

getSupportActionBar().setDisplayShowHomeEnabled(true);

along with

getSupportActionBar().setIcon(R.drawable.ic_launcher);

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

Test iOS app on device without apple developer program or jailbreak

Follow these Steps:

1.Open the Xcode->Select the project->select targets->Tick an automatically manage signing->then add your apple developer account->clean the project->build the project->run,everything works fine.

How to completely uninstall Android Studio on Mac?

Some of the files individually listed by Simon would also be found with something like the following command, but with some additional assurance about thoroughness, and without the recklessness of using rm -rf with wildcards:

find ~ \
  -path ~/Library/Caches/Metadata/Safari -prune -o \
  -iname \*android\*studio\* -print -prune

Also don't forget about the SDK, which is now separate from the application, and ~/.gradle/ (see vijay's answer).

How to perform update operations on columns of type JSONB in Postgres 9.4

Ideally, you don't use JSON documents for structured, regular data that you want to manipulate inside a relational database. Use a normalized relational design instead.

JSON is primarily intended to store whole documents that do not need to be manipulated inside the RDBMS. Related:

Updating a row in Postgres always writes a new version of the whole row. That's the basic principle of Postgres' MVCC model. From a performance perspective, it hardly matters whether you change a single piece of data inside a JSON object or all of it: a new version of the row has to be written.

Thus the advice in the manual:

JSON data is subject to the same concurrency-control considerations as any other data type when stored in a table. Although storing large documents is practicable, keep in mind that any update acquires a row-level lock on the whole row. Consider limiting JSON documents to a manageable size in order to decrease lock contention among updating transactions. Ideally, JSON documents should each represent an atomic datum that business rules dictate cannot reasonably be further subdivided into smaller datums that could be modified independently.

The gist of it: to modify anything inside a JSON object, you have to assign a modified object to the column. Postgres supplies limited means to build and manipulate json data in addition to its storage capabilities. The arsenal of tools has grown substantially with every new release since version 9.2. But the principal remains: You always have to assign a complete modified object to the column and Postgres always writes a new row version for any update.

Some techniques how to work with the tools of Postgres 9.3 or later:

This answer has attracted about as many downvotes as all my other answers on SO together. People don't seem to like the idea: a normalized design is superior for non-dynamic data. This excellent blog post by Craig Ringer explains in more detail:

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

How large should my recv buffer be when calling recv in the socket library

For SOCK_STREAM socket, the buffer size does not really matter, because you are just pulling some of the waiting bytes and you can retrieve more in a next call. Just pick whatever buffer size you can afford.

For SOCK_DGRAM socket, you will get the fitting part of the waiting message and the rest will be discarded. You can get the waiting datagram size with the following ioctl:

#include <sys/ioctl.h>
int size;
ioctl(sockfd, FIONREAD, &size);

Alternatively you can use MSG_PEEK and MSG_TRUNC flags of the recv() call to obtain the waiting datagram size.

ssize_t size = recv(sockfd, buf, len, MSG_PEEK | MSG_TRUNC);

You need MSG_PEEK to peek (not receive) the waiting message - recv returns the real, not truncated size; and you need MSG_TRUNC to not overflow your current buffer.

Then you can just malloc(size) the real buffer and recv() datagram.

Remove folder and its contents from git/GitHub's history

If you are here to copy-paste code:

This is an example which removes node_modules from history

git filter-branch --tree-filter "rm -rf node_modules" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo node_modules/ >> .gitignore
git add .gitignore
git commit -m 'Removing node_modules from git history'
git gc
git push origin master --force

What git actually does:

The first line iterates through all references on the same tree (--tree-filter) as HEAD (your current branch), running the command rm -rf node_modules. This command deletes the node_modules folder (-r, without -r, rm won't delete folders), with no prompt given to the user (-f). The added --prune-empty deletes useless (not changing anything) commits recursively.

The second line deletes the reference to that old branch.

The rest of the commands are relatively straightforward.

connecting MySQL server to NetBeans

Follow these 2 steps:

STEP 1 :

Follow these steps using the Services Tab:

  1. Right click on Database
  2. Create new Connection

Customize the New COnnection as follows:

  1. Connector Name: MYSQL (Connector/J Driver)
  2. Host: localhost
  3. Port: 3306
  4. Database: mysql ( mysql is the default or enter your database name)
  5. Username: enter your database username
  6. Password: enter your database password
  7. JDBC URL: jdbc:mysql://localhost:3306/mysql
  8. CLick Finish button

NB: DELETE the ?zeroDateTimeBehaviour=convertToNull part in the URL. Instead of mysql in the URL, you should see your database name)


STEP 2 :

  1. Right click on MySQL Server at localhost:3306:[username](...)
  2. Select Properties... from the shortcut menu

In the "MySQL Server Properties" dialog select the "Admin Properties" tab Enter the following in the textboxes specified:

For Linux users :

  1. Path to start command: /usr/bin/mysql
  2. Arguments: /etc/init.d/mysql start
  3. Path to Stop command: /usr/bin/mysql
  4. Arguments: /etc/init.d/mysql stop

For MS Windows users :

NOTE: Optional:

In the Path/URL to admin tool field, type or browse to the location of your MySQL Administration application such as the MySQL Admin Tool, PhpMyAdmin, or other web-based administration tools.

Note: mysqladmin is the MySQL admin tool found in the bin folder of the MySQL installation directory. It is a command-line tool and not ideal for use with the IDE.

Citations:
https://netbeans.org/kb/docs/ide/mysql.html?print=yes
http://javawebaction.blogspot.com/2013/04/how-to-register-mysql-database-server.html


We will use MySQL Workbench in this example. Please use the path of your installation if you have MySQL workbench and the path to MySQL.

  1. Path/URL to admin tool: C:\Program Files\MySQL\MySQL Workbench CE 5.2.47\MySQLWorkbench.exe
  2. Arguments: (Leave blank)
  3. Path to start command: C:\mysql\bin\mysqld (OR C:\mysql\bin\mysqld.exe)
  4. Arguments: (Leave blank)
  5. Path to Stop command: C:\mysql\bin\mysqladmin (OR C:\mysql\bin\mysqladmin.exe )
  6. Arguments: -u root shutdown (Try -u root stop)

Possible exampes of MySQL bin folder locations for Windows Users:

  • C:\mysql\bin
  • C:\Program Files\MySQL\MySQL Server 5.1\bin\
  • Installation Folder: ~\xampp\mysql\bin

How to create an integer array in Python?

>>> a = [0] * 10
>>> a
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How to replace ${} placeholders in a text file?

Sed!

Given template.txt:

The number is ${i}
The word is ${word}

we just have to say:

sed -e "s/\${i}/1/" -e "s/\${word}/dog/" template.txt

Thanks to Jonathan Leffler for the tip to pass multiple -e arguments to the same sed invocation.

Regex pattern inside SQL Replace function?

You can use PATINDEX to find the first index of the pattern (string's) occurrence. Then use STUFF to stuff another string into the pattern(string) matched.

Loop through each row. Replace each illegal characters with what you want. In your case replace non numeric with blank. The inner loop is if you have more than one illegal character in a current cell that of the loop.

DECLARE @counter int

SET @counter = 0

WHILE(@counter < (SELECT MAX(ID_COLUMN) FROM Table))
BEGIN  

    WHILE 1 = 1
    BEGIN
        DECLARE @RetVal varchar(50)

        SET @RetVal =  (SELECT Column = STUFF(Column, PATINDEX('%[^0-9.]%', Column),1, '')
        FROM Table
        WHERE ID_COLUMN = @counter)

        IF(@RetVal IS NOT NULL)       
          UPDATE Table SET
          Column = @RetVal
          WHERE ID_COLUMN = @counter
        ELSE
            break
    END

    SET @counter = @counter + 1
END

Caution: This is slow though! Having a varchar column may impact. So using LTRIM RTRIM may help a bit. Regardless, it is slow.

Credit goes to this StackOverFlow answer.

EDIT Credit also goes to @srutzky

Edit (by @Tmdean) Instead of doing one row at a time, this answer can be adapted to a more set-based solution. It still iterates the max of the number of non-numeric characters in a single row, so it's not ideal, but I think it should be acceptable in most situations.

WHILE 1 = 1 BEGIN
    WITH q AS
        (SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
        FROM Table)
    UPDATE Table
    SET Column = STUFF(Column, q.n, 1, '')
    FROM q
    WHERE Table.ID_Column = q.ID_Column AND q.n != 0;

    IF @@ROWCOUNT = 0 BREAK;
END;

You can also improve efficiency quite a lot if you maintain a bit column in the table that indicates whether the field has been scrubbed yet. (NULL represents "Unknown" in my example and should be the column default.)

DECLARE @done bit = 0;
WHILE @done = 0 BEGIN
    WITH q AS
        (SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
        FROM Table
        WHERE COALESCE(Scrubbed_Column, 0) = 0)
    UPDATE Table
    SET Column = STUFF(Column, q.n, 1, ''),
        Scrubbed_Column = 0
    FROM q
    WHERE Table.ID_Column = q.ID_Column AND q.n != 0;

    IF @@ROWCOUNT = 0 SET @done = 1;

    -- if Scrubbed_Column is still NULL, then the PATINDEX
    -- must have given 0
    UPDATE table
    SET Scrubbed_Column = CASE
        WHEN Scrubbed_Column IS NULL THEN 1
        ELSE NULLIF(Scrubbed_Column, 0)
    END;
END;

If you don't want to change your schema, this is easy to adapt to store intermediate results in a table valued variable which gets applied to the actual table at the end.

How to set the 'selected option' of a select dropdown list with jquery

The match between .val('Bruce jones') and value="Bruce Jones" is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase() on both.

How to convert MySQL time to UNIX timestamp using PHP?

You can mysql's UNIX_TIMESTAMP function directly from your query, here is an example:

SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');

Similarly, you can pass in the date/datetime field:

SELECT UNIX_TIMESTAMP(yourField);

How to git reset --hard a subdirectory?

According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:

git checkout -- a

(where a is the directory you want to hard-reset). The original behavior can be accessed via

git checkout --ignore-skip-worktree-bits -- a

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Disable the postback on an <ASP:LinkButton>

This may sound like an unhelpful answer ... But why are you using a LinkButton for something purely client-side? Use a standard HTML anchor tag and set its onclick action to your Javascript.

If you need the server to generate the text of that link, then use an asp:Label as the content between the anchor's start and end tags.

If you need to dynamically change the script behavior based on server-side code, consider asp:Literal as a technique.

But unless you're doing server-side activity from the Click event of the LinkButton, there just doesn't seem to be much point to using it here.

How to zip a whole folder using PHP

I assume this is running on a server where the zip application is in the search path. Should be true for all unix-based and I guess most windows-based servers.

exec('zip -r archive.zip "My folder"');
unlink('My\ folder/index.html');
unlink('My\ folder/picture.jpg');

The archive will reside in archive.zip afterwards. Keep in mind that blanks in file or folder names are a common cause of errors and should be avoided where possible.

What's the difference between deadlock and livelock?

Taken from http://en.wikipedia.org/wiki/Deadlock:

In concurrent computing, a deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock

A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.

A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.

Livelock is a risk with some algorithms that detect and recover from deadlock. If more than one process takes action, the deadlock detection algorithm can be repeatedly triggered. This can be avoided by ensuring that only one process (chosen randomly or by priority) takes action.

How to stop/shut down an elasticsearch node?

If you're running a node on localhost, try to use brew service stop elasticsearch

I run elasticsearch on iOS localhost.

A regex for version number parsing

This might work:

^(\*|\d+(\.\d+){0,2}(\.\*)?)$

At the top level, "*" is a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two ".nn" sequences, followed by an optional ".*". This regex would accept 1.2.3.* which may or may not be permitted in your application.

The code for retrieving the matched sequences, especially the (\.\d+){0,2} part, will depend on your particular regex library.

WPF User Control Parent

If you are finding this question and the VisualTreeHelper isn't working for you or working sporadically, you may need to include LogicalTreeHelper in your algorithm.

Here is what I am using:

public static T TryFindParent<T>(DependencyObject current) where T : class
{
    DependencyObject parent = VisualTreeHelper.GetParent(current);
    if( parent == null )
        parent = LogicalTreeHelper.GetParent(current);
    if( parent == null )
        return null;

    if( parent is T )
        return parent as T;
    else
        return TryFindParent<T>(parent);
}

What is the easiest way to get current GMT time in Unix timestamp format?

#First Example:
from datetime import datetime, timezone    
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)

Output: 1572878043380

#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)

Output: 1572878043

  • Here, we can see the first example gives more accurate time than second one.
  • Here I am using the first one.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

my problem was the newVersion in this code in web.config was not correct

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.1.0" />

you can see the version of Newtonsoft.Json package in nuget package manager and use it.

JQuery: dynamic height() with window resize()

I feel like there should be a no javascript solution, but how is this?

http://jsfiddle.net/NfmX3/2/

$(window).resize(function() {
    $('#content').height($(window).height() - 46);
});

$(window).trigger('resize');

How to log Apache CXF Soap Request and Soap Response using Log4j?

This worked for me.

Setup log4j as normal. Then use this code:

    // LOGGING 
    LoggingOutInterceptor loi = new LoggingOutInterceptor(); 
    loi.setPrettyLogging(true); 
    LoggingInInterceptor lii = new LoggingInInterceptor(); 
    lii.setPrettyLogging(true); 

    org.apache.cxf.endpoint.Client client = org.apache.cxf.frontend.ClientProxy.getClient(isalesService); 
    org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); 

    cxfEndpoint.getOutInterceptors().add(loi); 
    cxfEndpoint.getInInterceptors().add(lii);

Google Maps API Multiple Markers with Infowindows

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  

How permission can be checked at runtime without throwing SecurityException?

Sharing my methods in case someone needs them:

 /** Determines if the context calling has the required permission
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermission(Context context, String permission) {

    int res = context.checkCallingOrSelfPermission(permission);

    Log.v(TAG, "permission: " + permission + " = \t\t" + 
    (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));

    return res == PackageManager.PERMISSION_GRANTED;

}

/** Determines if the context calling has the required permissions
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermissions(Context context, String... permissions) {

    boolean hasAllPermissions = true;

    for(String permission : permissions) {
        //you can return false instead of assigning, but by assigning you can log all permission values
        if (! hasPermission(context, permission)) {hasAllPermissions = false; }
    }

    return hasAllPermissions;

}

And to call it:

boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {
                android.Manifest.permission.ACCESS_WIFI_STATE,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.ACCESS_NETWORK_STATE,
                android.Manifest.permission.INTERNET,
        });

MongoDB "root" user

I noticed a lot of these answers, use this command:

use admin

which switches to the admin database. At least in Mongo v4.0.6, creating a user in the context of the admin database will create a user with "_id" : "admin.administrator":

> use admin
> db.getUsers()
[ ]
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
> db.getUsers()
[
    {
        "_id" : "admin.administrator",
        "user" : "administrator",
        "db" : "admin",
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

I emphasize "admin.administrator", for I have a Mongoid (mongodb ruby adapter) application with a different database than admin and I use the URI to reference the database in my mongoid.yml configuration:

development:
  clients:
    default:
      uri: <%= ENV['MONGODB_URI'] %>
      options:
        connect_timeout: 15
        retry_writes: false

This references the following environment variable:

export MONGODB_URI='mongodb://administrator:[email protected]/mysite_development?retryWrites=true&w=majority'

Notice the database is mysite_development, not admin. When I try to run the application, I get an error "User administrator (mechanism: scram256) is not authorized to access mysite_development".

So I return to the Mongo shell delete the user, switch to the specified database and recreate the user:

$ mongo
> db.dropUser('administrator')
> db.getUsers()
[]
> use mysite_development
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
> db.getUsers()
[
    {
        "_id" : "mysite_development.administrator",
        "user" : "administrator",
        "db" : "mysite_development",
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

Notice that the _id and db changed to reference the specific database my application depends on:

"_id" : "mysite_development.administrator",
"db" : "mysite_development",

After making this change, the error went away and I was able to connect to MongoDB fine inside my application.

Extra Notes:

In my example above, I deleted the user and recreated the user in the right database context. Had you already created the user in the right database context but given it the wrong roles, you could assign a mongodb built-in role to the user:

db.grantRolesToUser('administrator', [{ role: 'root', db: 'admin' }])

There is also a db.updateUser command, albiet typically used to update the user password.

Brew doctor says: "Warning: /usr/local/include isn't writable."

You need to create /usr/local/include and /usr/local/lib if they don't exists:

$ sudo mkdir -p /usr/local/include
$ sudo chown -R $USER:admin /usr/local/include

Hibernate Group by Criteria Object

GroupBy using in Hibernate

This is the resulting code

public Map getStateCounts(final Collection ids) {
    HibernateSession hibernateSession = new HibernateSession();
    Session session = hibernateSession.getSession();
    Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
            .add(Restrictions.in("id", ids));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("state"));
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);
    List results = criteria.list();
    Map stateMap = new HashMap();
    for (Object[] obj : results) {
        DownloadState downloadState = (DownloadState) obj[0];
        stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
    }
    hibernateSession.closeSession();
    return stateMap;
}

How to execute Ant build in command line

Try running all targets individually to check that all are running correct

run ant target name to run a target individually

e.g. ant build-project

Also the default target you specified is

project basedir="." default="build" name="iControlSilk4J"

This will only execute build-subprojects,build-project and init

Generating random number between 1 and 10 in Bash Shell Script

To generate in the range: {0,..,9}

r=$(( $RANDOM % 10 )); echo $r

To generate in the range: {40,..,49}

r=$(( $RANDOM % 10 + 40 )); echo $r

How to use Git and Dropbox together?

I have faced a similar issue and have created a small script for the same. The idea is to use Dropbox with Git as simply as possible. Currently, I have quickly implemented Ruby code, and I will soon add more.

The script is accessible at https://github.com/nuttylabs/box-git.

How can I return to a parent activity correctly?

try this:

Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
    intent = getIntent();   
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_b, menu);
    return true;
}  

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpTo(this,intent);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

sorting dictionary python 3

Sorting dictionaries by value using comprehensions. I think it's nice as 1 line and no need for functions or lambdas

a = {'b':'foo', 'c':'bar', 'e': 'baz'}
a = {f:a[f] for f in sorted(a, key=a.__getitem__)}

Implementing INotifyPropertyChanged - does a better way exist?

I came up with this base class to implement the observable pattern, pretty much does what you need ("automatically" implementing the set and get). I spent line an hour on this as prototype, so it doesn't have many unit tests, but proves the concept. Note it uses the Dictionary<string, ObservablePropertyContext> to remove the need for private fields.

  public class ObservableByTracking<T> : IObservable<T>
  {
    private readonly Dictionary<string, ObservablePropertyContext> _expando;
    private bool _isDirty;

    public ObservableByTracking()
    {
      _expando = new Dictionary<string, ObservablePropertyContext>();

      var properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
      foreach (var property in properties)
      {
        var valueContext = new ObservablePropertyContext(property.Name, property.PropertyType)
        {
          Value = GetDefault(property.PropertyType)
        };

        _expando[BuildKey(valueContext)] = valueContext;
      }
    }

    protected void SetValue<T>(Expression<Func<T>> expression, T value)
    {
      var keyContext = GetKeyContext(expression);
      var key = BuildKey(keyContext.PropertyName, keyContext.PropertyType);

      if (!_expando.ContainsKey(key))
      {
        throw new Exception($"Object doesn't contain {keyContext.PropertyName} property.");
      }

      var originalValue = (T)_expando[key].Value;
      if (EqualityComparer<T>.Default.Equals(originalValue, value))
      {
        return;
      }

      _expando[key].Value = value;
      _isDirty = true;
    }

    protected T GetValue<T>(Expression<Func<T>> expression)
    {
      var keyContext = GetKeyContext(expression);
      var key = BuildKey(keyContext.PropertyName, keyContext.PropertyType);

      if (!_expando.ContainsKey(key))
      {
        throw new Exception($"Object doesn't contain {keyContext.PropertyName} property.");
      }

      var value = _expando[key].Value;
      return (T)value;
    }

    private KeyContext GetKeyContext<T>(Expression<Func<T>> expression)
    {
      var castedExpression = expression.Body as MemberExpression;
      if (castedExpression == null)
      {
        throw new Exception($"Invalid expression.");
      }

      var parameterName = castedExpression.Member.Name;

      var propertyInfo = castedExpression.Member as PropertyInfo;
      if (propertyInfo == null)
      {
        throw new Exception($"Invalid expression.");
      }

      return new KeyContext {PropertyType = propertyInfo.PropertyType, PropertyName = parameterName};
    }

    private static string BuildKey(ObservablePropertyContext observablePropertyContext)
    {
      return $"{observablePropertyContext.Type.Name}.{observablePropertyContext.Name}";
    }

    private static string BuildKey(string parameterName, Type type)
    {
      return $"{type.Name}.{parameterName}";
    }

    private static object GetDefault(Type type)
    {
      if (type.IsValueType)
      {
        return Activator.CreateInstance(type);
      }
      return null;
    }

    public bool IsDirty()
    {
      return _isDirty;
    }

    public void SetPristine()
    {
      _isDirty = false;
    }

    private class KeyContext
    {
      public string PropertyName { get; set; }
      public Type PropertyType { get; set; }
    }
  }

  public interface IObservable<T>
  {
    bool IsDirty();
    void SetPristine();
  }

Here's the usage

public class ObservableByTrackingTestClass : ObservableByTracking<ObservableByTrackingTestClass>
  {
    public ObservableByTrackingTestClass()
    {
      StringList = new List<string>();
      StringIList = new List<string>();
      NestedCollection = new List<ObservableByTrackingTestClass>();
    }

    public IEnumerable<string> StringList
    {
      get { return GetValue(() => StringList); }
      set { SetValue(() => StringIList, value); }
    }

    public IList<string> StringIList
    {
      get { return GetValue(() => StringIList); }
      set { SetValue(() => StringIList, value); }
    }

    public int IntProperty
    {
      get { return GetValue(() => IntProperty); }
      set { SetValue(() => IntProperty, value); }
    }

    public ObservableByTrackingTestClass NestedChild
    {
      get { return GetValue(() => NestedChild); }
      set { SetValue(() => NestedChild, value); }
    }

    public IList<ObservableByTrackingTestClass> NestedCollection
    {
      get { return GetValue(() => NestedCollection); }
      set { SetValue(() => NestedCollection, value); }
    }

    public string StringProperty
    {
      get { return GetValue(() => StringProperty); }
      set { SetValue(() => StringProperty, value); }
    }
  }

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

In Mac OS -moz-appearance: window; will remove the arrow accrding to the MDN docs here: https://developer.mozilla.org/en-US/docs/CSS/-moz-appearance. Tested on Firefox 13 on Mac OS X 10.8.2. Also see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c21.

Change hash without reload in jQuery

This works for me

$('ul.questions li a').click(function(event) {
    event.preventDefault();
    $('.tab').hide();
    window.location.hash = this.hash;
    $($(this).attr('href')).fadeIn('slow');
});

Check here http://jsbin.com/edicu for a demo with almost identical code

How do I retrieve the number of columns in a Pandas data frame?

In order to include the number of row index "columns" in your total shape I would personally add together the number of columns df.columns.size with the attribute pd.Index.nlevels/pd.MultiIndex.nlevels:

Set up dummy data

import pandas as pd

flat_index = pd.Index([0, 1, 2])
multi_index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), names=["letter", "id"])

columns = ["cat", "dog", "fish"]

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_df = pd.DataFrame(data, index=flat_index, columns=columns)
multi_df = pd.DataFrame(data, index=multi_index, columns=columns)

# Show data
# -----------------
# 3 columns, 4 including the index
print(flat_df)
    cat  dog  fish
id                
0     1    2     3
1     4    5     6
2     7    8     9

# -----------------
# 3 columns, 5 including the index
print(multi_df)
           cat  dog  fish
letter id                
a      1     1    2     3
       2     4    5     6
b      1     7    8     9

Writing our process as a function:

def total_ncols(df, include_index=False):
    ncols = df.columns.size
    if include_index is True:
        ncols += df.index.nlevels
    return ncols

print("Ignore the index:")
print(total_ncols(flat_df), total_ncols(multi_df))

print("Include the index:")
print(total_ncols(flat_df, include_index=True), total_ncols(multi_df, include_index=True))

This prints:

Ignore the index:
3 3

Include the index:
4 5

If you want to only include the number of indices if the index is a pd.MultiIndex, then you can throw in an isinstance check in the defined function.

As an alternative, you could use df.reset_index().columns.size to achieve the same result, but this won't be as performant since we're temporarily inserting new columns into the index and making a new index before getting the number of columns.

Facebook share link - can you customize the message body text?

You can't do this using sharer.php, but you can do something similar using the Dialog API. http://developers.facebook.com/docs/reference/dialogs/

http://www.facebook.com/dialog/feed?  
app_id=123050457758183&  
link=http://developers.facebook.com/docs/reference/dialogs/&
picture=http://fbrell.com/f8.jpg&  
name=Facebook%20Dialogs&  
caption=Reference%20Documentation& 
description=Dialogs%20provide%20a%20simple,%20consistent%20interface%20for%20applications%20to%20interact%20with%20users.&
message=Facebook%20Dialogs%20are%20so%20easy!&
redirect_uri=http://www.example.com/response

Facebook dialog example

The catch is you must create a dummy Facebook application just to have an app_id. Note that your Facebook application doesn't have to do ANYTHING at all. Just be sure that it is properly configured, and you should be all set.

detect back button click in browser

So as far as AJAX is concerned...

Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;   
            }
        };
    }
}

As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

How to get $(this) selected option in jQuery?

For the selected value: $(this).val()

If you need the selected option element, $("option:selected", this)

Is it possible to focus on a <div> using JavaScript focus() function?

<div id="inner" tabindex="0">
    this div can now have focus and receive keyboard events
</div>

Showing which files have changed between two revisions

If anyone is trying to generate a diff file from two branches :

git diff master..otherbranch > myDiffFile.diff

Disable button after click in JQuery

You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true);

I have made a simple example http://jsfiddle.net/4gnXL/2/

Materialize CSS - Select Doesn't Seem to Render

If you're using Angularjs, you can use the angular-materialize plugin, which provides some handy directives. Then you don't need to initialize in the js, just add material-select to your select:

<div input-field>
    <select class="" ng-model="select.value1" material-select>
        <option ng-repeat="value in select.choices">{{value}}</option>
    </select>
</div>

svn cleanup: sqlite: database disk image is malformed

I fixed this for an instance of it happening to me by deleting the hidden .svn folder and then performing a checkout on the folder to the same URL.

This did not overwrite any of my modified files & just versioned all of the existing files instead of grabbing fresh copies from the server.

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

Try doing reinstallation of pip :

curl -O https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
tar xvfz pip-1.2.1.tar.gz
cd pip-1.2.1
python setup.py install

If curl doesnot work , you will have proxy issues , Please fix that it should work fine. Check after opening google.com in your browser in linux.

The try installing

pip install virtualenv

Appending HTML string to the DOM

Performance

AppendChild (E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML(F) is fastest on firefox. The innerHTML= (B) (do not confuse with += (A)) is second fast solution on all browsers and it is much more handy than E and F.

Details

Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)

enter image description here

  • on Chrome E (140k operations per second) is fastest, B (47k) and F (46k) are second, A (332) is slowest
  • on firefox F (94k) is fastest, then B(80k), D (73k), E(64k), C (21k) slowest is A(466)
  • on Safari E(207k) is fastest, then B(89k), F(88k), D(83k), C (25k), slowest is A(509)

You can replay test in your machine here

_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML += '<p>A: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML = '<p>B: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  $('#container').append('<p>C: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
function D() {_x000D_
  var p = document.createElement("p");_x000D_
  p.innerHTML = 'D: Just some <span>text</span> here';_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function E() {    _x000D_
  var p = document.createElement("p");_x000D_
  var s = document.createElement("span"); _x000D_
  s.appendChild( document.createTextNode("text ") );_x000D_
  p.appendChild( document.createTextNode("E: Just some ") );_x000D_
  p.appendChild( s );_x000D_
  p.appendChild( document.createTextNode(" here") );_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
This snippet only for show code used in test (in jsperf.com) - it not perform test itself. _x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Best way to handle multiple constructors in Java

You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).

These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:

class Book {
    private String title; // not nullable
    private String isbn;  // nullable

    // Here we provide a default value, but we could also skip the 
    // parameterless constructor entirely, to force users of the class to
    // provide a title
    public Book()
    {
        this("Untitled"); 
    }

    public Book(String title) throws IllegalArgumentException
    {
        if (title == null) 
            throw new IllegalArgumentException("Book title can't be null");
        this.title = title;
        // leave isbn without value
    }
    // Constructor with title and isbn
}

However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.

Example of a strong and weak entity types

After browsing search engines for a few hours I came across a site with a great ERD example here: http://www.exploredatabase.com/2016/07/description-about-weak-entity-sets-in-DBMS.html

I've recreated the ERD. Unfortunately they did not specify the primary key of the weak entity.

enter image description here

If the building could only have one and only one apartment, then it seems the partial discriminator room number would not be created (i.e. discarded).

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

Syntactic sugar, makes it more obvious to the casual reader that the join isn't an inner one.

OpenCV & Python - Image too big to display

In opencv, cv.namedWindow() just creates a window object as you determine, but not resizing the original image. You can use cv2.resize(img, resolution) to solve the problem.

Here's what it displays, a 740 * 411 resolution image. The original image

image = cv2.imread("740*411.jpg")
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, it displays a 100 * 200 resolution image after resizing. Remember the resolution parameter use column first then is row.

Image after resizing

image = cv2.imread("740*411.jpg")
image = cv2.resize(image, (200, 100))
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Java compiler level does not match the version of the installed Java project facet

Right click the project and select properties Click the java compiler from the left and change to your required version Hope this helps

How to clear the cache of nginx?

In my nginx install I found I had to go to:

/opt/nginx/cache

and

sudo rm -rf *

in that directory. If you know the path to your nginx install and can find the cache directory the same may work for you. Be very careful with the rm -rf command, if you are in the wrong directory you could delete your entire hard drive.

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Bash script prints "Command Not Found" on empty lines

If you have Notepad++ and you get this .sh Error Message: "command not found" or this autoconf Error Message "line 615: ../../autoconf/bin/autom4te: No such file or directory".

On your Notepad++, Go to Edit -> EOL Conversion then check Macinthos(CR). This will edit your files. I also encourage to check all files with this command, because soon such an error will occur.

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

How to do sed like text replace with python?

massedit.py (http://github.com/elmotec/massedit) does the scaffolding for you leaving just the regex to write. It's still in beta but we are looking for feedback.

python -m massedit -e "re.sub(r'^# deb', 'deb', line)" /etc/apt/sources.list

will show the differences (before/after) in diff format.

Add the -w option to write the changes to the original file:

python -m massedit -e "re.sub(r'^# deb', 'deb', line)" -w /etc/apt/sources.list

Alternatively, you can now use the api:

>>> import massedit
>>> filenames = ['/etc/apt/sources.list']
>>> massedit.edit_files(filenames, ["re.sub(r'^# deb', 'deb', line)"], dry_run=True)

How to generate class diagram from project in Visual Studio 2013?

Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

Using DISTINCT and COUNT together in a MySQL Query

What the hell of all this work anthers

it's too simple

if you want a list of how much productId in each keyword here it's the code

SELECT count(productId),  keyword  FROM `Table_name` GROUP BY keyword; 

How to use a variable inside a regular expression?

you can try another usage using format grammer suger:

re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)  

How to toggle a boolean?

In a case where you may be storing true / false as strings, such as in localStorage where the protocol flipped to multi object storage in 2009 & then flipped back to string only in 2011 - you can use JSON.parse to interpret to boolean on the fly:

this.sidebar = !JSON.parse(this.sidebar);

How to locate the php.ini file (xampp)

I've always found the easiest way is php -i and filtering down.

*nix (including MacOS):

php -i | grep "Loaded Configuration File"

Windows:

php -i | findstr /C:"Loaded Configuration File"

Of course this assumes your CLI environment is using the same PHP binaries as your actual web server.

You can always check that to be sure using which php in *nix and where php in Windows.

Printf long long int in C with GCC?

You can try settings of code::block, there is a complier..., then you select in C mode.

enter image description here

Filter an array using a formula (without VBA)

Today, in Office 365, Excel has so called 'array functions'. The filter function does exactly what you want. No need to use CTRL+SHIFT+ENTER anymore, a simple enter will suffice.

In Office 365, your problem would be simply solved by using:

=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)

github markdown colspan

I recently needed to do the same thing, and was pleased that the colspan worked fine with consecutive pipes ||

MultiMarkdown v4.5

Tested on v4.5 (latest on macports) and the v5.4 (latest on homebrew). Not sure why it doesn't work on the live preview site you provide.

A simple test that I started with was:

| Header ||
|--------------|
| 0 | 1 |

using the command:

multimarkdown -t html test.md > test.html

how to delete files from amazon s3 bucket?

Below is code snippet you can use to delete the bucket,

import boto3, botocore
from botocore.exceptions import ClientError

s3 = boto3.resource("s3",aws_access_key_id='Your-Access-Key',aws_secret_access_key='Your-Secret-Key')
s3.Object('Bucket-Name', 'file-name as key').delete()

Could not reliably determine the server's fully qualified domain name

FQDN means the resolved name over DNS. It should be like "server-name.search-domain".

The warning you get just provides a notice that httpd can not find a FQDN, so it might not work right to handle a name-based virtual host. So make sure the expected FQDN is registered in your DNS server, or manually add the entry in /etc/hosts which is prior to hitting DNS.

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

Removing object properties with Lodash

Lodash unset is suitable for removing a few unwanted keys.

_x000D_
_x000D_
const myObj = {
    keyOne: "hello",
    keyTwo: "world"
}

unset(myObj, "keyTwo");

console.log(myObj); /// myObj = { keyOne: "hello" }
_x000D_
_x000D_
_x000D_

Oracle find a constraint

To get a more detailed description (which table/column references which table/column) you can run the following query:

SELECT   uc.constraint_name||CHR(10)
   ||      '('||ucc1.TABLE_NAME||'.'||ucc1.column_name||')' constraint_source
   ,       'REFERENCES'||CHR(10)
   ||      '('||ucc2.TABLE_NAME||'.'||ucc2.column_name||')' references_column
FROM user_constraints uc ,
  user_cons_columns ucc1 ,
  user_cons_columns ucc2
WHERE uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION        = ucc2.POSITION -- Correction for multiple column primary keys.
AND uc.constraint_type   = 'R'
AND uc.constraint_name   = 'SYS_C00381400'
ORDER BY ucc1.TABLE_NAME ,
  uc.constraint_name;

From here.

Android SDK manager won't open

Been trying to get the SDK manager to run for a while now following various threads with similar problems I could find.

Another solution to consider is to move android SDK to a dir without spaces in its name.

For instance in my case it resided in:

e:\Program Files (x86)\Android\android-sdk\

and would fail. When moved to:

c:\android_sdk_sucks\

It worked.

Display date in dd/mm/yyyy format in vb.net

First, uppercase MM are months and lowercase mm are minutes.

You have to pass CultureInfo.InvariantCulture to ToString to ensure that / as date separator is used since it would normally be replaced with the current culture's date separator:

MsgBox(dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture))

Another option is to escape that custom format specifier by embedding the / within ':

dt.ToString("dd'/'MM'/'yyyy")

MSDN: The "/" Custom Format Specifier:

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

Handle Button click inside a row in RecyclerView

You can check if you have any similar entries first, if you get a collection with size 0, start a new query to save.

OR

more professional and faster way. create a cloud trigger (before save)

check out this answer https://stackoverflow.com/a/35194514/1388852

Python 3 - Encode/Decode vs Bytes/Str

To add to add to the previous answer, there is even a fourth way that can be used

import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)

How to create an infinite loop in Windows batch file?

How about using good(?) old goto?

:loop

echo Ooops

goto loop

See also this for a more useful example.

File upload along with other object in Jersey restful web service

The request type is multipart/form-data and what you are sending is essentially form fields that go out as bytes with content boundaries separating different form fields.To send an object representation as form field (string), you can send a serialized form from the client that you can then deserialize on the server.

After all no programming environment object is actually ever traveling on the wire. The programming environment on both side are just doing automatic serialization and deserialization that you can also do. That is the cleanest and programming environment quirks free way to do it.

As an example, here is a javascript client posting to a Jersey example service,

submitFile(){

    let data = new FormData();
    let account = {
        "name": "test account",
        "location": "Bangalore"
    }

    data.append('file', this.file);
    data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
    data.append("device", "test001");
    data.append("account", JSON.stringify(account));
    
    let url = "http://localhost:9090/sensordb/test/file/multipart/upload";

    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    axios.post(url, data, config).then(function(data){
        console.log('SUCCESS!!');
        console.log(data.data);
    }).catch(function(){
        console.log('FAILURE!!');
    });
},

Here the client is sending a file, 2 form fields (strings) and an account object that has been stringified for transport. here is how the form fields look on the wire,

enter image description here

On the server, you can just deserialize the form fields the way you see fit. To finish this trivial example,

    @POST
@Path("/file/multipart/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition cdh,
        @FormDataParam("accountKey") String accountKey,
        @FormDataParam("account") String json)  {
    

    
    System.out.println(cdh.getFileName());
    System.out.println(cdh.getName());
    System.out.println(accountKey);
    
    try {
        Account account = Account.deserialize(json);
        System.out.println(account.getLocation());
        System.out.println(account.getName());
        
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return Response.ok().build();
    
}

How can I reverse a NSArray in Objective-C?

Georg Schölly's categories are very nice. However, for NSMutableArray, using NSUIntegers for the indices results in a crash when the array is empty. The correct code is:

@implementation NSMutableArray (Reverse)

- (void)reverse {
    NSInteger i = 0;
    NSInteger j = [self count] - 1;
    while (i < j) {
        [self exchangeObjectAtIndex:i
                  withObjectAtIndex:j];

        i++;
        j--;
    }
}

@end

Behaviour of increment and decrement operators in Python

While the others answers are correct in so far as they show what a mere + usually does (namely, leave the number as it is, if it is one), they are incomplete in so far as they don't explain what happens.

To be exact, +x evaluates to x.__pos__() and ++x to x.__pos__().__pos__().

I could imagine a VERY weird class structure (Children, don't do this at home!) like this:

class ValueKeeper(object):
    def __init__(self, value): self.value = value
    def __str__(self): return str(self.value)

class A(ValueKeeper):
    def __pos__(self):
        print 'called A.__pos__'
        return B(self.value - 3)

class B(ValueKeeper):
    def __pos__(self):
        print 'called B.__pos__'
        return A(self.value + 19)

x = A(430)
print x, type(x)
print +x, type(+x)
print ++x, type(++x)
print +++x, type(+++x)

How to run a SQL query on an Excel table?

I might be misunderstanding me, but isn't this exactly what a pivot table does? Do you have the data in a table or just a filtered list? If its not a table make it one (ctrl+l) if it is, then simply activate any cell in the table and insert a pivot table on another sheet. Then Add the columns lastname, firstname, phonenumber to the rows section. Then Add Phone number to the filter section and filter out the null values. Now Sort like normal.

How do I find if a string starts with another string in Ruby?

The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

Have a play with Rubular: http://rubular.com/

But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

'abcdefg' =~  /\Aabc/ 

How do you decrease navbar height in Bootstrap 3?

bootstrap had 15px top padding and 15px bottom padding on .navbar-nav > li > a so you need to decrease it by overriding it in your css file and .navbar has min-height:50px; decrease it as much you want.

for example

.navbar-nav > li > a {padding-top:5px !important; padding-bottom:5px !important;}
.navbar {min-height:32px !important}

add these classes to your css and then check.

What is an .inc and why use it?

In my opinion, these were used as a way to quickly find include files when developing. Really these have been made obsolete with conventions and framework designs.

Read .csv file in C

The following code is in plain c language and handles blank spaces. It only allocates memory once, so one free() is needed, for each processed line.

http://ideone.com/mSCgPM

/* Tiny CSV Reader */
/* Copyright (C) 2015, Deligiannidis Konstantinos

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://w...content-available-to-author-only...u.org/licenses/>.  */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>


/* For more that 100 columns or lines (when delimiter = \n), minor modifications are needed. */
int getcols( const char * const line, const char * const delim, char ***out_storage )

{
const char *start_ptr, *end_ptr, *iter;
char **out;
int i;                                          //For "for" loops in the old c style.
int tokens_found = 1, delim_size, line_size;    //Calculate "line_size" indirectly, without strlen() call.
int start_idx[100], end_idx[100];   //Store the indexes of tokens. Example "Power;": loc('P')=1, loc(';')=6
//Change 100 with MAX_TOKENS or use malloc() for more than 100 tokens. Example: "b1;b2;b3;...;b200"

if ( *out_storage != NULL )                 return -4;  //This SHOULD be NULL: Not Already Allocated
if ( !line || !delim )                      return -1;  //NULL pointers Rejected Here
if ( (delim_size = strlen( delim )) == 0 )  return -2;  //Delimiter not provided

start_ptr = line;   //Start visiting input. We will distinguish tokens in a single pass, for good performance.
                    //Then we are allocating one unified memory region & doing one memory copy.
while ( ( end_ptr = strstr( start_ptr, delim ) ) ) {

    start_idx[ tokens_found -1 ] = start_ptr - line;    //Store the Index of current token
    end_idx[ tokens_found - 1 ] = end_ptr - line;       //Store Index of first character that will be replaced with
                                                        //'\0'. Example: "arg1||arg2||end" -> "arg1\0|arg2\0|end"
    tokens_found++;                                     //Accumulate the count of tokens.
    start_ptr = end_ptr + delim_size;                   //Set pointer to the next c-string within the line
}

for ( iter = start_ptr; (*iter!='\0') ; iter++ );

start_idx[ tokens_found -1 ] = start_ptr - line;    //Store the Index of current token: of last token here.
end_idx[ tokens_found -1 ] = iter - line;           //and the last element that will be replaced with \0

line_size = iter - line;    //Saving CPU cycles: Indirectly Count the size of *line without using strlen();

int size_ptr_region = (1 + tokens_found)*sizeof( char* );   //The size to store pointers to c-strings + 1 (*NULL).
out = (char**) malloc( size_ptr_region + ( line_size + 1 ) + 5 );   //Fit everything there...it is all memory.
//It reserves a contiguous space for both (char**) pointers AND string region. 5 Bytes for "Out of Range" tests.
*out_storage = out;     //Update the char** pointer of the caller function.

//"Out of Range" TEST. Verify that the extra reserved characters will not be changed. Assign Some Values.
//char *extra_chars = (char*) out + size_ptr_region + ( line_size + 1 );
//extra_chars[0] = 1; extra_chars[1] = 2; extra_chars[2] = 3; extra_chars[3] = 4; extra_chars[4] = 5;

for ( i = 0; i < tokens_found; i++ )    //Assign adresses first part of the allocated memory pointers that point to
    out[ i ] = (char*) out + size_ptr_region + start_idx[ i ];  //the second part of the memory, reserved for Data.
out[ tokens_found ] = (char*) NULL; //[ ptr1, ptr2, ... , ptrN, (char*) NULL, ... ]: We just added the (char*) NULL.
                                                    //Now assign the Data: c-strings. (\0 terminated strings):
char *str_region = (char*) out + size_ptr_region;   //Region inside allocated memory which contains the String Data.
memcpy( str_region, line, line_size );   //Copy input with delimiter characters: They will be replaced with \0.

//Now we should replace: "arg1||arg2||arg3" with "arg1\0|arg2\0|arg3". Don't worry for characters after '\0'
//They are not used in standard c lbraries.
for( i = 0; i < tokens_found; i++) str_region[ end_idx[ i ] ] = '\0';

//"Out of Range" TEST. Wait until Assigned Values are Printed back.
//for ( int i=0; i < 5; i++ ) printf("c=%x ", extra_chars[i] ); printf("\n");

// *out memory should now contain (example data):
//[ ptr1, ptr2,...,ptrN, (char*) NULL, "token1\0", "token2\0",...,"tokenN\0", 5 bytes for tests ]
//   |__________________________________^           ^              ^             ^
//          |_______________________________________|              |             |
//                   |_____________________________________________|      These 5 Bytes should be intact.

return tokens_found;
}


int main()

{

char in_line[] = "Arg1;;Th;s is not Del;m;ter;;Arg3;;;;Final";
char delim[] = ";;";
char **columns;
int i;

printf("Example1:\n");
columns = NULL; //Should be NULL to indicate that it is not assigned to allocated memory. Otherwise return -4;

int cols_found = getcols( in_line, delim, &columns);
for ( i = 0; i < cols_found; i++ ) printf("Column[ %d ] = %s\n", i, columns[ i ] );  //<- (1st way).
// (2nd way) // for ( i = 0; columns[ i ]; i++) printf("start_idx[ %d ] = %s\n", i, columns[ i ] );

free( columns );    //Release the Single Contiguous Memory Space.
columns = NULL;     //Pointer = NULL to indicate it does not reserve space and that is ready for the next malloc().

printf("\n\nExample2, Nested:\n\n");

char example_file[] = "ID;Day;Month;Year;Telephone;email;Date of registration\n"
        "1;Sunday;january;2009;123-124-456;[email protected];2015-05-13\n"
        "2;Monday;March;2011;(+30)333-22-55;[email protected];2009-05-23";

char **rows;
int j;

rows = NULL; //getcols() requires it to be NULL. (Avoid dangling pointers, leaks e.t.c).

getcols( example_file, "\n", &rows);
for ( i = 0; rows[ i ]; i++) {
    {
        printf("Line[ %d ] = %s\n", i, rows[ i ] );
        char **columnX = NULL;
        getcols( rows[ i ], ";", &columnX);
        for ( j = 0; columnX[ j ]; j++) printf("  Col[ %d ] = %s\n", j, columnX[ j ] );
        free( columnX );
    }
}

free( rows );
rows = NULL;

return 0;
}

I need to convert an int variable to double

Converting to double can be done by casting an int to a double:

You can convert an int to a double by using this mechnism like so:

int i = 3; // i is 3
double d = (double) i; // d = 3.0

Alternative (using Java's automatic type recognition):

double d = 1.0 * i; // d = 3.0

Implementing this in your code would be something like:

double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));

Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:

double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));

Good luck.

SSH to Elastic Beanstalk instance

I came here looking for a way to add a key to an instance Beanstalk creates during provisioning (we're using Terraform). You can do the following in Terraform:

resource "aws_elastic_beanstalk_environment" "your-beanstalk" {
   ... 
   setting {
      namespace = "aws:autoscaling:launchconfiguration"
      name      = "EC2KeyName"
      value     = "${aws_key_pair.your-ssh-key.key_name}"
   }
   ...
}

You can then use that key to SSH into the box.

How to get ip address of a server on Centos 7 in bash

SERVER_IP="$(ip addr show ens160 | grep 'inet ' | cut -f2 | awk '{ print $2}')"

replace ens160 with your interface name

List of installed gems?

Try it in the terminal:

ruby -S gem list --local

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

SET XACT_ABORT ON instructs SQL Server to rollback the entire transaction and abort the batch when a run-time error occurs. It covers you in cases like a command timeout occurring on the client application rather than within SQL Server itself (which isn't covered by the default XACT_ABORT OFF setting.)

Since a query timeout will leave the transaction open, SET XACT_ABORT ON is recommended in all stored procedures with explicit transactions (unless you have a specific reason to do otherwise) as the consequences of an application performing work on a connection with an open transaction are disastrous.

There's a really great overview on Dan Guzman's Blog,

View's SELECT contains a subquery in the FROM clause

Looks to me as MySQL 3.6 gives the following error while MySQL 3.7 no longer errors out. I am yet to find anything in the documentation regarding this fix.

Can I run multiple programs in a Docker container?

You can run 2 processes in foreground by using wait. Just make a bash script with the following content. Eg start.sh:

# runs 2 commands simultaneously:

mongod & # your first application
P1=$!
python script.py & # your second application
P2=$!
wait $P1 $P2

In your Dockerfile, start it with

CMD bash start.sh

How to pick just one item from a generator?

generator = myfunct()
while True:
   my_element = generator.next()

make sure to catch the exception thrown after the last element is taken

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

How to sort multidimensional array by column?

You can use the sorted method with a key.

sorted(a, key=lambda x : x[1])

How to select a column name with a space in MySQL

If double quotes does not work , try including the string within square brackets.

For eg:

SELECT "Business Name","Other Name" FROM your_Table

can be changed as

SELECT [Business Name],[Other Name] FROM your_Table

What is the !! (not not) operator in JavaScript?

It's a double not operation. The first ! converts the value to boolean and inverts its logical value. The second ! inverts the logical value back.

Google Spreadsheet, Count IF contains a string

In case someone is still looking for the answer, this worked for me:

=COUNTIF(A2:A51, "*" & B1 & "*")

B1 containing the iPad string.

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

I'm pretty sure the classpath and the shared library search path have little to do with each other. According to The JNI Book (which admittedly is old), on Windows if you do not use the java.library.path system property, the DLL needs to be in the current working directory or in a directory listed in the Windows PATH environment variable.


Update:

Looks like Oracle has removed the PDF from its website. I've updated the link above to point to an instance of the PDF living at University of Texas - Arlington.

Also, you can also read Oracle's HTML version of the JNI Specification. That lives in the Java 8 section of the Java website and so hopefully will be around for a while.


Update 2:

At least in Java 8 (I haven't checked earlier versions) you can do:

java -XshowSettings:properties -version

to find the shared library search path. Look for the value of the java.library.path property in that output.

Django: How can I call a view function from template?

you can put the input inside a form like this:-

<script>
    $(document).ready(function(){
        $(document).on('click','#send', function(){
            $('#hid').val(data)
            document.forms["myForm"].submit();
        })
    })
</script>

<form id="myForm" action="/request_page url/" method="post">
    <input type="hidden" id="hid" name="hid"/>
</form>
<div id="send">Send Data</div>

Define css class in django Forms

You could also use Django Crispy Forms, it's a great tool to define forms in case you'd like to use some CSS framework like Bootstrap or Foundation. And it's easy to specify classes for your form fields there.

Your form class would like this then:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

    helper = FormHelper()
    helper.form_class = 'your-form-class'
    helper.layout = Layout(
        Field('name', css_class='name-class'),
        Field('age', css_class='age-class'),
        Field('django_hacker', css-class='hacker-class'),
        FormActions(
            Submit('save_changes', 'Save changes'),
        )
    )

convert base64 to image in javascript/jquery

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

How do I create a new user in a SQL Azure database?

I followed the answers here but when I tried to connect with my new user, I got an error message stating "The server principal 'newuser' is not able to access the database 'master' under the current security context".

I had to also create a new user in the master table to successfully log in with SSMS.

USE [master]
GO
CREATE LOGIN [newuser] WITH PASSWORD=N'blahpw'
GO
CREATE USER [newuser] FOR LOGIN [newuser] WITH DEFAULT_SCHEMA=[dbo]
GO

USE [MyDatabase]
CREATE USER newuser FOR LOGIN newuser WITH DEFAULT_SCHEMA = dbo
GO
EXEC sp_addrolemember N'db_owner', N'newuser'
GO

Adding an onclick event to a table row

Try changing the this.getElementsByTagName("td")[0]) line to read row.getElementsByTagName("td")[0];. That should capture the row reference in a closure, and it should work as expected.

Edit: The above is wrong, since row is a global variable -- as others have said, allocate a new variable and then use THAT in the closure.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

The ThreadPoolExecutor class is the base implementation for the executors that are returned from many of the Executors factory methods. So let's approach Fixed and Cached thread pools from ThreadPoolExecutor's perspective.

ThreadPoolExecutor

The main constructor of this class looks like this:

public ThreadPoolExecutor(
                  int corePoolSize,
                  int maximumPoolSize,
                  long keepAliveTime,
                  TimeUnit unit,
                  BlockingQueue<Runnable> workQueue,
                  ThreadFactory threadFactory,
                  RejectedExecutionHandler handler
)

Core Pool Size

The corePoolSize determines the minimum size of the target thread pool. The implementation would maintain a pool of that size even if there are no tasks to execute.

Maximum Pool Size

The maximumPoolSize is the maximum number of threads that can be active at once.

After the thread pool grows and becomes bigger than the corePoolSize threshold, the executor can terminate idle threads and reach to the corePoolSize again. If allowCoreThreadTimeOut is true, then the executor can even terminate core pool threads if they were idle more than keepAliveTime threshold.

So the bottom line is if threads remain idle more than keepAliveTime threshold, they may get terminated since there is no demand for them.

Queuing

What happens when a new task comes in and all core threads are occupied? The new tasks will be queued inside that BlockingQueue<Runnable> instance. When a thread becomes free, one of those queued tasks can be processed.

There are different implementations of the BlockingQueue interface in Java, so we can implement different queuing approaches like:

  1. Bounded Queue: New tasks would be queued inside a bounded task queue.

  2. Unbounded Queue: New tasks would be queued inside an unbounded task queue. So this queue can grow as much as the heap size allows.

  3. Synchronous Handoff: We can also use the SynchronousQueue to queue the new tasks. In that case, when queuing a new task, another thread must already be waiting for that task.

Work Submission

Here's how the ThreadPoolExecutor executes a new task:

  1. If fewer than corePoolSize threads are running, tries to start a new thread with the given task as its first job.
  2. Otherwise, it tries to enqueue the new task using the BlockingQueue#offer method. The offer method won't block if the queue is full and immediately returns false.
  3. If it fails to queue the new task (i.e. offer returns false), then it tries to add a new thread to the thread pool with this task as its first job.
  4. If it fails to add the new thread, then the executor is either shut down or saturated. Either way, the new task would be rejected using the provided RejectedExecutionHandler.

The main difference between the fixed and cached thread pools boils down to these three factors:

  1. Core Pool Size
  2. Maximum Pool Size
  3. Queuing

+-----------+-----------+-------------------+---------------------------------+
| Pool Type | Core Size |    Maximum Size   |         Queuing Strategy        |
+-----------+-----------+-------------------+---------------------------------+
|   Fixed   | n (fixed) |     n (fixed)     | Unbounded `LinkedBlockingQueue` |
+-----------+-----------+-------------------+---------------------------------+
|   Cached  |     0     | Integer.MAX_VALUE |        `SynchronousQueue`       |
+-----------+-----------+-------------------+---------------------------------+


Fixed Thread Pool


Here's how the Excutors.newFixedThreadPool(n) works:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

As you can see:

  • The thread pool size is fixed.
  • If there is high demand, it won't grow.
  • If threads are idle for quite some time, it won't shrink.
  • Suppose all those threads are occupied with some long-running tasks and the arrival rate is still pretty high. Since the executor is using an unbounded queue, it may consume a huge part of the heap. Being unfortunate enough, we may experience an OutOfMemoryError.

When should I use one or the other? Which strategy is better in terms of resource utilization?

A fixed-size thread pool seems to be a good candidate when we're going to limit the number of concurrent tasks for resource management purposes.

For example, if we're going to use an executor to handle web server requests, a fixed executor can handle the request bursts more reasonably.

For even better resource management, it's highly recommended to create a custom ThreadPoolExecutor with a bounded BlockingQueue<T> implementation coupled with reasonable RejectedExecutionHandler.


Cached Thread Pool


Here's how the Executors.newCachedThreadPool() works:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

As you can see:

  • The thread pool can grow from zero threads to Integer.MAX_VALUE. Practically, the thread pool is unbounded.
  • If any thread is idle for more than 1 minute, it may get terminated. So the pool can shrink if threads remain too much idle.
  • If all allocated threads are occupied while a new task comes in, then it creates a new thread, as offering a new task to a SynchronousQueue always fails when there is no one on the other end to accept it!

When should I use one or the other? Which strategy is better in terms of resource utilization?

Use it when you have a lot of predictable short-running tasks.

Using %s in C correctly - very basic level

For both *printf and *scanf, %s expects the corresponding argument to be of type char *, and for scanf, it had better point to a writable buffer (i.e., not a string literal).

char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";

printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);

scanf("%55s", str_buf);

Using %s in scanf without an explcit field width opens the same buffer overflow exploit that gets did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf, you can't supply the field with as a run time argument:

printf("%*s\n", field_width, string);

One option is to build the format string dynamically:

char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"

EDIT

Using scanf with the %s conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like

"This is a test"

then scanf("%55s", str_buf) will read and assign "This" to str_buf. Note that the field with specifier doesn't make a difference in this case.

How to check if a date is greater than another in Java?

Parse the two dates firstDate and secondDate using SimpleDateFormat.

firstDate.after(secondDate);

firstDate.before(secondDate);

best way to get the key of a key/value javascript object

Given your Object:

var foo = { 'bar' : 'baz' }

To get bar, use:

Object.keys(foo)[0]

To get baz, use:

foo[Object.keys(foo)[0]]

Assuming a single object