Programs & Examples On #Information architecture

Information Architecture is a diagram of the structure and organization of content. The objective of a information architecture diagram is not to provide a full-blown navigational specification; this level of detail is best kept in other documents, where it is less likely to confuse and distract.

How to check if image exists with given url?

Use Case

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API :

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

Note : rm means here risk managment .


Another Use Case :

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • 'http://example/1.png' : if not exist 'http://example/2.png'

  • 'http://example/2.png' : if not exist 'http://example/3.png'

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

SQL Server: IF EXISTS ; ELSE

EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b
  set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
  on b.id = a.id
where
  b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.

Android Studio Google JAR file causing GC overhead limit exceeded error

At some point a duplicate copy of apply plugin: 'com.android.application' got added to my build gradle. Removing the duplicate copy and making sure all my apply plugins were at the top fixed the issue for me.

Get selected item value from Bootstrap DropDown with specific ID

Try this code

<input type="TextBox" ID="yearBox" border="0" disabled>

$('#yearSelected li').on('click', function(){
                $('#yearBox').val($(this).text());
            });



<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fas fa-calendar-alt"></i> <span>Academic Years</span> <i class="fas fa-chevron-down"></i> </a>
          <ul class="dropdown-menu">
            <li>
              <ul class="menu" id="yearSelected">
                <li><a href="#">2014-2015</a></li>
                <li><a href="#">2015-2016</a></li>
                <li><a href="#">2016-2017</a></li>
                <li><a href="#">2017-2018</a></li>

              </ul>
            </li>
          </ul>

its work for me

How can I get the current directory name in Javascript?

You can use window.location.pathname.split('/');

That will produce an array with all of the items between the /'s

How to Install Sublime Text 3 using Homebrew

I did not have brew cask installed so I had to install it first,so these were the steps I followed:

brew install caskroom/cask/brew-cask
brew tap caskroom/versions
brew cask install sublime-text

System.out.println() shortcut on Intellij IDEA

If you want to know all the shortcut in intellij hit Ctrl + J. This shows all the shortcuts. For System.out.println() type sout and press Tab.

How can I commit files with git?

in standart Vi editor in this situation you should

  1. press Esc
  2. type ":wq" (without quotes)
  3. Press Enter

C++ Get name of type in template

typeid(T).name() is implementation defined and doesn't guarantee human readable string.

Reading cppreference.com :

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

...

With compilers such as gcc and clang, the returned string can be piped through c++filt -t to be converted to human-readable form.

But in some cases gcc doesn't return right string. For example on my machine I have gcc whith -std=c++11 and inside template function typeid(T).name() returns "j" for "unsigned int". It's so called mangled name. To get real type name, use abi::__cxa_demangle() function (gcc only):

#include <string>
#include <cstdlib>
#include <cxxabi.h>

template<typename T>
std::string type_name()
{
    int status;
    std::string tname = typeid(T).name();
    char *demangled_name = abi::__cxa_demangle(tname.c_str(), NULL, NULL, &status);
    if(status == 0) {
        tname = demangled_name;
        std::free(demangled_name);
    }   
    return tname;
}

Ways to insert javascript into URL?

JavaScript injection is not at attack on your web application. JavaScript injection simply adds JavaScript code for the browser to execute. The only way JavaScript could harm your web application is if you have a blog posting or some other area in which user input is stored. This could be a problem because an attacker could inject their code and leave it there for other users to execute. This attack is known as Cross-Site Scripting. The worst scenario would be Cross-Site Forgery, which allows attackers to inject a statement that will steal a user's cookie and therefore give the attacker their session ID.

How to set a default value for an existing column

The correct way to do this is as follows:

  1. Run the command:

    sp_help [table name] 
    
  2. Copy the name of the CONSTRAINT.

  3. Drop the DEFAULT CONSTRAINT:

    ALTER TABLE [table name] DROP [NAME OF CONSTRAINT] 
    
  4. Run the command below:

    ALTER TABLE [table name] ADD DEFAULT [DEFAULT VALUE] FOR [NAME OF COLUMN]
    

How to assert two list contain the same elements in Python?

As of Python 3.2 unittest.TestCase.assertItemsEqual(doc) has been replaced by unittest.TestCase.assertCountEqual(doc) which does exactly what you are looking for, as you can read from the python standard library documentation. The method is somewhat misleadingly named but it does exactly what you are looking for.

a and b have the same elements in the same number, regardless of their order

Here a simple example which compares two lists having the same elements but in a different order.

  • using assertCountEqual the test will succeed
  • using assertListEqual the test will fail due to the order difference of the two lists

Here a little example script.

import unittest


class TestListElements(unittest.TestCase):
    def setUp(self):
        self.expected = ['foo', 'bar', 'baz']
        self.result = ['baz', 'foo', 'bar']

    def test_count_eq(self):
        """Will succeed"""
        self.assertCountEqual(self.result, self.expected)

    def test_list_eq(self):
        """Will fail"""
        self.assertListEqual(self.result, self.expected)

if __name__ == "__main__":
    unittest.main()

Side Note : Please make sure that the elements in the lists you are comparing are sortable.

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

Have you unistalled your Internet Explorer? I did, and I had the same issues, if so, you have to:

  1. Reactivate IE (Control Panel -- Programs and Features -- Turn Windows features on or off).
  2. restarting the computer
  3. (important!) running Windows Update to get all available updates for Microsoft Explorer
  4. restarting the computer (again)

Finally it works!

Facebook Access Token for Pages

The documentation for this is good if not a little difficult to find.

Facebook Graph API - Page Tokens

After initializing node's fbgraph, you can run:

var facebookAccountID = yourAccountIdHere 

graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
  console.log(res); 
});

and receive a JSON response with the token you want to grab, located at:

res.data[0].access_token

nvm is not compatible with the npm config "prefix" option:

I ran into this while using node installed via nvm, with nvm installed via homebrew. I solved it by running brew uninstall nvm, rm -rf $NVM_DIR, then reinstalling nvm using the official install script and reinstalling the node version I needed.

Note: I also had $NVM_DIR mounted and symlinked. I moved it back into my homedir.

Easiest way to change font and font size

This should do it (bold as well);

label1.Font = new Font("Serif", 24,FontStyle.Bold);

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

The second question is easier to answer: you basically can use PyPy as a drop-in replacement if all your code is pure Python. However, many widely used libraries (including some of the standard library) are written in C and compiled as Python extensions. Some of these can be made to work with PyPy, some can't. PyPy provides the same "forward-facing" tool as Python --- that is, it is Python --- but its innards are different, so tools that interface with those innards won't work.

As for the first question, I imagine it is sort of a Catch-22 with the first: PyPy has been evolving rapidly in an effort to improve speed and enhance interoperability with other code. This has made it more experimental than official.

I think it's possible that if PyPy gets into a stable state, it may start getting more widely used. I also think it would be great for Python to move away from its C underpinnings. But it won't happen for a while. PyPy hasn't yet reached the critical mass where it is almost useful enough on its own to do everything you'd want, which would motivate people to fill in the gaps.

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

How can I add the sqlite3 module to Python?

Normally, it is included. However, as @ngn999 said, if your python has been built from source manually, you'll have to add it.

Here is an example of a script that will setup an encapsulated version (virtual environment) of Python3 in your user directory with an encapsulated version of sqlite3.

INSTALL_BASE_PATH="$HOME/local"
cd ~
mkdir build
cd build
[ -f Python-3.6.2.tgz ] || wget https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz
tar -zxvf Python-3.6.2.tgz

[ -f sqlite-autoconf-3240000.tar.gz ] || wget https://www.sqlite.org/2018/sqlite-autoconf-3240000.tar.gz
tar -zxvf sqlite-autoconf-3240000.tar.gz

cd sqlite-autoconf-3240000
./configure --prefix=${INSTALL_BASE_PATH}
make
make install

cd ../Python-3.6.2
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib configure
LDFLAGS="-L ${INSTALL_BASE_PATH}/lib"
CPPFLAGS="-I ${INSTALL_BASE_PATH}/include"
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib make
./configure --prefix=${INSTALL_BASE_PATH}
make
make install

cd ~
LINE_TO_ADD="export PATH=${INSTALL_BASE_PATH}/bin:\$PATH"
if grep -q -v "${LINE_TO_ADD}" $HOME/.bash_profile; then echo "${LINE_TO_ADD}" >> $HOME/.bash_profile; fi
source $HOME/.bash_profile

Why do this? You might want a modular python environment that you can completely destroy and rebuild without affecting your managed package installation. This would give you an independent development environment. In this case, the solution is to install sqlite3 modularly too.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I have this problem too.

I tried almost everything by adding the SSL cert to .keystore, but, it was not working with Java1_6_x. For me it helped if we start using newer version of Java, Java1_8_x as JVM.

Where are the recorded macros stored in Notepad++?

For Windows 7 macros are stored at C:\Users\Username\AppData\Roaming\Notepad++\shortcuts.xml.

CSS3 transform not working

This is merely an educated guess without seeing the rest of your HTML/CSS:

Have you applied display: block or display: inline-block to li a? If not, try it.

Otherwise, try applying the CSS3 transform rules to li instead.

React.js create loop through Array

You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

MYSQL query between two timestamps

Try below code. Worked in my case. Hope this helps!

    select id,total_Hour,
    (coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)) as weekday_Listing_Hrs,
    (coalesce(weekend_1,0)+coalesce(weekend_2,0)+coalesce(weekend_3,0)) as weekend_Listing_Hrs
    from
    select *,
    listing_duration_Hour-(coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)+coalesce(weekend_1,0)+coalesce(weekend_2,0)) as weekend_3 
    from 
    (
    select * , 
    case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (0,1,2,3,4) 
         then timestampdiff(hour,Start_Date,End_Date)
         when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (0,1,2,3,4) 
         then 24-timestampdiff(hour,date(Start_Date),Start_Date)
         end as weekday_1,  
    case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (0,1,2,3,4) 
         then timestampdiff(hour,date(End_Date),End_Date)
         end as weekday_2,
    case when date(Start_Date) != date(End_Date) then    
    (5*(DATEDIFF(date(End_Date),adddate(date(Start_Date),+1)) DIV 7) + 
    MID('0123455501234445012333450122234501101234000123450',7 * WEEKDAY(adddate(date(Start_Date),+1))
    + WEEKDAY(date(End_Date)) + 1, 1))* 24 end as  weekday_3,
    case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (5,6) 
         then timestampdiff(hour,Start_Date,End_Date)
         when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (5,6) 
         then 24-timestampdiff(hour,date(Start_Date),Start_Date)
         end as weekend_1,  
    case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (5,6) 
         then timestampdiff(hour,date(End_Date),End_Date)
         end as weekend_2
    from 
    TABLE_1
    )

Spring 3 MVC accessing HttpRequest from controller

Spring MVC will give you the HttpRequest if you just add it to your controller method signature:

For instance:

/**
 * Generate a PDF report...
 */
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
        @PathVariable("objectId") Long objectId, 
        HttpServletRequest request, 
        HttpServletResponse response) {

    // ...
    // Here you can use the request and response objects like:
    // response.setContentType("application/pdf");
    // response.getOutputStream().write(...);

}

As you see, simply adding the HttpServletRequest and HttpServletResponse objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession object too.

EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.

I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.

ASP.NET MVC Conditional validation

You need to validate at Person level, not on Senior level, or Senior must have a reference to its parent Person. It seems to me that you need a self validation mechanism that defines the validation on the Person and not on one of its properties. I'm not sure, but I don't think DataAnnotations supports this out of the box. What you can do create your own Attribute that derives from ValidationAttribute that can be decorated on class level and next create a custom validator that also allows those class-level validators to run.

I know Validation Application Block supports self-validation out-of the box, but VAB has a pretty steep learning curve. Nevertheless, here's an example using VAB:

[HasSelfValidation]
public class Person
{
    public string Name { get; set; }
    public bool IsSenior { get; set; }
    public Senior Senior { get; set; }

    [SelfValidation]
    public void ValidateRange(ValidationResults results)
    {
        if (this.IsSenior && this.Senior != null && 
            string.IsNullOrEmpty(this.Senior.Description))
        {
            results.AddResult(new ValidationResult(
                "A senior description is required", 
                this, "", "", null));
        }
    }
}

How to add new elements to an array?

As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.

String[] where = new String[10];

This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a dynamically growing collection, use the ArrayList.

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

Hide Spinner in Input Number - Firefox 29

I mixed few answers from answers above and from How to remove the arrows from input[type="number"] in Opera in scss:

input[type=number] {
  &,
  &::-webkit-inner-spin-button,
  &::-webkit-outer-spin-button {
    -webkit-appearance: none;
    -moz-appearance: textfield;
    appearance: none;

    &:hover,
    &:focus {
      -moz-appearance: number-input;
    }
  }
}

Tested on chrome, firefox, safari

Fatal error: Call to undefined function curl_init()

Don't have enough reputation to comment yet. Using Ubuntu and a simple:

sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart

Did NOT work for me.

For some reason curl.so was installed in a location not picked up by default. I checked the extension_dir in my php.ini and copied over the curl.so to my extension_dir

cp /usr/lib/php5/20090626/curl.so  /usr/local/lib/php/extensions/no-debug-non-zts-20090626

Hope this helps someone, adjust your path locations accordingly.

Iterate through a C++ Vector using a 'for' loop

Here is a simpler way to iterate and print values in vector.

for(int x: A) // for integer x in vector A
    cout<< x <<" "; 

How to make gradient background in android

Try with this :

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >

    <gradient
        android:angle="90"
        android:centerColor="#555994"
        android:endColor="#b5b6d2"
        android:startColor="#555994"
        android:type="linear" />

    <corners 
        android:radius="0dp"/>

</shape>

Why is document.write considered a "bad practice"?

I think the biggest problem is that any elements written via document.write are added to the end of the page's elements. That's rarely the desired effect with modern page layouts and AJAX. (you have to keep in mind that the elements in the DOM are temporal, and when the script runs may affect its behavior).

It's much better to set a placeholder element on the page, and then manipulate it's innerHTML.

Python - Join with newline

When you print it with this print 'I\nwould\nexpect\nmultiple\nlines' you would get:

I
would
expect
multiple
lines

The \n is a new line character specially used for marking END-OF-TEXT. It signifies the end of the line or text. This characteristics is shared by many languages like C, C++ etc.

How can prepared statements protect from SQL injection attacks?

Root Cause #1 - The Delimiter Problem

Sql injection is possible because we use quotation marks to delimit strings and also to be parts of strings, making it impossible to interpret them sometimes. If we had delimiters that could not be used in string data, sql injection never would have happened. Solving the delimiter problem eliminates the sql injection problem. Structure queries do that.

Root Cause #2 - Human Nature, People are Crafty and Some Crafty People Are Malicious And All People Make Mistakes

The other root cause of sql injection is human nature. People, including programmers, make mistakes. When you make a mistake on a structured query, it does not make your system vulnerable to sql injection. If you are not using structured queries, mistakes can generate sql injection vulnerability.

How Structured Queries Resolve the Root Causes of SQL Injection

Structured Queries Solve The Delimiter Problem, by by putting sql commands in one statement and putting the data in a separate programming statement. Programming statements create the separation needed.

Structured queries help prevent human error from creating critical security holes. With regard to humans making mistakes, sql injection cannot happen when structure queries are used. There are ways of preventing sql injection that don't involve structured queries, but normal human error in that approaches usually leads to at least some exposure to sql injection. Structured Queries are fail safe from sql injection. You can make all the mistakes in the world, almost, with structured queries, same as any other programming, but none that you can make can be turned into a ssstem taken over by sql injection. That is why people like to say this is the right way to prevent sql injection.

So, there you have it, the causes of sql injection and the nature structured queries that makes them impossible when they are used.

Remove commas from the string using JavaScript

This is the simplest way to do it.

let total = parseInt(('100,000.00'.replace(',',''))) + parseInt(('500,000.00'.replace(',','')))

Increasing Heap Size on Linux Machines

You can use the following code snippet :

java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
    -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

In my pc I am getting following output :

    uintx InitialHeapSize                          := 536870912       {product}
    uintx MaxHeapSize                              := 1073741824      {product}
    uintx PermSize                                 := 67108864        {pd product}
    uintx MaxPermSize                              := 134217728       {pd product}
     intx ThreadStackSize                          := 512             {pd product}

How do I set a checkbox in razor view?

only option is to set the value in the controller, If your view is Create then in the controller action add the empty model, and set the value like,

Public ActionResult Create()
{
UserRating ur = new UserRating();
ur.AllowRating = true;
return View(ur);
} 

Dynamic creation of table with DOM

It is because you're only creating two td elements and 2 text nodes.


Creating all nodes in a loop

Recreate the nodes inside your loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table');

for (var i = 1; i < 4; i++) {
    var tr = document.createElement('tr');

    tr.appendChild( document.createElement('td') );
    tr.appendChild( document.createElement('td') );

    tr.cells[0].appendChild( document.createTextNode('Text1') )
    tr.cells[1].appendChild( document.createTextNode('Text2') );

    table.appendChild(tr);
}

tablearea.appendChild(table);

Creating then cloning in a loop

Create them beforehand, and clone them inside the loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table'),
    tr = document.createElement('tr');

tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );

tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );

for (var i = 1; i < 4; i++) {
    table.appendChild(tr.cloneNode( true ));
}

tablearea.appendChild(table);

Table factory with text string

Make a table factory:

function populateTable(table, rows, cells, content) {
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
        }
        table.appendChild(row);
    }
    return table;
}

And use it like this:

document.getElementById('tablearea')
        .appendChild( populateTable(null, 3, 2, "Text") );

Table factory with text string or callback

The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.

function populateTable(table, rows, cells, content) {
    var is_func = (typeof content === 'function');
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            var text = !is_func ? (content + '') : content(table, i, j);
            row.cells[j].appendChild(document.createTextNode(text));
        }
        table.appendChild(row);
    }
    return table;
}

Used like this:

document.getElementById('tablearea')
        .appendChild(populateTable(null, 3, 2, function(t, r, c) {
                        return ' row: ' + r + ', cell: ' + c;
                     })
        );

How to run PowerShell in CMD

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

Can I make 'git diff' only the line numbers AND changed file names?

The cleanest output, i.e. file names/paths only, comes with

git diff-tree --no-commit-id --name-only -r

HTH

How to move files from one git repo to another (not a clone), preserving history

This becomes simpler by using git-filter-repo.

In order to move project2/sub/dir to project1/sub/dir:

# Create a new repo containing only the subdirectory:
git clone project2 project2_subdir
cd project2_subdir
git filter-repo --force --path sub/dir

# Merge the new repo:
cd ../project1
git remote add project2_subdir ../project2_subdir/
git merge remotes/project2_subdir/master --allow-unrelated-histories
git remote remove project2_subdir

To install the tool simply: pip3 install git-filter-repo (more details and options in README)

# Before: (root)
.
|-- project1
|   `-- 3
`-- project2
    |-- 1
    `-- sub
        `-- dir
            `-- 2

# After: (project1)
.
+-- 3
+-- sub
    +-- dir
        +-- 2

I'm getting favicon.ico error

I copied the favicon.ico to assets folder its worked for me .

Lowercase and Uppercase with jQuery

If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:

.myclass {
    text-transform: lowercase;
}

See https://developer.mozilla.org/en/CSS/text-transform for more info.

However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

Building executable jar with maven?

Right click the project and give maven build,maven clean,maven generate resource and maven install.The jar file will automatically generate.

"unadd" a file to svn before commit

Full process (Unix svn package):

Check files are not in SVN:

> svn st -u folder 
? folder

Add all (including ignored files):

> svn add folder
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt
A   folder/folderToIgnore
A   folder/folderToIgnore/fileToIgnore1.txt
A   fileToIgnore2.txt

Remove "Add" Flag to All * Ignore * files:

> cd folder

> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'


> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'

Edit svn ignore on folder

svn propedit svn:ignore .

Add two singles lines with just the following:

folderToIgnore
fileToIgnore2.txt

Check which files will be upload and commit:

> cd ..

> svn st -u
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt


> svn ci -m "Commit message here"

How to force Chrome's script debugger to reload javascript?

On Windows, Ctrl+Shift+r would force reload the script in chrome.

specifying goal in pom.xml

I've bumped into this question because I actually wanted to define a default goal in pom.xml. You can define a default goal under build:

<build>
    <defaultGoal>install</defaultGoal>
...
</build>

After that change, you can then simply run mvn which will do exactly the same as mvn install.

Note: I don't favor this as a default approach. My use case was to define a profile that downloaded a previous version of that project from Artifactory and wanted to tie that profile to a given phase. For convenience, I can run mvn -Pdownload-jar -Dversion=0.0.9 and don't need to specify a goal/phase there. I think it's reasonable to define a defaultGoal in a profile which has a very specific function for a particular phase.

Get a timestamp in C in microseconds?

First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert

if(tv.tv_usec<10)
{
 printf("00000");
} 
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
 printf("0000");
}

and so on...

How do I hide certain files from the sidebar in Visual Studio Code?

The "Make Hidden" extension works great!

Make Hidden provides more control over your project's directory by enabling context menus that allow you to perform hide/show actions effortlessly, a view pane explorer to see hidden items and the ability to save workspaces to quickly toggle between bulk hidden items.

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

String.replaceAll single backslashes with double backslashes

To avoid this sort of trouble, you can use replace (which takes a plain string) instead of replaceAll (which takes a regular expression). You will still need to escape backslashes, but not in the wild ways required with regular expressions.

React ignores 'for' attribute of the label element

For React you must use it's per-define keywords to define html attributes.

class -> className

is used and

for -> htmlFor

is used, as react is case sensitive make sure you must follow small and capital as required.

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

How to simulate a touch event in Android?

Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:

view.setOnTouchListener(new OnTouchListener()
{
    public boolean onTouch(View v, MotionEvent event)
    {
        Toast toast = Toast.makeText(
            getApplicationContext(), 
            "View touched", 
            Toast.LENGTH_LONG
        );
        toast.show();

        return true;
    }
});


// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
    downTime, 
    eventTime, 
    MotionEvent.ACTION_UP, 
    x, 
    y, 
    metaState
);

// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);

For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

Android: How to stretch an image to the screen width while maintaining aspect ratio?

I accomplished this with a custom view. Set layout_width="fill_parent" and layout_height="wrap_content", and point it to the appropriate drawable:

public class Banner extends View {

  private final Drawable logo;

  public Banner(Context context) {
    super(context);
    logo = context.getResources().getDrawable(R.drawable.banner);
    setBackgroundDrawable(logo);
  }

  public Banner(Context context, AttributeSet attrs) {
    super(context, attrs);
    logo = context.getResources().getDrawable(R.drawable.banner);
    setBackgroundDrawable(logo);
  }

  public Banner(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    logo = context.getResources().getDrawable(R.drawable.banner);
    setBackgroundDrawable(logo);
  }

  @Override protected void onMeasure(int widthMeasureSpec,
      int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = width * logo.getIntrinsicHeight() / logo.getIntrinsicWidth();
    setMeasuredDimension(width, height);
  }
}

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

I had the same problem as above and Eclipse suggested installing:

Hint: On 64-bit systems, make sure the 32-bit libraries are installed:   
   "sudo apt-get install ia32-libs"    
or on some systems,  
   "sudo apt-get install lib32z1"   

When I tried to install ia32-libs, Ubuntu prompted to install three other packages:

$ sudo apt-get install ia32-libs  
Reading package lists... Done  
Building dependency tree         
Reading state information... Done  
Package ia32-libs is not available, but is referred to by another package.  
This may mean that the package is missing, has been obsoleted, or  
is only available from another source  
However the following packages replace it:  
  lib32z1 lib32ncurses5 lib32bz2-1.0  

E: Package 'ia32-libs' has no installation candidate  
$   
$ sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0    

With Android Studio and intellij, I also had to install the 32bit version of libstdc++6:

sudo apt-get install lib32stdc++6

WPF TemplateBinding vs RelativeSource TemplatedParent

I thought TemplateBinding does not support Freezable types (which includes brush objects). To get around the problem. One can make use of TemplatedParent

How to make a div with a circular shape?

By using a border-radius of 50% you can make a circle. Here is an example:

CSS:

#exampleCircle{
    width: 500px;
    height: 500px;
    background: red;
    border-radius: 50%;
}

HTML:

<div id = "exampleCircle"></div>

how to do file upload using jquery serialization

HTML5 introduces FormData class that can be used to file upload with ajax.

FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+

FormData - Mozilla.org

Using both Python 2.x and Python 3.x in IPython Notebook

From my Linux installation I did:

sudo ipython2 kernelspec install-self

And now my python 2 is back on the list.

Reference:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


UPDATE:

The method above is now deprecated and will be dropped in the future. The new method should be:

sudo ipython2 kernel install

Unzip a file with php

I updated answer of @rdlowrey to a cleaner and better code, This will unzip a file into current directory using __DIR__.

<?php 
    // config
    // -------------------------------
    // only file name + .zip
    $zip_filename = "YOURFILENAME.zip";
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' >
    <title>Unzip</title>
    <style>
        body{
            font-family: arial, sans-serif;
            word-wrap: break-word;
        }
        .wrapper{
            padding:20px;
            line-height: 1.5;
            font-size: 1rem;
        }
        span{
            font-family: 'Consolas', 'courier new', monospace;
            background: #eee;
            padding:2px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php
        echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
        echo "current dir: <span>" . __DIR__ . "</span><br>";
        $zip = new ZipArchive;
        $res = $zip->open(__DIR__ . '/' .$zip_filename);
        if ($res === TRUE) {
          $zip->extractTo(__DIR__);
          $zip->close();
          echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
        } else {
          echo '<p style="color:red;">Zip file not found!</p><br>';
        }
        ?>
        End Script.
    </div>
</body>
</html> 

Java: Difference between the setPreferredSize() and setSize() methods in components

setSize() or setBounds() can be used when no layout manager is being used.

However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize() methods like setPreferredSize() and setMinimumSize() etc.

And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout, GridBagLayout, and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.

How to write a CSS hack for IE 11?

You can use the following code inside the style tag:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
/* IE10+ specific styles go here */  
}

Below is an example that worked for me:

<style type="text/css">

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
   #flashvideo {
        width:320px;
        height:240;
        margin:-240px 0 0 350px;
        float:left;
    }

    #googleMap {
        width:320px;
        height:240;
        margin:-515px 0 0 350px;
        float:left;
        border-color:#000000;
    }
}

#nav li {
    list-style:none;
    width:240px;
    height:25px;
    }

#nav a {
    display:block;
    text-indent:-5000px;
    height:25px;
    width:240px;
    }
</style>

Please note that since (#nav li) and (#nav a) are outside of the @media screen ..., they are general styles.

Delete files older than 10 days using shell script in Unix

find is the common tool for this kind of task :

find ./my_dir -mtime +10 -type f -delete

EXPLANATIONS

  • ./my_dir your directory (replace with your own)
  • -mtime +10 older than 10 days
  • -type f only files
  • -delete no surprise. Remove it to test your find filter before executing the whole command

And take care that ./my_dir exists to avoid bad surprises !

How to convert UTF8 string to byte array?

The TextEncoder and TextDecoder Encoding API will let you both encode and decode UTF-8 easily (using typed arrays):

const encoded = new TextEncoder().encode("Ge?a s?? ??sµe");
const decoded = new TextDecoder().decode(encoded);

console.log(encoded, decoded);

Browser support isn't too bad, and there's a polyfill that should work in IE11 and older versions of Edge.


Older versions of TextEncoder supported other different encodings as a string constructor parameter argument, but since Firefox 48 and Chrome 53 this is no-longer supported and TextEncoder and TextDecoder support only UTF-8.

So this will no-longer work in modern web-browsers used since 2016:

new TextDecoder("shift-jis").decode(new Uint8Array(textbuffer))

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.

Javascript: formatting a rounded number to N decimals

Hopefully working code (didn't do much testing):

function toFixed(value, precision) {
    var precision = precision || 0,
        neg = value < 0,
        power = Math.pow(10, precision),
        value = Math.round(value * power),
        integral = String((neg ? Math.ceil : Math.floor)(value / power)),
        fraction = String((neg ? -value : value) % power),
        padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');

    return precision ? integral + '.' +  padding + fraction : integral;
}

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

How to change the minSdkVersion of a project?

Create a new AVD with the AVD Manager and set the Target to API Level 7. Try running your application with that AVD. Additionally, make sure that your min sdk in your Manifest file is at least set to 7.

Google API authentication: Not valid origin for the client

Clear your browser cache. Started getting this error in Chrome and then I created a new client id and was still getting the issue. Opened firefox and it worked, so I cleared the cache on Chrome and it started working.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Personally I'd go with AJAX.

If you cannot switch to @Ajax... helpers, I suggest you to add a couple of properties in your model

public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }

Change your view to a strongly typed Model via

@using MyModel

Before returning the View, in case of successfull creation do something like

MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);

then in your view, add this

@{
   if (model.TriggerOnLoad) {
   <text>
   <script type="text/javascript">
     alert('@Model.TriggerOnLoadMessage');
   </script>
   </text>
   }
}

Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:

$(document).ready(function () {
   alert('@Model.TriggerOnLoadMessage');
});

Please remember to reset the Model properties upon successfully alert emission.

Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:

@Html.EditorFor (m => m.TriggerOnLoadMessage)

But in case you want to build up such a thing, maybe it's better to define your own C# class:

class ClientMessageNotification {
    public bool TriggerOnLoad { get; set; }
    public string TriggerOnLoadMessage { get; set: }
}

and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.

How to change DataTable columns order

Try to use the DataColumn.SetOrdinal method. For example:

dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1); 

UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:

Extension method:

public static class DataTableExtensions
{
    public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
    {
        int columnIndex = 0;
        foreach(var columnName in columnNames)
        {
            table.Columns[columnName].SetOrdinal(columnIndex);
            columnIndex++;
        }
    }
}

Usage:

table.SetColumnsOrder("Qty", "Unit", "Id");

or

table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});

Bootstrap 3: Text overlay on image

You need to set the thumbnail class to position relative then the post-content to absolute.

Check this fiddle

.post-content {
    top:0;
    left:0;
    position: absolute;
}

.thumbnail{
    position:relative;

}

Giving it top and left 0 will make it appear in the top left corner.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

IF YOUR PROBLEM IS NOT SOLVED YET:

Visual studio's error is :

"The process cannot access the file 'bin\Debug**app.exe**' because it is being used by another process."

So ,go to task manager of windows(Ctrl+Shift+Esc),find your application name and force it to close by Endprocces.

Fast way to discover the row count of a table in PostgreSQL

Reference taken from this Blog.

You can use below to query to find row count.

Using pg_class:

 SELECT reltuples::bigint AS EstimatedCount
    FROM   pg_class
    WHERE  oid = 'public.TableName'::regclass;

Using pg_stat_user_tables:

SELECT 
    schemaname
    ,relname
    ,n_live_tup AS EstimatedCount 
FROM pg_stat_user_tables 
ORDER BY n_live_tup DESC;

Setting initial values on load with Select2 with Ajax

Ravi, for 4.0.1-rc.1:

  1. Add all <option> elements inside <select>.
  2. call $element.val(yourarray).trigger("change"); after select2 init function.

HTML:

<select name="Tags" id="Tags" class="form-control input-lg select2" multiple="multiple">
       <option value="1">tag 1</option>
       <option value="2">tag 2</option>
       <option value="3">tag 3</option>
 </select>

JS:

var $tagsControl = $("#Tags").select2({
        ajax: {
            url: '/Tags/Search',
            dataType: 'json',
            delay: 250,
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.text,
                            id: item.id
                        }
                    })
                };
            },
            cache: false
        },
        minimumInputLength: 2,
        maximumSelectionLength: 6
    });

    var data = [];
    var tags = $("#Tags option").each(function () {
        data.push($(this).val());
    });
    $tagsControl.val(data).trigger("change");

This issue was reported but it still opened. https://github.com/select2/select2/issues/3116#issuecomment-146568753

Not equal <> != operator on NULL

NULL Cannot be compared to any value using the comparison operators. NULL = NULL is false. Null is not a value. The IS operator is specially designed to handle NULL comparisons.

How to control font sizes in pgf/tikz graphics in latex?

\begin{tikzpicture}
    \tikzstyle{every node}=[font=\fontsize{30}{30}\selectfont]
\end{tikzpicture}

How do you get a list of the names of all files present in a directory in Node.js?

I've recently built a tool for this that does just this... It fetches a directory asynchronously and returns a list of items. You can either get directories, files or both, with folders being first. You can also paginate the data in case where you don't want to fetch the entire folder.

https://www.npmjs.com/package/fs-browser

This is the link, hope it helps someone!

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

Skip first couple of lines while reading lines in Python file

Here is a method to get lines between two line numbers in a file:

import sys

def file_line(name,start=1,end=sys.maxint):
    lc=0
    with open(s) as f:
        for line in f:
            lc+=1
            if lc>=start and lc<=end:
                yield line


s='/usr/share/dict/words'
l1=list(file_line(s,235880))
l2=list(file_line(s,1,10))
print l1
print l2

Output:

['Zyrian\n', 'Zyryan\n', 'zythem\n', 'Zythia\n', 'zythum\n', 'Zyzomys\n', 'Zyzzogeton\n']
['A\n', 'a\n', 'aa\n', 'aal\n', 'aalii\n', 'aam\n', 'Aani\n', 'aardvark\n', 'aardwolf\n', 'Aaron\n']

Just call it with one parameter to get from line n -> EOF

How can I prevent the backspace key from navigating back?

Simplest way to prevent navigation on pressing backspace

$(document).keydown(function () {
    if (event.keyCode == 8) {
        if (event.target.nodeName == 'BODY') {
            event.preventDefault();
        }
    }
});

How to get the fields in an Object via reflection?

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);
    }
}

To learn more about reflection, check the Sun tutorial on the subject.


That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);
        }
    }
}

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

How to sort a HashSet?

You can use guava library for the same

Set<String> sortedSet = FluentIterable.from(myHashSet).toSortedSet(new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // descending order of relevance
        //required code
    }
});

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

I meet the same problem, @progrAmmar enlightened me, "took a closer look at the user table in mysql database".

My problem is not ssl_type, instead of the first field:Host. I changed the value by using

update user set Host='localhost' where User='root' and Host='%';

in mysqld_safe --skip-grant-tables model.

Then it works well.

load external URL into modal jquery ui dialog

I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.

var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
    modal: true,
    height: $("#body").height(),
    width: $("#body").width()*.8
});

How to configure Eclipse build path to use Maven dependencies?

I had a slight variation that caused some issues - multiple sub projects within one project. In this case I needed to go into each individual folder that contained a POM, execute the mvn eclipse:eclipse command and then manually copy/merge the classpath entries into my project classpath file.

Java JTextField with input hint

Here is a single class copy/paste solution:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;


public class HintTextFieldUI extends BasicTextFieldUI implements FocusListener {

    private String hint;
    private boolean hideOnFocus;
    private Color color;

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
        repaint();
    }

    private void repaint() {
        if(getComponent() != null) {
            getComponent().repaint();           
        }
    }

    public boolean isHideOnFocus() {
        return hideOnFocus;
    }

    public void setHideOnFocus(boolean hideOnFocus) {
        this.hideOnFocus = hideOnFocus;
        repaint();
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
        repaint();
    }
    public HintTextFieldUI(String hint) {
        this(hint,false);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus) {
        this(hint,hideOnFocus, null);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus, Color color) {
        this.hint = hint;
        this.hideOnFocus = hideOnFocus;
        this.color = color;
    }

    @Override
    protected void paintSafely(Graphics g) {
        super.paintSafely(g);
        JTextComponent comp = getComponent();
        if(hint!=null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))){
            if(color != null) {
                g.setColor(color);
            } else {
                g.setColor(comp.getForeground().brighter().brighter().brighter());              
            }
            int padding = (comp.getHeight() - comp.getFont().getSize())/2;
            g.drawString(hint, 2, comp.getHeight()-padding-1);          
        }
    }

    @Override
    public void focusGained(FocusEvent e) {
        if(hideOnFocus) repaint();

    }

    @Override
    public void focusLost(FocusEvent e) {
        if(hideOnFocus) repaint();
    }
    @Override
    protected void installListeners() {
        super.installListeners();
        getComponent().addFocusListener(this);
    }
    @Override
    protected void uninstallListeners() {
        super.uninstallListeners();
        getComponent().removeFocusListener(this);
    }
}

Use it like this:

TextField field = new JTextField();
field.setUI(new HintTextFieldUI("Search", true));

Note that it is happening in protected void paintSafely(Graphics g).

How to convert local time string to UTC?

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

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

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

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

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

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

The import javax.servlet can't be resolved

You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar in Tomcat's lib folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.

If you want to leave the JAR in Tomcat's lib folder:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click the Libraries tab
  • Click Add External JARs...
  • Browse to find servlet-api.jar and select it.
  • Click OK to update the build path.

Or, if you copy the JAR into your project:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click Add JARs...
  • Find servlet-api.jar in your project and select it.
  • Click OK to update the build path.

CSS fill remaining width

I did a quick experiment after looking at a number of potential solutions all over the place. This is what I ended up with:

http://jsbin.com/hapelawake

Correct way to convert size in bytes to KB, MB, GB in JavaScript

_x000D_
_x000D_
var SIZES = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];_x000D_
_x000D_
function formatBytes(bytes, decimals) {_x000D_
  for(var i = 0, r = bytes, b = 1024; r > b; i++) r /= b;_x000D_
  return `${parseFloat(r.toFixed(decimals))} ${SIZES[i]}`;_x000D_
}
_x000D_
_x000D_
_x000D_

SQL Server: Get data for only the past year

I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.

At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.

SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))

Thanks to those above whose solutions helped me arrive at what I needed.

How to round up a number to nearest 10?

$value = 23;
$rounded_value = $value - ($value % 10 - 10);
//$rounded_value is now 30

Redirecting to previous page after login? PHP

Use hidden input in your login page. Like:

<input name="location" value="<?php if(!empty($_SERVER['HTTP_REFERER'])) echo $_SERVER['HTTP_REFERER']; else echo 'products.php'; ?>" type="text" style="display: none;" />

Docker - Cannot remove dead container

I got the same issue and both answers did not help.

What helped for me is just creating the directories that are missing and them remove them:

mkdir /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3
mkdir /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3-init
docker rm 656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

Get values from an object in JavaScript

use

console.log(variable)

and if you using google chrome open Console by using Ctrl+Shift+j

Goto >> Console

Insert new item in array on any position in PHP

if unsure, then DONT USE THESE:

$arr1 = $arr1 + $arr2;

OR

$arr1 += $arr2;

because with + original array will be overwritten. (see source)

Redirect HTTP to HTTPS on default virtual host without ServerName

I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)

I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):

mkcert -install
mkcert localhost "*.dev.net"

This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)

localhost+1.pem
localhost+1-key.pem

Overwrite the XAMPP default certs:

copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem"  C:\xampp\apache\conf\ssl.key\server.key

Now, in Apache2 for Debian 10, activate SSL & vhost_alias

a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2

For vhost_alias add this Apache2 config:

nano /etc/apache2/sites-available/999-vhosts_alias.conf

With this content:

<VirtualHost *:80>
   UseCanonicalName Off
   ServerAlias *.dev.net
   VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>

Add the site:

a2ensite 999-vhosts_alias

Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:

systemctl stop apache2

mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak

cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key

chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key

systemctl start apache2

Edit the SSL config

nano /etc/apache2/sites-enabled/default-ssl.conf

At the start edit the file with this content:

<IfModule mod_ssl.c>
    <VirtualHost *:443>

            UseCanonicalName Off
            ServerAlias *.dev.net
            ServerAdmin webmaster@localhost

            # DocumentRoot /var/www/html/
            VirtualDocumentRoot /var/www/html/%0/

...

Last restart:

systemctl restart apache2

NOTE: don´t forget to create the folders for your subdomains in /var/www/html/

/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net

how to convert rgb color to int in java

Use getRGB(), it helps ( no complicated programs )

Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.

How to make a progress bar

I tried a simple progress bar. It is not clickable just displays the actual percentage. There's a good explication and code here: http://ruwix.com/simple-javascript-html-css-slider-progress-bar/

How to insert text at beginning of a multi-line selection in vi/Vim

This adds # at the beginning of every line:

:%s/^/#/

And people will stop complaining about your lack of properly commenting scripts.

When should you NOT use a Rules Engine?

I'm a big fan of Business Rules Engines, since it can help you make your life much easier as a programmer. One of the first experiences I've had while working on a Data Warehouse project was to find Stored Procedures containing complicated CASE structures stretching over entire pages. It was a nightmare to debug, since it was very difficult to understand the logic applied in such long CASE structures, and to determine if you have an overlapping between a rule at page 1 of the code and another from page 5. Overall, we had more than 300 such rules embedded in the code.

When we've received a new development requirement, for something called Accounting Destination, which was involving treating more than 3000 rules, i knew something had to change. Back then I've been working on a prototype which later on become the parent of what now is a Custom Business Rule engine, capable of handling all SQL standard operators. Initially we've been using Excel as an authoring tool and , later on, we've created an ASP.net application which will allow the Business Users to define their own business rules, without the need of writing code. Now the system works fine, with very few bugs, and contains over 7000 rules for calculating this Accounting Destination. I don't think such scenario would have been possible by just hard-coding. And the users are pretty happy that they can define their own rules without IT becoming their bottleneck.

Still, there are limits to such approach:

  • You need to have capable business users which have an excellent understanding of the company business.
  • There is a significant workload on searching the entire system (in our case a Data Warehouse), in order to determine all hard-coded conditions which make sense to translate into rules to be handled by a Business Rule Engine. We've also had to take good care that these initial templates to be fully understandable by Business Users.
  • You need to have an application used for rules authoring, in which algorithms for detection of overlapping business rules is implemented. Otherwise you'll end up with a big mess, where no one understands anymore the results they get. When you have a bug in a generic component like a Custom Business Rule Engine, it can be very difficult to debug and involve extensive tests to make sure that things that worked before also work now.

More details on this topic can be found on a post I've written: http://dwhbp.com/post/2011/10/30/Implementing-a-Business-Rule-Engine.aspx

Overall, the biggest advantage of using a Business Rule Engines is that it allows the users to take back control over the Business Rule definitions and authoring, without the need of going to the IT department each time they need to modify something. It also the reduces the workload over IT development teams, which can now focus on building stuff with more added value.

Cheers,

Nicolae

Android changing Floating Action Button color

The document suggests that it takes the @color/accent by default. But we can override it on code by using

fab.setBackgroundTintList(ColorStateList)

Also remember,

The minimum API version to use this library is 15 so you need to update it! if you dont want to do it then you need to define a custom drawable and decorate it!

Ignore files that have already been committed to a Git repository

If you want to stop tracking file without deleting the file from your local system, which I prefer for ignoring config/database.yml file. Simply try:

git rm --cached config/database.yml
# this will delete your file from git history but not from your local system.

now, add this file to .gitignore file and commit the changes. And from now on, any changes made to config/database.yml will not get tracked by git.

$ echo config/database.yml >> .gitignore

Thanks

"Please provide a valid cache path" error in laravel

You can edit your readme.md with instructions to install your laravel app in other environment like this:

## Create folders

```
#!terminal

cp .env.example .env && mkdir bootstrap/cache storage storage/framework && cd storage/framework && mkdir sessions views cache

```

## Folder permissions

```
#!terminal

sudo chown :www-data app storage bootstrap -R
sudo chmod 775 app storage bootstrap -R

```

## Install dependencies

```
#!terminal

composer install

```

Finding common rows (intersection) in two Pandas dataframes

If I understand you correctly, you can use a combination of Series.isin() and DataFrame.append():

In [80]: df1
Out[80]:
   rating  user_id
0       2  0x21abL
1       1  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
5       2  0x21abL
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
9       1  0x21abL

In [81]: df2
Out[81]:
   rating      user_id
0       2      0x1d14L
1       1    0xdbdcad7
2       1      0x21abL
3       3      0x21abL
4       3      0x21abL
5       1  0x5734a81e2
6       2      0x1d14L
7       0       0xdafL
8       0      0x1d14L
9       4  0x5734a81e2

In [82]: ind = df2.user_id.isin(df1.user_id) & df1.user_id.isin(df2.user_id)

In [83]: ind
Out[83]:
0     True
1    False
2     True
3     True
4     True
5    False
6     True
7     True
8     True
9    False
Name: user_id, dtype: bool

In [84]: df1[ind].append(df2[ind])
Out[84]:
   rating  user_id
0       2  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
0       2  0x1d14L
2       1  0x21abL
3       3  0x21abL
4       3  0x21abL
6       2  0x1d14L
7       0   0xdafL
8       0  0x1d14L

This is essentially the algorithm you described as "clunky", using idiomatic pandas methods. Note the duplicate row indices. Also, note that this won't give you the expected output if df1 and df2 have no overlapping row indices, i.e., if

In [93]: df1.index & df2.index
Out[93]: Int64Index([], dtype='int64')

In fact, it won't give the expected output if their row indices are not equal.

Set Icon Image in Java

Use Default toolkit for this

frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));

How to convert an int value to string in Go?

You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (
    "fmt"
)

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)
    fmt.Println(s)
}

Append a tuple to a list - what's the difference between two ways?

There should be no difference, but your tuple method is wrong, try:

a_list.append(tuple([3, 4]))

Doctrine findBy 'does not equal'

Based on the answer from Luis, you can do something more like the default findBy method.

First, create a default repository class that is going to be used by all your entities.

/* $config is the entity manager configuration object. */
$config->setDefaultRepositoryClassName( 'MyCompany\Repository' );

Or you can edit this in config.yml

doctrine: orm: default_repository_class: MyCompany\Repository

Then:

<?php

namespace MyCompany;

use Doctrine\ORM\EntityRepository;

class Repository extends EntityRepository {

    public function findByNot( array $criteria, array $orderBy = null, $limit = null, $offset = null )
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $expr = $this->getEntityManager()->getExpressionBuilder();

        $qb->select( 'entity' )
            ->from( $this->getEntityName(), 'entity' );

        foreach ( $criteria as $field => $value ) {
            // IF INTEGER neq, IF NOT notLike
            if($this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldMapping($field)["type"]=="integer") {
                $qb->andWhere( $expr->neq( 'entity.' . $field, $value ) );
            } else {
                $qb->andWhere( $expr->notLike( 'entity.' . $field, $qb->expr()->literal($value) ) );
            }
        }

        if ( $orderBy ) {

            foreach ( $orderBy as $field => $order ) {

                $qb->addOrderBy( 'entity.' . $field, $order );
            }
        }

        if ( $limit )
            $qb->setMaxResults( $limit );

        if ( $offset )
            $qb->setFirstResult( $offset );

        return $qb->getQuery()
            ->getResult();
    }

}

The usage is the same than the findBy method, example:

$entityManager->getRepository( 'MyRepo' )->findByNot(
    array( 'status' => Status::STATUS_DISABLED )
);

Trigger change event <select> using jquery

If you want to do some checks then use this way

 <select size="1" name="links" onchange="functionToTriggerClick(this.value)">
    <option value="">Select a Search Engine</option>        
    <option value="http://www.google.com">Google</option>
    <option value="http://www.yahoo.com">Yahoo</option>
</select>

<script>

   function functionToTriggerClick(link) {

     if(link != ''){
        window.location.href=link;
        }
    }  

</script>

Starting Docker as Daemon on Ubuntu

I had the same issue on 14.04 with docker 1.9.1.

The upstart service command did work when I used sudo, even though I was root:

$ whoami
root
$ service docker status
status: Unbekannter Auftrag: docker

$ sudo service docker status
docker start/running, process 7394

It seems to depend on the environment variables.

service docker status works when becoming root with su -, but not when only using su:

$ su
Password:
$ service docker status
status: unknown job: docker
$ exit
$ su -
Password:
$ service docker status
docker start/running, process 2342

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

Delete all documents from a collection in cmd:

cd C:\Program Files\MongoDB\Server\4.2\bin
mongo
use yourdb
db.yourcollection.remove( { } )

Using column alias in WHERE clause of MySQL query produces an error

As Victor pointed out, the problem is with the alias. This can be avoided though, by putting the expression directly into the WHERE x IN y clause:

SELECT `users`.`first_name`,`users`.`last_name`,`users`.`email`,SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE SUBSTRING(`locations`.`raw`,-6,4) NOT IN #this is where the fake col is being used
(
 SELECT `postcode` FROM `postcodes` WHERE `region` IN
 (
  'australia'
 )
)

However, I guess this is very inefficient, since the subquery has to be executed for every row of the outer query.

How can I install an older version of a package via NuGet?

Now, it's very much simplified in Visual Studio 2015 and later. You can do downgrade / upgrade within the User interface itself, without executing commands in the Package Manager Console.

  1. Right click on your project and *go to Manage NuGet Packages.

  2. Look at the below image.

    • Select your Package and Choose the Version, which you wanted to install.

NuGet Package Manager window of Project

Very very simple, isn't it? :)

UnicodeEncodeError: 'latin-1' codec can't encode character

The best solution is

  1. set mysql's charset to 'utf-8'
  2. do like this comment(add use_unicode=True and charset="utf8")

    db = MySQLdb.connect(host="localhost", user = "root", passwd = "", db = "testdb", use_unicode=True, charset="utf8") – KyungHoon Kim Mar 13 '14 at 17:04

detail see :

class Connection(_mysql.connection):

    """MySQL Database Connection Object"""

    default_cursor = cursors.Cursor

    def __init__(self, *args, **kwargs):
        """

        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        host
          string, host to connect

        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        conv
          conversion dictionary, see MySQLdb.converters

        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        cursorclass
          class object, used to create cursors (keyword only)

        use_unicode
          If True, text-like columns are returned as unicode objects
          using the connection's character set.  Otherwise, text-like
          columns are returned as strings.  columns are returned as
          normal strings. Unicode objects will always be encoded to
          the connection's character set regardless of this setting.

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer). This implies
          use_unicode=True.

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.

        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables

        autocommit
          If False (default), autocommit is disabled.
          If True, autocommit is enabled.
          If None, autocommit isn't set and server default is used.

        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.

        """

Syntax for a single-line Bash infinite while loop

It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.

while sleep 2; do echo thinking; done

How to show what a commit did?

This is one way I know of. With git, there always seems to be more than one way to do it.

git log -p commit1 commit2

How to select all checkboxes with jQuery?

This code works fine with me

<script type="text/javascript">
$(document).ready(function(){ 
$("#select_all").change(function(){
  $(".checkbox_class").prop("checked", $(this).prop("checked"));
  });
});
</script>

you only need to add class checkbox_class to all checkbox

Easy and simple :D

Using app.config in .Net Core

To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.

protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");

To use the EF core SqlServer provider and compile the above code install the EF SqlServer package

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

After compilation before running the code do the following for the first time

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update

To run the code

dotnet run

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

Convert int to char in java

look at the following program for complete conversion concept

class typetest{
    public static void main(String args[]){
        byte a=1,b=2;
        char c=1,d='b';
        short e=3,f=4;
        int g=5,h=6;
        float i;
        double k=10.34,l=12.45;
        System.out.println("value of char variable c="+c);
        // if we assign an integer value in char cariable it's possible as above
        // but it's not possible to assign int value from an int variable in char variable 
        // (d=g assignment gives error as incompatible type conversion)
        g=b;
        System.out.println("char to int conversion is possible");
        k=g;
        System.out.println("int to double conversion is possible");
        i=h;
        System.out.println("int to float is possible and value of i = "+i);
        l=i;
        System.out.println("float to double is possible");
    }
}

hope ,it will help at least something

How to get the jQuery $.ajax error response text?

If you're not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == 'error'

Load image with jQuery and append it to the DOM

$('<img src="'+ imgPath +'">').load(function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

If you want to do for several images then:

function loadImage(path, width, height, target) {
    $('<img src="'+ path +'">').load(function() {
      $(this).width(width).height(height).appendTo(target);
    });
}

Use:

loadImage(imgPath, 800, 800, '#some_target');

How to make android listview scrollable?

Never put ListView in ScrollView. ListView itself is scrollable.

Import MySQL database into a MS SQL Server

I found a way for this on the net

It demands a little bit of work, because it has to be done table by table. But anyway, I could copy the tables, data and constraints into a MS SQL database.

Here is the link

http://www.codeproject.com/KB/database/migrate-mysql-to-mssql.aspx

Check if a value exists in ArrayList

We can use contains method to check if an item exists if we have provided the implementation of equals and hashCode else object reference will be used for equality comparison. Also in case of a list contains is O(n) operation where as it is O(1) for HashSet so better to use later. In Java 8 we can use streams also to check item based on its equality or based on a specific property.

Java 8

CurrentAccount conta5 = new CurrentAccount("João Lopes", 3135);
boolean itemExists = lista.stream().anyMatch(c -> c.equals(conta5)); //provided equals and hashcode overridden
System.out.println(itemExists); // true

String nameToMatch = "Ricardo Vitor";
boolean itemExistsBasedOnProp = lista.stream().map(CurrentAccount::getName).anyMatch(nameToMatch::equals);
System.out.println(itemExistsBasedOnProp); //true

How to return more than one value from a function in Python?

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly

When is del useful in Python?

Deleting a variable is different than setting it to None

Deleting variable names with del is probably something used rarely, but it is something that could not trivially be achieved without a keyword. If you can create a variable name by writing a=1, it is nice that you can theoretically undo this by deleting a.

It can make debugging easier in some cases as trying to access a deleted variable will raise an NameError.

You can delete class instance attributes

Python lets you write something like:

class A(object):
    def set_a(self, a):
        self.a=a
a=A()
a.set_a(3)
if hasattr(a, "a"):
    print("Hallo")

If you choose to dynamically add attributes to a class instance, you certainly want to be able to undo it by writing

del a.a

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch.

    http://github.com/user/repository/

-to-

http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

Razor/CSHTML - Any Benefit over what we have?

Ex Microsoft Developer's Opinion

I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.

Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.

One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

Use Conda instead of pip. It works perfectly

conda install PyAudio

Simple PHP calculator

<?php
$cal1= $_GET['cal1'];
$cal2= $_GET['cal2'];
$symbol =$_GET['symbol'];


if($symbol == '+')
{
    $add = $cal1 + $cal2;
    echo "Addition is:".$add;
}

else if($symbol == '-')
{
    $subs = $cal1 - $cal2;
    echo "Substraction is:".$subs;
}

 else if($symbol == '*')
{
    $mul = $cal1 * $cal2;
    echo "Multiply is:".$mul;
}

else if($symbol == '/')
{
    $div = $cal1 / $cal2;
    echo "Division is:".$div;
}

  else
{

    echo "Oops ,something wrong in your code son";
}


?>

How can I manually set an Angular form field as invalid?

I was trying to call setErrors() inside a ngModelChange handler in a template form. It did not work until I waited one tick with setTimeout():

template:

<input type="password" [(ngModel)]="user.password" class="form-control" 
 id="password" name="password" required (ngModelChange)="checkPasswords()">

<input type="password" [(ngModel)]="pwConfirm" class="form-control"
 id="pwConfirm" name="pwConfirm" required (ngModelChange)="checkPasswords()"
 #pwConfirmModel="ngModel">

<div [hidden]="pwConfirmModel.valid || pwConfirmModel.pristine" class="alert-danger">
   Passwords do not match
</div>

component:

@ViewChild('pwConfirmModel') pwConfirmModel: NgModel;

checkPasswords() {
  if (this.pwConfirm.length >= this.user.password.length &&
      this.pwConfirm !== this.user.password) {
    console.log('passwords do not match');
    // setErrors() must be called after change detection runs
    setTimeout(() => this.pwConfirmModel.control.setErrors({'nomatch': true}) );
  } else {
    // to clear the error, we don't have to wait
    this.pwConfirmModel.control.setErrors(null);
  }
}

Gotchas like this are making me prefer reactive forms.

How do you create a dropdownlist from an enum in ASP.NET MVC?

A super easy way to get this done - without all the extension stuff that seems overkill is this:

Your enum:

    public enum SelectedLevel
    {
       Level1,
       Level2,
       Level3,
       Level4
    }

Inside of your controller bind the Enum to a List:

    List<SelectedLevel> myLevels = Enum.GetValues(typeof(SelectedLevel)).Cast<SelectedLevel>().ToList();

After that throw it into a ViewBag:

    ViewBag.RequiredLevel = new SelectList(myLevels);

Finally simply bind it to the View:

    @Html.DropDownList("selectedLevel", (SelectList)ViewBag.RequiredLevel, new { @class = "form-control" })

This is by far the easiest way I found and does not require any extensions or anything that crazy.

UPDATE: See Andrews comment below.

How to Add a Dotted Underline Beneath HTML Text

It's impossible without CSS. In fact, the <u> tag is simply adding text-decoration:underline to the text with the browser's built-in CSS.

Here's what you can do:

<html>
<head>
<!-- Other head stuff here, like title or meta -->

<style type="text/css">
u {    
    border-bottom: 1px dotted #000;
    text-decoration: none;
}
</style>
</head>
<!-- Body, content here -->
</html>

What is Linux’s native GUI API?

Strictly speaking, the API of Linux consists of its system calls. These are all of the kernel functions that can be called by a user-mode (non-kernel) program. This is a very low-level interface that allows programs to do things like open and read files. See http://en.wikipedia.org/wiki/System_call for a general introduction.

A real Linux system will also have an entire "stack" of other software running on it, in order to provide a graphical user interface and other features. Each element of this stack will offer its own API.

Difference between null and empty string

String s1 = ""; means that the empty String is assigned to s1. In this case, s1.length() is the same as "".length(), which will yield 0 as expected.

String s2 = null; means that (null) or "no value at all" is assigned to s2. So this one, s2.length() is the same as null.length(), which will yield a NullPointerException as you can't call methods on null variables (pointers, sort of) in Java.

Also, a point, the statement

String s1;

Actually has the same effect as:

String s1 = null;

Whereas

String s1 = "";

Is, as said, a different thing.

What are the best practices for SQLite on Android?

Concurrent Database Access

Same article on my blog(I like formatting more)

I wrote small article which describe how to make access to your android database thread safe.


Assuming you have your own SQLiteOpenHelper.

public class DatabaseHelper extends SQLiteOpenHelper { ... }

Now you want to write data to database in separate threads.

 // Thread 1
 Context context = getApplicationContext();
 DatabaseHelper helper = new DatabaseHelper(context);
 SQLiteDatabase database = helper.getWritableDatabase();
 database.insert(…);
 database.close();

 // Thread 2
 Context context = getApplicationContext();
 DatabaseHelper helper = new DatabaseHelper(context);
 SQLiteDatabase database = helper.getWritableDatabase();
 database.insert(…);
 database.close();

You will get following message in your logcat and one of your changes will not be written.

android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5)

This is happening because every time you create new SQLiteOpenHelper object you are actually making new database connection. If you try to write to the database from actual distinct connections at the same time, one will fail. (from answer above)

To use database with multiple threads we need to make sure we are using one database connection.

Let’s make singleton class Database Manager which will hold and return single SQLiteOpenHelper object.

public class DatabaseManager {

    private static DatabaseManager instance;
    private static SQLiteOpenHelper mDatabaseHelper;

    public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
        if (instance == null) {
            instance = new DatabaseManager();
            mDatabaseHelper = helper;
        }
    }

    public static synchronized DatabaseManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
                    " is not initialized, call initialize(..) method first.");
        }

        return instance;
    }

    public SQLiteDatabase getDatabase() {
        return new mDatabaseHelper.getWritableDatabase();
    }

}

Updated code which write data to database in separate threads will look like this.

 // In your application class
 DatabaseManager.initializeInstance(new MySQLiteOpenHelper());
 // Thread 1
 DatabaseManager manager = DatabaseManager.getInstance();
 SQLiteDatabase database = manager.getDatabase()
 database.insert(…);
 database.close();

 // Thread 2
 DatabaseManager manager = DatabaseManager.getInstance();
 SQLiteDatabase database = manager.getDatabase()
 database.insert(…);
 database.close();

This will bring you another crash.

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase

Since we are using only one database connection, method getDatabase() return same instance of SQLiteDatabase object for Thread1 and Thread2. What is happening, Thread1 may close database, while Thread2 is still using it. That’s why we have IllegalStateException crash.

We need to make sure no-one is using database and only then close it. Some folks on stackoveflow recommended to never close your SQLiteDatabase. This will result in following logcat message.

Leak found
Caused by: java.lang.IllegalStateException: SQLiteDatabase created and never closed

Working sample

public class DatabaseManager {

    private int mOpenCounter;

    private static DatabaseManager instance;
    private static SQLiteOpenHelper mDatabaseHelper;
    private SQLiteDatabase mDatabase;

    public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
        if (instance == null) {
            instance = new DatabaseManager();
            mDatabaseHelper = helper;
        }
    }

    public static synchronized DatabaseManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
                    " is not initialized, call initializeInstance(..) method first.");
        }

        return instance;
    }

    public synchronized SQLiteDatabase openDatabase() {
        mOpenCounter++;
        if(mOpenCounter == 1) {
            // Opening new database
            mDatabase = mDatabaseHelper.getWritableDatabase();
        }
        return mDatabase;
    }

    public synchronized void closeDatabase() {
        mOpenCounter--;
        if(mOpenCounter == 0) {
            // Closing database
            mDatabase.close();

        }
    }

}

Use it as follows.

SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
database.insert(...);
// database.close(); Don't close it directly!
DatabaseManager.getInstance().closeDatabase(); // correct way

Every time you need database you should call openDatabase() method of DatabaseManager class. Inside this method, we have a counter, which indicate how many times database is opened. If it equals to one, it means we need to create new database connection, if not, database connection is already created.

The same happens in closeDatabase() method. Every time we call this method, counter is decreased, whenever it goes to zero, we are closing database connection.


Now you should be able to use your database and be sure it's thread safe.

Android Paint: .measureText() vs .getTextBounds()

DISCLAIMER: This solution is not 100% accurate in terms of determining the minimal width.

I was also figuring out how to measure text on a canvas. After reading the great post from mice i had some problems on how to measure multiline text. There is no obvious way from these contributions but after some research i cam across the StaticLayout class. It allows you to measure multiline text (text with "\n") and configure much more properties of your text via the associated Paint.

Here is a snippet showing how to measure multiline text:

private StaticLayout measure( TextPaint textPaint, String text, Integer wrapWidth ) {
    int boundedWidth = Integer.MAX_VALUE;
    if (wrapWidth != null && wrapWidth > 0 ) {
       boundedWidth = wrapWidth;
    }
    StaticLayout layout = new StaticLayout( text, textPaint, boundedWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false );
    return layout;
}

The wrapwitdh is able to determin if you want to limit your multiline text to a certain width.

Since the StaticLayout.getWidth() only returns this boundedWidth you have to take another step to get the maximum width required by your multiline text. You are able to determine each lines width and the max width is the highest line width of course:

private float getMaxLineWidth( StaticLayout layout ) {
    float maxLine = 0.0f;
    int lineCount = layout.getLineCount();
    for( int i = 0; i < lineCount; i++ ) {
        if( layout.getLineWidth( i ) > maxLine ) {
            maxLine = layout.getLineWidth( i );
        }
    }
    return maxLine;
}

When does socket.recv(recv_size) return?

It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

Send inline image in email

Try this

 string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";
 AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);

 LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg);
 inline.ContentId = Guid.NewGuid().ToString();
 avHtml.LinkedResources.Add(inline);

 MailMessage mail = new MailMessage();
 mail.AlternateViews.Add(avHtml);

 Attachment att = new Attachment(filePath);
 att.ContentDisposition.Inline = true;

 mail.From = from_email;
 mail.To.Add(data.email);
 mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";
 mail.Body = String.Format(
            "<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
            @"<img src=""cid:{0}"" />", att.ContentId);

 mail.IsBodyHtml = true;
 mail.Attachments.Add(att);

SQL select join: is it possible to prefix all columns as 'prefix.*'?

Developing from this solution, this is how I would approach the problem:

First create a list of all the AS statements:

DECLARE @asStatements varchar(8000)

SELECT @asStatements = ISNULL(@asStatements + ', ','') + QUOTENAME(table_name) + '.' + QUOTENAME(column_name) + ' AS ' + '[' + table_name + '.' + column_name + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TABLE_A' OR TABLE_NAME = 'TABLE_B'
ORDER BY ORDINAL_POSITION

Then use it in your query:

EXEC('SELECT ' + @asStatements + ' FROM TABLE_A a JOIN TABLE_B b USING (some_id)');

However, this might need modifications because something similar is only tested in SQL Server. But this code doesn't exactly work in SQL Server because USING is not supported.

Please comment if you can test/correct this code for e.g. MySQL.

Java Try Catch Finally blocks without Catch

The Java Language Specification(1) describes how try-catch-finally is executed. Having no catch is equivalent to not having a catch able to catch the given Throwable.

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    • If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then …
    • If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
      • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
      • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).

(1) Execution of try-catch-finally

How do I disable "missing docstring" warnings at a file-level in Pylint?

In my case, with Pylint 2.6.0, the missing docstring messages wouldn't disappear, even after explicitly disabling missing-module-docstring, missing-class-docstring and missing-function-docstring in my .pylintrc file. Finally, the following configuration worked for me:

[MESSAGES CONTROL]

disable=missing-docstring,empty-docstring

Apparently, Pylint 2.6.0 still validates docstrings unless both checks are disabled.

How to convert a timezone aware string to datetime in Python without dateutil?

As of Python 3.7, datetime.datetime.fromisoformat() can handle your format:

>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.

Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.

As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil is too heavy-weight for you, use iso8601 instead, it'll parse your specific format just fine:

>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)

iso8601 is a whopping 4KB small. Compare that tot python-dateutil's 148KB.

As of Python 3.2 Python can handle simple offset-based timezones, and %z will parse -hhmm and +hhmm timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the : in the timezone:

>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.

How to automate drag & drop functionality using Selenium WebDriver Java

There is a page documenting Advanced User Interactions; which has a lot of great examples on how to generate a sequence of actions, you can find it here

// Configure the action
Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .click(someOtherElement)
   .keyUp(Keys.CONTROL);

// Then get the action:
Action selectMultiple = builder.build();

// And execute it:
selectMultiple.perform();   

or

Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(someElement)
   .moveToElement(otherElement)
   .release(otherElement)
   .build();

dragAndDrop.perform();

How to make a simple collection view with Swift

For swift 4.2 --

//MARK: UICollectionViewDataSource

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
    configureCell(cell: cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.black


    //Customise your cell

}

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // When user selects the cell
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    // When user deselects the cell
}

How to check whether a pandas DataFrame is empty?

I use the len function. It's much faster than empty. len(df.index) is even faster.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))

def empty(df):
    return df.empty

def lenz(df):
    return len(df) == 0

def lenzi(df):
    return len(df.index) == 0

'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)

10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop

len on index seems to be faster
'''

What are the differences between Visual Studio Code and Visual Studio?

For Unity3D users ...

  • VSCode is incredibly faster than VS. Files open instantly from Unity. VS is very slow. VSCode launches instantly. VS takes forever to launch.

  • VS can literally compile code, build apps and so on, it's a huge IDE like Unity itself or XCode. VSCode is indeed "just" a full-featured text editor. VSCode is NOT a compiler (far less a huge, build-everything system that can literally create apps and software of all types): VSCode is literally "just a text editor".

  • With VSCode, you DO need to install the "Visual Studio Code" package. (Not to be confused with the "Visual Studio" package.) (It seems to me that VS works fine without the VS package, but, with VS Code, you must install Unity's VSCode package.)

enter image description here

  • When you first download and install VSCode, simply open any C# file on your machine. It will instantly prompt you to install the needed C# package. This is harmless and easy.

  • Unfortunately VSCode generally has only one window! You cannot, really, easily drag files to separate windows. If this is important to you, you may need to go with VS.

  • The biggest problem with VS is that the overall concept of settings and preferences are absolutely horrible. In VS, it is all-but impossible to change the font, etc. In contrast, VSCode has FANTASTIC preferences - dead simple, never a problem.

  • As far as I can see, every single feature in VS which you use in Unity is present in VSCode. (So, code coloring, jump to definitions, it understands/autocompletes every single thing in Unity, it opens from Unity, double clicking something in the Unity console opens the file to that line, etc etc)

  • If you are used to VS. And you want to change to VSCode. It's always hard changing editors, they are so intimate, but it's pretty similar; you won't have a big heartache.

In short if you're a VS for Unity3D user,

and you're going to try VSCode...

  1. VSCode is on the order of 19 trillion times faster in every way. It will blow your mind.

  2. It does seem to have every feature.

  3. Basically VS is the world's biggest IDE and application building system: VSCode is just an editor. (Indeed, that's exactly what you want with Unity, since Unity itself is the IDE.)

  4. Don't forget to just click to install the relevant Unity package.

If I'm not mistaken, there is no reason whatsoever to use VS with Unity.

Unity is an IDE so you just need a text editor, and that is what VSCode is. VSCode is hugely better in both speed and preferences. The only possible problem - multiple-windows are a bit clunky in VSCode!

That horrible "double copy" problem in VS ... solved!

If you are using VS with Unity. There is an infuriating problem where often VS will try to open twice, that is you will end up with two or more copies of VS running. Nobody has ever been able to fix this or figure out what the hell causes it. Fortunately, this problem never happens with VSCode.

Installing VSCode on a Mac - unbelievably easy.

There are no installers, etc etc etc. On the download page, you download a zipped Mac app. Put it in the Applications folder and you're done.

Folding! (Mac/Windows keystrokes are different)

Bizarrely there's no menu entry / docu whatsoever for folding, but here are the keys:

https://stackoverflow.com/a/30077543/294884

Setting colors and so on in VSCode - the critical tips

Particularly for Mac users who may find the colors strange:

Priceless post #1:

https://stackoverflow.com/a/45640244/294884

Priceless post #2:

https://stackoverflow.com/a/63303503/294884

Meta files ...

To keep the "Explorer" list of files on the left tidy, in the Unity case:

enter image description here

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

The only way to do explicit scaling in CSS is to use tricks such as found here.

IE6 only, you could also use filters (check out PNGFix). But applying them automatically to the page will need javascript, though that javascript could be embedded in the CSS file.

If you are going to require javascript, then you might want to just have javascript fill in the missing value for the height by inspecting the image once the content has loaded. (Sorry I do not have a reference for this technique).

Finally, and pardon me for this soapbox, you might want to eschew IE6 support in this matter. You could add _width: auto after your width: 75px rule, so that IE6 at least renders the image reasonably, even if it is the wrong size.

I recommend the last solution simply because IE6 is on the way out: 20% and going down almost a percent a month. Also, I note that your site is recreational and in the UK. Both of these help the demographic lean to be away from IE6: IE6 usage drops nearly 40% during weekends (no citation sorry), and UK has a much lower IE6 demographic (again no citation, sorry).

Good luck!

Fatal error: Call to undefined function mysql_connect()

The problem shows up when you're using mysql_connect in your code lines so just add it as in mysqli_cOnnect and it will solve the Problem.
you also Have to then use mysqli throughout your code lines or the Problem would surface again.
example mysql_select_db will then be mysqL_select_db.
That's for selecting Database.

Thanks hope this helps

What is the difference between React Native and React?

In summary: React.js for Web Development while React-Native for Mobile App Development

How do I make a Windows batch script completely silent?

To suppress output, use redirection to NUL.

There are two kinds of output that console commands use:

  • standard output, or stdout,

  • standard error, or stderr.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

or

COPY file1 file2 1>NUL

or

>NUL COPY file1 file2

or

1>NUL COPY file1 file2

suppresses all of COPY's standard output.

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

or

2>NUL DEL file

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

SDK Manager.exe doesn't work

I had this same problem and after trying a variety of things like changing the path variables I went to java.com on a whim and downloaded java, installed, and lo and behold the sdk manager worked after that.

A button to start php script, how?

What exactly do you mean by "starts my php script"? What kind of PHP script? One to generate an HTML response for an end-user, or one that simply performs some kind of data processing task? If you are familiar with using the tag and how it interacts with PHP, then you should only need to POST to your target PHP script using an button of type "submit". If you are not familiar with forms, take a look here.

SQL Query to search schema of all tables

You can also try doing this using one of many third party tools that are available for this.

Queries are great for simple searches but if you need to do more manipulation with data, search for references and such this is where you can do a much better job with these.

Also, these come in very handy when some objects are encrypted and you need to search for

I’m using ApexSQL Search which is free but there are also many more (also free) on the market such as Red Gate or SSMS Tool Pack.

AFNetworking Post Request

for login screen;

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary 

dictionaryWithObjectsAndKeys:_usernametf.text, @"username",_passwordtf.text, @"password", nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

[manager POST:@"enter your url" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"%@", responseObject);

}
      failure:^(NSURLSessionTask *operation, NSError *error) {
          NSLog(@"Error: %@", error);
      }];

}

Disable validation of HTML5 form elements

The best solution is to use a text input and add the attribute inputmode="url" to provide the URL keyboard facilities. The HTML5 specification was thought for this purpose. If you keep type="url" you get the syntax validation which is not useful in every case (it is better to check if it returns a 404 error instead of the syntax which is quite permissive and is not of a great help).

You also have the possibility to override the default pattern with the attribute pattern="https?://.+" for example to be more permissive.

Putting the novalidate attribute to the form is not the right answer to the asked question because it removes validation for all the fields in the form and you may want to keep validation for email fields for example.

Using jQuery to disable validation is also a bad solution because it should absolutely work without JavaScript.

In my case, I put a select element with 2 options (http:// or https://) before the URL input because I just need websites (and no ftp:// or other things). This way I avoid typing this weird prefix (the biggest regret of Tim Berners-Lee and maybe the main source of URL syntax errors) and I use a simple text input with inputmode="url" with placeholders (without HTTP). I use jQuery and server side script to validate the real existence of the web site (no 404) and to remove the HTTP prefix if inserted (I avoid to use a pattern like pattern="^((?http).)*$" to prevent putting the prefix because I think it is better to be more permissive)

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How to set a CMake option() at command line

An additional option is to go to your build folder and use the command ccmake .

This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.

The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .

Navigation Controller Push View Controller

-  (void) loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                error:(NSError *)error{
    UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:@"nav"];
    ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"LoggedInVC"];
    [nav pushViewController:vc animated:YES];
    [self presentViewController:nav animated:YES completion:nil];
}

"nav" is the Storyboard ID for my navigation controller "vc" is the Storyboard ID for my first view controller connected to my navigation controller

-hope this helps

How do you make Git work with IntelliJ?

You need to specify the executable path of Git in the Git Settings, as mentionned in the per-requesites:

The Git integration plugin is enabled and the location of the Git executable file is correctly specified on the Git page of the Settings dialog box.

As long as you see "a message indicating that the Git execution path is not correct", the rest of the instructions won't work.

Path to Git executable

In this text box, specify the path to the Git executable file.
Type the path manually or click the Browse button to open the Select Path - Git Configuration dialog box and select the location of the Git executable file in the directories tree.

See "Where is git.exe located?" for the path of Git on Windows.

OR

    c:\path\to\PortableGit-2.6.2-64-bit\usr\bin

OR

    c:\path\to\PortableGit-2.x.\mingw64\bin
  • With GitHub Desktop:

      %USERPROFILE%\AppData\Local\GitHub\PORTAB~1\bin\git.exe
    

Update 2020, three years later:

As noted by Daniel Connelly in the comments

IntelliJ now lets people install it through the path specified in the help above (just look for the "Download Now" button on the Git menu).
If you download Git from the website, a version that IntelliJ does not support will be installed.

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

Another suggestion is to use imagesLoaded plugin.

$("img").imagesLoaded(function(){
alert( $(this).width() );
alert( $(this).height() );
});

ORA-01036: illegal variable name/number when running query through C#

I have faced same problem ... For the problem is like this, I am calling the PRC inside cpp program and my PRC taking 4 arguments but while calling I used only 1 arguments so this error came for me.

Begin Example_PRC(:1); End; // this cause the problem 
Begin Example_PRC(:1,:2,:3,:4); End; // this is the solution

How do I select a MySQL database through CLI?

Switch to a database.

mysql> use [db name];

MySQL Commands

"Continue" (to next iteration) on VBScript

I think you are intended to contain ALL YOUR LOGIC under your if statement. Basically:

' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
  ' you want to say
  ' If i = 4 CONTINUE but VBScript has no continue
  If i <> 4 Then ' just invert the logic
    WSH.Echo( i )
  End If
Next

This can make the code a bit longer, but some people don't like break or continue anyway.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

"location" directive should be inside a 'server' directive, e.g.

server {
    listen       8765;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

Use CSS to remove the space between images

The best solution I've found for this is to contain them in a parent div, and give that div a font-size of 0.

Get key by value in dictionary

I tried to read as many solutions as I can to prevent giving duplicate answer. However, if you are working on a dictionary which values are contained in lists and if you want to get keys that have a particular element you could do this:

d = {'Adams': [18, 29, 30],
     'Allen': [9, 27],
     'Anderson': [24, 26],
     'Bailey': [7, 30],
     'Baker': [31, 7, 10, 19],
     'Barnes': [22, 31, 10, 21],
     'Bell': [2, 24, 17, 26]}

Now lets find names that have 24 in their values.

for key in d.keys():    
    if 24 in d[key]:
        print(key)

This would work with multiple values as well.

Is key-value pair available in Typescript?

Is key-value pair available in Typescript?

Yes. Called an index signature:

interface Foo {
   [key: string]: Bar;
} 
let foo:Foo = {};

Here keys are string and values are Bar.

More

You can use an es6 Map for proper dictionaries, polyfilled by core-js.

$.focus() not working

if you use bootstrap + modal, this worked for me :

  $(myModal).modal('toggle');
  $(myModal).on('shown.bs.modal', function() {
    $('#modalSearchBox').focus()
  });

open read and close a file in 1 line of code

Python Standard Library Pathlib module does what you looking for:

Path('pagehead.section.htm').read_text()

Don't forget to import Path:

jsk@dev1:~$ python3
Python 3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> (Path("/etc") / "hostname").read_text()
'dev1.example\n'

On Python 27 install backported pathlib or pathlib2

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

I had similar issue and the below line helped me solving the issue.Thanks to rene. I just pasted this line above the authentication code and it worked

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

SSH Key - Still asking for password and passphrase

Same problem to me and the solution was:

See this github doc to convert remote's URL from https to ssh. To check if remote's URL is ssh or https, use git remote -v. To switch from https to ssh: git remote set-url origin [email protected]:USERNAME/REPOSITORY.git @jeeYem

Split string into array of character strings

"cat".split("(?!^)")

This will produce

array ["c", "a", "t"]

Redirecting a request using servlets and the "setHeader" method not working

Another way of doing this if you want to redirect to any url source after the specified point of time

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

public class MyServlet extends HttpServlet


{

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException

{

response.setContentType("text/html");

PrintWriter pw=response.getWriter();

pw.println("<b><centre>Redirecting to Google<br>");


response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url  after 5 seconds


pw.close();
}

}

Java, How to get number of messages in a topic in apache kafka

Apache Kafka command to get un handled messages on all partitions of a topic:

kafka-run-class kafka.tools.ConsumerOffsetChecker 
    --topic test --zookeeper localhost:2181 
    --group test_group

Prints:

Group      Topic        Pid Offset          logSize         Lag             Owner
test_group test         0   11051           11053           2               none
test_group test         1   10810           10812           2               none
test_group test         2   11027           11028           1               none

Column 6 is the un-handled messages. Add them up like this:

kafka-run-class kafka.tools.ConsumerOffsetChecker 
    --topic test --zookeeper localhost:2181 
    --group test_group 2>/dev/null | awk 'NR>1 {sum += $6} 
    END {print sum}'

awk reads the rows, skips the header line and adds up the 6th column and at the end prints the sum.

Prints

5