Programs & Examples On #Subclassing

A subclass, "derived class", heir class, or child class is a modular, derivative class that inherits one or more language entities from one or more other classes.

How do I write a custom init for a UIView subclass in Swift?

I create a common init for the designated and required. For convenience inits I delegate to init(frame:) with frame of zero.

Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews() or updateConstraints(). These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints() or layoutSubviews(). updateContstraints() is called first, then layoutSubviews(). In updateConstraints() make sure to call super last. In layoutSubviews(), call super first.

Here's what I do:

@IBDesignable
class MyView: UIView {

      convenience init(args: Whatever) {
          self.init(frame: CGRect.zero)
          //assign custom vars
      }

      override init(frame: CGRect) {
           super.init(frame: frame)
           commonInit()
      }

      required init?(coder aDecoder: NSCoder) {
           super.init(coder: aDecoder)
           commonInit()
      }

      override func prepareForInterfaceBuilder() {
           super.prepareForInterfaceBuilder()
           commonInit()
      }

      private func commonInit() {
           //custom initialization
      }

      override func updateConstraints() {
           //set subview constraints here
           super.updateConstraints()
      }

      override func layoutSubviews() {
           super.layoutSubviews()
           //manually set subview frames here
      }

}

Python class returning value

You are describing a function, not a class.

def Myclass():
    return []

How do I assert equality on two classes without an equals method?

I had the exact same conundrum when unit testing an Android app, and the easiest solution I came up with was simply to use Gson to convert my actual and expected value objects into json and compare them as strings.

String actual = new Gson().toJson( myObj.getValues() );
String expected = new Gson().toJson( new MyValues(true,1) );

assertEquals(expected, actual);

The advantages of this over manually comparing field-by-field is that you compare all your fields, so even if you later on add a new field to your class it will get automatically tested, as compared to if you were using a bunch of assertEquals() on all the fields, which would then need to be updated if you add more fields to your class.

jUnit also displays the strings for you so you can directly see where they differ. Not sure how reliable the field ordering by Gson is though, that could be a potential problem.

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.

You can scale the pixmap by keeping its aspect ratio every time it changes:

QPixmap p; // load pixmap
// get label dimensions
int w = label->width();
int h = label->height();

// set a scaled pixmap to a w x h window keeping its aspect ratio 
label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));

There are two places where you should add this code:

  • When the pixmap is updated
  • In the resizeEvent of the widget that contains the label

Singletons vs. Application Context in Android?

They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.

What is a mixin, and why are they useful?

This answer aims to explain mixins with examples that are:

  • self-contained: short, with no need to know any libraries to understand the example.

  • in Python, not in other languages.

    It is understandable that there were examples from other languages such as Ruby since the term is much more common in those languages, but this is a Python thread.

It shall also consider the controversial question:

Is multiple inheritance necessary or not to characterize a mixin?

Definitions

I have yet to see a citation from an "authoritative" source clearly saying what is a mixin in Python.

I have seen 2 possible definitions of a mixin (if they are to be considered as different from other similar concepts such as abstract base classes), and people don't entirely agree on which one is correct.

The consensus may vary between different languages.

Definition 1: no multiple inheritance

A mixin is a class such that some method of the class uses a method which is not defined in the class.

Therefore the class is not meant to be instantiated, but rather serve as a base class. Otherwise the instance would have methods that cannot be called without raising an exception.

A constraint which some sources add is that the class may not contain data, only methods, but I don't see why this is necessary. In practice however, many useful mixins don't have any data, and base classes without data are simpler to use.

A classic example is the implementation of all comparison operators from only <= and ==:

class ComparableMixin(object):
    """This class has methods which use `<=` and `==`,
    but this class does NOT implement those methods."""
    def __ne__(self, other):
        return not (self == other)
    def __lt__(self, other):
        return self <= other and (self != other)
    def __gt__(self, other):
        return not self <= other
    def __ge__(self, other):
        return self == other or self > other

class Integer(ComparableMixin):
    def __init__(self, i):
        self.i = i
    def __le__(self, other):
        return self.i <= other.i
    def __eq__(self, other):
        return self.i == other.i

assert Integer(0) <  Integer(1)
assert Integer(0) != Integer(1)
assert Integer(1) >  Integer(0)
assert Integer(1) >= Integer(1)

# It is possible to instantiate a mixin:
o = ComparableMixin()
# but one of its methods raise an exception:
#o != o 

This particular example could have been achieved via the functools.total_ordering() decorator, but the game here was to reinvent the wheel:

import functools

@functools.total_ordering
class Integer(object):
    def __init__(self, i):
        self.i = i
    def __le__(self, other):
        return self.i <= other.i
    def __eq__(self, other):
        return self.i == other.i

assert Integer(0) < Integer(1)
assert Integer(0) != Integer(1)
assert Integer(1) > Integer(0)
assert Integer(1) >= Integer(1)

Definition 2: multiple inheritance

A mixin is a design pattern in which some method of a base class uses a method it does not define, and that method is meant to be implemented by another base class, not by the derived like in Definition 1.

The term mixin class refers to base classes which are intended to be used in that design pattern (TODO those that use the method, or those that implement it?)

It is not easy to decide if a given class is a mixin or not: the method could be just implemented on the derived class, in which case we're back to Definition 1. You have to consider the author's intentions.

This pattern is interesting because it is possible to recombine functionalities with different choices of base classes:

class HasMethod1(object):
    def method(self):
        return 1

class HasMethod2(object):
    def method(self):
        return 2

class UsesMethod10(object):
    def usesMethod(self):
        return self.method() + 10

class UsesMethod20(object):
    def usesMethod(self):
        return self.method() + 20

class C1_10(HasMethod1, UsesMethod10): pass
class C1_20(HasMethod1, UsesMethod20): pass
class C2_10(HasMethod2, UsesMethod10): pass
class C2_20(HasMethod2, UsesMethod20): pass

assert C1_10().usesMethod() == 11
assert C1_20().usesMethod() == 21
assert C2_10().usesMethod() == 12
assert C2_20().usesMethod() == 22

# Nothing prevents implementing the method
# on the base class like in Definition 1:

class C3_10(UsesMethod10):
    def method(self):
        return 3

assert C3_10().usesMethod() == 13

Authoritative Python occurrences

At the official documentatiton for collections.abc the documentation explicitly uses the term Mixin Methods.

It states that if a class:

  • implements __next__
  • inherits from a single class Iterator

then the class gets an __iter__ mixin method for free.

Therefore at least on this point of the documentation, mixin does not not require multiple inheritance, and is coherent with Definition 1.

The documentation could of course be contradictory at different points, and other important Python libraries might be using the other definition in their documentation.

This page also uses the term Set mixin, which clearly suggests that classes like Set and Iterator can be called Mixin classes.

In other languages

  • Ruby: Clearly does not require multiple inheritance for mixin, as mentioned in major reference books such as Programming Ruby and The Ruby programming Language

  • C++: A virtual method that is set =0 is a pure virtual method.

    Definition 1 coincides with the definition of an abstract class (a class that has a pure virtual method). That class cannot be instantiated.

    Definition 2 is possible with virtual inheritance: Multiple Inheritance from two derived classes

Retrieve list of tasks in a queue in Celery

If you control the code of the tasks then you can work around the problem by letting a task trigger a trivial retry the first time it executes, then checking inspect().reserved(). The retry registers the task with the result backend, and celery can see that. The task must accept self or context as first parameter so we can access the retry count.

@task(bind=True)
def mytask(self):
    if self.request.retries == 0:
        raise self.retry(exc=MyTrivialError(), countdown=1)
    ...

This solution is broker agnostic, ie. you don't have to worry about whether you are using RabbitMQ or Redis to store the tasks.

EDIT: after testing I've found this to be only a partial solution. The size of reserved is limited to the prefetch setting for the worker.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

How to select all elements with a particular ID in jQuery?

Try this for selecting div by first id

$('div[id^="c-"]')

Get next element in foreach loop

The general solution could be a caching iterator. A properly implemented caching iterator works with any Iterator, and saves memory. PHP SPL has a CachingIterator, but it is very odd, and has very limited functionality. However, you can write your own lookahead iterator like this:

<?php

class NeighborIterator implements Iterator
{

    protected $oInnerIterator;

    protected $hasPrevious = false;
    protected $previous = null;
    protected $previousKey = null;

    protected $hasCurrent = false;
    protected $current = null;
    protected $currentKey = null;

    protected $hasNext = false;
    protected $next = null;
    protected $nextKey = null;

    public function __construct(Iterator $oInnerIterator)
    {
        $this->oInnerIterator = $oInnerIterator;
    }

    public function current()
    {
        return $this->current;
    }

    public function key()
    {
        return $this->currentKey;
    }

    public function next()
    {
        if ($this->hasCurrent) {
            $this->hasPrevious = true;
            $this->previous = $this->current;
            $this->previousKey = $this->currentKey;
            $this->hasCurrent = $this->hasNext;
            $this->current = $this->next;
            $this->currentKey = $this->nextKey;
            if ($this->hasNext) {
                $this->oInnerIterator->next();
                $this->hasNext = $this->oInnerIterator->valid();
                if ($this->hasNext) {
                    $this->next = $this->oInnerIterator->current();
                    $this->nextKey = $this->oInnerIterator->key();
                } else {
                    $this->next = null;
                    $this->nextKey = null;
                }
            }
        }
    }

    public function rewind()
    {
        $this->hasPrevious = false;
        $this->previous = null;
        $this->previousKey = null;
        $this->oInnerIterator->rewind();
        $this->hasCurrent = $this->oInnerIterator->valid();
        if ($this->hasCurrent) {
            $this->current = $this->oInnerIterator->current();
            $this->currentKey = $this->oInnerIterator->key();
            $this->oInnerIterator->next();
            $this->hasNext = $this->oInnerIterator->valid();
            if ($this->hasNext) {
                $this->next = $this->oInnerIterator->current();
                $this->nextKey = $this->oInnerIterator->key();
            } else {
                $this->next = null;
                $this->nextKey = null;
            }
        } else {
            $this->current = null;
            $this->currentKey = null;
            $this->hasNext = false;
            $this->next = null;
            $this->nextKey = null;
        }
    }

    public function valid()
    {
        return $this->hasCurrent;
    }

    public function hasNext()
    {
        return $this->hasNext;
    }

    public function getNext()
    {
        return $this->next;
    }

    public function getNextKey()
    {
        return $this->nextKey;
    }

    public function hasPrevious()
    {
        return $this->hasPrevious;
    }

    public function getPrevious()
    {
        return $this->previous;
    }

    public function getPreviousKey()
    {
        return $this->previousKey;
    }

}


header("Content-type: text/plain; charset=utf-8");
$arr = [
    "a" => "alma",
    "b" => "banan",
    "c" => "cseresznye",
    "d" => "dio",
    "e" => "eper",
];
$oNeighborIterator = new NeighborIterator(new ArrayIterator($arr));
foreach ($oNeighborIterator as $key => $value) {

    // you can get previous and next values:

    if (!$oNeighborIterator->hasPrevious()) {
        echo "{FIRST}\n";
    }
    echo $oNeighborIterator->getPreviousKey() . " => " . $oNeighborIterator->getPrevious() . " ----->        ";
    echo "[ " . $key . " => " . $value . " ]        -----> ";
    echo $oNeighborIterator->getNextKey() . " => " . $oNeighborIterator->getNext() . "\n";
    if (!$oNeighborIterator->hasNext()) {
        echo "{LAST}\n";
    }
}

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

POSTing JSON to URL via WebClient in C#

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

In my case there was problem in URL. I've use https://example.com - but they ensure 'www.' - so when i switched to https://www.example.com everything was ok. The proper header was sent 'Host: www.example.com'.

You can try make a request in firefox brwoser, persist it and copy as cURL - that how I've found it.

AssertNull should be used or AssertNotNull

The assertNotNull() method means "a passed parameter must not be null": if it is null then the test case fails.
The assertNull() method means "a passed parameter must be null": if it is not null then the test case fails.

String str1 = null;
String str2 = "hello";              

// Success.
assertNotNull(str2);

// Fail.
assertNotNull(str1);

// Success.
assertNull(str1);

// Fail.
assertNull(str2);

Draw a line in a div

Answered this just to emphasize @rblarsen comment on question :

You don't need the style tags in the CSS-file

If you remove the style tag from your css file it will work.

How do I find out what version of Sybase is running

1)From OS level(UNIX):-

dataserver -v

2)From Syabse isql:-

select @@version
go

sp_version
go

node.js string.replace doesn't work?

If you just want to clobber all of the instances of a substring out of a string without using regex you can using:

    var replacestring = "A B B C D"
    const oldstring = "B";
    const newstring = "E";
    while (replacestring.indexOf(oldstring) > -1) {
        replacestring = replacestring.replace(oldstring, newstring);
    }        
    //result: "A E E C D"

Example to use shared_ptr?

Learning to use smart pointers is in my opinion one of the most important steps to become a competent C++ programmer. As you know whenever you new an object at some point you want to delete it.

One issue that arise is that with exceptions it can be very hard to make sure a object is always released just once in all possible execution paths.

This is the reason for RAII: http://en.wikipedia.org/wiki/RAII

Making a helper class with purpose of making sure that an object always deleted once in all execution paths.

Example of a class like this is: std::auto_ptr

But sometimes you like to share objects with other. It should only be deleted when none uses it anymore.

In order to help with that reference counting strategies have been developed but you still need to remember addref and release ref manually. In essence this is the same problem as new/delete.

That's why boost has developed boost::shared_ptr, it's reference counting smart pointer so you can share objects and not leak memory unintentionally.

With the addition of C++ tr1 this is now added to the c++ standard as well but its named std::tr1::shared_ptr<>.

I recommend using the standard shared pointer if possible. ptr_list, ptr_dequeue and so are IIRC specialized containers for pointer types. I ignore them for now.

So we can start from your example:

std::vector<gate*> G; 
G.push_back(new ANDgate);  
G.push_back(new ORgate); 
for(unsigned i=0;i<G.size();++i) 
{ 
  G[i]->Run(); 
} 

The problem here is now that whenever G goes out scope we leak the 2 objects added to G. Let's rewrite it to use std::tr1::shared_ptr

// Remember to include <memory> for shared_ptr
// First do an alias for std::tr1::shared_ptr<gate> so we don't have to 
// type that in every place. Call it gate_ptr. This is what typedef does.
typedef std::tr1::shared_ptr<gate> gate_ptr;    
// gate_ptr is now our "smart" pointer. So let's make a vector out of it.
std::vector<gate_ptr> G; 
// these smart_ptrs can't be implicitly created from gate* we have to be explicit about it
// gate_ptr (new ANDgate), it's a good thing:
G.push_back(gate_ptr (new ANDgate));  
G.push_back(gate_ptr (new ORgate)); 
for(unsigned i=0;i<G.size();++i) 
{ 
   G[i]->Run(); 
} 

When G goes out of scope the memory is automatically reclaimed.

As an exercise which I plagued newcomers in my team with is asking them to write their own smart pointer class. Then after you are done discard the class immedietly and never use it again. Hopefully you acquired crucial knowledge on how a smart pointer works under the hood. There's no magic really.

How to iterate over the keys and values with ng-repeat in AngularJS?

we can follow below procedure to avoid display of key-values in alphabetical order.

Javascript

$scope.data = {
   "id": 2,
   "project": "wewe2012",
   "date": "2013-02-26",
   "description": "ewew",
   "eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
    var test = {};
    test[key]=$scope.data[key];
    array.push(test);
}
$scope.data = array;

HTML

<p ng-repeat="obj in data">
   <font ng-repeat="(key, value) in obj">
      {{key}} : {{value}}
   </font>
</p>

Use cases for the 'setdefault' dict method

The different use case for setdefault() is when you don't want to overwrite the value of an already set key. defaultdict overwrites, while setdefault() does not. For nested dictionaries it is more often the case that you want to set a default only if the key is not set yet, because you don't want to remove the present sub dictionary. This is when you use setdefault().

Example with defaultdict:

>>> from collection import defaultdict()
>>> foo = defaultdict()
>>> foo['a'] = 4
>>> foo['a'] = 2
>>> print(foo)
defaultdict(None, {'a': 2})

setdefault doesn't overwrite:

>>> bar = dict()
>>> bar.setdefault('a', 4)
>>> bar.setdefault('a', 2)
>>> print(bar)
{'a': 4}

A JOIN With Additional Conditions Using Query Builder or Eloquent

The sql query sample like this

LEFT JOIN bookings  
    ON rooms.id = bookings.room_type_id
    AND (bookings.arrival = ?
        OR bookings.departure = ?)

Laravel join with multiple conditions

->leftJoin('bookings', function($join) use ($param1, $param2) {
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(function($query) use ($param1, $param2) {
        $query->on('bookings.arrival', '=', $param1);
        $query->orOn('departure', '=',$param2);
    });
})

SyntaxError: Use of const in strict mode?

I had a similar issue recently and ended up in this Q&A. This is not the solution the OP was looking for but may help others with a similar issue.

I'm using PM2 to run a project and in a given staging server I had a really old version of Node, NPM and PM2. I updated everything, however, I kept keeping the same error:

SyntaxError: Use of const in strict mode.

I tried to stop and start the application several times. Also tried to update everything again. Nothing worked. Until I noticed a warning when I ran pm2 start:

>>>> In-memory PM2 is out-of-date, do:
>>>> $ pm2 update
In memory PM2 version: 0.15.10
Local PM2 version: 3.2.9

Gotcha! After running pm2 update, I finally was able to get the application running as expected. No "const in strict mode" errors anymore.

How to discard uncommitted changes in SourceTree?

On SourceTree for Mac, right click the files you want to discard (in the Files in the working tree list), and choose Reset.

On SourceTree for Windows, right click the files you want to discard (in the Working Copy Changes list), and choose Discard.

On git, you'd simply do:

git reset --hard to discard changes made to versioned files;

git clean -xdf to erase new (untracked) files, including ignored ones (the x option). d is to also remove untracked directories and f to force.

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:

Math.Truncate(number)

and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

What version of MongoDB is installed on Ubuntu

ANSWER: Read the instructions #dua

Ok the magic was in this line that I apparently missed when installing was:

$ sudo apt-get install mongodb-10gen=2.4.6

And the full process as described here http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ is

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
$ sudo apt-get update
$ sudo apt-get install mongodb-10gen
$ sudo apt-get install mongodb-10gen=2.2.3
$ echo "mongodb-10gen hold" | sudo dpkg --set-selections
$ sudo service mongodb start

$ mongod --version
db version v2.4.6
Wed Oct 16 12:21:39.938 git version: b9925db5eac369d77a3a5f5d98a145eaaacd9673

IMPORTANT: Make sure you change 2.4.6 to the latest version (or whatever you want to install). Find the latest version number here http://www.mongodb.org/downloads

syntax error when using command line in python

I faced a similar problem, on my Windows computer, please do check that you have set the Environment Variables correctly.

To check that Environment variable is set correctly:

  1. Open cmd.exe

  2. Type Python and press return

  3. (a) If it outputs the version of python then the environment variables are set correctly.

    (b) If it outputs "no such program or file name" then your environment variable are not set correctly.

To set environment variable:

  1. goto Computer-> System Properties-> Advanced System Settings -> Set Environment Variables
  2. Goto path in the system variables; append ;C:\Python27 in the end.

If you have correct variables already set; then you are calling the file inside the python interpreter.

Remove border from buttons

You can also try background:none;border:0px to buttons.

also the css selectors are div#yes button{..} and div#no button{..} . hopes it helps

How do I get the MAX row with a GROUP BY in LINQ query?

The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:

from x in db.Serials 
group x by x.Serial_Number into g 
orderby g.Key 
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()

... this will avoid the "select new"

What's the difference between commit() and apply() in SharedPreferences

The docs give a pretty good explanation of the difference between apply() and commit():

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself. As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

Run a Python script from another Python script, passing in arguments

Try using os.system:

os.system("script2.py 1")

execfile is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv didn't change for you.

Convenient C++ struct initialisation

For versions of C++ prior to C++20 (which introduces the named initialization, making your option A valid in C++), consider the following:

int main()
{
    struct TFoo { int val; };
    struct TBar { float val; };

    struct FooBar {
        TFoo foo;
        TBar bar;
    };

    FooBar mystruct = { TFoo{12}, TBar{3.4} };

    std::cout << "foo = " << mystruct.foo.val << " bar = " << mystruct.bar.val << std::endl;

}

Note that if you try to initialize the struct with FooBar mystruct = { TFoo{12}, TFoo{3.4} }; you will get a compilation error.

The downside is that you have to create one additional struct for each variable inside your main struct, and also you have to use the inner value with mystruct.foo.val. But on the other hand, it`s clean, simple, pure and standard.

Disable F5 and browser refresh using JavaScript

If you want to disable ctrl+f5 , ctrl+R , f5 ,backspace then you can use this simple code. This code is working in Mozila as well as Chrome . Add this code inside your body tag:

<body onkeydown="return (event.keyCode == 154)">

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

Add header:

#include<math.h>

Note: use abs(), sometimes at the time of evaluation sqrt() can take negative values which leave to domain error.

abs()- provides absolute values;

example, abs(-3) =3

Include -lm at the end of your command during compilation time:

gcc <filename.extension> -lm

How do I get time of a Python program's execution?

To use metakermit's updated answer for Python 2.7, you will require the monotonic package.

The code would then be as follows:

from datetime import timedelta
from monotonic import monotonic

start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))

Convert a String to int?

You can use the FromStr trait's from_str method, which is implemented for i32:

let my_num = i32::from_str("9").unwrap_or(0);

Why does IE9 switch to compatibility mode on my website?

As an aside on more modern websites, if you are using conditional statements on your html tag as per boilerplate, this will for some reason cause ie9 to default to compatibility mode. The fix here is to move your conditional statements off the html tag and add them to the body tag, in other words out of the head section. That way you can still use those classes in your style sheet to target older browsers.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

Try opening Visual Studio with Administrator privileges. In my case, it gave access to the IIS site and made this error go away. I was then able to switch the project to use IIS Express which doesn't seem to need administrator privileges.

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

The problem is that once the page is served up, the content is going to be in the encoding described in the content-type meta tag. The content in "wrong" encoding is already garbled.

You're best to do this on the server before serving up the page. Or as I have been know to say: UTF-8 end-to-end or die.

ASP.NET MVC controller actions that return JSON or partial html

PartialViewResult and JSONReuslt inherit from the base class ActionResult. so if return type is decided dynamically declare method output as ActionResult.

public ActionResult DynamicReturnType(string parameter)
        {
            if (parameter == "JSON")
                return Json("<JSON>", JsonRequestBehavior.AllowGet);
            else if (parameter == "PartialView")
                return PartialView("<ViewName>");
            else
                return null;


        }

Remove the first character of a string

Just do this:

r = "hello"
r = r[1:]
print(r) # ello

Remove non-utf8 characters from string

I have made a function that deletes invalid UTF-8 characters from a string. I'm using it to clear description of 27000 products before it generates the XML export file.

public function stripInvalidXml($value) {
    $ret = "";
    $current;
    if (empty($value)) {
        return $ret;
    }
    $length = strlen($value);
    for ($i=0; $i < $length; $i++) {
        $current = ord($value{$i});
        if (($current == 0x9) || ($current == 0xA) || ($current == 0xD) || (($current >= 0x20) && ($current <= 0xD7FF)) || (($current >= 0xE000) && ($current <= 0xFFFD)) || (($current >= 0x10000) && ($current <= 0x10FFFF))) {
                $ret .= chr($current);
        }
        else {
            $ret .= "";
        }
    }
    return $ret;
}

When should we implement Serializable interface?

  1. From What's this "serialization" thing all about?:

    It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).

    Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."

    So, implement the Serializable interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.

  2. Because you want to store or send an object.

  3. It makes storing and sending objects easy. It has nothing to do with security.

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

Problem 1 : Different applications use different scales for HSV. For example gimp uses H = 0-360, S = 0-100 and V = 0-100. But OpenCV uses H: 0-179, S: 0-255, V: 0-255. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255).

Problem 2: And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows:

cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)

Now run it. I got an output as follows:

enter image description here

Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid.

EDIT:

As Karl Philip told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new cv2 module, so users can compare the easiness and flexibility of new cv2 module.

import cv2
import numpy as np

img = cv2.imread('sof.jpg')

ORANGE_MIN = np.array([5, 50, 50],np.uint8)
ORANGE_MAX = np.array([15, 255, 255],np.uint8)

hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
cv2.imwrite('output2.jpg', frame_threshed)

It gives the same result as above. But code is much more simpler.

Make EditText ReadOnly

My approach to this has been creating a custom TextWatcher class as follows:

class ReadOnlyTextWatcher implements TextWatcher {
    private final EditText textEdit;
    private String originalText;
    private boolean mustUndo = true;

    public ReadOnlyTextWatcher(EditText textEdit) {
        this.textEdit = textEdit;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (mustUndo) {
            originalText = charSequence.toString();
        }
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (mustUndo) {
            mustUndo = false;
            textEdit.setText(originalText);
        } else {
            mustUndo = true;
        }
    }
}

Then you just add that watcher to any field you want to be read only despite being enabled:

editText.addTextChangedListener(new ReadOnlyTextWatcher(editText));

Resizing Images in VB.NET

    Dim x As Integer = 0
    Dim y As Integer = 0
    Dim k = 0
    Dim l = 0
    Dim bm As New Bitmap(p1.Image)
    Dim om As New Bitmap(p1.Image.Width, p1.Image.Height)
    Dim r, g, b As Byte
    Do While x < bm.Width - 1
        y = 0
        l = 0
        Do While y < bm.Height - 1
            r = 255 - bm.GetPixel(x, y).R
            g = 255 - bm.GetPixel(x, y).G
            b = 255 - bm.GetPixel(x, y).B
            om.SetPixel(k, l, Color.FromArgb(r, g, b))
            y += 3
            l += 1
        Loop
        x += 3
        k += 1
    Loop
    p2.Image = om

How to stop process from .BAT file?

When you start a process from a batch file, it starts as a separate process with no hint towards the batch file that started it (since this would have finished running in the meantime, things like the parent process ID won't help you).

If you know the process name, and it is unique among all running processes, you can use taskkill, like @IVlad suggests in a comment.

If it is not unique, you might want to look into jobs. These terminate all spawned child processes when they are terminated.

Docker-Compose can't connect to Docker Daemon

I had this problem and did not want to mess things up using sudo. When investigating, I tried to get some info :

docker info

Surprinsingly, I had the following error :

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http:///var/run/docker.sock/v1.38/info: dial unix /var/run/docker.sock: connect: permission denied

For some reason I did not have enough privileges, the following command solved my problem :

sudo chown $USER /var/run/docker.sock

Et voilà !

How to get the absolute coordinates of a view

Get Both View Position and Dimension on screen

val viewTreeObserver: ViewTreeObserver = videoView.viewTreeObserver;

    if (viewTreeObserver.isAlive) {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                //Remove Listener
                videoView.viewTreeObserver.removeOnGlobalLayoutListener(this);
                
                //View Dimentions
                viewWidth = videoView.width;
                viewHeight = videoView.height;

                //View Location
                val point = IntArray(2)
                videoView.post {
                    videoView.getLocationOnScreen(point) // or getLocationInWindow(point)
                    viewPositionX = point[0]
                    viewPositionY = point[1]
                }

            }
        });
    }

Detect Browser Language in PHP

The official way to handle this is using the PECL HTTP library. Unlike some answers here, this correctly handles the language priorities (q-values), partial language matches and will return the closest match, or when there are no matches it falls back to the first language in your array.

PECL HTTP:
http://pecl.php.net/package/pecl_http

How to use:
http://php.net/manual/fa/function.http-negotiate-language.php

$supportedLanguages = [
    'en-US', // first one is the default/fallback
    'fr',
    'fr-FR',
    'de',
    'de-DE',
    'de-AT',
    'de-CH',
];

// Returns the negotiated language 
// or the default language (i.e. first array entry) if none match.
$language = http_negotiate_language($supportedLanguages, $result);

How to change Label Value using javascript

very simple

$('#label-ID').text("label value which you want to set");

How to force uninstallation of windows service

sc delete sericeName

Just make sure the service is stopped before doing this. I have seen this work most times. There are times where I have seen windows get stuck on something and it insists on a reboot.

jQuery toggle CSS?

The best option would be to set a class style in CSS like .showMenu and .hideMenu with the various styles inside. Then you can do something like

$("#user_button").addClass("showMenu"); 

Byte and char conversion in Java

new String(byteArray, Charset.defaultCharset())

This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.

How can I reset or revert a file to a specific revision?

Here is my way.

a) In Android Studio, open the file.

b) git -> Show History, find the previous commit I want to revert to. Get the commit_id (i.e. commit hash).

c) git checkout commit_id file_path

How can I remove an element from a list?

If you have a named list and want to remove a specific element you can try:

lst <- list(a = 1:4, b = 4:8, c = 8:10)

if("b" %in% names(lst)) lst <- lst[ - which(names(lst) == "b")]

This will make a list lst with elements a, b, c. The second line removes element b after it checks that it exists (to avoid the problem @hjv mentioned).

or better:

lst$b <- NULL

This way it is not a problem to try to delete a non-existent element (e.g. lst$g <- NULL)

Hibernate: get entity by id

use get instead of load

// ...
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            user =  (User) session.get(User.class, user_id);
        } catch (Exception e) {
 // ...

Replace given value in vector

Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")

replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

The most useful thing you can do here is display/i $pc, before using stepi as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi command.

(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

How to change package name in flutter?

Change App Package Name with single command by using following package. It makes the process very easy and fast.

flutter pub run change_app_package_name:main com.new.package.name

https://pub.dev/packages/change_app_package_name

Angular ForEach in Angular4/Typescript?

in angular4 foreach like that. try this.

 selectChildren(data, $event) {
      let parentChecked = data.checked;
       this.hierarchicalData.forEach(obj => {
          obj.forEach(childObj=> {
            value.checked = parentChecked;
         });
      });
    }

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

Create a shortcut with something like this as the "Target":

powershell.exe -command "& 'C:\A path with spaces\MyScript.ps1' -MyArguments blah"

Scroll back to the top of scrollable div

scrollTo

window.scrollTo(0, 0);

is the ultimate solution for scrolling the windows to the top - the best part is that it does not require any id selector and even if we use the IFRAME structure it will work extremely well.

The scrollTo() method scrolls the document to the specified coordinates.
window.scrollTo(xpos, ypos);
xpos Number Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
ypos Number Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

jQuery

Another option to do the same is using jQuery and it will give a smoother look for the same

$('html,body').animate({scrollTop: 0}, 100);

where 0 after the scrollTop specifies the vertical scrollbar position in the pixel and second parameter is an optional parameter which shows the time in microseconds to complete the task.

Why Choose Struct Over Class?

As struct are value types and you can create the memory very easily which stores into stack.Struct can be easily accessible and after the scope of the work it's easily deallocated from the stack memory through pop from the top of the stack. On the other hand class is a reference type which stores in heap and changes made in one class object will impact to other object as they are tightly coupled and reference type.All members of a structure are public whereas all the members of a class are private.

The disadvantages of struct is that it can't be inherited .

Carriage return in C?

From 5.2.2/2 (character display semantics) :

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n (new line) Moves the active position to the initial position of the next line.

\r (carriage return) Moves the active position to the initial position of the current line.

Here, your code produces :

  • <new_line>ab
  • \b : back one character
  • write si : overrides the b with s (producing asi on the second line)
  • \r : back at the beginning of the current line
  • write ha : overrides the first two characters (producing hai on the second line)

In the end, the output is :

\nhai

What is a non-capturing group in regular expressions?

Groups that capture you can use later on in the regex to match OR you can use them in the replacement part of the regex. Making a non-capturing group simply exempts that group from being used for either of these reasons.

Non-capturing groups are great if you are trying to capture many different things and there are some groups you don't want to capture.

Thats pretty much the reason they exist. While you are learning about groups, learn about Atomic Groups, they do a lot! There is also lookaround groups but they are a little more complex and not used so much.

Example of using later on in the regex (backreference):

<([A-Z][A-Z0-9]*)\b[^>]*>.*?</\1> [ Finds an xml tag (without ns support) ]

([A-Z][A-Z0-9]*) is a capturing group (in this case it is the tagname)

Later on in the regex is \1 which means it will only match the same text that was in the first group (the ([A-Z][A-Z0-9]*) group) (in this case it is matching the end tag).

Get the date (a day before current time) in Bash

Advanced Bash-scripting Guide

date +%Y:%m:%d -d "yesterday"

For details about the date format see the man page for date

date --date='-1 day'

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Regular expression to extract text between square brackets

The @Tim Pietzcker's answer here

(?<=\[)[^]]+(?=\])

is almost the one I've been looking for. But there is one issue that some legacy browsers can fail on positive lookbehind. So I had to made my day by myself :). I manged to write this:

/([^[]+(?=]))/g

Maybe it will help someone.

_x000D_
_x000D_
console.log("this is a [sample] string with [some] special words. [another one]".match(/([^[]+(?=]))/g));
_x000D_
_x000D_
_x000D_

Route [login] not defined

Laravel has introduced Named Routes in Laravel 4.2.

WHAT IS NAMED ROUTES?

Named Routes allows you to give names to your router path. Hence using the name we can call the routes in required file.


HOW TO CREATE NAMED ROUTES?

Named Routes created in two different way : as and name()

METHOD 1:

Route::get('about',array('as'=>'about-as',function()
    {
            return view('about');
     }
));

METHOD 2:

 Route::get('about',function()
{
 return view('about');
})->name('about-as');

How we use in views?

<a href="{{ URL::route("about-as") }}">about-as</a>

Hence laravel 'middleware'=>'auth' has already predefined for redirect as login page if user has not yet logged in.Hence we should use as keyword

    Route::get('login',array('as'=>'login',function(){
    return view('login');
}));

How to validate an Email in PHP?

I always use this:

function validEmail($email){
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
            return false;
        }
    }
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
                return false;
            }
        }
    }

    return true;
}

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

ERROR in Cannot find module 'node-sass'

In my case I had to also had to perform:

npm install sass-loader

To fix the problem

Minimum 6 characters regex expression

Something along the lines of this?

<asp:TextBox id="txtUsername" runat="server" />

<asp:RegularExpressionValidator
    id="RegularExpressionValidator1"
    runat="server"
    ErrorMessage="Field not valid!"
    ControlToValidate="txtUsername"
    ValidationExpression="[0-9a-zA-Z]{6,}" />

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

Why can't I have "public static const string S = "stuff"; in my Class?

From the C# language specification (PDF page 287 - or 300th page of the PDF):

Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.

How to decode a QR-code image in (preferably pure) Python?

There is a library called BoofCV which claims to better than ZBar and other libraries.
Here are the steps to use that (any OS).

Pre-requisites:

  • Ensure JDK 14+ is installed and set in $PATH
  • pip install pyboof

Class to decode:

import os
import numpy as np
import pyboof as pb

pb.init_memmap() #Optional

class QR_Extractor:
    # Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
    def __init__(self):
        self.detector = pb.FactoryFiducial(np.uint8).qrcode()
    
    def extract(self, img_path):
        if not os.path.isfile(img_path):
            print('File not found:', img_path)
            return None
        image = pb.load_single_band(img_path, np.uint8)
        self.detector.detect(image)
        qr_codes = []
        for qr in self.detector.detections:
            qr_codes.append({
                'text': qr.message,
                'points': qr.bounds.convert_tuple()
            })
        return qr_codes

Usage:

qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)

Tested and works on Python 3.8 (Windows & Ubuntu)

How to include quotes in a string

I use:

var value = "'Field1','Field2','Field3'".Replace("'", "\""); 

as opposed to the equivalent

var value = "\"Field1\",\"Field2\",\"Field3\"";

Because the former has far less noise than the latter, making it easier to see typo's etc.

I use it a lot in unit tests.

Does Python SciPy need BLAS?

For Windows users there is a nice binary package by Chris (warning: it's a pretty large download, 191 MB):

MySQL Where DateTime is greater than today

SELECT * 
FROM customer 
WHERE joiningdate >= NOW();

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

If you are using the package device_id to get the unique device id then that will add an android.permission.READ_PHONE_STATE without your knowledge which eventually will lead to the Play Store warning.

Instead you can use the device_info package for the same purpose without the need of the extra permission. Check this SO thread

How to set the height of an input (text) field in CSS?

You should use font-size for controlling the height, it is widely supported amongst browsers. And in order to add spacing, you should use padding. Forexample,

.inputField{
  font-size: 30px;
  padding-top: 10px;
  padding-bottom: 10px;
}

ORA-00904: invalid identifier

FYI, in this case the cause was found to be mixed case column name in the DDL for table creation.

However, if you are mixing "old style" and ANSI joins you could get the same error message even when the DDL was done properly with uppercase table name. This happened to me, and google sent me to this stackoverflow page so I thought I'd share since I was here.

--NO PROBLEM: ANSI syntax
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM PS_PERSON A
INNER JOIN PS_NAME_PWD_VW B ON B.EMPLID = A.EMPLID
INNER JOIN PS_HCR_PERSON_NM_I C ON C.EMPLID = A.EMPLID
WHERE 
    LENGTH(A.EMPLID) = 9
    AND LENGTH(B.LAST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
ORDER BY 1, 2, 3
/

--NO PROBLEM: OLD STYLE/deprecated/traditional oracle proprietary join syntax
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM PS_PERSON A
, PS_NAME_PWD_VW B 
, PS_HCR_PERSON_NM_I C 
WHERE 
    B.EMPLID = A.EMPLID
    and C.EMPLID = A.EMPLID
    and LENGTH(A.EMPLID) = 9
    AND LENGTH(B.LAST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
ORDER BY 1, 2, 3
/

The two SQL statements above are equivalent and produce no error.

When you try to mix them you can get lucky, or you can get an Oracle has a ORA-00904 error.

--LUCKY: mixed syntax (ANSI joins appear before OLD STYLE)
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM 
    PS_PERSON A
    inner join PS_HCR_PERSON_NM_I C on C.EMPLID = A.EMPLID
    , PS_NAME_PWD_VW B
WHERE 
    B.EMPLID = A.EMPLID
    and LENGTH(A.EMPLID) = 9
    AND LENGTH(B.FIRST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
/

--PROBLEM: mixed syntax (OLD STYLE joins appear before ANSI)
--http://sqlfascination.com/2013/08/17/oracle-ansi-vs-old-style-joins/
SELECT A.EMPLID, B.FIRST_NAME, C.LAST_NAME
FROM 
    PS_PERSON A
    , PS_NAME_PWD_VW B
    inner join PS_HCR_PERSON_NM_I C on C.EMPLID = A.EMPLID
WHERE 
    B.EMPLID = A.EMPLID
    and LENGTH(A.EMPLID) = 9
    AND LENGTH(B.FIRST_NAME) > 5
    AND LENGTH(C.LAST_NAME) > 5
/

And the unhelpful error message that doesn't really describe the problem at all:

>[Error] Script lines: 1-12 -------------------------
ORA-00904: "A"."EMPLID": invalid identifier  Script line 6, statement line 6,
column 51 

I was able to find some research on this in the following blog post:

In my case, I was attempting to manually convert from old style to ANSI style joins, and was doing so incrementally, one table at a time. This appears to have been a bad idea. Instead, it's probably better to convert all tables at once, or comment out a table and its where conditions in the original query in order to compare with the new ANSI query you are writing.

Maintaining the final state at end of a CSS3 animation

If you are using more animation attributes the shorthand is:

animation: bubble 2s linear 0.5s 1 normal forwards;

This gives:

  • bubble animation name
  • 2s duration
  • linear timing-function
  • 0.5s delay
  • 1 iteration-count (can be 'infinite')
  • normal direction
  • forwards fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})

Add line break to ::after or ::before pseudo-element content

I had to have new lines in a tooltip. I had to add this CSS on my :after :

.tooltip:after {
  width: 500px;
  white-space: pre;
  word-wrap: break-word;
}

The word-wrap seems necessary.

In addition, the \A didn't work in the middle of the text to display, to force a new line.

 &#13;&#10; 

worked. I was then able to get such a tooltip :

enter image description here

regular expression: match any word until first space

Derived from the answer of @SilentGhost I would use:

^([\S]+)

Check out this interactive regexr.com page to see the result and explanation for the suggested solution.

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

Check if a div does NOT exist with javascript

var myElem = document.getElementById('myElementId');
if (myElem === null) alert('does not exist!');

AppFabric installation failed because installer MSI returned with error code : 1603

In my case it was a localgroup which was already existed through a previous install. Removing localgroup (AS_Observers) resolved my issue.

net localgroup AS_Observers /delete

hope this might help someone.

How can I convert uppercase letters to lowercase in Notepad++

First select the text
To convert lowercase to uppercase, press Ctrl+Shift+U
To convert uppercase to lowercase, press Ctrl+U

Creating a simple XML file using python

Yattag http://www.yattag.org/ or https://github.com/leforestier/yattag provides an interesting API to create such XML document (and also HTML documents).

It's using context manager and with keyword.

from yattag import Doc, indent

doc, tag, text = Doc().tagtext()

with tag('root'):
    with tag('doc'):
        with tag('field1', name='blah'):
            text('some value1')
        with tag('field2', name='asdfasd'):
            text('some value2')

result = indent(
    doc.getvalue(),
    indentation = ' '*4,
    newline = '\r\n'
)

print(result)

so you will get:

<root>
    <doc>
        <field1 name="blah">some value1</field1>
        <field2 name="asdfasd">some value2</field2>
    </doc>
</root>

Fast Linux file count for a large number of files

You can change the output based on your requirements, but here is a Bash one-liner I wrote to recursively count and report the number of files in a series of numerically named directories.

dir=/tmp/count_these/ ; for i in $(ls -1 ${dir} | sort -n) ; { echo "$i => $(find ${dir}${i} -type f | wc -l),"; }

This looks recursively for all files (not directories) in the given directory and returns the results in a hash-like format. Simple tweaks to the find command could make what kind of files you're looking to count more specific, etc.

It results in something like this:

1 => 38,
65 => 95052,
66 => 12823,
67 => 10572,
69 => 67275,
70 => 8105,
71 => 42052,
72 => 1184,

fatal error LNK1169: one or more multiply defined symbols found in game programming

You can't put variable definitions in header files, as these will then be a part of all source file you include the header into.

The #pragma once is just to protect against multiple inclusions in the same source file, not against multiple inclusions in multiple source files.

You could declare the variables as extern in the header file, and then define them in a single source file. Or you could declare the variables as const in the header file and then the compiler and linker will manage it.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

If you are using Maven you may have both src/{main,test}/resources/META-INF/persistence.xml. This is a common setup: test your JPA code with h2 or Derby and deploy it with PostgreSQL or some other full DBMS. If you're using this pattern, do make sure the two files have different unit names, else some versions of the Persistence class will try to load BOTH (because of course your test-time CLASSPATH includes both classes and test-classes); this will cause conflicting definitions of the persistence unit, resulting in the dreaded annoying message that we all hate so much!

Worse: this may "work" with some older versions of e.g., Hibernate, but fail with current versions. Worth getting it right anyway...

How can I return an empty IEnumerable?

I think the simplest way would be

 return new Friend[0];

The requirements of the return are merely that the method return an object which implements IEnumerable<Friend>. The fact that under different circumstances you return two different kinds of objects is irrelevant, as long as both implement IEnumerable.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Can you create nested WITH clauses for Common Table Expressions?

With does not work embedded, but it does work consecutive

;WITH A AS(
...
),
B AS(
...
)
SELECT *
FROM A
UNION ALL
SELECT *
FROM B

EDIT Fixed the syntax...

Also, have a look at the following example

SQLFiddle DEMO

When a 'blur' event occurs, how can I find out which element focus went *to*?

The type FocusEvent instances have relatedTarget attribute, however, up to version 47 of the FF, specifically, this attribute returns null, from 48 already works.

You can to see more here.

failed to find target with hash string android-23

For me the problem was in that I wrote compileSdkVersion '23' instead of 23. The quotes were the problem.

Asynchronous Function Call in PHP

There is also http v2 which is a wrapper for curl. Can be installed via pecl.

http://devel-m6w6.rhcloud.com/mdref/http/

What is the "-->" operator in C/C++?

-- is the decrement operator and > is the greater-than operator.

The two operators are applied as a single one like -->.

How to start up spring-boot application via command line?

You will need to build the jar file first. Here is the syntax to run the main class from a jar file.

java -jar path/to/your/jarfile.jar fully.qualified.package.Application 

JWT refresh token flow

Below are the steps to do revoke your JWT access token:

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
  5. Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
  6. Once the refresh token is expired, the User will be logged out.

Please let me know if you need more details, I can share the code (Java + Spring boot) as well.

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

Setting up PostgreSQL ODBC on Windows

As I see PostgreSQL installer doesn't include 64 bit version of ODBC driver, which is necessary in your case. Download psqlodbc_09_00_0310-x64.zip and install it instead. I checked that on Win 7 64 bit and PostgreSQL 9.0.4 64 bit and it looks ok:

enter image description here

Test connection:

enter image description here

How can a file be copied?

For small files and using only python built-ins, you can use the following one-liner:

with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())

As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

http://developer.android.com/tools/support-library/setup.html has a bug. In Property->Java build path->'Project' and 'Order and Export', there should not be any jar's. Removing them, and checking 'Android Private Libraries' and 'Android Dependencies' solved my problem.

How to get certain commit from GitHub project

Sivan's answer in gif enter image description here

1.Click on commits in github

2.Select Browse code on the right side of each commit

3.Click on download zip , which will download source code at that point of time of commit

Bootstrap modal appearing under background

Hi I had the same issue then I realize that when you using bootsrap 3.1 Unlike in older versions of bootsrap (2.3.2) the html structure of the modal was changed!

you must wrap your modal header body and footer with modal-dialog and modal-content

<div class="modal hide fade">

  <div class="modal-dialog">
    <div class="modal-content">

    **here goes the modal header body and footer**

    </div>
  </div>

 </div>

Create a new line in Java's FileWriter

I would tackle the problem like this:

    BufferedWriter output;
    output = new BufferedWriter(new FileWriter("file.txt", true));
    String sizeX = jTextField1.getText();
    String sizeY = jTextField2.getText();
    output.append(sizeX);
    output.append(sizeY);
    output.newLine();
    output.close();

The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?

How to add "Maven Managed Dependencies" library in build path eclipse?

I have the same issue using SpringSource Tool Suite. I was importing an existing Maven project which ran fine from the command line. However, when I imported the project using import -> Maven -> existing Maven project, the project did not import correctly import and I could not add the maven managed dependencies library to the build path.

If I ran mvn install from the command line the project built successfully. If I ran mvn eclipse:eclipse and then imported into STS, then everything worked as expected, except of course I'd have to re-run this every time I updated the pom, which was undesirable.

I worked around it by running mvn eclipse:eclipse and then manually updating .classpath to eliminate the M2_REPO dependencies added by eclipse:eclipse and adding the m2eclipse dependency entry:

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
  <attributes>
    <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
  </attributes>
</classpathentry>

Then I imported existing Maven project and it worked as expected.

This is a hack and I'm not sure what other consequences running eclipse:ecplise has when working with m2eclipse. But it did at least allow me to get my project compiling so I could get to coding.


EDIT 1/4/2013

The workaround I posted above will work temporarily, and I never discovered any negative side effects. However, I've had this issue a few times now and each time the problem is that there is some section of the pom that maven accepts but m2eclipse barfs on.

So I recommend removing parts of the pom 1 by 1 until you can mavenize the project successfully. Just keep running maven -> update configuration after each pom edit until it works as it should. I usually start by removing the plugin configuration tag blocks one at a time, starting with the most suspicious (i.e. most complicated).

Once it mavenizes properly, you can revert the pom and it should still work as expected.

After I get running, I'd research the offending configuration(s) to try to figure out what the 'proper' fix is (according to m2eclipse, anyway).

Hopefully this approach leads to the permanent solution instead of settling for a hacky workaround!

Why do I get an error instantiating an interface?

IUser is the interface, you can't instantiate the interface.

You need to instantiate the concrete class that implements the interface.

IUser user = new User();

or

User user = new User();

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

I have found another reason: different versions used for icons in toolbox and references in the project. After inserting the objects in some form, the error started.

Find string between two substrings

Just converting the OP's own solution into an answer:

def find_between(s, start, end):
  return (s.split(start))[1].split(end)[0]

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

This fixed the problem by having it as the first two lines of the script:

!pip install opencv-python
!apt update && apt install -y libsm6 libxext6
!apt-get install -y libxrender-dev

How to save local data in a Swift app?

Okey so thanks to @bploat and the link to http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/

I've found that the answer is quite simple for some basic string storage.

let defaults = NSUserDefaults.standardUserDefaults()

// Store
defaults.setObject("theGreatestName", forKey: "username")

// Receive
if let name = defaults.stringForKey("username")
{
    print(name)
    // Will output "theGreatestName"
}

I've summarized it here http://ridewing.se/blog/save-local-data-in-swift/

POI setting Cell Background to a Custom Color

As pointed in Vlad's answer, you are running out of free color slots. One way to get around that would be to cache the colors: whenever you try a RGB combination, the routine should first check if the combination is in the cache; if it is in the cache, then it should use that one instead of creating a new one from scratch; new colors would then only be created if they're not yet in cache.

Here's the implementation I use; it uses XSSF plus Guava's LoadingCache and is geared towards generationg XSSF colors from CSS rgb(r, g, b) declarations, but it should be relatively trivial to adapt it to HSSF:

    private final LoadingCache<String, XSSFColor> colorsFromCSS = CacheBuilder.newBuilder()
            .build(new CacheLoader<String, XSSFColor>() {

                private final Pattern RGB = Pattern.compile("rgb\\(\\s*(\\d+)\\s*, \\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)");

                @Override
                public XSSFColor load(String style) throws Exception {
                    Matcher mat = RGB.matcher(style);
                    if (!mat.find()) {
                        throw new IllegalStateException("Couldn't read CSS color: " + style);
                    }                       
                    return new XSSFColor(new java.awt.Color(
                            Integer.parseInt(mat.group(1)), 
                            Integer.parseInt(mat.group(2)), 
                            Integer.parseInt(mat.group(3))));
                }

            });

Perhaps someone else could post a HSSF equivalent? ;)

Find control by name from Windows Forms controls

You can use:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

Delete last commit in bitbucket

Here is a simple approach in up to 4 steps:

0 - Advise the team you are going to fix the repository

Connect with the team and let them know of the upcoming changes.

1 - Remove the last commit

Assuming your target branch is master:

$ git checkout master              # move to the target branch
$ git reset --hard HEAD^           # remove the last commit
$ git push -f                      # push to fix the remote

At this point you are done if you are working alone.

2 - Fix your teammate's local repositories

On your teammate's:

$ git checkout master              # move to the target branch
$ git fetch                        # update the local references but do not merge  
$ git reset --hard origin/master   # match the newly fetched remote state

If your teammate had no new commits, you are done at this point and you should be in sync.

3 - Bringing back lost commits

Let's say a teammate had a new and unpublished commit that were lost in this process.

$ git reflog                       # find the new commit hash
$ git cherry-pick <commit_hash>

Do this for as many commits as necessary.

I have successfully used this approach many times. It requires a team effort to make sure everything is synchronized.

Property 'map' does not exist on type 'Observable<Response>'

for all those linux users that are having this problem, check if the rxjs-compat folder is locked. I had this exact same issue and I went in terminal, used the sudo su to give permission to the whole rxjs-compat folder and it was fixed. Thats assuming you imported

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch'; 

in the project.ts file where the original .map error occurred.

Rendering React Components from Array of Objects

There are couple of way which can be used.

const stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)

Solution 1

<p>{callList.join(', ')}</p>

Solution 2

<ol>    
  { callList && callList.map(item => <li>{item}</li>) }
</ol>

Edit kind-antonelli-z8372

Of course there are other ways also available.

How much memory can a 32 bit process access on a 64 bit operating system?

The limit is not 2g or 3gb its 4gb for 32bit.

The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.

Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.

4Gig not 3 not 2 got it?

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Conditional Logic on Pandas DataFrame

In [1]: df
Out[1]:
   data
0     1
1     2
2     3
3     4

You want to apply a function that conditionally returns a value based on the selected dataframe column.

In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0     true
1     true
2    false
3    false
Name: data

You can then assign that returned column to a new column in your dataframe:

In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')

In [4]: df
Out[4]:
   data desired_output
0     1           true
1     2           true
2     3          false
3     4          false

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.

The apk must be signed with the same certificates as the previous version

I highly recommend Keystore Explorer (https://keystore-explorer.org/) which lets you access your keystore without having to upload it to Google Play. This way you can troubleshoot whether you are entering your password incorrectly.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

Core jQuery doesn't have anything special for touch events, but you can easily build your own using the following events

  • touchstart
  • touchmove
  • touchend
  • touchcancel

For example, the touchmove

document.addEventListener('touchmove', function(e) {
    e.preventDefault();
    var touch = e.touches[0];
    alert(touch.pageX + " - " + touch.pageY);
}, false);

This works in most WebKit based browsers (incl. Android).

Here is some good documentation.

Reflection generic get field value

    ` 
//Here is the example I used for get the field name also the field value
//Hope This will help to someone
TestModel model = new TestModel ("MyDate", "MyTime", "OUT");
//Get All the fields of the class
 Field[] fields = model.getClass().getDeclaredFields();
//If the field is private make the field to accessible true
fields[0].setAccessible(true);
//Get the field name
  System.out.println(fields[0].getName());
//Get the field value
System.out.println(fields[0].get(model));
`

Lock down Microsoft Excel macro

you can set a password to your vba code but this can be quite easily broken up.

you can also create an addin and compile it into a DLL. See here for more information. That's at least the most secure way to protect your code.

Regards,

What is the fastest way to transpose a matrix in C++?

intel mkl suggests in-place and out-of-place transposition/copying matrices. here is the link to the documentation. I would recommend trying out of place implementation as faster ten in-place and into the documentation of the latest version of mkl contains some mistakes.

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

Getting All Variables In Scope

If you just want to inspect the variables manually to help debug, just fire up the debugger:

debugger;

Straight into the browser console.

How do you calculate program run time in python?

Quick alternative

import timeit

start = timeit.default_timer()

#Your statements here

stop = timeit.default_timer()

print('Time: ', stop - start)  

inline conditionals in angular.js

Angular UI library has built-in directive ui-if for condition in template/Views upto angular ui 1.1.4

Example: Support in Angular UI upto ui 1.1.4

<div ui-if="array.length>0"></div>

ng-if available in all the angular version after 1.1.4

<div ng-if="array.length>0"></div>

if you have any data in array variable then only the div will appear

Reading value from console, interactively

I have craeted a little script for read directory and write a console name new file (example: 'name.txt' ) and text into file.

const readline = require('readline');
const fs = require('fs');

const pathFile = fs.readdirSync('.');

const file = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

file.question('Insert name of your file? ', (f) => {
  console.log('File is: ',f.toString().trim());
  try{
    file.question('Insert text of your file? ', (d) => {
      console.log('Text is: ',d.toString().trim());
      try {
        if(f != ''){
          if (fs.existsSync(f)) {
            //file exists
            console.log('file exist');
            return file.close();
          }else{
            //save file
            fs.writeFile(f, d, (err) => {
                if (err) throw err;
                console.log('The file has been saved!');
                file.close();
            });
          }
        }else{
          //file empty 
          console.log('Not file is created!');
          console.log(pathFile);
          file.close();
        }
      } catch(err) {
        console.error(err);
        file.close();
      }
    });
  }catch(err){
    console.log(err);
    file.close();
  }
});

ImportError: No module named 'encodings'

Had the same problem when updating my mac to macOS Catalina, while using pipenv. Pipenv creates and manages a virtualenv for you, so the earlier suggestion from @Anoop-Malav is the same, just using pipenv to remove the virtual environment based on the current dir and reset it:

pipenv --rm
pipenv shell  # recreate a virtual env with your current Pipfile

Reading a plain text file in Java

My favorite way to read a small file is to use a BufferedReader and a StringBuilder. It is very simple and to the point (though not particularly effective, but good enough for most cases):

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}

Some has pointed out that after Java 7 you should use try-with-resources (i.e. auto close) features:

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
}

When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation.

Though if I want to actually just read a file into a String, I always use Apache Commons IO with the class IOUtils.toString() method. You can have a look at the source here:

http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html

FileInputStream inputStream = new FileInputStream("foo.txt");
try {
    String everything = IOUtils.toString(inputStream);
} finally {
    inputStream.close();
}

And even simpler with Java 7:

try(FileInputStream inputStream = new FileInputStream("foo.txt")) {     
    String everything = IOUtils.toString(inputStream);
    // do something with everything string
}

Maven: How to include jars, which are not available in reps into a J2EE project?

As you've said you don't want to set up your own repository, perhaps this will help.

You can use the install-file goal of the maven-install-plugin to install a file to the local repository. If you create a script with a Maven invocation for each file and keep it alongside the jars, you (and anyone else with access) can easily install the jars (and associated pom files) to their local repository.

For example:

mvn install:install-file -Dfile=/usr/jars/foo.jar -DpomFile=/usr/jars/foo.pom
mvn install:install-file -Dfile=/usr/jars/bar.jar -DpomFile=/usr/jars/bar.pom

or just

mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0 -Dpackaging=jar

You can then reference the dependencies as normal in your project.

However your best bet is still to set up an internal remote repository and I'd recommend using Nexus myself. It can run on your development box if needed, and the overhead is minimal.

Reduce left and right margins in matplotlib plot

For me, the answers above did not work with matplotlib.__version__ = 1.4.3 on Win7. So, if we are only interested in the image itself (i.e., if we don't need annotations, axis, ticks, title, ylabel etc), then it's better to simply save the numpy array as image instead of savefig.

from pylab import *

ax = subplot(111)
ax.imshow(some_image_numpyarray)
imsave('test.tif', some_image_numpyarray)

# or, if the image came from tiff or png etc
RGBbuffer = ax.get_images()[0].get_array()
imsave('test.tif', RGBbuffer)

Also, using opencv drawing functions (cv2.line, cv2.polylines), we can do some drawings directly on the numpy array. http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html

How can I convert an image into Base64 string using JavaScript?

Here is the way you can do with Javascript Promise.

const getBase64 = (file) => new Promise(function (resolve, reject) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject('Error: ', error);
})

Now, use it in event handler.

const _changeImg = (e) => {
        const file = e.target.files[0];
        let encoded;
        getBase64(file)
          .then((result) => {
            encoded = result;
           })
          .catch(e => console.log(e))
    }

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Note: Due to reputation I cannot comment on bdeem's post. I'm posting my findings as an answer instead.

Following bdeem's post, I did the following (in order):

1. I modified the [project].csproj file. Added the <Content Include="" /> tags to the ItemGroup for the different config files and made them dependent on the original config file.

Note: Using <None Include="" /> will not work with the transformation.

<!-- App.config Settings -->
<!-- Create App.($Configuration).config files here. -->
<Content Include="App.config" />
<Content Include="App.Debug.config">
  <DependentUpon>App.config</DependentUpon>
</Content>
<Content Include="App.Release.config">
  <DependentUpon>App.config</DependentUpon>
</Content>

2. At the bottom of the [project].csproj file (before the closing </Project> tag), I imported the ${MSBuildToolsPath\Microsoft.CSharp.targets file, added the UsingTask to transform the XML and added the Target to copy the transformed App.config file to the output location.

Note: The Target will also overwrite the App.Config in the local directory to see immediate changes working locally. The Target also uses the Name="Afterbuild" property to ensure the config files can be transformed after the executables are generated. For reasons I do not understand, when using WCF endpoints, if I use Name="CoreCompile", I will get warnings about the service attributes. Name="Afterbuild" resolved this.

  <!-- Task to transform the App.config using the App.($Configuration).config file. -->
  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />

  <!-- Only compile the App.config if the App.($Configuration).config file exists. -->
  <!-- Make sure to use the AfterBuild name instead of CoreCompile to avoid first time build errors and WCF endpoint errors. -->
  <Target Name="AfterBuild" Condition="exists('App.$(Configuration).config')">
    <!-- Generate transformed App.config in the intermediate output directory -->    
    <TransformXml Source="App.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="App.$(Configuration).config" />
    
    <!-- Modify the original App.config file with the transformed version. -->
    <TransformXml Source="App.config" Destination="App.config" Transform="App.$(Configuration).config" />

    <!-- Force build process to use the transformed configuration file from now on. -->
    <ItemGroup>
      <AppConfigWithTargetPath Remove="App.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>
</Project>

3. Went back into Visual Studio and reloaded the modified files.

4. Manually added the App.*.config files to the project. This allowed them to group under the original App.config file.

Note: Make sure the App.*.config files have the proper XML structure.

<?xml version="1.0" encoding="utf-8"?>

<!-- For more information on using web.config transformation visit https://go.microsoft.com/fwlink/?LinkId=125889 -->

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="myConn" connectionString=""; Initial Catalog=; User ID=; Password=;" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
  </connectionStrings>
</configuration>

5. Re-built the project.

Datatable vs Dataset

When you are only dealing with a single table anyway, the biggest practical difference I have found is that DataSet has a "HasChanges" method but DataTable does not. Both have a "GetChanges" however, so you can use that and test for null.

"Could not find a version that satisfies the requirement opencv-python"

I faced the same issue but the mistake which I was making was pip install python-opencv where I should have used pip install opencv-python. Hope this helps to anyone. It took me few hours to find.

Delete directories recursively in Java

You should check out Apache's commons-io. It has a FileUtils class that will do what you want.

FileUtils.deleteDirectory(new File("directory"));

Modulo operator in Python

Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3

Beware of floating point accuracy issues.

android - listview get item view by position

Use this :

public View getViewByPosition(int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

I had this problem and the comprehensive descriptions proposed in this helped me to fix it.

The second declared problem was my issue. I used a third-party repository which I had just added it do the repository part of the pom file in my project. I add the same repository information into pluginrepository to resolve this problem.

Most efficient way to concatenate strings in JavaScript?

You can also do string concat with template literals. I updated the other posters' JSPerf tests to include it.

for (var res = '', i = 0; i < data.length; i++) {
  res = `${res}${data[i]}`;
}

How to set MimeBodyPart ContentType to "text/html"?

Don't know why (the method is not documented), but by looking at the source code, this line should do it :

mime_body_part.setHeader("Content-Type", "text/html");

How to get the ActionBar height?

While @birdy's answer is an option if you want to explicitly control the ActionBar size, there is a way to pull it up without locking the size that I found in support documentation. It's a little awkward but it's worked for me. You'll need a context, this example would be valid in an Activity.

// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
    Int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}

Kotlin:

val tv = TypedValue()
if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
}

The performance impact of using instanceof in Java

I write a performance test based on jmh-java-benchmark-archetype:2.21. JDK is openjdk and version is 1.8.0_212. The test machine is mac pro. Test result is:

Benchmark                Mode  Cnt    Score   Error   Units
MyBenchmark.getClasses  thrpt   30  510.818 ± 4.190  ops/us
MyBenchmark.instanceOf  thrpt   30  503.826 ± 5.546  ops/us

The result shows that: getClass is better than instanceOf, which is contrary with other test. However, I don't know why.

The test code is below:

public class MyBenchmark {

public static final Object a = new LinkedHashMap<String, String>();

@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean instanceOf() {
    return a instanceof Map;
}

@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean getClasses() {
    return a.getClass() == HashMap.class;
}

public static void main(String[] args) throws RunnerException {
    Options opt =
        new OptionsBuilder().include(MyBenchmark.class.getSimpleName()).warmupIterations(20).measurementIterations(30).forks(1).build();
    new Runner(opt).run();
}
}

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

On Android >=6.0, We have to request permission runtime.

Step1: add in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Step2: Request permission.

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
    //TODO
}

Step3: Handle callback when you request permission.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

Edit: Read official guide here Requesting Permissions at Run Time

How do I cast a JSON Object to a TypeScript class?

https://jvilk.com/MakeTypes/

you can use this site to generate a proxy for you. it generates a class and can parse and validate your input JSON object.

Git stash pop- needs merge, unable to refresh index

I have found that the best solution is to branch off your stash and do a resolution afterwards.

git stash branch <branch-name>

if you drop of clear your stash, you may lose your changes and you will have to recur to the reflog.

What does the servlet <load-on-startup> value signify

As stated on other answer and this load-on-startup article zero is acceptable and in the absent of any other servlet this will take priority on loading and loaded during deployment. Best use of load-on statup is to load servlets which takes longer time to initialize well before first request come like servlets which creates connection pool or make network call or hold bulky resource, this will significantly reduce response time for first few request.

JavaScript Extending Class

For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.

     function AbstractClass() {
      this.superclass_method = function(message) {
          // do something
        };
     }

     function Child() {
         AbstractClass.apply(this);
         // Now Child will have superclass_method()
     }

Example on angularjs:

http://plnkr.co/edit/eFixlsgF3nJ1LeWUJKsd?p=preview

app.service('noisyThing', 
  ['notify',function(notify){
    this._constructor = function() {
      this.scream = function(message) {
          message = message + " by " + this.get_mouth();
          notify(message); 
          console.log(message);
        };

      this.get_mouth = function(){
        return 'abstract mouth';
      }
    }
  }])
  .service('cat',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.meow = function() {
      this.scream('meooooow');
    }
    this.get_mouth = function(){
      return 'fluffy mouth';
    }
  }])
  .service('bird',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.twit = function() {
      this.scream('fuuuuuuck');
    }
  }])

Custom Authentication in ASP.Net-Core

Creating custom authentication in ASP.NET Core can be done in a variety of ways. If you want to build off existing components (but don't want to use identity), checkout the "Security" category of docs on docs.asp.net. https://docs.asp.net/en/latest/security/index.html

Some articles you might find helpful:

Using Cookie Middleware without ASP.NET Identity

Custom Policy-Based Authorization

And of course, if that fails or docs aren't clear enough, the source code is at https://github.com/dotnet/aspnetcore/tree/master/src/Security which includes some samples.

How do I check if a type is a subtype OR the type of an object?

I'm posting this answer with the hope of someone sharing with me if and why it would be a bad idea. In my application, I have a property of Type that I want to check to be sure it is typeof(A) or typeof(B), where B is any class derived from A. So my code:

public class A
{
}

public class B : A
{
}

public class MyClass
{
    private Type _helperType;
    public Type HelperType
    {
        get { return _helperType; }
        set 
        {
            var testInstance = (A)Activator.CreateInstance(value);
            if (testInstance==null)
                throw new InvalidCastException("HelperType must be derived from A");
            _helperType = value;
        }
    }
}

I feel like I might be a bit naive here so any feedback would be welcome.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

I just use eco to do the job for me. eco is supported by Sprockets by default. It's a shorthand for Embedded Coffeescript which takes a eco file and compile into a Javascript template file, and the file will be treated like any other js files you have in your assets folder.

All you need to do is to create a template with extension .jst.eco and write some html code in there, and rails will automatically compile and serve the file with the assets pipeline, and the way to access the template is really easy: JST['path/to/file']({var: value}); where path/to/file is based on the logical path, so if you have file in /assets/javascript/path/file.jst.eco, you can access the template at JST['path/file']()

To make it work with angularjs, you can pass it into the template attribute instead of templateDir, and it will start working magically!

Using curl to upload POST data with files

After a lot of tries this command worked for me:

curl -v -F filename=image.jpg -F [email protected] http://localhost:8080/api/upload

'console' is undefined error for Internet Explorer

I'm using fauxconsole; I modified the css a bit so that it looks nicer but works very well.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

If you already have nodejs installed (check with which nodejs) and don't want to install another package, you can, as root:

update-alternatives --install /usr/bin/node node /usr/bin/nodejs 99

How to add comments into a Xaml file in WPF?

For anyone learning this stuff, comments are more important, so drawing on Xak Tacit's idea
(from User500099's link) for Single Property comments, add this to the top of the XAML code block:

<!--Comments Allowed With Markup Compatibility (mc) In XAML!
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
    mc:Ignorable="ØignoreØ"
    Usage in property:
ØignoreØ:AttributeToIgnore="Text Of AttributeToIgnore"-->

Then in the code block

<Application FooApp:Class="Foo.App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
...

AttributeNotToIgnore="TextNotToIgnore"
...

...
ØignoreØ:IgnoreThisAttribute="IgnoreThatText"
...   
>
</Application>

How to trim a string to N chars in Javascript?

Little late... I had to respond. This is the simplest way.

_x000D_
_x000D_
// JavaScript_x000D_
function fixedSize_JS(value, size) {_x000D_
  return value.padEnd(size).substring(0, size);_x000D_
}_x000D_
_x000D_
// JavaScript (Alt)_x000D_
var fixedSize_JSAlt = function(value, size) {_x000D_
  return value.padEnd(size).substring(0, size);_x000D_
}_x000D_
_x000D_
// Prototype (preferred)_x000D_
String.prototype.fixedSize = function(size) {_x000D_
  return this.padEnd(size).substring(0, size);_x000D_
}_x000D_
_x000D_
// Overloaded Prototype_x000D_
function fixedSize(value, size) {_x000D_
  return value.fixedSize(size);_x000D_
}_x000D_
_x000D_
// usage_x000D_
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');_x000D_
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');_x000D_
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');_x000D_
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');
_x000D_
_x000D_
_x000D_

Step by step. .padEnd - Guarentees the length of the string

"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository." source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

.substring - limits to the length you need

If you choose to add ellipses, append them to the output.

I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

This is how use SignarR in order to target a specific user (without using any provider):

 private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();

 public string Login(string username)
 {
     clients.TryAdd(Context.ConnectionId, username);            
     return username;
 }

// The variable 'contextIdClient' is equal to Context.ConnectionId of the user, 
// once logged in. You have to store that 'id' inside a dictionaty for example.  
Clients.Client(contextIdClient).send("Hello!");

How to wait for 2 seconds?

As mentioned in other answers, all of the following will work for the standard string-based syntax.

WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds

There is also an alternative method of passing it a DATETIME value. You might think I'm confusing this with WAITFOR TIME, but it also works for WAITFOR DELAY.

Considerations for passing DATETIME:

  • It must be passed as a variable, so it isn't a nice one-liner anymore.
  • The delay is measured as the time since the Epoch ('1900-01-01').
  • For situations that require a variable amount of delay, it is much easier to manipulate a DATETIME than to properly format a VARCHAR.

How to wait for 2 seconds:

--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1

--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2

A note on waiting for TIME vs DELAY:

Have you ever noticed that if you accidentally pass WAITFOR TIME a date that already passed, even by just a second, it will never return? Check it out:

--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER

Unfortunately, WAITFOR DELAY will do the same thing if you pass it a negative DATETIME value (yes, that's a thing).

--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER

However, I would still recommend using WAITFOR DELAY over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR statement.

Floating point comparison functions for C#

static class FloatUtil {

    static bool IsEqual(float a, float b, float tolerance = 0.001f) {
      return Math.Abs(a - b) < tolerance;
    }

    static bool IsGreater(float a, float b) {
      return a > b;
    }

    static bool IsLess(float a, float b) {
      return a < b;
    }
}

The value of tolerance that is passed into IsEqual is something that the client could decide.

IsEqual(1.002, 1.001);          -->   False
IsEqual(1.002, 1.001, 0.01);    -->   True

Setting Java heap space under Maven 2 on Windows

It should be the same command, except SET instead of EXPORT

  • set MAVEN_OPTS=-Xmx512m would give it 512Mb of heap
  • set MAVEN_OPTS=-Xmx2048m would give it 2Gb of heap

How to pass multiple parameters in json format to a web service using jquery?

I think the best way is:

data: "{'Ids':['2','2']}"

To read this values Ids[0], Ids[1].

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

How to add header row to a pandas DataFrame

col_Names=["Sequence", "Start", "End", "Coverage"]
my_CSV_File= pd.read_csv("yourCSVFile.csv",names=col_Names)

having done this, just check it with[well obviously I know, u know that. But still...

my_CSV_File.head()

Hope it helps ... Cheers

Add event handler for body.onload by javascript within <body> part

body.addEventListener("load", init(), false);

That init() is saying run this function now and assign whatever it returns to the load event.

What you want is to assign the reference to the function, not the result. So you need to drop the ().

body.addEventListener("load", init, false);

Also you should be using window.onload and not body.onload

addEventListener is supported in most browsers except IE 8.

How to implement authenticated routes in React Router 4?

You're going to want to use the Redirect component. There's a few different approaches to this problem. Here's one I like, have a PrivateRoute component that takes in an authed prop and then renders based on that props.

function PrivateRoute ({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}

Now your Routes can look something like this

<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />

If you're still confused, I wrote this post that may help - Protected routes and authentication with React Router v4

How can I save a screenshot directly to a file in Windows?

Of course you could write a program that monitors the clipboard and displays an annoying SaveAs-dialog for every image in the clipboard ;-). I guess you can even find out if the last key pressed was PrintScreen to limit the number of false positives.

While I'm thinking about it.. you could also google for someone who already did exactly that.


EDIT: .. or just wait for someone to post the source here - as just happend :-)

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Select SQL results grouped by weeks

Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'
From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
        Sale as 'Sale'
From dbo.WeekReport

-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

OUTPUT LOOK LIKE THIS

a   0   0   0   0   20
b   0   0   0   0   4
c   0   0   0   0   3

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message is pretty straightforward: getComputedStyle expects an Element as its first argument, and something else was passed to it.

If what you are really asking for is help with debugging your skin, you should make more of an effort to isolate the error.

Android button with different background colors

You have to put the selector.xml file in the drwable folder. Then write: android:background="@drawable/selector". This takes care of the pressed and focussed states.

How do I calculate r-squared using Python and Numpy?

From yanl (yet-another-library) sklearn.metrics has an r2_score function;

from sklearn.metrics import r2_score

coefficient_of_dermination = r2_score(y, p(x))

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

To jump between words and start/end of lines in iTerm2 pick one of the two solutions below.

1. Simple solution (recommended)

  1. Open Preferences
  2. Click "Profile" tab
  3. Select a profile in the list on the left (eg "Default") and click "Keys" tab
  4. Click the "Presets" dropdown and select "Natural Text Editing"

enter image description here


2. Mapping keys manually (Advanced)

If you don't want to use the "Natural Text Editing" preset mentioned above, you can map the keys you need manually:

  1. Open Preferences
  2. Click “Keys” tab
  3. Click the [+] icon

You can now add the following keyboard shortcuts:

Move cursor one word left

  • Keyboard shortcut: ? + ?
  • Action: Send Hex Code
  • Code: 0x1b 0x62

enter image description here

Move cursor one word right

  • Keyboard Combination: ? + ?
  • Action: Send Hex Code
  • Code: 0x1b 0x66

Move cursor to beginning of line

  • Keyboard Combination: ? + ?
  • Action: Send Hex Code
  • Code: 0x01

Move cursor to end of line

  • Keyboard Combination: ? + ?
  • Action: Send Hex Code
  • Code: 0x05

Delete word

  • Keyboard Combination: ? + ?Delete
  • Action: Send Hex Code
  • Code: 0x1b 0x08

Delete line

  • Keyboard Combination: ? + ?Delete
  • Action: Send Hex Code
  • Code: 0x15

Undo

  • Keyboard Combination: ? + z
  • Action: Send Hex Code
  • Code: 0x1f

Don't forget to remove the previous bindings:

  • Open the “Profiles” tab
  • Click the sub-tab ”Keys”
  • Remove the mappings for key combinations ? + ? and ? + ?

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

How to read appSettings section in the web.config file?

Add namespace

using System.Configuration;

and in place of

ConfigurationSettings.AppSettings

you should use

ConfigurationManager.AppSettings

String path = ConfigurationManager.AppSettings["configFile"];

Using Python's ftplib to get a directory listing, portably

There's no standard for the layout of the LIST response. You'd have to write code to handle the most popular layouts. I'd start with Linux ls and Windows Server DIR formats. There's a lot of variety out there, though.

Fall back to the nlst method (returning the result of the NLST command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length.

Counting how many times a certain char appears in a string before any other char appears

public static int GetHowManyTimeOccurenceCharInString(string text, char c)
{
    int count = 0;
    foreach(char ch in text)
    {
        if(ch.Equals(c))
        {
            count++;
        }

    }
    return count;
}

java.lang.ClassCastException

It's because you're casting to the wrong thing - you're trying to convert to a particular type, and the object that your express refers to is incompatible with that type. For example:

Object x = "this is a string";
InputStream y = (InputStream) x; // This will throw ClassCastException

If you could provide a code sample, that would really help...

git rebase fatal: Needed a single revision

Check that you spelled the branch name correctly. I was rebasing a story branch (i.e. branch_name) and forgot the story part. (i.e. story/branch_name) and then git spit this error at me which didn't make much sense in this context.

Is calculating an MD5 hash less CPU intensive than SHA family functions?

sha1sum is quite a bit faster on Power9 than md5sum

$ uname -mov
#1 SMP Mon May 13 12:16:08 EDT 2019 ppc64le GNU/Linux

$ cat /proc/cpuinfo
processor       : 0
cpu             : POWER9, altivec supported
clock           : 2166.000000MHz
revision        : 2.2 (pvr 004e 1202)

$ ls -l linux-master.tar
-rw-rw-r-- 1 x x 829685760 Jan 29 14:30 linux-master.tar

$ time sha1sum linux-master.tar
10fbf911e254c4fe8e5eb2e605c6c02d29a88563  linux-master.tar

real    0m1.685s
user    0m1.528s
sys     0m0.156s

$ time md5sum linux-master.tar
d476375abacda064ae437a683c537ec4  linux-master.tar

real    0m2.942s
user    0m2.806s
sys     0m0.136s

$ time sum linux-master.tar
36928 810240

real    0m2.186s
user    0m1.917s
sys     0m0.268s

Android Linear Layout - How to Keep Element At Bottom Of View?

Update: I still get upvotes on this question, which is still the accepted answer and which I think I answered poorly. In the spirit of making sure the best info is out there, I have decided to update this answer.

In modern Android I would use ConstraintLayout to do this. It is more performant and straightforward.

<ConstraintLayout>
   <View
      android:id="@+id/view1"
      ...other attributes elided... />
   <View
      android:id="@id/view2"        
      app:layout_constraintTop_toBottomOf="@id/view1" />
      ...other attributes elided... />

   ...etc for other views that should be aligned top to bottom...

   <TextView
    app:layout_constraintBottom_toBottomOf="parent" />

If you don't want to use a ConstraintLayout, using a LinearLayout with an expanding view is a straightforward and great way to handle taking up the extra space (see the answer by @Matthew Wills). If you don't want to expand the background of any of the Views above the bottom view, you can add an invisible View to take up the space.

The answer I originally gave works but is inefficient. Inefficiency may not be a big deal for a single top level layout, but it would be a terrible implementation in a ListView or RecyclerView, and there just isn't any reason to do it since there are better ways to do it that are roughly the same level of effort and complexity if not simpler.

Take the TextView out of the LinearLayout, then put the LinearLayout and the TextView inside a RelativeLayout. Add the attribute android:layout_alignParentBottom="true" to the TextView. With all the namespace and other attributes except for the above attribute elided:

<RelativeLayout>
  <LinearLayout>
    <!-- All your other elements in here -->
  </LinearLayout>
  <TextView
    android:layout_alignParentBottom="true" />
</RelativeLayout>

Creating runnable JAR with Gradle

  1. Configure Main Class to your Manifest

If you are using gradle project, just add the following into your build.gradle

jar {
    manifest {
        attributes(
               'Main-Class': 'pokerhandscorer.PokerHandScorer'
        )
    }
}
  • Where 'pokerhandscorer' is the name of the package name, and PokerHandScorer is the main class name

This creates a jar file into your \build\libs{jarFilename}.jar

  1. Run jar file using java -jar /{path}/{jarFileName.jar}

java -jar /{path}/{jarFileName.jar}

Complex JSON nesting of objects and arrays

Make sure you follow the language definition for JSON. In your second example, the section:

"labs":[{
    ""
}]

Is invalid since an object must be composed of zero or more key-value pairs "a" : "b", where "b" may be any valid value. Some parsers may automatically interpret { "" } to be { "" : null }, but this is not a clearly defined case.

Also, you are using a nested array of objects [{}] quite a bit. I would only do this if:

  1. There is no good "identifier" string for each object in the array.
  2. There is some clear reason for having an array over a key-value for that entry.

how to read all files inside particular folder

using System.IO;

DirectoryInfo di = new DirectoryInfo(folder);
FileInfo[] files = di.GetFiles("*.xml");

Perform a Shapiro-Wilk Normality Test

What does shapiro.test do?

shapiro.test tests the Null hypothesis that "the samples come from a Normal distribution" against the alternative hypothesis "the samples do not come from a Normal distribution".

How to perform shapiro.test in R?

The R help page for ?shapiro.test gives,

x - a numeric vector of data values. Missing values are allowed, 
    but the number of non-missing values must be between 3 and 5000.

That is, shapiro.test expects a numeric vector as input, that corresponds to the sample you would like to test and it is the only input required. Since you've a data.frame, you'll have to pass the desired column as input to the function as follows:

> shapiro.test(heisenberg$HWWIchg)
#   Shapiro-Wilk normality test

# data:  heisenberg$HWWIchg 
# W = 0.9001, p-value = 0.2528

Interpreting results from shapiro.test:

First, I strongly suggest you read this excellent answer from Ian Fellows on testing for normality.

As shown above, the shapiro.test tests the NULL hypothesis that the samples came from a Normal distribution. This means that if your p-value <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution. As Ian Fellows nicely put it, you are testing against the assumption of Normality". In other words (correct me if I am wrong), it would be much better if one tests the NULL hypothesis that the samples do not come from a Normal distribution. Why? Because, rejecting a NULL hypothesis is not the same as accepting the alternative hypothesis.

In case of the null hypothesis of shapiro.test, a p-value <= 0.05 would reject the null hypothesis that the samples come from normal distribution. To put it loosely, there is a rare chance that the samples came from a normal distribution. The side-effect of this hypothesis testing is that this rare chance happens very rarely. To illustrate, take for example:

set.seed(450)
x <- runif(50, min=2, max=4)
shapiro.test(x)
#   Shapiro-Wilk normality test
# data:  runif(50, min = 2, max = 4) 
# W = 0.9601, p-value = 0.08995

So, this (particular) sample runif(50, min=2, max=4) comes from a normal distribution according to this test. What I am trying to say is that, there are many many cases under which the "extreme" requirements (p < 0.05) are not satisfied which leads to acceptance of "NULL hypothesis" most of the times, which might be misleading.

Another issue I'd like to quote here from @PaulHiemstra from under comments about the effects on large sample size:

An additional issue with the Shapiro-Wilk's test is that when you feed it more data, the chances of the null hypothesis being rejected becomes larger. So what happens is that for large amounts of data even very small deviations from normality can be detected, leading to rejection of the null hypothesis event though for practical purposes the data is more than normal enough.

Although he also points out that R's data size limit protects this a bit:

Luckily shapiro.test protects the user from the above described effect by limiting the data size to 5000.

If the NULL hypothesis were the opposite, meaning, the samples do not come from a normal distribution, and you get a p-value < 0.05, then you conclude that it is very rare that these samples do not come from a normal distribution (reject the NULL hypothesis). That loosely translates to: It is highly likely that the samples are normally distributed (although some statisticians may not like this way of interpreting). I believe this is what Ian Fellows also tried to explain in his post. Please correct me if I've gotten something wrong!

@PaulHiemstra also comments about practical situations (example regression) when one comes across this problem of testing for normality:

In practice, if an analysis assumes normality, e.g. lm, I would not do this Shapiro-Wilk's test, but do the analysis and look at diagnostic plots of the outcome of the analysis to judge whether any assumptions of the analysis where violated too much. For linear regression using lm this is done by looking at some of the diagnostic plots you get using plot(lm()). Statistics is not a series of steps that cough up a few numbers (hey p < 0.05!) but requires a lot of experience and skill in judging how to analysis your data correctly.

Here, I find the reply from Ian Fellows to Ben Bolker's comment under the same question already linked above equally (if not more) informative:

For linear regression,

  1. Don't worry much about normality. The CLT takes over quickly and if you have all but the smallest sample sizes and an even remotely reasonable looking histogram you are fine.

  2. Worry about unequal variances (heteroskedasticity). I worry about this to the point of (almost) using HCCM tests by default. A scale location plot will give some idea of whether this is broken, but not always. Also, there is no a priori reason to assume equal variances in most cases.

  3. Outliers. A cooks distance of > 1 is reasonable cause for concern.

Those are my thoughts (FWIW).

Hope this clears things up a bit.

Error CS2001: Source file '.cs' could not be found

In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

In Java, how do I check if a string contains a substring (ignoring case)?

I'd use a combination of the contains method and the toUpper method that are part of the String class. An example is below:

String string1 = "AAABBBCCC"; 
String string2 = "DDDEEEFFF";
String searchForThis = "AABB";

System.out.println("Search1="+string1.toUpperCase().contains(searchForThis.toUpperCase()));

System.out.println("Search2="+string2.toUpperCase().contains(searchForThis.toUpperCase()));

This will return:

Search1=true
Search2=false

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

Remove Duplicate objects from JSON Array

I know there are many answers already but the best one that worked for me for a complex json structure is:

_x000D_
_x000D_
var arr = [{ "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }];_x000D_
_x000D_
var clean = arr.filter((arr, index, self) =>_x000D_
    index === self.findIndex((t) => (t.save === arr.save && t.State === arr.State)))_x000D_
_x000D_
console.log(clean);
_x000D_
_x000D_
_x000D_

You can try this directly to chrome browser console and edit according to your need.

I hope this helps someone.

Regex for numbers only

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$");

Use "^\d+$" if you need to match more than one digit.


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ??????????. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

What is the use of hashCode in Java?

Although hashcode does nothing with your business logic, we have to take care of it in most cases. Because when your object is put into a hash based container(HashSet, HashMap...), the container puts/gets the element's hashcode.

Adding new column to existing DataFrame in Python pandas

Easiest ways:-

data['new_col'] = list_of_values

data.loc[ : , 'new_col'] = list_of_values

This way you avoid what is called chained indexing when setting new values in a pandas object. Click here to read further.

Unsigned keyword in C++

Does the unsigned keyword default to a data type in C++

Yes,signed and unsigned may also be used as standalone type specifiers

The integer data types char, short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero).

An unsigned integer containing n bits can have a value between 0 and 2n - 1 (which is 2n different values).

However,signed and unsigned may also be used as standalone type specifiers, meaning the same as signed int and unsigned int respectively. The following two declarations are equivalent:

unsigned NextYear;
unsigned int NextYear;