Programs & Examples On #Xunit.net

xUnit.net is a unit testing tool for the .NET Framework. Written by the original inventor of NUnit, xUnit.net is the latest technology for unit testing C#, F#, VB.NET and other .NET languages. It works with ReSharper, CodeRush, and TestDriven.NET. http://xunit.github.io/

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

It's not a big deal on a small/personal scale, but it can become a bigger deal quickly on a larger scale. My employer is a large Microsoft shop, but won't/can't buy into Team System/TFS for a number of reasons. We currently use Subversion + Orcas + MBUnit + TestDriven.NET and it works well, but getting TD.NET was a huge hassle. The version sensitivity of MBUnit + TestDriven.NET is also a big hassle, and having one additional commercial thing (TD.NET) for legal to review and procurement to handle and manage, isn't trivial. My company, like a lot of companies, are fat and happy with a MSDN Subscription model, and it's just not used to handling one off procurements for hundreds of developers. In other words, the fully integrated MS offer, while definitely not always best-of-bread, is a significant value-add in my opinion.

I think we'll stay with our current step because it works and we've already gotten over the hump organizationally, but I sure do wish MS had a compelling offering in this space so we could consolidate and simplify our dev stack a bit.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

In Chrome (v.56 is what I'm using but I AFAIK this applies generally) you can set title=" " (a single space) and the automatic title text will be overridden and nothing displayed. (If you try to make it just an empty string, though, it will treat it as if it isn't set and add that automatic tooltip text you've been getting).

I haven't tested this in other browsers, because I found it whilst making a Google Chrome Extension. I'm sure once I port things to other browsers, though, I'll see if it works in them (if even necessary), too.

How do I validate a date string format in python?

The Python dateutil library is designed for this (and more). It will automatically convert this to a datetime object for you and raise a ValueError if it can't.

As an example:

>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)

This raises a ValueError if the date is not formatted correctly:

>>> parse("2003-09-251")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month

dateutil is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: dateutil parsing examples.

It also handles timezones if you need that.

Update based on comments: parse also accepts the keyword argument dayfirst which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.

>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11

npm install Error: rollbackFailedOptional

Try this all command answered here to solve the problem https://stackoverflow.com/a/54173142/12142401 if problem persists Do the following Steps

Completely Uninstall the nodejs checkout this answer for complete uninstallation of nodejs https://stackoverflow.com/a/20711410/12142401

Download the updated nodejs setup from their website Install it in any drive but not on previously installed drive like if you installed in C drive then install in D,S,G Drive Run your npm command it will completely work fine

PostgreSQL: How to make "case-insensitive" query

You can also read up on the ILIKE keyword. It can be quite useful at times, albeit it does not conform to the SQL standard. See here for more information: http://www.postgresql.org/docs/9.2/static/functions-matching.html

memcpy() vs memmove()

The memory in memcpy cannot overlap or you risk undefined behaviour, while the memory in memmove can overlap.

char a[16];
char b[16];

memcpy(a,b,16);           // valid
memmove(a,b,16);          // Also valid, but slower than memcpy.
memcpy(&a[0], &a[1],10);  // Not valid since it overlaps.
memmove(&a[0], &a[1],10); // valid. 

Some implementations of memcpy might still work for overlapping inputs but you cannot count of that behaviour. While memmove must allow for overlapping.

Integer value comparison

well i might be late on this but i would like to share something:

Given the input: System.out.println(isGreaterThanZero(-1));

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

Returns false

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

Returns true So i think in yourcase 'compareTo' will be more accurate.

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

What is the best way to tell if a character is a letter or number in Java without using regexes?

Use the below code

Character.isLetterOrDigit(string.charAt(index))

How to force maven update?

I used the IntelliJ IDE and I had a similar problem and to solve I clicked in "Generate Sources and Update Folders for All Projects" in Maven tab.

enter image description here

Getting DOM elements by classname

I think the accepted way is better, but I guess this might work as well

function getElementByClass(&$parentNode, $tagName, $className, $offset = 0) {
    $response = false;

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    $tagCount = 0;
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            if ($tagCount == $offset) {
                $response = $temp;
                break;
            }

            $tagCount++;
        }

    }

    return $response;
}

writing a batch file that opens a chrome URL

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"

How to print a list of symbols exported from a dynamic library

Use nm -a your.dylib

It will print all the symbols including globals

Get input type="file" value when it has multiple files selected

The files selected are stored in an array: [input].files

For example, you can access the items

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

For jQuery-comfortable people, it's similarly easy

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

Sorting dropdown alphabetically in AngularJS

Angular has an orderBy filter that can be used like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>

See this fiddle for an example.

It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I had very hard time with this error :

Reason: Incompatible library version: php requires version 44.0.0 or later, but libpng16.16.dylib provides version 42.0.0 Trace/BPT trap: 6

I did all the above things with brew and much more ... but it wasn't this !

Check where your library is :

sudo find / -name libpng16.16.dylib

In my case here was the relevant result :

  • /usr/local/lib/libpng16.16.dylib
  • /usr/local/Cellar/libpng/1.6.34/lib/libpng16.16.dylib
  • /Applications/MAMP/Library/lib/libpng16.16.dylib
  • /opt/X11/lib/libpng16.16.dylib

So as I'm a MAMP user it turn out that the error appeared while I was trying to update from PHP 7.1.0 to 7.1.8 (last MAMP php available) as Symfony4 require at least 7.1.3

At the end I instaled the new version of MAMP and it worked (4.1 to 4.2). However be carreful when you're doing this, you need to backup first everything in your MAMP/htdoc folder. Also keep a backup of your custom compiled php version than can live in MAMP/bin/php. (In my case I had a special PHP version with Oracle drivers).

Also if you configured the MAMP php version to be your CLI php interpreter, you'll need to update the PATH in your .bash_profile

It should look something like this :

export PATH=/Applications/MAMP/bin/php/php7.1.8/bin:$PATH

I hope this can help.

Adding css class through aspx code behind

Syntax:

controlName.CssClass="CSS Class Name";

Example:

txtBank.CssClass = "csError";

php var_dump() vs print_r()

It's too simple. The var_dump() function displays structured information about variables/expressions including its type and value. Whereas The print_r() displays information about a variable in a way that's readable by humans.

Example: Say we have got the following array and we want to display its contents.

$arr = array ('xyz', false, true, 99, array('50'));

print_r() function - Displays human-readable output

Array
(
    [0] => xyz
    [1] =>
    [2] => 1
    [3] => 99
    [4] => Array
        (
            [0] => 50
        )
)

var_dump() function - Displays values and types

array(5) {
  [0]=>
  string(3) "xyz"
  [1]=>
  bool(false)
  [2]=>
  bool(true)
  [3]=>
  int(100)
  [4]=>
  array(1) {
    [0]=>
    string(2) "50"
  }
}

For more details: https://stackhowto.com/how-to-display-php-variable-values-with-echo-print_r-and-var_dump/

What is the 'dynamic' type in C# 4.0 used for?

The best use case of 'dynamic' type variables for me was when, recently, I was writing a data access layer in ADO.NET (using SQLDataReader) and the code was invoking the already written legacy stored procedures. There are hundreds of those legacy stored procedures containing bulk of the business logic. My data access layer needed to return some sort of structured data to the business logic layer, C# based, to do some manipulations (although there are almost none). Every stored procedures returns different set of data (table columns). So instead of creating dozens of classes or structs to hold the returned data and pass it to the BLL, I wrote the below code which looks quite elegant and neat.

public static dynamic GetSomeData(ParameterDTO dto)
        {
            dynamic result = null;
            string SPName = "a_legacy_stored_procedure";
            using (SqlConnection connection = new SqlConnection(DataConnection.ConnectionString))
            {
                SqlCommand command = new SqlCommand(SPName, connection);
                command.CommandType = System.Data.CommandType.StoredProcedure;                
                command.Parameters.Add(new SqlParameter("@empid", dto.EmpID));
                command.Parameters.Add(new SqlParameter("@deptid", dto.DeptID));
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        dynamic row = new ExpandoObject();
                        row.EmpName = reader["EmpFullName"].ToString();
                        row.DeptName = reader["DeptName"].ToString();
                        row.AnotherColumn = reader["AnotherColumn"].ToString();                        
                        result = row;
                    }
                }
            }
            return result;
        }

How to slice a Pandas Data Frame by position?

dataframe[:n] - Will return first n-1 rows

Is there a way I can retrieve sa password in sql server 2005

There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).

Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.

enter image description here

Now write down the new SA password.

How to rename a table in SQL Server?

If you try exec sp_rename and receieve a LockMatchID error then it might help to add a use [database] statement first:

I tried

 exec sp_rename '[database_name].[dbo].[table_name]', 'new_table_name';
 -- Invalid EXECUTE statement using object "Object", method "LockMatchID".

What I had to do to fix it was to rewrite it to:

use database_name
exec sp_rename '[dbo].[table_name]', 'new_table_name';

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

CSS3 Transform Skew One Side

I know this is old, but I would like to suggest using a linear-gradient to achieve the same effect instead of margin offset. This is will maintain any content at its original place.

http://jsfiddle.net/zwXaf/2/

HTML

<ul>
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
</ul>

CSS

/* reset */
ul, li, a {
    margin: 0; padding: 0;
}
/* nav stuff */
ul, li, a {
    display: inline-block;
    text-align: center;
}
/* appearance styling */
ul {
    /* hacks to make one side slant only */
    overflow: hidden;
    background: linear-gradient(to right, red, white, white, red);
}
li {
    background-color: red;
     transform:skewX(-20deg);
    -ms-transform:skewX(-20deg);
    -webkit-transform:skewX(-20deg);
}
li a {
    padding: 3px 6px 3px 6px;
    color: #ffffff;
    text-decoration: none;
    width: 80px;
     transform:skewX(20deg);
    -ms-transform:skewX(20deg);
    -webkit-transform:skewX(20deg);
}

proper hibernate annotation for byte[]

Here goes what O'reilly Enterprise JavaBeans, 3.0 says

JDBC has special types for these very large objects. The java.sql.Blob type represents binary data, and java.sql.Clob represents character data.

Here goes PostgreSQLDialect source code

public PostgreSQLDialect() {
    super();
    ...
    registerColumnType(Types.VARBINARY, "bytea");
    /**
      * Notice it maps java.sql.Types.BLOB as oid
      */
    registerColumnType(Types.BLOB, "oid");
}

So what you can do

Override PostgreSQLDialect as follows

public class CustomPostgreSQLDialect extends PostgreSQLDialect {

    public CustomPostgreSQLDialect() {
        super();

        registerColumnType(Types.BLOB, "bytea");
    }
}

Now just define your custom dialect

<property name="hibernate.dialect" value="br.com.ar.dialect.CustomPostgreSQLDialect"/>

And use your portable JPA @Lob annotation

@Lob
public byte[] getValueBuffer() {

UPDATE

Here has been extracted here

I have an application running in hibernate 3.3.2 and the applications works fine, with all blob fields using oid (byte[] in java)

...

Migrating to hibernate 3.5 all blob fields not work anymore, and the server log shows: ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: column is of type oid but expression is of type bytea

which can be explained here

This generaly is not bug in PG JDBC, but change of default implementation of Hibernate in 3.5 version. In my situation setting compatible property on connection did not helped.

...

Much more this what I saw in 3.5 - beta 2, and i do not know if this was fixed is Hibernate - without @Type annotation - will auto-create column of type oid, but will try to read this as bytea

Interesting is because when he maps Types.BOLB as bytea (See CustomPostgreSQLDialect) He get

Could not execute JDBC batch update

when inserting or updating

Disable HttpClient logging

I've been plagued by the same issue for quite some time now and finally decided to look into this. It turned out the issue is that my project had a dependency on http-builder-0.5.2.jar which bundled a log4j.xml file within itself. And sure enough, the log level for org.apache.http.wire was DEBUG! The way I found it was just to go through all the jar files in my dependencies and do "jar tvf" and grepping for log4j.

While this discovery led to the eventual solution of upping the version of my http-builder dependency to 0.6, it still baffles me what must have gone through the developer's mind when bundling the log4j.xml file into the jar file. Anyway, that's probably not relevant to this thread for now. But I figured it's useful to mention this solution I found given that when I was searching for a solution before now, mine never came up. Hopefully someone will find this useful.

HTML input textbox with a width of 100% overflows table cells

I solved the problem by applying box-sizing:border-box; to the table cells themselves, besides doing the same with the input and the wrapper.

Edit Crystal report file without Crystal Report software

If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154

Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.

Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)

How to increment an iterator by 2?

Assuming list size may not be an even multiple of step you must guard against overflow:

static constexpr auto step = 2;

// Guard against invalid initial iterator.
if (!list.empty())
{
    for (auto it = list.begin(); /*nothing here*/; std::advance(it, step))
    {
        // do stuff...

        // Guard against advance past end of iterator.
        if (std::distance(it, list.end()) > step)
            break;
    }
}

Depending on the collection implementation, the distance computation may be very slow. Below is optimal and more readable. The closure could be changed to a utility template with the list end value passed by const reference:

const auto advance = [&](list_type::iterator& it, size_t step)
{
    for (size_t i = 0; it != list.end() && i < step; std::next(it), ++i);
};

static constexpr auto step = 2;

for (auto it = list.begin(); it != list.end(); advance(it, step))
{
    // do stuff...
}

If there is no looping:

static constexpr auto step = 2;
auto it = list.begin();

if (step <= list.size())
{
    std::advance(it, step);
}

python: How do I know what type of exception occurred?

You can start as Lauritz recommended, with:

except Exception as ex:

and then just to print ex like so:

try:
    #your try code here
except Exception as ex:
    print ex

MySQL - Rows to Columns

Taking advantage of Matt Fenwick's idea that helped me to solve the problem (a lot of thanks), let's reduce it to only one query:

select
    history.*,
    coalesce(sum(case when itemname = "A" then itemvalue end), 0) as A,
    coalesce(sum(case when itemname = "B" then itemvalue end), 0) as B,
    coalesce(sum(case when itemname = "C" then itemvalue end), 0) as C
from history
group by hostid

Background thread with QThread in PyQt

According to the Qt developers, subclassing QThread is incorrect (see http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/). But that article is really hard to understand (plus the title is a bit condescending). I found a better blog post that gives a more detailed explanation about why you should use one style of threading over another: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

In my opinion, you should probably never subclass thread with the intent to overload the run method. While that does work, you're basically circumventing how Qt wants you to work. Plus you'll miss out on things like events and proper thread safe signals and slots. Plus as you'll likely see in the above blog post, the "correct" way of threading forces you to write more testable code.

Here's a couple of examples of how to take advantage of QThreads in PyQt (I posted a separate answer below that properly uses QRunnable and incorporates signals/slots, that answer is better if you have a lot of async tasks that you need to load balance).

import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt

# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    dataReady = QtCore.pyqtSignal(list, dict)

    @QtCore.pyqtSlot()
    def processA(self):
        print "Worker.processA()"
        self.finished.emit()

    @QtCore.pyqtSlot(str, list, list)
    def processB(self, foo, bar=None, baz=None):
        print "Worker.processB()"
        for thing in bar:
            # lots of processing...
            self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
        self.finished.emit()


class Thread(QtCore.QThread):
    """Need for PyQt4 <= 4.6 only"""
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)

     # this class is solely needed for these two methods, there
     # appears to be a bug in PyQt 4.6 that requires you to
     # explicitly call run and start from the subclass in order
     # to get the thread to actually start an event loop

    def start(self):
        QtCore.QThread.start(self)

    def run(self):
        QtCore.QThread.run(self)


app = QtGui.QApplication(sys.argv)

thread = Thread() # no parent!
obj = Worker() # no parent!
obj.moveToThread(thread)

# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)

# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread.  As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.start()

# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
                                QtCore.Q_ARG(str, "Hello World!"),
                                QtCore.Q_ARG(list, ["args", 0, 1]),
                                QtCore.Q_ARG(list, []))

# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for 
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls.  Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking

app.exec_()

# Without this you may get weird QThread messages in the shell on exit
app.deleteLater()        

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use -b or --bind flag.

python -m http.server 8000 --bind 127.0.0.1

The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

All in all, to save symbols that require 4 bytes you need to update characher-set and collation for utf8mb4:

  1. database table/column: alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci
  2. database server connection (see)

On my development enviromnt for #2 I prefer to set parameters on command line when starting the server: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci


btw, pay attention to Connector/J behavior with SET NAMES 'utf8mb4':

Do not issue the query set names with Connector/J, as the driver will not detect that the character set has changed, and will continue to use the character set detected during the initial connection setup.

And avoid setting characterEncoding parameter in connection url as it will override configured server encoding:

To override the automatically detected encoding on the client side, use the characterEncoding property in the URL used to connect to the server.

Implement an input with a mask

Input masks can be implemented using a combination of the keyup event, and the HTMLInputElement value, selectionStart, and selectionEnd properties. Here's a very simple implementation which does some of what you want. It's certainly not perfect, but works well enough to demonstrate the principle:

_x000D_
_x000D_
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);_x000D_
_x000D_
function applyDataMask(field) {_x000D_
    var mask = field.dataset.mask.split('');_x000D_
    _x000D_
    // For now, this just strips everything that's not a number_x000D_
    function stripMask(maskedData) {_x000D_
        function isDigit(char) {_x000D_
            return /\d/.test(char);_x000D_
        }_x000D_
        return maskedData.split('').filter(isDigit);_x000D_
    }_x000D_
    _x000D_
    // Replace `_` characters with characters from `data`_x000D_
    function applyMask(data) {_x000D_
        return mask.map(function(char) {_x000D_
            if (char != '_') return char;_x000D_
            if (data.length == 0) return char;_x000D_
            return data.shift();_x000D_
        }).join('')_x000D_
    }_x000D_
    _x000D_
    function reapplyMask(data) {_x000D_
        return applyMask(stripMask(data));_x000D_
    }_x000D_
    _x000D_
    function changed() {   _x000D_
        var oldStart = field.selectionStart;_x000D_
        var oldEnd = field.selectionEnd;_x000D_
        _x000D_
        field.value = reapplyMask(field.value);_x000D_
        _x000D_
        field.selectionStart = oldStart;_x000D_
        field.selectionEnd = oldEnd;_x000D_
    }_x000D_
    _x000D_
    field.addEventListener('click', changed)_x000D_
    field.addEventListener('keyup', changed)_x000D_
}
_x000D_
ISO Date: <input type="text" value="____-__-__" data-mask="____-__-__"/><br/>_x000D_
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>
_x000D_
_x000D_
_x000D_

(View in JSFiddle)

There are also a number of libraries out there which perform this function. Some examples include:

Unit testing void methods?

Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.

Select records from today, this week, this month php mysql

Assuming your date column is an actual MySQL date column:

SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;        
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;

How to use function srand() with time.h?

If you chose to srand, it is a good idea to then call rand() at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.

srand(time(NULL));
rand();
//Now use rand()

If available, either random or arc4rand would be better.

What is the purpose of Node.js module.exports and how do you use it?

There are some default or existing modules in node.js when you download and install node.js like http, sys etc.

Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.

Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.

Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo

Huh, so that's the reason, we do like

exports.additionTwo = function(x)
{return x+2;};

Be careful with the path

Lets say you have created an addition.js module,

exports.additionTwo = function(x){
return x + 2;
};

When you run this on your NODE.JS command prompt:

node
var run = require('addition.js');

This will error out saying

Error: Cannot find module addition.js

This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH

set NODE_PATH = path/to/your/additon.js

Now, this should run successfully without any errors!!

One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:

node
var run = require('./addition.js');

Since we are providing the path here by saying it's in the current directory ./ this should also run successfully.

SQL Row_Number() function in Where Clause

I feel like all the answers showing use of a CTE or Sub Query are sufficient fixes for this, but I don't see anyone getting to the heart of why OP has a problem. The reason why what OP suggested doesn't work is due to logical query processing order here:

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE/ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP
  12. OFFSET/FETCH

I believe this contributes to the answer greatly, because it explains why issues like this one occur. WHERE is always processed before SELECT making a CTE or Sub Query necessary for many functions. You will see this a lot in SQL Server.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

I just got the solution to this problem from a friend. he said: Add ob_start(); under your session code. You can add exit(); under the header. I tried it and it worked. Hope this helps

This is for those on a rented Hosting sever who do not have access to php.init file.

gem install: Failed to build gem native extension (can't find header files)

Red Hat, Fedora:

sudo dnf -y install gcc-c++ redhat-rpm-config ruby-devel gcc mysql-devel rubygems

PHP Warning Permission denied (13) on session_start()

You don't appear to have write permission to the /tmp directory on your server. This is a bit weird, but you can work around it. Before the call to session_start() put in a call to session_save_path() and give it the name of a directory writable by the server. Details are here.

FirebaseInstanceIdService is deprecated

For kotlin I use the following

val fcmtoken = FirebaseMessaging.getInstance().token.await()

and for the extension functions

public suspend fun <T> Task<T>.await(): T {
    // fast path
    if (isComplete) {
        val e = exception
        return if (e == null) {
            if (isCanceled) {
                throw CancellationException("Task $this was cancelled normally.")
            } else {
                @Suppress("UNCHECKED_CAST")
                result as T
            }
        } else {
            throw e
        }
    }

    return suspendCancellableCoroutine { cont ->
        addOnCompleteListener {
            val e = exception
            if (e == null) {
                @Suppress("UNCHECKED_CAST")
                if (isCanceled) cont.cancel() else cont.resume(result as T)
            } else {
                cont.resumeWithException(e)
            }
        }
    }
}

What is the difference between \r and \n?

\r is Carriage Return; \n is New Line (Line Feed) ... depends on the OS as to what each means. Read this article for more on the difference between '\n' and '\r\n' ... in C.

Parse an HTML string with JS

It's quite simple:

var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/html');
// do whatever you want with htmlDoc.getElementsByTagName('a');

According to MDN, to do this in chrome you need to parse as XML like so:

var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/xml');
// do whatever you want with htmlDoc.getElementsByTagName('a');

It is currently unsupported by webkit and you'd have to follow Florian's answer, and it is unknown to work in most cases on mobile browsers.

Edit: Now widely supported

What does '?' do in C++?

This is a ternary operator, it's basically an inline if statement

x ? y : z

works like

if(x) y else z

except, instead of statements you have expressions; so you can use it in the middle of a more complex statement.

It's useful for writing succinct code, but can be overused to create hard to maintain code.

Get Selected value of a Combobox

You can use the below change event to which will trigger when the combobox value will change.

Private Sub ComboBox1_Change()
'your code here
End Sub

Also you can get the selected value using below

ComboBox1.Value

Difference between DOMContentLoaded and load events

See the difference yourself:

DEMO

From Microsoft IE

The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images. DOMContentLoaded is a great event to use to hookup UI functionality to complex web pages.

From Mozilla Developer Network

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

Adding an onclick event to a div element

Depends in how you are hiding your div, diplay=none is different of visibility=hidden and the opacity=0

  • Visibility then use ...style.visibility='visible'

  • Display then use ...style.display='block' (or others depends how
    you setup ur css, inline, inline-block, flex...)

  • Opacity then use ...style.opacity='1';

Send file using POST from a Python script

You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.

How to return a html page from a restful controller in spring boot?

The answer from Kukkuz did not work for me until I added in this dependency into the pom file:

<!-- Spring boot Thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

From the guide here.

As well as updating the registry resources as outlined here.

It then started working just fine. If anyone in the future runs into the same issue and following the first answer does not solve your problem, follow these 2 other steps after utilizing the code in @Kukkuz's answer and see if that makes a difference.

How to increase number of threads in tomcat thread pool?

You would have to tune it according to your environment.

Sometimes it's more useful to increase the size of the backlog (acceptCount) instead of the maximum number of threads.

Say, instead of

<Connector ... maxThreads="500" acceptCount="50"

you use

<Connector ... maxThreads="300" acceptCount="150"

you can get much better performance in some cases, cause there would be less threads disputing the resources and the backlog queue would be consumed faster.

In any case, though, you have to do some benchmarks to really know what is best.

Current date and time - Default in MVC razor

If you want to display date time on view without model, just write this:

Date : @DateTime.Now

The output will be:

Date : 16-Aug-17 2:32:10 PM

what is the use of "response.setContentType("text/html")" in servlet

response.setContentType("text/html");

Above code would be include in "HTTP response" to inform the browser about the format of the response, so that the browser can interpret it.

How to view data saved in android database(SQLite)?

I recommend the firefox plugin(SQLLite Manager) if you always use firefox.

Here is the link

How to check a string starts with numeric number?

This should work:

String s = "123foo";
Character.isDigit(s.charAt(0));

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

How to add display:inline-block in a jQuery show() function?

The best .let it's parent display :inline-block or add a parent div what CSS only have display :inline-block.

Array functions in jQuery

There's a plugin for jQuery called 'rich array' discussed in Rich Array jQuery plugin .

Pass props in Link react-router

After install react-router-dom

<Link
    to={{
      pathname: "/product-detail",
      productdetailProps: {
       productdetail: "I M passed From Props"
      }
   }}>
    Click To Pass Props
</Link>

and other end where the route is redirected do this

componentDidMount() {
            console.log("product props is", this.props.location.productdetailProps);
          }

How to uninstall a windows service and delete its files without rebooting

If in .net ( I'm not sure if it works for all windows services)

  • Stop the service (THis may be why you're having a problem.)
  • InstallUtil -u [name of executable]
  • Installutil -i [name of executable]
  • Start the service again...

Unless I'm changing the service's public interface, I often deploy upgraded versions of my services without even unistalling/reinstalling... ALl I do is stop the service, replace the files and restart the service again...

Split text file into smaller multiple text file using command line

Syntax looks like:

$ split [OPTION] [INPUT [PREFIX]] 

where prefix is PREFIXaa, PREFIXab, ...

Just use proper one and youre done or just use mv for renameing. I think $ mv * *.txt should work but test it first on smaller scale.

:)

Properly close mongoose's connection once you're done

Just as Jake Wilson said: You can set the connection to a variable then disconnect it when you are done:

let db;
mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
    db = dbConnection;
    afterwards();
});


function afterwards(){

    //do stuff

    db.disconnect();
}

or if inside Async function:

(async ()=>{
    const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: 
                  true })

    //do stuff

    db.disconnect()
})

otherwise when i was checking it in my environment it has an error.

How do you auto format code in Visual Studio?

I used to use these combinations. I automated this process on Save of a document. You can try mine extension Format Document on Save

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

Bootstrap 4 - Responsive cards in card-columns

If you are using Sass:

$card-column-sizes: (
    xs: 2,
    sm: 3,
    md: 4,
    lg: 5,
);

@each $breakpoint-size, $column-count in $card-column-sizes {
    @include media-breakpoint-up($breakpoint-size) {
      .card-columns {
        column-count: $column-count;
        column-gap: 1.25rem;

        .card {
          display: inline-block;
          width: 100%; // Don't let them exceed the column width
        }
      }
    }
}

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

Xcode Product -> Archive disabled

Change the active scheme Device from Simulator to Generic iOS Device

What is the best way to initialize a JavaScript Date to midnight?

Just going to add this here because I landed on this page looking for how to do this in moment.js and others may do too.

[Rationale: the word "moment" already appears elsewhere on this page so search engines direct here, and moment.js is widespread enough to warrant to being covered going on how often it is mentioned in other date-related SO questions]

So, in version 2.0.0 and above:

date.startOf('day');

For earlier versions:

date.sod();

Docs:

http://momentjs.com/docs/#/manipulating/start-of/

Count the cells with same color in google spreadsheet

You can use this working script:

/**
* @param {range} countRange Range to be evaluated
* @param {range} colorRef Cell with background color to be searched for in countRange
* @return {number}
* @customfunction
*/

function countColoredCells(countRange,colorRef) {
  var activeRange = SpreadsheetApp.getActiveRange();
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();

  var rangeA1Notation = formula.match(/\((.*)\,/).pop();
  var range = activeSheet.getRange(rangeA1Notation);
  var bg = range.getBackgrounds();
  var values = range.getValues();

  var colorCellA1Notation = formula.match(/\,(.*)\)/).pop();
  var colorCell = activeSheet.getRange(colorCellA1Notation);
  var color = colorCell.getBackground();

  var count = 0;

  for(var i=0;i<bg.length;i++)
    for(var j=0;j<bg[0].length;j++)
      if( bg[i][j] == color )
        count=count+1;
  return count;
};

Then call this function in your google sheets:

=countColoredCells(D5:D123,Z11)

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

max(length(field)) in mysql

Use:

  SELECT mt.name 
    FROM MY_TABLE mt
GROUP BY mt.name
  HAVING MAX(LENGTH(mt.name)) = 18

...assuming you know the length beforehand. If you don't, use:

  SELECT mt.name 
    FROM MY_TABLE mt
    JOIN (SELECT MAX(LENGTH(x.name) AS max_length
            FROM MY_TABLE x) y ON y.max_length = LENGTH(mt.name)

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd/mm/yy format.

select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

How to write specific CSS for mozilla, chrome and IE

You could use php to echo the browser name as a body class, e.g.

<body class="mozilla">

Then, your conditional CSS would look like

.ie #container { top: 5px;}
.mozilla #container { top: 5px;}
.chrome #container { top: 5px;}

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

Make sure that Spring version and xsd version both are same.In my case I am using Spring 4.1.1 so my all xsd should be version *-4.1.xsd

How to increase the max upload file size in ASP.NET?

If it works in your local machine and does not work after deployment in IIS (i used Windows Server 2008 R2) i have a solution.

Open IIS (inetmgr) Go to your website At right hand side go to Content (Request Filtering) Go to Edit Feature Settings Change maximum content size as (Bytes you required) This will work. You can also take help from following thread http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.

The difference between firstOrCreate() and firstOrNew():

  • firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
  • firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.

Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name or some mandatory field), you should use firstOrNew(). If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().

What can I use for good quality code coverage for C#/.NET?

An alternative to NCover can be PartCover, is an open source code coverage tool for .NET very similar to NCover, it includes a console application, a GUI coverage browser, and XSL transforms for use in CruiseControl.NET.

It is a very interesting product.

OpenCover has replaced PartCover.

belongs_to through associations

My approach was to make a virtual attribute instead of adding database columns.

class Choice
  belongs_to :user
  belongs_to :answer

  # ------- Helpers -------
  def question
    answer.question
  end

  # extra sugar
  def question_id
    answer.question_id
  end
end

This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer from the db, and then question. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.

There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.

How can I pretty-print JSON in a shell script?

You can simply use standard tools like jq or json_pp.

echo '{ "foo": "lorem", "bar": "ipsum" }' | json_pp

or

echo '{ "foo": "lorem", "bar": "ipsum" }' | jq

will both prettify output like the following (jq even more colorful):

{
  "foo": "lorem",
  "bar": "ipsum"
}

The huge advantage of jq is that it can do A LOT more if you'd like to parse and process the json.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

If you want to target IE 10 with Vanilla JavaScript, you might want to try CSS property detection:

if (document.body.style.msTouchAction != undefined) {
  document.body.className = 'ie10';
}

CSS properties

Instead of msTouchAction you can also use one of these CSS properties, because they are currently only available in IE 10. But this might change in the future.

  • msTouchAction
  • msWrapFlow
  • msWrapMargin
  • msWrapThrough
  • msScrollLimit
  • msScrollLimitXMin
  • msScrollLimitYMin
  • msScrollLimitXMax
  • msScrollLimitYMax
  • msFlexbox
  • msFlex
  • msFlexOrder

Test page

I've put together a test page with all properties on CodePen.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

My solution (VB.Net, the "staging" (UAT) version of this application needs to work with the "staging" certificate but not affect requests once they are on the live site):

    ...
        Dim url As String = ConfigurationManager.AppSettings("APIURL") & "token"
        If url.ToLower().Contains("staging") Then
           System.Net.ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
        End If
    ...

    Private  Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
        Return True
    End Function

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

Adding to a vector of pair

Use std::make_pair:

revenue.push_back(std::make_pair("string",map[i].second));

Sort & uniq in Linux shell

There is one slight difference: return code.

The thing is that unless shopt -o pipefail is set the return code of the piped command will be return code of the last one. And uniq always returns zero (success). Try examining exit code, and you'll see something like this (pipefail is not set here):

pavel@lonely ~ $ sort -u file_that_doesnt_exist ; echo $?
sort: open failed: file_that_doesnt_exist: No such file or directory
2
pavel@lonely ~ $ sort file_that_doesnt_exist | uniq ; echo $?
sort: open failed: file_that_doesnt_exist: No such file or directory
0

Other than this, the commands are equivalent.

Mailto on submit button

Or you can create a form with action:mailto

<form action="mailto:[email protected]"> 

check this out.

http://webdesign.about.com/od/forms/a/aa072699mailto.htm

But this actually submits a form via email.Is this what you wanted? You can also use just

<button onclick=""> and then some javascript with it to ahieve this.

And you can make a <a> look like button. There can be a lot of ways to work this around. Do a little search.

Best method to download image from url in Android

Add This Dependency For Android Networking Into Your Project

compile 'com.amitshekhar.android:android-networking:1.0.0'

    String url = "http://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/11136/production/_95324996_defoe_rex.jpg";
    File file;
    String dirPath, fileName;
    Button downldImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialization Of DownLoad Button
        downldImg = (Button) findViewById(R.id.DownloadButton);

        // Initialization Of DownLoad Button
        AndroidNetworking.initialize(getApplicationContext());

        //Folder Creating Into Phone Storage
        dirPath = Environment.getExternalStorageDirectory() + "/Image";

        fileName = "image.jpeg";

        //file Creating With Folder & Fle Name
        file = new File(dirPath, fileName);

        //Click Listener For DownLoad Button
        downldImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AndroidNetworking.download(url, dirPath, fileName)
                        .build()
                        .startDownload(new DownloadListener() {
                            @Override
                            public void onDownloadComplete() {

                                Toast.makeText(MainActivity.this, "DownLoad Complete", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(ANError anError) {

                            }
                        });
            }
        });
    }
}

After Run This Code Check Your Phone Memory You Can See There A Folder - Image Check Inside This Folder , You see There a Image File with name of "image.jpeg"

Thank You !!!

JavaScript closure inside loops – simple practical example

The main issue with the code shown by the OP is that i is never read until the second loop. To demonstrate, imagine seeing an error inside of the code

funcs[i] = function() {            // and store them in funcs
    throw new Error("test");
    console.log("My value: " + i); // each should log its value.
};

The error actually does not occur until funcs[someIndex] is executed (). Using this same logic, it should be apparent that the value of i is also not collected until this point either. Once the original loop finishes, i++ brings i to the value of 3 which results in the condition i < 3 failing and the loop ending. At this point, i is 3 and so when funcs[someIndex]() is used, and i is evaluated, it is 3 - every time.

To get past this, you must evaluate i as it is encountered. Note that this has already happened in the form of funcs[i] (where there are 3 unique indexes). There are several ways to capture this value. One is to pass it in as a parameter to a function which is shown in several ways already here.

Another option is to construct a function object which will be able to close over the variable. That can be accomplished thusly

jsFiddle Demo

funcs[i] = new function() {   
    var closedVariable = i;
    return function(){
        console.log("My value: " + closedVariable); 
    };
};

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Use IGNORE_DUP_KEY = OFF during primary key definition to ignore the duplicates while insert. for example

create table X( col1.....)

CONSTRAINT [pk_X] PRIMARY KEY CLUSTERED 
(
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 70) ON [PRIMARY]
) ON [PRIMARY]

Java Strings: "String s = new String("silly");"

In your first example, you are creating a String, "silly" and then passing it as a parameter to another String's copy constructor, which makes a second String which is identical to the first. Since Java Strings are immutable (something that frequently stings people who are used to C strings), this is a needless waste of resources. You should instead use the second example because it skips several needless steps.

However, the String literal is not a CaseInsensitiveString so there you cannot do what you want in your last example. Furthermore, there is no way to overload a casting operator like you can in C++ so there is literally no way to do what you want. You must instead pass it in as a parameter to your class's constructor. Of course, I'd probably just use String.toLowerCase() and be done with it.

Also, your CaseInsensitiveString should implement the CharSequence interface as well as probably the Serializable and Comparable interfaces. Of course, if you implement Comparable, you should override equals() and hashCode() as well.

Finding whether a point lies inside a rectangle or not

How is the rectangle represented? Three points? Four points? Point, sides and angle? Two points and a side? Something else? Without knowing that, any attempts to answer your question will have only purely academic value.

In any case, for any convex polygon (including rectangle) the test is very simple: check each edge of the polygon, assuming each edge is oriented in counterclockwise direction, and test whether the point lies to the left of the edge (in the left-hand half-plane). If all edges pass the test - the point is inside. If at least one fails - the point is outside.

In order to test whether the point (xp, yp) lies on the left-hand side of the edge (x1, y1) - (x2, y2), you just need to calculate

D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)

If D > 0, the point is on the left-hand side. If D < 0, the point is on the right-hand side. If D = 0, the point is on the line.


The previous version of this answer described a seemingly different version of left-hand side test (see below). But it can be easily shown that it calculates the same value.

... In order to test whether the point (xp, yp) lies on the left-hand side of the edge (x1, y1) - (x2, y2), you need to build the line equation for the line containing the edge. The equation is as follows

A * x + B * y + C = 0

where

A = -(y2 - y1)
B = x2 - x1
C = -(A * x1 + B * y1)

Now all you need to do is to calculate

D = A * xp + B * yp + C

If D > 0, the point is on the left-hand side. If D < 0, the point is on the right-hand side. If D = 0, the point is on the line.

However, this test, again, works for any convex polygon, meaning that it might be too generic for a rectangle. A rectangle might allow a simpler test... For example, in a rectangle (or in any other parallelogram) the values of A and B have the same magnitude but different signs for opposing (i.e. parallel) edges, which can be exploited to simplify the test.

Java: Enum parameter in method

I am not too sure I would go and use an enum as a full fledged class - this is an object oriented language, and one of the most basic tenets of object orientation is that a class should do one thing and do it well.

An enum is doing a pretty good job at being an enum, and a class is doing a good job as a class. Mixing the two I have a feeling will get you into trouble - for example, you can't pass an instance of an enum as a parameter to a method, primarily because you can't create an instance of an enum.

So, even though you might be able to enum.process() does not mean that you should.

What does "@" mean in Windows batch scripts

By default, a batch file will display its command as it runs. The purpose of this first command which @echo off is to turn off this display. The command "echo off" turns off the display for the whole script, except for the "echo off" command itself. The "at" sign "@" in front makes the command apply to itself as well.

Does Python have an argc argument?

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

Why do I have to "git push --set-upstream origin <branch>"?

TL;DR: git branch --set-upstream-to origin/solaris


The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.

If you do not have upstream for the current branch, however, Git changes its behavior on git push, and on other commands as well.

The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default which now defaults to simple. For several versions of Git before and after 2.0, every time you ran git push, Git would spew lots of noise trying to convince you to set push.default just to get git push to shut up.

You do not mention which version of Git you are running, nor whether you have configured push.default, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default to simple to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.

What is an upstream?

An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.

Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.

The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B or local like master). That is, if the current branch B has upstream U, git rev-parse U should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv, will show the upstream setting but mark it as "gone".

What good is an upstream?

If your push.default is set to simple or upstream, the upstream setting will make git push, used with no additional arguments, just work.

That's it—that's all it does for git push. But that's fairly significant, since git push is one of the places where a simple typo causes major headaches.

If your push.default is set to nothing, matching, or current, setting an upstream does nothing at all for git push.

(All of this assumes your Git version is at least 2.0.)

The upstream affects git fetch

If you run git fetch with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin.)

The upstream affects git merge and git rebase too

If you run git merge or git rebase with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.

The upstream affects git pull

You should never2 use git pull anyway, but if you do, git pull uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull does the same thing as git fetch—because it actually runs git fetch—and then does the same thing as git merge or git rebase, because it actually runs git merge or git rebase.

(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)

The upstream affects git status

This may actually be the most important. Once you have an upstream set, git status can report the difference between your current branch and its upstream, in terms of commits.

If, as is the normal case, you are on branch B with its upstream set to origin/B, and you run git status, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.

This is because git status runs:

  • git rev-list --count @{u}..HEAD: how many commits do you have on B that are not on origin/B?
  • git rev-list --count HEAD..@{u}: how many commits do you have on origin/B that are not on B?

Setting an upstream gives you all of these things.

How come master already has an upstream set?

When you first clone from some remote, using:

$ git clone git://some.host/path/to/repo.git

or similar, the last step Git does is, essentially, git checkout master. This checks out your local branch master—only you don't have a local branch master.

On the other hand, you do have a remote-tracking branch named origin/master, because you just cloned it.

Git guesses that you must have meant: "make me a new local master that points to the same commit as remote-tracking origin/master, and, while you're at it, set the upstream for master to origin/master."

This happens for every branch you git checkout that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.

But this doesn't work for new branches, i.e., branches with no remote-tracking branch yet.

If you create a new branch:

$ git checkout -b solaris

there is, as yet, no origin/solaris. Your local solaris cannot track remote-tracking branch origin/solaris because it does not exist.

When you first push the new branch:

$ git push origin solaris

that creates solaris on origin, and hence also creates origin/solaris in your own Git repository. But it's too late: you already have a local solaris that has no upstream.3

Shouldn't Git just set that, now, as the upstream automatically?

Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.

The fact is, it doesn't today, unless you use --set-upstream or -u during the git push. That's what the message is telling you.

You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris on origin, through an earlier push, and as your git branch output shows, you already have origin/solaris in your local repository.

You just don't have it set as the upstream for solaris.

To set it now, rather than during the first push, use git branch --set-upstream-to. The --set-upstream-to sub-command takes the name of any existing branch, such as origin/solaris, and sets the current branch's upstream to that other branch.

That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch, then look around, then run git merge or git rebase as appropriate, then make new commits and run git push, without a bunch of additional fussing-around.


1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".

2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch actually did, and they can then see what git merge or git rebase will do next.

3If you run your first git push as git push -u origin solaris—i.e., if you add the -u flag—Git will set origin/solaris as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to is easier, if you forgot.

4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.

Setting Margin Properties in code

One could simply use this

MyControl.Margin = new System.Windows.Thickness(10, 0, 5, 0);

How do I add a new class to an element dynamically?

CSS really doesn't have the ability to modify an object in the same manner as JavaScript, so in short - no.

How to open an external file from HTML

If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.

You can use something like this "ASP.Net Serve File For Download" example (archived copy of 2).

Get the size of the screen, current web page and browser window

function wndsize(){
  var w = 0;var h = 0;
  //IE
  if(!window.innerWidth){
    if(!(document.documentElement.clientWidth == 0)){
      //strict mode
      w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
    } else{
      //quirks mode
      w = document.body.clientWidth;h = document.body.clientHeight;
    }
  } else {
    //w3c
    w = window.innerWidth;h = window.innerHeight;
  }
  return {width:w,height:h};
}
function wndcent(){
  var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
  var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
  //IE
  if(!window.pageYOffset){
    //strict mode
    if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
    //quirks mode
    else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
    //w3c
    else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
    return{x:_x,y:_y};
}
var center = wndcent({width:350,height:350});
document.write(center.x+';<br>');
document.write(center.y+';<br>');
document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--? ?????????, ? ??? ?? ?????????? flash ?????.--></div>');

How do I read the source code of shell commands?

Direct links to source for some popular programs in coreutils:

Full list here.

GetFiles with multiple extensions

You can't do that, because GetFiles only accepts a single search pattern. Instead, you can call GetFiles with no pattern, and filter the results in code:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.GetFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

If you're working with .NET 4, you can use the EnumerateFiles method to avoid loading all FileInfo objects in memory at once:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.EnumerateFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

how to delete default values in text field using selenium?

And was the code helpful? Because the code you are writing should do the thing:

driver.findElement("locator").clear();

If it does not help, then try this:

WebElement toClear = driver.findElement("locator");
toClear.sendKeys(Keys.CONTROL + "a");
toClear.sendKeys(Keys.DELETE);

maybe you will have to do some convert of the Keys.CONTROL + "a" to CharSequence, but the first approach should do the magic

Failed to load ApplicationContext for JUnit test of Spring controller

Solved by adding the following dependency into pom.xml file :

<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
</dependency>

How can I loop through a C++ map of maps?

Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:

std::map<std::string, std::map<std::string, std::string>> mymap;

for(auto const &ent1 : mymap) {
  // ent1.first is the first key
  for(auto const &ent2 : ent1.second) {
    // ent2.first is the second key
    // ent2.second is the data
  }
}

this should be much cleaner than the earlier versions, and avoids unnecessary copies.

Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):

for(auto const &ent1 : mymap) {
  auto const &outer_key = ent1.first;
  auto const &inner_map = ent1.second;
  for(auto const &ent2 : inner_map) {
    auto const &inner_key   = ent2.first;
    auto const &inner_value = ent2.second;
  }
}

How can I be notified when an element is added to the page?

ETA 24 Apr 17 I wanted to simplify this a bit with some async/await magic, as it makes it a lot more succinct:

Using the same promisified-observable:

const startObservable = (domNode) => {
  var targetNode = domNode;

  var observerConfig = {
    attributes: true,
    childList: true,
    characterData: true
  };

  return new Promise((resolve) => {
      var observer = new MutationObserver(function (mutations) {
         // For the sake of...observation...let's output the mutation to console to see how this all works
         mutations.forEach(function (mutation) {
             console.log(mutation.type);
         });
         resolve(mutations)
     });
     observer.observe(targetNode, observerConfig);
   })
} 

Your calling function can be as simple as:

const waitForMutation = async () => {
    const button = document.querySelector('.some-button')
    if (button !== null) button.click()
    try {
      const results = await startObservable(someDomNode)
      return results
    } catch (err) { 
      console.error(err)
    }
}

If you wanted to add a timeout, you could use a simple Promise.race pattern as demonstrated here:

const waitForMutation = async (timeout = 5000 /*in ms*/) => {
    const button = document.querySelector('.some-button')
    if (button !== null) button.click()
    try {

      const results = await Promise.race([
          startObservable(someDomNode),
          // this will throw after the timeout, skipping 
          // the return & going to the catch block
          new Promise((resolve, reject) => setTimeout(
             reject, 
             timeout, 
             new Error('timed out waiting for mutation')
          )
       ])
      return results
    } catch (err) { 
      console.error(err)
    }
}

Original

You can do this without libraries, but you'd have to use some ES6 stuff, so be cognizant of compatibility issues (i.e., if your audience is mostly Amish, luddite or, worse, IE8 users)

First, we'll use the MutationObserver API to construct an observer object. We'll wrap this object in a promise, and resolve() when the callback is fired (h/t davidwalshblog)david walsh blog article on mutations:

const startObservable = (domNode) => {
    var targetNode = domNode;

    var observerConfig = {
        attributes: true,
        childList: true,
        characterData: true
    };

    return new Promise((resolve) => {
        var observer = new MutationObserver(function (mutations) {
            // For the sake of...observation...let's output the mutation to console to see how this all works
            mutations.forEach(function (mutation) {
                console.log(mutation.type);
            });
            resolve(mutations)
        });
        observer.observe(targetNode, observerConfig);
    })
} 

Then, we'll create a generator function. If you haven't used these yet, then you're missing out--but a brief synopsis is: it runs like a sync function, and when it finds a yield <Promise> expression, it waits in a non-blocking fashion for the promise to be fulfilled (Generators do more than this, but this is what we're interested in here).

// we'll declare our DOM node here, too
let targ = document.querySelector('#domNodeToWatch')

function* getMutation() {
    console.log("Starting")
    var mutations = yield startObservable(targ)
    console.log("done")
}

A tricky part about generators is they don't 'return' like a normal function. So, we'll use a helper function to be able to use the generator like a regular function. (again, h/t to dwb)

function runGenerator(g) {
    var it = g(), ret;

    // asynchronously iterate over generator
    (function iterate(val){
        ret = it.next( val );

        if (!ret.done) {
            // poor man's "is it a promise?" test
            if ("then" in ret.value) {
                // wait on the promise
                ret.value.then( iterate );
            }
            // immediate value: just send right back in
            else {
                // avoid synchronous recursion
                setTimeout( function(){
                    iterate( ret.value );
                }, 0 );
            }
        }
    })();
}

Then, at any point before the expected DOM mutation might happen, simply run runGenerator(getMutation).

Now you can integrate DOM mutations into a synchronous-style control flow. How bout that.

HTML Code for text checkbox '?'

Just make sure that your HTML file is encoded with UTF-8 and that your web server sends a HTTP header with that charset, then you just can write that character directly into your HTMl file.

http://www.w3.org/International/O-HTTP-charset

If you can't use UTF-8 for some reason, you can look up the codes in a unicode list such as http://en.wikipedia.org/wiki/List_of_Unicode_characters and use &#xABCD; where ABCD is the hexcode from that list (U+ABCD).

How to commit and rollback transaction in sql server?

Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

Creating a PDF from a RDLC Report in the Background

You can instanciate LocalReport

                FicheInscriptionBean fiche = new FicheInscriptionBean();
                fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
                list.Add(fiche);
                ReportDataSource rds = new ReportDataSource();
                rds = new ReportDataSource("InscriptionDataSet", list);
                // attachement du QrCode.
                string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
                Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
                MemoryStream ms = new MemoryStream();
                BitmapCaptcha.Save(ms, ImageFormat.Gif);
                var base64Data = Convert.ToBase64String(ms.ToArray());
                string QR_IMG = base64Data;
                ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);

                LocalReport report = new LocalReport();
                report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
                report.DataSources.Clear();
                report.SetParameters(new ReportParameter[] { parameter });
                report.DataSources.Add(rds);
                report.Refresh();

                string FileName = "FichePreinscription_" + numinscription + ".pdf";
                string extension;
                string encoding;
                string mimeType;
                string[] streams;
                Warning[] warnings;
                Byte[] mybytes = report.Render("PDF", null,
                              out extension, out encoding,
                              out mimeType, out streams, out warnings);
                using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
                {
                    fs.Write(mybytes, 0, mybytes.Length);
                }
                Response.ClearHeaders();
                Response.ClearContent();
                Response.Buffer = true;
                Response.Clear();
                Response.Charset = "";
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
                Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));

                Response.Flush();
                File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
                Response.Close();
                Response.End();

Creating a div element in jQuery

Create an in-memory DIV

$("<div/>");

Add click handlers, styles etc - and finally insert into DOM into a target element selector:

_x000D_
_x000D_
$("<div/>", {_x000D_
_x000D_
  // PROPERTIES HERE_x000D_
  _x000D_
  text: "Click me",_x000D_
  id: "example",_x000D_
  "class": "myDiv",      // ('class' is still better in quotes)_x000D_
  css: {           _x000D_
    color: "red",_x000D_
    fontSize: "3em",_x000D_
    cursor: "pointer"_x000D_
  },_x000D_
  on: {_x000D_
    mouseenter: function() {_x000D_
      console.log("PLEASE... "+ $(this).text());_x000D_
    },_x000D_
    click: function() {_x000D_
      console.log("Hy! My ID is: "+ this.id);_x000D_
    }_x000D_
  },_x000D_
  append: "<i>!!</i>",_x000D_
  appendTo: "body"      // Finally, append to any selector_x000D_
  _x000D_
}); // << no need to do anything here as we defined the properties internally.
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Similar to ian's answer, but I found no example that properly addresses the use of methods within the properties object declaration so there you go.

Expand and collapse with angular js

See http://angular-ui.github.io/bootstrap/#/collapse

function CollapseDemoCtrl($scope) {
  $scope.isCollapsed = false;
}



<div ng-controller="CollapseDemoCtrl">
    <button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
    <hr>
    <div collapse="isCollapsed">
        <div class="well well-large">Some content</div> 
    </div>
</div>

Display help message with python argparse when script is called without any arguments

This isn't good (also, because intercepts all errors), but:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)

    parser.add_argument(...)
    ...

Here is definition of the error function of the ArgumentParser class:

https://github.com/python/cpython/blob/276eb67c29d05a93fbc22eea5470282e73700d20/Lib/argparse.py#L2374

. As you see, following signature, it takes two arguments. However, functions outside the class nothing knows about first argument: self, because, roughly speaking, this is parameter for the class. (I know, that you know...) Thereby, just pass own self and message in _error(...) can't (

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error
    ...
...

will output:

...
"AttributeError: 'str' object has no attribute 'print_help'"

). You can pass parser (self) in _error function, by calling it:

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)
    ...
...

, but you don't want exit the program, right now. Then return it:

def _error(parser):
    def wrapper():
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Nonetheless, parser doesn't know, that it has been modified, thus when an error occurs, it will send cause of it (by the way, its localized translation). Well, then intercept it:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Now, when error occurs and parser will send cause of it, you'll intercept it, look at this, and... throw out.

Video streaming over websockets using JavaScript

To answer the question:

What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes, Websocket can be used to transmit over 30 fps and even 60 fps.

The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.

There was no endpoint listening at (url) that could accept the message

I tried a bunch of these ideas to get HTTPS working, but the key for me was adding the protocol mapping. Here's what my server config file looks like, this works for both HTTP and HTTPS client connections:

  <system.serviceModel>
    <protocolMapping>
      <add scheme="https" binding="wsHttpBinding" bindingConfiguration="TransportSecurityBinding" />
    </protocolMapping>
    <services>
      <service name="FeatureService" behaviorConfiguration="HttpsBehavior">
        <endpoint address="soap" binding="wsHttpBinding" contract="MyServices.IFeature" bindingConfiguration="TransportSecurityBinding" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="HttpsBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="TransportSecurityBinding" maxReceivedMessageSize="2147483647">
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

jQuery animated number counter from zero to value

Here is my solution and it's also working, when element shows into the viewport


You can see the code in action by clicking jfiddle

var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
    var firEvent = false,
        objectPosTop = $('.go-counterTeaser').offset().top;

        //when element shows at bottom
        var elementViewInBottom = objectPosTop - winHeight;
    $(window).on('scroll', function() {
        var currentPosition = $(document).scrollTop();
        //when element position starting in viewport
      if (currentPosition > elementViewInBottom && firEvent === false) {
        firEvent = true;
        animationCounter();
      }   
    });
}

//counter function will animate by using external js also add seprator "."
 function animationCounter(){
        $('.numberBlock h2').each(function () {
            var comma_separator_number_step =           $.animateNumber.numberStepFactories.separator('.');
            var counterValv = $(this).text();
            $(this).animateNumber(
                {
                  number: counterValv,
                  numberStep: comma_separator_number_step
                }
            );
        });
    }


https://jsfiddle.net/uosahmed/frLoxm34/9/

Child inside parent with min-height: 100% not inheriting height

after trying for ours! chrome understands that I want the child element to be 100% height when I set the display value to inline block. btw setting float will causing it.

display:inline-block

update

this is not working. the solution is to get the parentnode offsetheight and use it at the and of the page with javascript.

<script>
    SomedivElement = document.getElementById('mydiv');
    SomedivElement.style.height = String(nvleft.parentNode.offsetHeight) + 'px';    
</script>

Customize the Authorization HTTP header

You can create your own custom auth schemas that use the Authorization: header - for example, this is how OAuth works.

As a general rule, if servers or proxies don't understand the values of standard headers, they will leave them alone and ignore them. It is creating your own header keys that can often produce unexpected results - many proxies will strip headers with names they don't recognise.

Having said that, it is possibly a better idea to use cookies to transmit the token, rather than the Authorization: header, for the simple reason that cookies were explicitly designed to carry custom values, whereas the specification for HTTP's built in auth methods does not really say either way - if you want to see exactly what it does say, have a look here.

The other point about this is that many HTTP client libraries have built-in support for Digest and Basic auth but may make life more difficult when trying to set a raw value in the header field, whereas they will all provide easy support for cookies and will allow more or less any value within them.

eclipse won't start - no java virtual machine was found

On Centos 7 I fixed this problem (after a big yum upgrade) by changing my setting for vm in:

~/eclipse/java-oxygen/eclipse/eclipse.ini

to:

-vm
/etc/alternatives/jre/bin

(which will always point to the latest installed java)

How to autosize and right-align GridViewColumn data in WPF?

I have created the following class and used across the application wherever required in place of GridView:

/// <summary>
/// Represents a view mode that displays data items in columns for a System.Windows.Controls.ListView control with auto sized columns based on the column content     
/// </summary>
public class AutoSizedGridView : GridView
{        
    protected override void PrepareItem(ListViewItem item)
    {
        foreach (GridViewColumn column in Columns)
        {
            // Setting NaN for the column width automatically determines the required
            // width enough to hold the content completely.

            // If the width is NaN, first set it to ActualWidth temporarily.
            if (double.IsNaN(column.Width))
              column.Width = column.ActualWidth;

            // Finally, set the column with to NaN. This raises the property change
            // event and re computes the width.
            column.Width = double.NaN;              
        }            
        base.PrepareItem(item);
    }
}

How can I compile a Java program in Eclipse without running it?

Right click on the file on package Explorer Then go to Show in Under it go to terminal Eclipse will have a terminal then Use javac fileName to compile

How do I create my own URL protocol? (e.g. so://...)

For most Microsoft products (Internet Explorer, Office, "open file" dialogs etc) you can register an application to be run when URI with appropriate prefix is opened. This is a part of more common explanation - how to implement your own protocol.

For Mozilla the explanation is here, Java - here.

XAMPP - Error: MySQL shutdown unexpectedly

You must:

  • Close the xampp
  • Go to the folder where you installed it, if in (c:) may be something like C:\xampp\ , access folder C:\xampp\mysql\data
  • Delete the file ibdata1
  • Starts XAMPP again.

React.js: Identifying different inputs with one onChange handler

You can use the .bind method to pre-build the parameters to the handleChange method. It would be something like:

  var Hello = React.createClass({
    getInitialState: function() {
        return {input1:0, 
                input2:0};
    },
    render: function() {
      var total = this.state.input1 + this.state.input2;
      return (
        <div>{total}<br/>
          <input type="text" value={this.state.input1} 
                             onChange={this.handleChange.bind(this, 'input1')} />
          <input type="text" value={this.state.input2} 
                             onChange={this.handleChange.bind(this, 'input2')} />
        </div>
      );
    },
    handleChange: function (name, e) {
      var change = {};
      change[name] = e.target.value;
      this.setState(change);
    }
  });

  React.renderComponent(<Hello />, document.getElementById('content'));

(I also made total be computed at render time, as it is the recommended thing to do.)

Setting focus to a textbox control

To set focus,

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox1.Focus()
End Sub

Set the TabIndex by

Me.TextBox1.TabIndex = 0

DateTimePicker time picker in 24 hour but displaying in 12hr?

With seconds!

$('.Timestamp').datetimepicker({
    format: 'DD/MM/YYYY HH:mm:ss'
});

To skip future dates:

$(function () {
    var date = new Date();
    var currentMonth = date.getMonth();
    var currentDate = date.getDate();
    var currentYear = date.getFullYear();
    $('#datetimepicker,#datetimepicker1').datetimepicker({
        pickTime: false,
        format: "DD-MM-YYYY",  
        maxDate: new Date(currentYear, currentMonth, currentDate + 1)
    });
});

Which is the fastest algorithm to find prime numbers?

#include<stdio.h>
main()
{
    long long unsigned x,y,b,z,e,r,c;
    scanf("%llu",&x);
    if(x<2)return 0;
    scanf("%llu",&y);
    if(y<x)return 0;
    if(x==2)printf("|2");
    if(x%2==0)x+=1;
    if(y%2==0)y-=1;
    for(b=x;b<=y;b+=2)
    {
        z=b;e=0;
        for(c=2;c*c<=z;c++)
        {
            if(z%c==0)e++;
            if(e>0)z=3;
        }
        if(e==0)
        {
            printf("|%llu",z);
            r+=1;
        }
    }
    printf("|\n%llu outputs...\n",r);
    scanf("%llu",&r);
}    

Regular expression to match standard 10 digit phone number

^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$

Matches the following

123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890

If you do not want a match on non-US numbers use

^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$

Update :
As noticed by user Simon Weaver below, if you are also interested in matching on unformatted numbers just make the separator character class optional as [\s.-]?

^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$

Can you call Directory.GetFiles() with multiple filters?

for

var exts = new[] { "mp3", "jpg" };

You could:

public IEnumerable<string> FilterFiles(string path, params string[] exts) {
    return
        Directory
        .EnumerateFiles(path, "*.*")
        .Where(file => exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}

But the real benefit of EnumerateFiles shows up when you split up the filters and merge the results:

public IEnumerable<string> FilterFiles(string path, params string[] exts) {
    return 
        exts.Select(x => "*." + x) // turn into globs
        .SelectMany(x => 
            Directory.EnumerateFiles(path, x)
            );
}

It gets a bit faster if you don't have to turn them into globs (i.e. exts = new[] {"*.mp3", "*.jpg"} already).

Performance evaluation based on the following LinqPad test (note: Perf just repeats the delegate 10000 times) https://gist.github.com/zaus/7454021

( reposted and extended from 'duplicate' since that question specifically requested no LINQ: Multiple file-extensions searchPattern for System.IO.Directory.GetFiles )

Is there a way to avoid null check before the for-each loop iteration starts?

Another Java 8+ way would be to create a forEach method that does not crash when using a null value:

public static <T> void forEach(Iterable<T> set, Consumer<T> action) {
    if (set != null) {
        set.forEach(action);
    }
}

The usage of the own defined foreach is close to the native Java 8 one:

ArrayList<T> list = null;

//java 8+ (will throw a NullPointerException)
list.forEach(item -> doSomething(...) );

//own implementation
forEach(list, item -> doSomething(...) );

Git add all files modified, deleted, and untracked?

git add --all or git add -A or git add -A . Stages All

git add . Stages New & Modified But Without Deleted

git add -u Stages Modified & Deleted But Without New

git commit -a Means git add -u And git commit -m "message"

After writing this command follow these steps:-

  1. press i
  2. write your message
  3. press esc
  4. press :wq
  5. press enter

git add <list of files> add specific file

git add *.txt add all the txt files in current directory

git add docs/*/txt add all txt files in docs directory

git add docs/ add all files in docs directory

git add "*.txt" or git add '*.txt' add all the files in the whole project

jQuery: Check if div with certain class name exists

The best way in Javascript:

if (document.getElementsByClassName("search-box").length > 0) {
// do something
}

Validate decimal numbers in JavaScript - IsNumeric()

I think my code is perfect ...

_x000D_
_x000D_
/**_x000D_
 * @param {string} s_x000D_
 * @return {boolean}_x000D_
 */_x000D_
var isNumber = function(s) {_x000D_
    return s.trim()!=="" && !isNaN(Number(s));_x000D_
};
_x000D_
_x000D_
_x000D_

Largest and smallest number in an array

Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
 foreach(Int i in number)

    {
       If(!Result.HasValue || i< Result)

        { 

            Result =i;
         }
     }

     Console.WriteLine(Result);
   }

How to convert uint8 Array to base64 Encoded String?

If all you want is a JS implementation of a base64-encoder, so that you can send data back, you can try the btoa function.

b64enc = btoa(uint);

A couple of quick notes on btoa - it's non-standard, so browsers aren't forced to support it. However, most browsers do. The big ones, at least. atob is the opposite conversion.

If you need a different implementation, or you find an edge-case where the browser has no idea what you're talking about, searching for a base64 encoder for JS wouldn't be too hard.

I think there are 3 of them hanging around on my company's website, for some reason...

PHP ini file_get_contents external url

The answers provided above solve the problem but don't explain the strange behaviour the OP described. This explanation should help anyone testing communication between sites in a development environment where these sites all reside on the same host (and the same virtualhost; I'm working with apache 2.4 and php7.0).

There's a subtlety with file_get_contents() I came across that is absolutely relevant here but unaddressed (probably because it's either barely documented or not documented from what I can tell or is documented in an obscure php security model whitepaper I can't find).

With allow_url_fopen set to Off in all relevant contexts (e.g. /etc/php/7.0/apache2/php.ini, /etc/php/7.0/fpm/php.ini, etc...) and allow_url_fopen set to On in the command line context (i.e. /etc/php/7.0/cli/php.ini), calls to file_get_contents() for a local resource will be allowed and no warning will be logged such as:

file_get_contents('php://input');

or

// Path outside document root that webserver user agent has permission to read. e.g. for an apache2 webserver this user agent might be www-data so a file at /etc/php/7.0/filetoaccess would be successfully read if www-data had permission to read this file
file_get_contents('<file path to file on local machine user agent can access>');

or

// Relative path in same document root
file_get_contents('data/filename.dat')

To conclude, the restriction allow_url_fopen = Off is analogous to an iptables rule in the OUTPUT chain, where the restriction is only applied when an attempt to "exit the system" or "change contexts" is made.

N.B. allow_url_fopen set to On in the command line context (i.e. /etc/php/7.0/cli/php.ini) is what I had on my system but I suspect it would have no bearing on the explanation I provided even if it were set to Off unless of course you're testing by running your scripts from the command line itself. I did not test the behaviour with allow_url_fopen set to Off in the command line context.

phpmailer error "Could not instantiate mail function"

Check if sendmail is enabled, mostly if your server is provided by another company.

jQuery get textarea text

the best way: $('#myTextBox').val('new value').trim();

Using parameters in batch files at Windows command line

Batch Files automatically pass the text after the program so long as their are variables to assign them to. They are passed in order they are sent; e.g. %1 will be the first string sent after the program is called, etc.

If you have Hello.bat and the contents are:

@echo off
echo.Hello, %1 thanks for running this batch file (%2)
pause

and you invoke the batch in command via

hello.bat APerson241 %date%

you should receive this message back:

Hello, APerson241 thanks for running this batch file (01/11/2013)

How to set cornerRadius for only top-left and top-right corner of a UIView?

Swift 4 Swift 5 easy way in 1 line

Usage:

//MARK:- Corner Radius of only two side of UIViews
self.roundCorners(view: yourview, corners: [.bottomLeft, .topRight], radius: 12.0)

Function:

//MARK:- Corner Radius of only two side of UIViews
func roundCorners(view :UIView, corners: UIRectCorner, radius: CGFloat){
        let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        view.layer.mask = mask
}

In Objective-C

Usage:

[self.verticalSeparatorView roundCorners:UIRectCornerTopLeft radius:10.0];

Function used in a Category (only one corner):

-(void)roundCorners: (UIRectCorner) corners radius:(CGFloat)radius {
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
        CAShapeLayer *mask = [[CAShapeLayer alloc] init];
        mask.path = path.CGPath;
        self.layer.mask = mask;
    }

html5 audio player - jquery toggle click play/pause?

Simply Use

$('audio').trigger('pause');

How to set a header in an HTTP response?

First of all you have to understand the nature of

response.sendRedirect(newUrl);

It is giving the client (browser) 302 http code response with an URL. The browser then makes a separate GET request on that URL. And that request has no knowledge of headers in the first one.

So sendRedirect won't work if you need to pass a header from Servlet A to Servlet B.

If you want this code to work - use RequestDispatcher in Servlet A (instead of sendRedirect). Also, it is always better to use relative path.

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    String userName=request.getParameter("userName");
    String newUrl = "ServletB";
    response.addHeader("REMOTE_USER", userName);
    RequestDispatcher view = request.getRequestDispatcher(newUrl);
    view.forward(request, response);
}

========================

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    String sss = response.getHeader("REMOTE_USER");
}

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

try with

<form formGroup="userForm">

instead of

<form [formGroup]="userForm">

Do I commit the package-lock.json file created by npm 5?

To the people complaining about the noise when doing git diff:

git diff -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'

What I did was use an alias:

alias gd="git diff --ignore-all-space --ignore-space-at-eol --ignore-space-change --ignore-blank-lines -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'"

To ignore package-lock.json in diffs for the entire repository (everyone using it), you can add this to .gitattributes:

package-lock.json binary
yarn.lock binary

This will result in diffs that show "Binary files a/package-lock.json and b/package-lock.json differ whenever the package lock file was changed. Additionally, some Git services (notably GitLab, but not GitHub) will also exclude these files (no more 10k lines changed!) from the diffs when viewing online when doing this.

How to do an update + join in PostgreSQL?

First Table Name: tbl_table1 (tab1). Second Table Name: tbl_table2 (tab2).

Set the tbl_table1's ac_status column to "INACTIVE"

update common.tbl_table1 as tab1
set ac_status= 'INACTIVE' --tbl_table1's "ac_status"
from common.tbl_table2 as tab2
where tab1.ref_id= '1111111' 
and tab2.rel_type= 'CUSTOMER';

How to have the formatter wrap code with IntelliJ?

IntelliJ IDEA 14, 15, 2016 & 2017

Format existing code

  1. Ensure right margin is not exceeded

    File > Settings > Editor > Code Style > Java > Wrapping and Braces > Ensure right margin is not exceeded

    File Settings Ensure right margin

  2. Reformat code

    Code > Reformat code...

    Reformat code

    or press Ctrl + Alt + L

    warning If you have something like this:

    thisLineIsVeryLongAndWillBeChanged();   // comment
    

    it will be converted to

    thisLineIsVeryLongAndWillBeChanged();   
    // comment  
    

    instead of

    // comment  
    thisLineIsVeryLongAndWillBeChanged();   
    

    This is why I select pieces of code before reformatting if the code looks like in the previous example.

Wrap when typing reaches right margin

  • IntelliJ IDEA 14: File > Settings > Editor > Code Style > Wrap when typing reaches right margin

    Wrap when typing

  • IntelliJ IDEA 15, 2016 & 2017: File > Settings > Editor > Code Style > Wrap on typing

    Wrap on typing

Javascript to sort contents of select element

function sortItems(c) {
var options = c.options;
Array.prototype.sort.call(options, function (a, b) {
    var aText = a.text.toLowerCase();
    var bText = b.text.toLowerCase();
    if (aText < bText) {
        return -1;
    } else if (aText > bText) {
        return 1;
    } else {
        return 0;
    }
});
}

sortItems(document.getElementById('lstALL'));

ORA-00972 identifier is too long alias column name

The object where Oracle stores the name of the identifiers (e.g. the table names of the user are stored in the table named as USER_TABLES and the column names of the user are stored in the table named as USER_TAB_COLUMNS), have the NAME columns (e.g. TABLE_NAME in USER_TABLES) of size Varchar2(30)...and it's uniform through all system tables of objects or identifiers --

 DBA_ALL_TABLES         ALL_ALL_TABLES        USER_ALL_TABLES
 DBA_PARTIAL_DROP_TABS  ALL_PARTIAL_DROP_TABS USER_PARTIAL_DROP_TABS
 DBA_PART_TABLES        ALL_PART_TABLES       USER_PART_TABLES 
 DBA_TABLES             ALL_TABLES            USER_TABLES           
 DBA_TABLESPACES        USER_TABLESPACES      TAB
 DBA_TAB_COLUMNS      ALL_TAB_COLUMNS         USER_TAB_COLUMNS 
 DBA_TAB_COLS         ALL_TAB_COLS            USER_TAB_COLS 
 DBA_TAB_COMMENTS     ALL_TAB_COMMENTS        USER_TAB_COMMENTS 
 DBA_TAB_HISTOGRAMS   ALL_TAB_HISTOGRAMS      USER_TAB_HISTOGRAMS 
 DBA_TAB_MODIFICATIONS  ALL_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS 
 DBA_TAB_PARTITIONS   ALL_TAB_PARTITIONS      USER_TAB_PARTITIONS

Common CSS Media Queries Break Points

Consider using twitter bootstrap's break points. with such a massive adoption rate you should be safe...

R: Comment out block of code

Most of the editors take some kind of shortcut to comment out blocks of code. The default editors use something like command or control and single quote to comment out selected lines of code. In RStudio it's Command or Control+/. Check in your editor.

It's still commenting line by line, but they also uncomment selected lines as well. For the Mac RGUI it's command-option ' (I'm imagining windows is control option). For Rstudio it's just Command or Control + Shift + C again.

These shortcuts will likely change over time as editors get updated and different software becomes the most popular R editors. You'll have to look it up for whatever software you have.

phpmyadmin "no data received to import" error, how to fix?

xampp in ubuntu

cd /opt/lampp/etc
vim php.ini

Find:
  post_max_size = 8M
  upload_max_filesize = 2M
  max_execution_time = 30
  max_input_time = 60
  memory_limit = 8M

Change to:
  post_max_size = 750M
  upload_max_filesize = 750M
  max_execution_time = 5000
  max_input_time = 5000
  memory_limit = 1000M

sudo /opt/lampp/lampp restart

Difference between <input type='button' /> and <input type='submit' />

A 'button' is just that, a button, to which you can add additional functionality using Javascript. A 'submit' input type has the default functionality of submitting the form it's placed in (though, of course, you can still add additional functionality using Javascript).

Python JSON dump / append to .txt with each variable on new line

Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.

Remove Object from Array using JavaScript

How about this?

$.each(someArray, function(i){
    if(someArray[i].name === 'Kristian') {
        someArray.splice(i,1);
        return false;
    }
});

How can I create an editable dropdownlist in HTML?

I am not sure there is a way to do it automatically without javascript.

What you need is something which runs on the browser side to submit your form back to the server when they user makes a selection - hence, javascript.

Also, ensure you have an alternate means (i.e. a submit button) for those who have javascript turned off.

A good example: Combo-Box Viewer

I had even a more sophisticated combo-box yesterday, with this dhtmlxCombo , using ajax to retrieve pertinent values amongst large quantity of data.

Remove non-numeric characters (except periods and commas) from a string

If letters are always in the beginning or at the end, you can simply just use trim...no regex needed

$string = trim($string, "a..zA..Z"); // this also take care of lowercase

"AR3,373.31" --> "3,373.31"
"12.322,11T" --> "12.322,11"
"12.322,11"  --> "12.322,11"

Python logging not outputting anything

Many years later there seems to still be a usability problem with the Python logger. Here's some explanations with examples:

import logging
# This sets the root logger to write to stdout (your console).
# Your script/app needs to call this somewhere at least once.
logging.basicConfig()

# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)

# The following line sets the root logger level as well.
# It's equivalent to both previous statements combined:
logging.basicConfig(level=logging.NOTSET)


# You can either share the `logger` object between all your files or the
# name handle (here `my-app`) and call `logging.getLogger` with it.
# The result is the same.
handle = "my-app"
logger1 = logging.getLogger(handle)
logger2 = logging.getLogger(handle)
# logger1 and logger2 point to the same object:
# (logger1 is logger2) == True


# Convenient methods in order of verbosity from highest to lowest
logger.debug("this will get printed")
logger.info("this will get printed")
logger.warning("this will get printed")
logger.error("this will get printed")
logger.critical("this will get printed")


# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")

# If you wish to control the logging levels, you can set the level anywhere 
# in the hierarchy:
#
# - root
#   - my-app
#     - component-a
#

# Example for development:
logger.setLevel(logging.DEBUG)

# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)


# For production you rather want:
logger.setLevel(logging.WARNING)

A common source of confusion comes from a badly initialised root logger. Consider this:

import logging
log = logging.getLogger("myapp")
log.warning("woot")
logging.basicConfig()
log.warning("woot")

Output:

woot
WARNING:myapp:woot

Depending on your runtime environment and logging levels, the first log line (before basic config) might not show up anywhere.

Angularjs - Pass argument to directive

<button my-directive="push">Push to Go</button>

app.directive("myDirective", function() {
    return {
        restrict : "A",
         link: function(scope, elm, attrs) {
                elm.bind('click', function(event) {

                    alert("You pressed button: " + event.target.getAttribute('my-directive'));
                });
        }
    };
});

here is what I did

I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push" And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive').

What is the difference between Amazon SNS and Amazon SQS?

SNS is a distributed publish-subscribe system. Messages are pushed to subscribers as and when they are sent by publishers to SNS.

SQS is distributed queuing system. Messages are not pushed to receivers. Receivers have to poll or pull messages from SQS. Messages can't be received by multiple receivers at the same time. Any one receiver can receive a message, process and delete it. Other receivers do not receive the same message later. Polling inherently introduces some latency in message delivery in SQS unlike SNS where messages are immediately pushed to subscribers. SNS supports several end points such as email, SMS, HTTP end point and SQS. If you want unknown number and type of subscribers to receive messages, you need SNS.

You don't have to couple SNS and SQS always. You can have SNS send messages to email, SMS or HTTP end point apart from SQS. There are advantages to coupling SNS with SQS. You may not want an external service to make connections to your hosts (a firewall may block all incoming connections to your host from outside).

Your end point may just die because of heavy volume of messages. Email and SMS maybe not your choice of processing messages quickly. By coupling SNS with SQS, you can receive messages at your pace. It allows clients to be offline, tolerant to network and host failures. You also achieve guaranteed delivery. If you configure SNS to send messages to an HTTP end point or email or SMS, several failures to send message may result in messages being dropped.

SQS is mainly used to decouple applications or integrate applications. Messages can be stored in SQS for a short duration of time (maximum 14 days). SNS distributes several copies of messages to several subscribers. For example, let’s say you want to replicate data generated by an application to several storage systems. You could use SNS and send this data to multiple subscribers, each replicating the messages it receives to different storage systems (S3, hard disk on your host, database, etc.).

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

SQL Error with Order By in Subquery

Good day

for some guys the order by in the sub-query is questionable. the order by in sub-query is a must to use if you need to delete some records based on some sorting. like

delete from someTable Where ID in (select top(1) from sometable where condition order by insertionstamp desc)

so that you can delete the last insertion form table. there are three way to do this deletion actually.

however, the order by in the sub-query can be used in many cases.

for the deletion methods that uses order by in sub-query review below link

http://web.archive.org/web/20100212155407/http://blogs.msdn.com/sqlcat/archive/2009/05/21/fast-ordered-delete.aspx

i hope it helps. thanks you all

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

Instagram API: How to get all user media?

What I had to do is (in Javascript) is go through all pages by using a recursive function. It's dangerouse as instagram users could have thousands of pictures i a part from that (so your have to controle it) I use this code: (count parameter I think , doesn't do much)

        instagramLoadDashboard = function(hash)
    {
        code = hash.split('=')[1];

        $('#instagram-pictures .images-list .container').html('').addClass('loading');


        ts = Math.round((new Date()).getTime() / 1000);
        url = 'https://api.instagram.com/v1/users/self/media/recent?count=200&min_timestamp=0&max_timestamp='+ts+'&access_token='+code;

        instagramLoadMediaPage(url, function(){

            galleryHTML = instagramLoadGallery(instagramData);
            //console.log(galleryHTML);
            $('#instagram-pictures .images-list .container').html(galleryHTML).removeClass('loading');
            initImages('#instagram-pictures');

            IGStatus = 'loaded';

        });

    };

    instagramLoadMediaPage = function (url, callback)
    {
        $.ajax({
                url : url,
                dataType : 'jsonp',
                cache : false,
                success:  function(response){

                                        console.log(response);

                                        if(response.code == '400')
                                        {
                                            alert(response.error_message);
                                            return false;
                                        }

                                        if(response.pagination.next_url !== undefined) {
                                            instagramData = instagramData.concat(response.data);
                                            return instagramLoadMediaPage(response.pagination.next_url,callback);
                                        }

                                        instagramData = instagramData.concat(response.data);
                                        callback.apply();
                                    }
        });
    };

    instagramLoadGallery = function(images)
    {
        galleryHTML ='<ul>';

        for(var i=0;i<images.length;i++)
        {
            galleryHTML += '<li><img src="'+images[i].images.thumbnail.url+'" width="120" id="instagram-'+images[i].id+' data-type="instagram" data-source="'+images[i].images.standard_resolution.url+'" class="image"/></li>';

        }

        galleryHTML +='</ul>';

        return galleryHTML;
    };

There some stuff related to print out a gallery of picture.

Weird behavior of the != XPath operator

I've always used this syntax, which yields more predictable results than using !=.

<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')" />

Is null reference possible?

References are not pointers.

8.3.2/1:

A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]

1.9/4:

Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)

As Johannes says in a deleted answer, there's some doubt whether "dereferencing a null pointer" should be categorically stated to be undefined behavior. But this isn't one of the cases that raise doubts, since a null pointer certainly does not point to a "valid object or function", and there is no desire within the standards committee to introduce null references.

How to find whether a number belongs to a particular range in Python?

print 'yes' if 0 < x < 0.5 else 'no'

range() is for generating arrays of consecutive integers

How to change the background-color of jumbrotron?

You can use the following to change the background-color of a Jumbotron:

<div class="container">
    <div class="jumbotron text-white" style="background-color: #8c6278;">
        <h1>Coffee lover project !</h1>
    </div>
</div>

Adb over wireless without usb cable at all for not rooted phones

There are actually apps on the Play store to enable wifi connections automatically. You'll need root though to do it without a cable. The top choices in https://play.google.com/store/search?q=adb%20wireless all have root and non-root options. Without root you'll need to connect your cable as before; with root you can just enable the app. That saves you having to mess with the Bluetooth option.

If you also add adb to your system path on windows it makes connecting via wifi very quick and easy. Enable the app and type one line in any terminal window and you're connected.

Close Bootstrap modal on form submit

If you do not want to use jQuery, make the button type a normal button and add a click listener pointing to the function you would like to execute, and send the form in as a parameter. The button would be as follows:

<button (click)="yourSubmitFunction(yourForm)" [disabled]="!yourForm.valid" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>

Remember to remove: (ngSubmit)="yourSubmitFunction(yourForm)" from the form div if you use this method.

jQuery Event Keypress: Which key was pressed?

I'll just supplement solution code with this line e.preventDefault();. In case of input field of form we don't attend to submit on enter pressed

var code = (e.keyCode ? e.keyCode : e.which);
 if(code == 13) { //Enter keycode
   e.preventDefault();
   //Do something
 }

hidden field in php

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

Yes (haven't you tried?)

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

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


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

TypeScript: Interfaces vs Types

Other answers are great! Few other things which Type can do but Interface can't

You can use union in type

type Name = string | { FullName: string };

const myName = "Jon"; // works fine

const myFullName: Name = {
  FullName: "Jon Doe", //also works fine
};

Iterating over union properties in type

type Keys = "firstName" | "lastName";

type Name = {
  [key in Keys]: string;
};

const myName: Name = {
  firstName: "jon",
  lastName: "doe",
};

Intersection in type ( however, also supported in Interface with extends)

type Name = {
  firstName: string;
  lastName: string;
};

type Address = {
  city: string;
};

const person: Name & Address = {
  firstName: "jon",
  lastName: "doe",
  city: "scranton",
};

Also not that type was introduced later as compared to interface and according to the latest release of TS type can do *almost everything which interface can and much more!


*except Declaration merging (personal opinion: It's good that it's not supported in type as it may lead to inconsistency in code)

What are the differences between delegates and events?

Here is another good link to refer to. http://csharpindepth.com/Articles/Chapter2/Events.aspx

Briefly, the take away from the article - Events are encapsulation over delegates.

Quote from article:

Suppose events didn't exist as a concept in C#/.NET. How would another class subscribe to an event? Three options:

  1. A public delegate variable

  2. A delegate variable backed by a property

  3. A delegate variable with AddXXXHandler and RemoveXXXHandler methods

Option 1 is clearly horrible, for all the normal reasons we abhor public variables.

Option 2 is slightly better, but allows subscribers to effectively override each other - it would be all too easy to write someInstance.MyEvent = eventHandler; which would replace any existing event handlers rather than adding a new one. In addition, you still need to write the properties.

Option 3 is basically what events give you, but with a guaranteed convention (generated by the compiler and backed by extra flags in the IL) and a "free" implementation if you're happy with the semantics that field-like events give you. Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription.

How do I add a simple jQuery script to WordPress?

Do you only need to load jquery?

1) Like the other guides say, register your script in your functions.php file like so:

// register scripts
if (!is_admin()) {
    // here is an example of loading a custom script in a /scripts/ folder in your theme:
    wp_register_script('sandbox.common', get_bloginfo('template_url').'/scripts/common.js', array('jquery'), '1.0', true);
    // enqueue these scripts everywhere
    wp_enqueue_script('jquery');
    wp_enqueue_script('sandbox.common');
}

2) Notice that we don't need to register jQuery because it's already in the core. Make sure wp_footer() is called in your footer.php and wp_head() is called in your header.php (this is where it will output the script tag), and jQuery will load on every page. When you enqueue jQuery with WordPress it will be in "no conflict" mode, so you have to use jQuery instead of $. You can deregister jQuery if you want and re-register your own by doing wp_deregister_script('jquery').

Android: where are downloaded files saved?

In my experience all the files which i have downloaded from internet,gmail are stored in

/sdcard/download

on ics

/sdcard/Download

You can access it using

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

shell init issue when click tab, what's wrong with getcwd?

By chance, is this occurring on a directory using OverlayFS (or some other special file system type)?

I just had this issue where my cross-compiled version of bash would use an internal implementation of getcwd which has issues with OverlayFS. I found information about this here:

It seems that this can be traced to an internal implementation of getcwd() in bash. When cross-compiled, it can't check for getcwd() use of malloc, so it is cautious and sets GETCWD_BROKEN and uses an internal implementation of getcwd(). This internal implementation doesn't seem to work well with OverlayFS.

http://permalink.gmane.org/gmane.linux.embedded.yocto.general/25204

You can configure and rebuild bash with bash_cv_getcwd_malloc=yes (if you're actually building bash and your C library does malloc a getcwd call).

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

.NET / C# - Convert char[] to string

One other way:

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = string.Join("", chars);
//we get "a string"
// or for fun:
string s = string.Join("_", chars);
//we get "a_ _s_t_r_i_n_g"

How to install MySQLi on MacOS

I had the same issue, I went to EasyApache4 from the WHM clicked on customize button then PHP Extension tab.. I selected and installed the extension php72-php-mysqlnd and my was solved

I do not understand how execlp() works in Linux

The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:

execl("/bin/ls", "ls", "-la", NULL);

The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:

execlp("ls", "ls", "-la", NULL);

JPA EntityManager: Why use persist() over merge()?

Scenario X:

Table:Spitter (One) ,Table: Spittles (Many) (Spittles is Owner of the relationship with a FK:spitter_id)

This scenario results in saving : The Spitter and both Spittles as if owned by Same Spitter.

        Spitter spitter=new Spitter();  
    Spittle spittle3=new Spittle();     
    spitter.setUsername("George");
    spitter.setPassword("test1234");
    spittle3.setSpittle("I love java 2");       
    spittle3.setSpitter(spitter);               
    dao.addSpittle(spittle3); // <--persist     
    Spittle spittle=new Spittle();
    spittle.setSpittle("I love java");
    spittle.setSpitter(spitter);        
    dao.saveSpittle(spittle); //<-- merge!!

Scenario Y:

This will save the Spitter, will save the 2 Spittles But they will not reference the same Spitter!

        Spitter spitter=new Spitter();  
    Spittle spittle3=new Spittle();     
    spitter.setUsername("George");
    spitter.setPassword("test1234");
    spittle3.setSpittle("I love java 2");       
    spittle3.setSpitter(spitter);               
    dao.save(spittle3); // <--merge!!       
    Spittle spittle=new Spittle();
    spittle.setSpittle("I love java");
    spittle.setSpitter(spitter);        
    dao.saveSpittle(spittle); //<-- merge!!

Array vs. Object efficiency in JavaScript

I had a similar problem that I am facing where I need to store live candlesticks from an event source limited to x items. I could have them stored in an object where the timestamp of each candle would act as the key and the candle itself would act as the value. Another possibility was that I could store it in an array where each item was the candle itself. One problem about live candles is that they keep sending updates on the same timestamp where the latest update holds the most recent data therefore you either update an existing item or add a new one. So here is a nice benchmark that attempts to combine all 3 possibilities. Arrays in the solution below are atleast 4x faster on average. Feel free to play

"use strict";

const EventEmitter = require("events");
let candleEmitter = new EventEmitter();

//Change this to set how fast the setInterval should run
const frequency = 1;

setInterval(() => {
    // Take the current timestamp and round it down to the nearest second
    let time = Math.floor(Date.now() / 1000) * 1000;
    let open = Math.random();
    let high = Math.random();
    let low = Math.random();
    let close = Math.random();
    let baseVolume = Math.random();
    let quoteVolume = Math.random();

    //Clear the console everytime before printing fresh values
    console.clear()

    candleEmitter.emit("candle", {
        symbol: "ABC:DEF",
        time: time,
        open: open,
        high: high,
        low: low,
        close: close,
        baseVolume: baseVolume,
        quoteVolume: quoteVolume
    });



}, frequency)

// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)

// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)

//Container for the object version of candles
let objectOhlc = {}

//Container for the array version of candles
let arrayOhlc = {}

//Store a max 30 candles and delete older ones
let limit = 30

function storeAsObject(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;

    // Create the object structure to store the current symbol
    if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}

    // The timestamp of the latest candle is used as key with the pair to store this symbol
    objectOhlc[symbol][time] = candle;

    // Remove entries if we exceed the limit
    const keys = Object.keys(objectOhlc[symbol]);
    if (keys.length > limit) {
        for (let i = 0; i < (keys.length - limit); i++) {
            delete objectOhlc[symbol][keys[i]];
        }
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)
}

function storeAsArray(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;
    if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []

    //Get the bunch of candles currently stored
    const candles = arrayOhlc[symbol];

    //Get the last candle if available
    const lastCandle = candles[candles.length - 1] || {};

    // Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
    if (time !== lastCandle.time) {
        candles.push(candle);
    }

    //If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
    else {
        candles[candles.length - 1] = candle
    }

    if (candles.length > limit) {
        candles.splice(0, candles.length - limit);
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]


    console.log("Storing as array", end - start, arrayOhlc[symbol].length)
}

Conclusion 10 is the limit here

Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10

What is PAGEIOLATCH_SH wait type in SQL Server?

PAGEIOLATCH_SH wait type usually comes up as the result of fragmented or unoptimized index.

Often reasons for excessive PAGEIOLATCH_SH wait type are:

  • I/O subsystem has a problem or is misconfigured
  • Overloaded I/O subsystem by other processes that are producing the high I/O activity
  • Bad index management
  • Logical or physical drive misconception
  • Network issues/latency
  • Memory pressure
  • Synchronous Mirroring and AlwaysOn AG

In order to try and resolve having high PAGEIOLATCH_SH wait type, you can check:

  • SQL Server, queries and indexes, as very often this could be found as a root cause of the excessive PAGEIOLATCH_SH wait types
  • For memory pressure before jumping into any I/O subsystem troubleshooting

Always keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH can be expected.

You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types

How do I dump an object's fields to the console?

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

Android RatingBar change star colors

1) declare this xml

<LinearLayout 
             android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:orientation="horizontal"
         android:paddingLeft="20dp"
         android:paddingRight="20dp"
         android:layout_marginBottom="20dp"
         android:background="#323232"
         android:gravity="center_horizontal">

       <com.example.android.custom_ratingbar.CustomRatingBar
        android:id="@+id/coloredRatingBar5"
        style="@style/coloredRatingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"

         />
       </LinearLayout>

2) in style.xml

<style name="coloredRatingBarStyleSmall">
        <item name="indicator">false</item>
        <item name="type">small</item>
    </style>

3)

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class CustomRatingBar extends View{

    private static final String TAG="ColoredRatingBar";
    private static final int NORMAL = 0;
    private static final int SMALL = 1;

    Bitmap[] drawables;
    Bitmap progressBackground;
    Context mContext;
    private int mNumStars =9;
    private float mRating =0;
    private boolean mIndicator;
    private float slidePosition;
    private int mType;

    /**
     * A callback that notifies clients when the rating has been changed. This
     * includes changes that were initiated by the user through a touch gesture
     * or arrow key/trackball as well as changes that were initiated
     * programmatically.
     */
    public interface OnRatingBarChangeListener {

        /**
         * Notification that the rating has changed. Clients can use the
         * fromUser parameter to distinguish user-initiated changes from those
         * that occurred programmatically. This will not be called continuously
         * while the user is dragging, only when the user finalizes a rating by
         * lifting the touch.
         *
         * @param ratingBar The RatingBar whose rating has changed.
         * @param rating The current rating. This will be in the range
         *            0..numStars.
         * @param fromUser True if the rating change was initiated by a user's
         *            touch gesture or arrow key/horizontal trackbell movement.
         */
        void onRatingChanged(CustomRatingBar ratingBar, float rating, boolean fromUser);

    }

    private OnRatingBarChangeListener mOnRatingBarChangeListener;

    public CustomRatingBar(Context context) {
        this(context, null);
    }
    public CustomRatingBar(Context context, AttributeSet attrs) {
        this(context, attrs,0);//R.attr.coloredRatingBarStyle
    }

    public CustomRatingBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomRatingBar,defStyle, 0);
        final boolean indicator = a.getBoolean(R.styleable.CustomRatingBar_indicator, false);
        final float rating = a.getFloat(R.styleable.CustomRatingBar_setrating, -1);
        final int type = a.getInt(R.styleable.CustomRatingBar_type, 0);
        a.recycle();

        setIndicator(indicator);
        setRating(rating);
        setType(type);
        init(context);
    }

    public int getType() {
        return mType;
    }

    public void setType(int type) {
        this.mType = type;
    }

    private void init(Context context) {
        mContext = context;
        Resources res = getResources();
        if(mType==SMALL){
            drawables = new Bitmap[]{BitmapFactory.decodeResource(res, R.drawable.rating_inactive),BitmapFactory.decodeResource(res, R.drawable.rating_active)};
            progressBackground = BitmapFactory.decodeResource(res, R.drawable.rating_inactive);
        }else{
            drawables = new Bitmap[]{BitmapFactory.decodeResource(res, R.drawable.rating_inactive),BitmapFactory.decodeResource(res, R.drawable.rating_active)};
            progressBackground = BitmapFactory.decodeResource(res, R.drawable.rating_inactive);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //draw empty stars bg
        for(int i=0;i< mNumStars;i++){
            drawStar(canvas,i);
        }

    }


    private void drawStar(Canvas canvas, int position) {
        float fraction = mRating -(position);
        Bitmap ratedStar1 = getRatedStar();
        Paint paint=getPaint(position);
        int division=getSize();
        Bitmap ratedStar=null;
        Bitmap emptyStar=null;
       if(!isInEditMode()){
        ratedStar=Bitmap.createScaledBitmap(ratedStar1, division, division, false);
        emptyStar=Bitmap.createScaledBitmap(progressBackground, division, division, false);
       }
        if((position)< mRating){
            if(!isInEditMode()){
           canvas.drawBitmap(ratedStar,(position* division),0,paint);
            }

        } else{

                if(!isInEditMode()){
              canvas.drawBitmap(emptyStar,(position*division),0,null);

            }
        }


    }
    private int getSize(){
        return (getWidth()/mNumStars);
    }

    private Bitmap getRatedStar() {

        if(mRating==0){
            return drawables[0];
        }
        else{
            return drawables[1];
        }
    }

    private Paint getPaint(int position){
        int value=(255*(position+1))/mNumStars;
        String hexString=Integer.toHexString(value).equals("0")?"00":Integer.toHexString(value);
        String hexvalue="#"+hexString+"000000";//FEE98E
        //Log.e("TAG", position+"/"+value+"/"+hexvalue);

        Paint paint=new Paint();

        paint.setColor(Color.parseColor(hexvalue));

        return paint;
    }

    public int getNumStars() {
        return mNumStars;
    }

    public void setNumStars(int numStars) {
        this.mNumStars = numStars;
    }

    public float getRating() {
        return mRating;
    }

    public void setRating(float rating) {
        setRating(rating,false);
    }

    void setRating(float rating,boolean fromUser) {
        if(rating>mNumStars){
            this.mRating = mNumStars;
        }
        this.mRating = rating;
        invalidate();
        dispatchRatingChange(fromUser);
    }

    public boolean isIndicator() {
        return mIndicator;
    }

    public void setIndicator(boolean indicator) {
        this.mIndicator = indicator;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (progressBackground != null) {

            final int width = progressBackground.getWidth() * mNumStars;
            final int height = progressBackground.getHeight();

            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            Bitmap emptyStar=Bitmap.createScaledBitmap(progressBackground, widthSize/mNumStars, widthSize/mNumStars, false);
            int heightSize = emptyStar.getHeight();

            setMeasuredDimension(resolveSizeAndState(widthSize, widthMeasureSpec, 0),
                    resolveSizeAndState(heightSize, heightMeasureSpec, 0));
        }
        else{
              int desiredWidth = 100;
            int desiredHeight = 50;

            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            int width;
            int height;

            //Measure Width
            if (widthMode == MeasureSpec.EXACTLY) {
                //Must be this size
                width = widthSize;
            } else if (widthMode == MeasureSpec.AT_MOST) {
                //Can't be bigger than...
                width = Math.min(desiredWidth, widthSize);
            } else {
                //Be whatever you want
                width = desiredWidth;
            }

            //Measure Height
            if (heightMode == MeasureSpec.EXACTLY) {
                //Must be this size
                height = heightSize;
            } else if (heightMode == MeasureSpec.AT_MOST) {
                //Can't be bigger than...
                height = Math.min(desiredHeight, heightSize);
            } else {
                //Be whatever you want
                height = desiredHeight;
            }

            //MUST CALL THIS
          setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),resolveSizeAndState(height, heightMeasureSpec, 0));
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mIndicator){
            return false;
        }

        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                slidePosition = getRelativePosition(event.getX());

                int newRating = (int)(slidePosition>0?slidePosition+1:0) ;
                if(newRating>mNumStars){
                    newRating=mNumStars;
                }

             //   Log.e("TAG", ""+newRating);
                if (newRating != mRating) {
                    setRating(newRating,true);
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
        }

        return true;
    }

    private float getRelativePosition(float x) {
        Bitmap emptyStar=Bitmap.createScaledBitmap(progressBackground, getWidth()/mNumStars, getWidth()/mNumStars, false);
        int widthSize = emptyStar.getWidth();
      //  Log.e("TAG", widthSize+"/"+x);
         float position = x / widthSize;
       position = Math.max(position, 0);
       return Math.min(position, mNumStars);
    }

    /**
     * Sets the listener to be called when the rating changes.
     *
     * @param listener The listener.
     */
    public void setOnRatingBarChangeListener(OnRatingBarChangeListener listener) {
        mOnRatingBarChangeListener = listener;
    }

    /**
     * @return The listener (may be null) that is listening for rating change
     *         events.
     */
    public OnRatingBarChangeListener getOnRatingBarChangeListener() {
        return mOnRatingBarChangeListener;
    }

    void dispatchRatingChange(boolean fromUser) {
        if (mOnRatingBarChangeListener != null) {
            mOnRatingBarChangeListener.onRatingChanged(this, getRating(),
                    fromUser);
        }
    }
}


5) then in calling activity---

CustomRatingBar coloredRatingBar5=(CustomRatingBar)findViewById(R.id.coloredRatingBar5);
        coloredRatingBar5.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(CustomRatingBar ratingBar, float rating,boolean fromUser) {
                // TODO Auto-generated method stub
                Log.e("RATING", ""+rating);

            }
        });

6) rating active---take any image with dark color coz it will be used as color transparency for different rating

rating_inactive--take any image of same size of above image with light background..it will used when no rating is selected

Java out.println() how is this possible?

@sfussenegger's answer explains how to make this work. But I'd say don't do it!

Experienced Java programmers use, and expect to see

        System.out.println(...);

and not

        out.println(...);

A static import of System.out or System.err is (IMO) bad style because:

  • it breaks the accepted idiom, and
  • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.

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

You have to replace YourID and value="3" for your current ones.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#YourID option[value="3"]').attr("selected", "selected");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
  <option value="1">A</option>_x000D_
  <option value="2">B</option>_x000D_
  <option value="3">C</option>_x000D_
  <option value="4">D</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

and value="3" for your current ones.

$('#YourID option[value="3"]').attr("selected", "selected");

<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>

Change the class from factor to numeric of many columns in a data frame

I think that ucfagls found why your loop is not working.

In case you still don't want use a loop here is solution with lapply:

factorToNumeric <- function(f) as.numeric(levels(f))[as.integer(f)] 
cols <- c(1, 3:ncol(stats))
stats[cols] <- lapply(stats[cols], factorToNumeric)

Edit. I found simpler solution. It seems that as.matrix convert to character. So

stats[cols] <- as.numeric(as.matrix(stats[cols]))

should do what you want.

Read response body in JAX-RS client from a post request

I also had the same issue, trying to run a unit test calling code that uses readEntity. Can't use getEntity in production code because that just returns a ByteInputStream and not the content of the body and there is no way I am adding production code that is hit only in unit tests.

My solution was to create a response and then use a Mockito spy to mock out the readEntity method:

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

Note that you can't use the when(mockResponse.readEntity(String.class) option because that throws the same IllegalStateException.

Hope this helps!

How to fix Error: listen EADDRINUSE while using nodejs?

if you want to solve this

$ node server events.js:141 throw er; // Unhandled 'error' event ^

Error: listen EADDRINUSE :::3000 at Object.exports._errnoException (util.js:907:11) at exports._exceptionWithHostPort (util.js:930:20) at Server._listen2 (net.js:1250:14) at listen (net.js:1286:10) at Server.listen (net.js:1382:5) at EventEmitter.listen (C:\sendbox\mean\node_modules\express\lib\application .js:617:24) at Object. (C:\sendbox\mean\server.js:28:5) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32)

change your port number to 8000

how to get login option for phpmyadmin in xampp

You can use

  1. Go browser & type localhost/phpmyadmin/
  2. Go to User accounts
  3. Edit privileges from marked bellow image in last options root->localhost-> Yes->ALL PRIVILEGES->Yes-> Edit privileges

Here is image like bellow enter image description here

  1. you can click on Edit privileges last option above image
  2. Then you can click on Change password. It shows enter password screen
  3. Enter your password & retype your password in password the field
  4. Then click on GO
  5. Then Go to XAMPP->xamppfiles->config.inc.php
  6. Open config.inc.php file & go to /* Authentication type */ sections
  7. change config to cookie & type your password in ' ' in password like bellow

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = 'your password';
    
  8. Then save & type on browser localhost/phpmyadmin/

  9. Enter your given password & enjoy

How do I modify fields inside the new PostgreSQL JSON datatype?

With Postgresql 9.5 it can be done by following-

UPDATE test
SET data = data - 'a' || '{"a":5}'
WHERE data->>'b' = '2';

OR

UPDATE test
SET data = jsonb_set(data, '{a}', '5'::jsonb);

Somebody asked how to update many fields in jsonb value at once. Suppose we create a table:

CREATE TABLE testjsonb ( id SERIAL PRIMARY KEY, object JSONB );

Then we INSERT a experimental row:

INSERT INTO testjsonb
VALUES (DEFAULT, '{"a":"one", "b":"two", "c":{"c1":"see1","c2":"see2","c3":"see3"}}');

Then we UPDATE the row:

UPDATE testjsonb SET object = object - 'b' || '{"a":1,"d":4}';

Which does the following:

  1. Updates the a field
  2. Removes the b field
  3. Add the d field

Selecting the data:

SELECT jsonb_pretty(object) FROM testjsonb;

Will result in:

      jsonb_pretty
-------------------------
 {                      +
     "a": 1,            +
     "c": {             +
         "c1": "see1",  +
         "c2": "see2",  +
         "c3": "see3",  +
     },                 +
     "d": 4             +
 }
(1 row)

To update field inside, Dont use the concat operator ||. Use jsonb_set instead. Which is not simple:

UPDATE testjsonb SET object =
jsonb_set(jsonb_set(object, '{c,c1}','"seeme"'),'{c,c2}','"seehim"');

Using the concat operator for {c,c1} for example:

UPDATE testjsonb SET object = object || '{"c":{"c1":"seedoctor"}}';

Will remove {c,c2} and {c,c3}.

For more power, seek power at postgresql json functions documentation. One might be interested in the #- operator, jsonb_set function and also jsonb_insert function.