Programs & Examples On #Glassfish embedded

Printing an array in C++?

Just iterate over the elements. Like this:

for (int i = numElements - 1; i >= 0; i--) 
    cout << array[i];

Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.

Creating a list of dictionaries results in a list of copies of the same dictionary

You are not creating a separate dictionary for each iframe, you just keep modifying the same dictionary over and over, and you keep adding additional references to that dictionary in your list.

Remember, when you do something like content.append(info), you aren't making a copy of the data, you are simply appending a reference to the data.

You need to create a new dictionary for each iframe.

for iframe in soup.find_all('iframe'):
   info = {}
    ...

Even better, you don't need to create an empty dictionary first. Just create it all at once:

for iframe in soup.find_all('iframe'):
    info = {
        "src":    iframe.get('src'),
        "height": iframe.get('height'),
        "width":  iframe.get('width'),
    }
    content.append(info)

There are other ways to accomplish this, such as iterating over a list of attributes, or using list or dictionary comprehensions, but it's hard to improve upon the clarity of the above code.

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

How to update SQLAlchemy row entry?

With the help of user=User.query.filter_by(username=form.username.data).first() statement you will get the specified user in user variable.

Now you can change the value of the new object variable like user.no_of_logins += 1 and save the changes with the session's commit method.

javascript : sending custom parameters with window.open() but its not working

You can use this but there remains a security issue

<script type="text/javascript">
function fnc1()
{
    var a=window.location.href;

    username="p";
    password=1234;
    window.open(a+'?username='+username+'&password='+password,"");

}   
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext"  />

How to use EOF to run through a text file in C?

You should check the EOF after reading from file.

fscanf_s                   // read from file
while(condition)           // check EOF
{
   fscanf_s               // read from file
}

Rounding SQL DateTime to midnight

In SQL Server 2008 and newer you can cast the DateTime to a Date, which removes the time element.

WHERE Orders.OrderStatus = 'Shipped'  
AND Orders.ShipDate >= (cast(GETDATE()-6 as date))  

In SQL Server 2005 and below you can use:

WHERE Orders.OrderStatus = 'Shipped'  
AND Orders.ShipDate >= DateAdd(Day, Datediff(Day,0, GetDate() -6), 0)

Negative matching using grep (match lines that do not contain foo)

You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

Lines not containing foo:

awk '!/foo/'

Lines containing neither foo nor bar:

awk '!/foo/ && !/bar/'

Lines containing neither foo nor bar which contain either foo2 or bar2:

awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'

And so on.

How can I read and parse CSV files in C++?

This solution detects these 4 cases

complete class is at

https://github.com/pedro-vicente/csv-parser

1,field 2,field 3,
1,field 2,"field 3 quoted, with separator",
1,field 2,"field 3
with newline",
1,field 2,"field 3
with newline and separator,",

It reads the file character by character, and reads 1 row at a time to a vector (of strings), therefore suitable for very large files.

Usage is

Iterate until an empty row is returned (end of file). A row is a vector where each entry is a CSV column.

read_csv_t csv;
csv.open("../test.csv");
std::vector<std::string> row;
while (true)
{
  row = csv.read_row();
  if (row.size() == 0)
  {
    break;
  }
}

the class declaration

class read_csv_t
{
public:
  read_csv_t();
  int open(const std::string &file_name);
  std::vector<std::string> read_row();
private:
  std::ifstream m_ifs;
};

the implementation

std::vector<std::string> read_csv_t::read_row()
{
  bool quote_mode = false;
  std::vector<std::string> row;
  std::string column;
  char c;
  while (m_ifs.get(c))
  {
    switch (c)
    {
      /////////////////////////////////////////////////////////////////////////////////////////////////////
      //separator ',' detected. 
      //in quote mode add character to column
      //push column if not in quote mode
      /////////////////////////////////////////////////////////////////////////////////////////////////////

    case ',':
      if (quote_mode == true)
      {
        column += c;
      }
      else
      {
        row.push_back(column);
        column.clear();
      }
      break;

      /////////////////////////////////////////////////////////////////////////////////////////////////////
      //quote '"' detected. 
      //toggle quote mode
      /////////////////////////////////////////////////////////////////////////////////////////////////////

    case '"':
      quote_mode = !quote_mode;
      break;

      /////////////////////////////////////////////////////////////////////////////////////////////////////
      //line end detected
      //in quote mode add character to column
      //return row if not in quote mode
      /////////////////////////////////////////////////////////////////////////////////////////////////////

    case '\n':
    case '\r':
      if (quote_mode == true)
      {
        column += c;
      }
      else
      {
        return row;
      }
      break;

      /////////////////////////////////////////////////////////////////////////////////////////////////////
      //default, add character to column
      /////////////////////////////////////////////////////////////////////////////////////////////////////

    default:
      column += c;
      break;
    }
  }

  //return empty vector if end of file detected 
  m_ifs.close();
  std::vector<std::string> v;
  return v;
}

Java: how to represent graphs?

A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html

Explanation copied from the above page.

The Graph class represents an undirected graph of vertices named 0 through V - 1.

It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.

This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.

Return value in SQL Server stored procedure

You can either do 1 of the following:

Change:

SET @UserId = 0 to SELECT @UserId

This will return the value in the same way your 2nd part of the IF statement is.


Or, seeing as @UserId is set as an Output, change:

SELECT SCOPE_IDENTITY() to SET @UserId = SCOPE_IDENTITY()


It depends on how you want to access the data afterwards. If you want the value to be in your result set, use SELECT. If you want to access the new value of the @UserId parameter afterwards, then use SET @UserId


Seeing as you're accepting the 2nd condition as correct, the query you could write (without having to change anything outside of this query) is:

@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
IF 
    (SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress) > 0
    BEGIN
        SELECT 0
    END
ELSE
    BEGIN
        INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
        SELECT SCOPE_IDENTITY()
    END

END

How to set env variable in Jupyter notebook

If you're using Python, you can define your environment variables in a .env file and load them from within a Jupyter notebook using python-dotenv.

Install python-dotenv:

pip install python-dotenv

Load the .env file in a Jupyter notebook:

%load_ext dotenv
%dotenv

Flash CS4 refuses to let go

Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:

C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso

On a Mac, the directory structure is similar in /Users/username/Library/Application Support/


You can remove those files by hand, or in Flash you can select Control->Delete ASO files to remove them.

How do you see the entire command history in interactive Python?

@Jason-V, it really help, thanks. then, i found this examples and composed to own snippet.

#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
  readline.read_history_file(python_history)
  readline.parse_and_bind("tab: complete")
  readline.set_history_length(5000)
  atexit.register(readline.write_history_file, python_history)
except IOError:
  pass
del os, python_history, readline, atexit 

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

I got this message while trying to commit a fragment using attach to root to true instead of false, like so:

return inflater.inflate(R.layout.fragment_profile, container, true)

After doing:

return inflater.inflate(R.layout.fragment_profile, container, false)

It worked.

Add newline to VBA or Visual Basic 6

Use this code between two words:

& vbCrLf &

Using this, the next word displays on the next line.

Visual Studio: ContextSwitchDeadlock

The above solution is good in some scenarios but there is another scenario where this happens when you are unit testing and you try to "Debug Selected Tests" from the Test Explorer when you solution is not set to Debug.

In this case you need to change your solution from Release or whatever it is set to to Debug in this case. If this is the problem then changing "ContextSwitchDeadlock" won't really help you.

I missed this myself because the error message was so nasty I didn't check the obvious thing which was the Debug setting!

How to get second-highest salary employees in a table

this is the simple query .. if u want the second minimum then just change the max to min and change the less than(<) sign to grater than(>).

    select max(column_name) from table_name where column_name<(select max(column_name) from table_name)

Python function to convert seconds into minutes, hours, and days

Patching as well Ralph Bolton's answer. Moving to a class and moving tulp of tulp (intervals) to dictionary. Adding an optional rounded function depending of granularity (enable by default). Ready to translation using gettext (default is disable). This is intend to be load from an module. This is for python3 (tested 3.6 - 3.8)

import gettext
import locale
from itertools import chain

mylocale = locale.getdefaultlocale()
# see --> https://stackoverflow.com/a/10174657/11869956 thx 
#localedir = os.path.join(os.path.dirname(__file__), 'locales')
# or python > 3.4:
try:
    localedir = pathlib.Path(__file__).parent/'locales'
    lang_translations = gettext.translation('utils', localedir, 
                                            languages=[mylocale[0]])
    lang_translations.install()
    _ = lang_translations.gettext
except Exception as exc:
    print('Error: unexcept error while initializing translation:', file=sys.stderr)
    print(f'Error: {exc}', file=sys.stderr)
    print(f'Error: localedir={localedir}, languages={mylocale[0]}', file=sys.stderr)
    print('Error: translation has been disabled.', file=sys.stderr)
    _ = gettext.gettext

Here is the class:

class FormatTimestamp:
    """Convert seconds to, optional rounded, time depending of granularity's degrees.
        inspired by https://stackoverflow.com/a/24542445/11869956"""
    def __init__(self):
        # For now i haven't found a way to do it better
        # TODO: optimize ?!? ;)
        self.intervals = {
            # 'years'     :   31556952,  # https://www.calculateme.com/time/years/to-seconds/
            # https://www.calculateme.com/time/months/to-seconds/ -> 2629746 seconds
            # But it's outputing some strange result :
            # So 3 seconds less (2629743) : 4 weeks, 2 days, 10 hours, 29 minutes and 3 seconds
            # than after 3 more seconds : 1 month ?!?
            # Google give me 2628000 seconds
            # So 3 seconds less (2627997): 4 weeks, 2 days, 9 hours, 59 minutes and 57 seconds
            # Strange as well 
            # So for the moment latest is week ...
            #'months'    :   2419200, # 60 * 60 * 24 * 7 * 4 
            'weeks'     :   604800,  # 60 * 60 * 24 * 7
            'days'      :   86400,    # 60 * 60 * 24
            'hours'     :   3600,    # 60 * 60
            'minutes'   :   60,
            'seconds'  :   1
            }
        self.nextkey = {
            'seconds'   :   'minutes',
            'minutes'   :   'hours',
            'hours'     :   'days',
            'days'      :   'weeks',
            'weeks'     :   'weeks',
            #'months'    :   'months',
            #'years'     :   'years' # stop here
            }
        self.translate = {
            'weeks'     :   _('weeks'),
            'days'      :   _('days'),
            'hours'     :   _('hours'),
            'minutes'   :   _('minutes'),
            'seconds'   :   _('seconds'),
            ## Single
            'week'      :   _('week'),
            'day'       :   _('day'),
            'hour'      :   _('hour'),
            'minute'    :   _('minute'),
            'second'    :   _('second'),
            ' and'      :   _('and'),
            ','         :   _(','),     # This is for compatibility
            ''          :   '\0'        # same here BUT we CANNOT pass empty string to gettext 
                                        # or we get : warning: Empty msgid.  It is reserved by GNU gettext:
                                        # gettext("") returns the header entry with
                                        # meta information, not the empty string.
                                        # Thx to --> https://stackoverflow.com/a/30852705/11869956 - saved my day
            }

    def convert(self, seconds, granularity=2, rounded=True, translate=False):
        """Proceed the conversion"""

        def _format(result):
            """Return the formatted result
            TODO : numpy / google docstrings"""
            start = 1 
            length = len(result)
            none = 0
            next_item = False
            for item in reversed(result[:]):
                if item['value']:
                    # if we have more than one item
                    if length - none > 1:
                        # This is the first 'real' item 
                        if start == 1:
                            item['punctuation'] = ''
                            next_item = True
                        elif next_item:
                            # This is the second 'real' item
                            # Happened 'and' to key name
                            item['punctuation'] = ' and'
                            next_item = False
                        # If there is more than two 'real' item
                        # than happened ','
                        elif 2 < start:
                            item['punctuation'] = ','
                        else:
                            item['punctuation'] = ''
                    else:
                        item['punctuation'] = ''
                    start += 1
                else:
                    none += 1
            return [ { 'value'        :   mydict['value'], 
                       'name'         :   mydict['name_strip'],
                       'punctuation'  :   mydict['punctuation'] } for mydict in result \
                                                                  if mydict['value'] is not None ]


        def _rstrip(value, name):
            """Rstrip 's' name depending of value"""
            if value == 1:
                name = name.rstrip('s')
            return name


        # Make sure granularity is an integer
        if not isinstance(granularity, int):
            raise ValueError(f'Granularity should be an integer: {granularity}')

        # For seconds only don't need to compute
        if seconds < 0:
            return 'any time now.'
        elif seconds < 60:
            return 'less than a minute.'

        result = []
        for name, count in self.intervals.items():
            value = seconds // count
            if value:
                seconds -= value * count
                name_strip = _rstrip(value, name)
                # save as dict: value, name_strip (eventually strip), name (for reference), value in seconds
                # and count (for reference)
                result.append({ 
                        'value'        :   value,
                        'name_strip'   :   name_strip,
                        'name'         :   name, 
                        'seconds'      :   value * count,
                        'count'        :   count
                                 })
            else:
                if len(result) > 0:
                    # We strip the name as second == 0
                    name_strip = name.rstrip('s')
                    # adding None to key 'value' but keep other value
                    # in case when need to add seconds when we will 
                    # recompute every thing
                    result.append({ 
                        'value'        :   None,
                        'name_strip'   :   name_strip,
                        'name'         :   name, 
                        'seconds'      :   0,
                        'count'        :   count
                                 })

        # Get the length of the list
        length = len(result)
        # Don't need to compute everything / every time
        if length < granularity or not rounded:
            if translate:
                return ' '.join('{0} {1}{2}'.format(item['value'], _(self.translate[item['name']]), 
                                                _(self.translate[item['punctuation']])) \
                                                for item in _format(result))
            else:
                return ' '.join('{0} {1}{2}'.format(item['value'], item['name'], item['punctuation']) \
                                                for item in _format(result))

        start = length - 1
        # Reverse list so the firsts elements 
        # could be not selected depending on granularity.
        # And we can delete item after we had his seconds to next
        # item in the current list (result)
        for item in reversed(result[:]):
            if granularity <= start <= length - 1:
                # So we have to round
                current_index = result.index(item)
                next_index = current_index - 1
                # skip item value == None
                # if the seconds of current item is superior
                # to the half seconds of the next item: round
                if item['value'] and item['seconds'] > result[next_index]['count'] // 2:
                    # +1 to the next item (in seconds: depending on item count)
                    result[next_index]['seconds'] += result[next_index]['count']
                # Remove item which is not selected
                del result[current_index]
            start -= 1
        # Ok now recalculate everything
        # Reverse as well 
        for item in reversed(result[:]):
            # Check if seconds is superior or equal to the next item 
            # but not from 'result' list but from 'self.intervals' dict
            # Make sure it's not None
            if item['value']:
                next_item_name = self.nextkey[item['name']]
                # This mean we are at weeks
                if item['name'] == next_item_name:
                    # Just recalcul
                    item['value'] = item['seconds'] // item['count']
                    item['name_strip'] = _rstrip(item['value'], item['name'])
                # Stop to weeks to stay 'right' 
                elif item['seconds'] >= self.intervals[next_item_name]:
                    # First make sure we have the 'next item'
                    # found via --> https://stackoverflow.com/q/26447309/11869956
                    # maybe there is a faster way to do it ? - TODO
                    if any(search_item['name'] == next_item_name for search_item in result):
                        next_item_index = result.index(item) - 1
                        # Append to
                        result[next_item_index]['seconds'] += item['seconds']
                        # recalculate value
                        result[next_item_index]['value'] = result[next_item_index]['seconds'] // \
                                                           result[next_item_index]['count']
                        # strip or not
                        result[next_item_index]['name_strip'] = _rstrip(result[next_item_index]['value'],
                                                                       result[next_item_index]['name'])
                    else:
                        # Creating 
                        next_item_index = result.index(item) - 1
                        # get count
                        next_item_count = self.intervals[next_item_name]
                        # convert seconds
                        next_item_value = item['seconds'] // next_item_count
                        # strip 's' or not
                        next_item_name_strip = _rstrip(next_item_value, next_item_name)
                        # added to dict
                        next_item = {
                                       'value'      :   next_item_value,
                                       'name_strip' :   next_item_name_strip,
                                       'name'       :   next_item_name,
                                       'seconds'    :   item['seconds'],
                                       'count'      :   next_item_count
                                       }
                        # insert to the list
                        result.insert(next_item_index, next_item)
                    # Remove current item
                    del result[result.index(item)]
                else:
                    # for current item recalculate
                    # keys 'value' and 'name_strip'
                    item['value'] = item['seconds'] // item['count']
                    item['name_strip'] = _rstrip(item['value'], item['name'])
        if translate:
            return ' '.join('{0} {1}{2}'.format(item['value'], 
                                                _(self.translate[item['name']]), 
                                                _(self.translate[item['punctuation']])) \
                                                for item in _format(result))
        else:
            return ' '.join('{0} {1}{2}'.format(item['value'], item['name'], item['punctuation']) \
                                                for item in _format(result))

To use it:

myformater = FormatTimestamp()
myconverter = myformater.convert(seconds) 

granularity = 1 - 5, rounded = True / False, translate = True / False

Some test to show difference:

myformater = FormatTimestamp()
for firstrange in [131440, 563440, 604780, 2419180, 113478160]:
    print(f'#### Seconds : {firstrange} ####')
    print('\tFull - function: {0}'.format(display_time(firstrange, granularity=5)))
    print('\tFull -    class: {0}'.format(myformater.convert(firstrange, granularity=5))) 
    for secondrange in range(1, 6, 1):
        print('\tGranularity   this   answer ({0}): {1}'.format(secondrange, 
                                                             myformater.convert(firstrange,
                                                                                granularity=secondrange, translate=False)))
        print('\tGranularity Bolton\'s answer ({0}): {1}'.format(secondrange, display_time(firstrange,
                                                                                granularity=secondrange)))
    print()
Seconds : 131440
    Full - function: 1 day, 12 hours, 30 minutes, 40 seconds
    Full -    class: 1 day, 12 hours, 30 minutes and 40 seconds
    Granularity   this   answer (1): 2 days
    Granularity Bolton's answer (1): 1 day
    Granularity   this   answer (2): 1 day and 13 hours
    Granularity Bolton's answer (2): 1 day, 12 hours
    Granularity   this   answer (3): 1 day, 12 hours and 31 minutes
    Granularity Bolton's answer (3): 1 day, 12 hours, 30 minutes
    Granularity   this   answer (4): 1 day, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (4): 1 day, 12 hours, 30 minutes, 40 seconds
    Granularity   this   answer (5): 1 day, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (5): 1 day, 12 hours, 30 minutes, 40 seconds
Seconds : 563440
    Full - function: 6 days, 12 hours, 30 minutes, 40 seconds
    Full -    class: 6 days, 12 hours, 30 minutes and 40 seconds
    Granularity   this   answer (1): 1 week
    Granularity Bolton's answer (1): 6 days
    Granularity   this   answer (2): 6 days and 13 hours
    Granularity Bolton's answer (2): 6 days, 12 hours
    Granularity   this   answer (3): 6 days, 12 hours and 31 minutes
    Granularity Bolton's answer (3): 6 days, 12 hours, 30 minutes
    Granularity   this   answer (4): 6 days, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (4): 6 days, 12 hours, 30 minutes, 40 seconds
    Granularity   this   answer (5): 6 days, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (5): 6 days, 12 hours, 30 minutes, 40 seconds
Seconds : 604780
    Full - function: 6 days, 23 hours, 59 minutes, 40 seconds
    Full -    class: 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity   this   answer (1): 1 week
    Granularity Bolton's answer (1): 6 days
    Granularity   this   answer (2): 1 week
    Granularity Bolton's answer (2): 6 days, 23 hours
    Granularity   this   answer (3): 1 week
    Granularity Bolton's answer (3): 6 days, 23 hours, 59 minutes
    Granularity   this   answer (4): 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity Bolton's answer (4): 6 days, 23 hours, 59 minutes, 40 seconds
    Granularity   this   answer (5): 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity Bolton's answer (5): 6 days, 23 hours, 59 minutes, 40 seconds
Seconds : 2419180
    Full - function: 3 weeks, 6 days, 23 hours, 59 minutes, 40 seconds
    Full -    class: 3 weeks, 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity   this   answer (1): 4 weeks
    Granularity Bolton's answer (1): 3 weeks
    Granularity   this   answer (2): 4 weeks
    Granularity Bolton's answer (2): 3 weeks, 6 days
    Granularity   this   answer (3): 4 weeks
    Granularity Bolton's answer (3): 3 weeks, 6 days, 23 hours
    Granularity   this   answer (4): 4 weeks
    Granularity Bolton's answer (4): 3 weeks, 6 days, 23 hours, 59 minutes
    Granularity   this   answer (5): 3 weeks, 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity Bolton's answer (5): 3 weeks, 6 days, 23 hours, 59 minutes, 40 seconds
Seconds : 113478160
    Full - function: 187 weeks, 4 days, 9 hours, 42 minutes, 40 seconds
    Full -    class: 187 weeks, 4 days, 9 hours, 42 minutes and 40 seconds
    Granularity   this   answer (1): 188 weeks
    Granularity Bolton's answer (1): 187 weeks
    Granularity   this   answer (2): 187 weeks and 4 days
    Granularity Bolton's answer (2): 187 weeks, 4 days
    Granularity   this   answer (3): 187 weeks, 4 days and 10 hours
    Granularity Bolton's answer (3): 187 weeks, 4 days, 9 hours
    Granularity   this   answer (4): 187 weeks, 4 days, 9 hours and 43 minutes
    Granularity Bolton's answer (4): 187 weeks, 4 days, 9 hours, 42 minutes
    Granularity   this   answer (5): 187 weeks, 4 days, 9 hours, 42 minutes and 40 seconds
    Granularity Bolton's answer (5): 187 weeks, 4 days, 9 hours, 42 minutes, 40 seconds

I have a french translation ready. But it's fast to do the translation ... just few words. Hope this could help as the other answer help me a lot.

How to convert a String to long in javascript?

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

What is the difference between encrypting and signing in asymmetric encryption?

Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.

Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.

As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.

Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

How to call VS Code Editor from terminal / command line

Other easyway to do it on mac is :go to Command Palette[ Shift ?+ Command (?)+P] and type :Shell Command: Install 'code' command in PATH

once installed: Shell command 'code' successfully installed in PATH.

Then you can use code from the terminal as well.

How can I autoplay a video using the new embed code style for Youtube?

Okay this is an example for the new embed code for youtube videos.

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM" frameborder="0" allowFullScreen></iframe>

if you want to autoplay it, at the src="http://www.youtube.com/embed/8v_4O44sfjM" add the ?autoplay=1 parameter

So the code will look like this:

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM?autoplay=1" frameborder="0" allowFullScreen></iframe>

i tried this on my blog and it works ! Hope this help (:

MaxLength Attribute not generating client-side validation attributes

Props to @Nick-Harrison for his answer:

$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});

I was wondering what the parseInt() is for there? I've simplified it to this with no problems...

$("input[data-val-length-max]").each(function (index, element) {
    element.setAttribute("maxlength", element.getAttribute("data-val-length-max"))
});

I would have commented on Nicks answer but don't have enough rep yet.

Enable/Disable a dropdownbox in jquery

$(document).ready(function() {
 $('#chkdwn2').click(function() {
   if ($('#chkdwn2').prop('checked')) {
      $('#dropdown').prop('disabled', true);
   } else {
      $('#dropdown').prop('disabled', false);  
   }
 });
});

making use of .prop in the if statement.

Git: How to find a deleted file in the project commit history?

Suppose you want to recover a file called MyFile, but are uncertain of its path (or its extension, for that matter):

Preliminary: Avoid confusion by stepping to the git root

A nontrivial project may have multiple directories with similar or identical filenames.

> cd <project-root>
  1. Find the full path

    git log --diff-filter=D --summary | grep delete | grep MyFile

    delete mode 100644 full/path/to/MyFile.js

full/path/to/MyFile.js is the path & file you're seeking.

  1. Determine all the commits that affected that file

    git log --oneline --follow -- full/path/to/MyFile.js

    bd8374c Some helpful commit message

    ba8d20e Another prior commit message affecting that file

    cfea812 The first message for a commit in which that file appeared.

  2. Checkout the file

If you choose the first-listed commit (the last chronologically, here bd8374c), the file will not be found, since it was deleted in that commit.

> git checkout bd8374c -- full/path/to/MyFile.js

`error: pathspec 'full/path/to/MyFile.js' did not match any file(s) known to git.`

Just select the preceding (append a caret) commit:

> git checkout bd8374c^ -- full/path/to/MyFile.js

Show Image View from file path?

onLoadImage Full load

private void onLoadImage(final String imagePath) {
    ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size

    //ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
    com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));

    imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(final String imageUri, View view) {
            super.onLoadingStarted(imageUri, view);

            progress2.setVisibility(View.VISIBLE);

            new Handler().post(new Runnable() {
                public void run() {
                    progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

                    // Picasso.with(getContext()).load(imagePath).into(imageView);
                    // Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);

                    Glide.with(getContext())
                            .load(imagePath)
                            .asBitmap()
                            .into(imageView);
                }
          });
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            // else { 
              Log.e("onLoadImage", "onLoadingComplete");
            //   progress2.setVisibility(View.INVISIBLE);
            // }
            // setLoagingCompileImage();
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            super.onLoadingFailed(imageUri, view, failReason);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadingFailed", imageUri);
            Log.e("onLoadingFailed", failReason.toString());
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            super.onLoadingCancelled(imageUri, view);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadImage", "onLoadingCancelled");
        }
    });
}

How to disable Python warnings?

import sys
if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")

Change ignore to default when working on the file or adding new functionality to re-enable warnings.

Multiple separate IF conditions in SQL Server

To avoid syntax errors, be sure to always put BEGIN and END after an IF clause, eg:

IF (@A!= @SA)
   BEGIN
   --do stuff
   END
IF (@C!= @SC)
   BEGIN
   --do stuff
   END

... and so on. This should work as expected. Imagine BEGIN and END keyword as the opening and closing bracket, respectively.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

Using split()

Snippet :

_x000D_
_x000D_
var data =$('#date').text();_x000D_
var arr = data.split('/');_x000D_
$("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);   
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="date">23/05/2013</div>
_x000D_
_x000D_
_x000D_

Fiddle

When you split this string ---> 23/05/2013 on /

var myString = "23/05/2013";
var arr = myString.split('/');

you'll get an array of size 3

arr[0] --> 23
arr[1] --> 05
arr[2] --> 2013

remove all special characters in java

You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W you will not replace underscores.

Scanner scan = new Scanner(System.in);

while(scan.hasNextLine()){
    System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}

Excel - Button to go to a certain sheet

Alternately, if you are using a Macro Enabled workbook:

Add any control at all from the Developer -> Insert (Probably a button)

When it asks what Macro to assign, choose New. For the code for the generated module enter something like:

Thisworkbook.Sheets("Sheet Name").Activate

However, if you are not using Macros in your work book. Ooo's approach is definitely surperior as hyperlinks will work with no need to trust the document.

Best way to make WPF ListView/GridView sort on column-header clicking?

I made an adaptation of the Microsoft way, where I override the ListView control to make a SortableListView:

public partial class SortableListView : ListView
    {        
        private GridViewColumnHeader lastHeaderClicked = null;
        private ListSortDirection lastDirection = ListSortDirection.Ascending;       

        public void GridViewColumnHeaderClicked(GridViewColumnHeader clickedHeader)
        {
            ListSortDirection direction;

            if (clickedHeader != null)
            {
                if (clickedHeader.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (clickedHeader != lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    string sortString = ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path;

                    Sort(sortString, direction);

                    lastHeaderClicked = clickedHeader;
                    lastDirection = direction;
                }
            }
        }

        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource != null ? this.ItemsSource : this.Items);

            dataView.SortDescriptions.Clear();
            SortDescription sD = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sD);
            dataView.Refresh();
        }
    }

The line ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path bit handles the cases where your column names are not the same as their binding paths, which the Microsoft method does not do.

I wanted to intercept the GridViewColumnHeader.Click event so that I wouldn't have to think about it anymore, but I couldn't find a way to to do. As a result I add the following in XAML for every SortableListView:

GridViewColumnHeader.Click="SortableListViewColumnHeaderClicked"

And then on any Window that contains any number of SortableListViews, just add the following code:

private void SortableListViewColumnHeaderClicked(object sender, RoutedEventArgs e)
        {
            ((Controls.SortableListView)sender).GridViewColumnHeaderClicked(e.OriginalSource as GridViewColumnHeader);
        }

Where Controls is just the XAML ID for the namespace in which you made the SortableListView control.

So, this does prevent code duplication on the sorting side, you just need to remember to handle the event as above.

How to create a md5 hash of a string in C?

As other answers have mentioned, the following calls will compute the hash:

MD5Context md5;
MD5Init(&md5);
MD5Update(&md5, data, datalen);
MD5Final(digest, &md5);

The purpose of splitting it up into that many functions is to let you stream large datasets.

For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update on them.

MD5Context md5;
MD5Init(&md5);

fread(/* Read a block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);

...

//  Now finish to get the final hash value.
MD5Final(digest, &md5);

How to reset all checkboxes using jQuery or pure JS?

 $(":checkbox:checked").each(function () {

 this.click(); 
});

to unchecked checked box, turn your logic around to do opposite

How can I check if a date is the same day as datetime.today()?

If you want to just compare dates,

yourdatetime.date() < datetime.today().date()

Or, obviously,

yourdatetime.date() == datetime.today().date()

If you want to check that they're the same date.

The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about. Unless your question is about a function/module named "snake".

Basically, the datetime module has three types for storing a point in time:

  • date for year, month, day of month
  • time for hours, minutes, seconds, microseconds, time zone info
  • datetime combines date and time. It has the methods date() and time() to get the corresponding date and time objects, and there's a handy combine function to combine date and time into a datetime.

Why is there an unexplainable gap between these inline-block div elements?

In this instance, your div elements have been changed from block level elements to inline elements. A typical characteristic of inline elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)

There are a few solutions that can be used to solve this.

Method 1 - Remove the whitespace from the markup

Example 1 - Comment the whitespace out: (example)

<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>

Example 2 - Remove the line breaks: (example)

<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>

Example 3 - Close part of the tag on the next line (example)

<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>

Example 4 - Close the entire tag on the next line: (example)

<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>

Method 2 - Reset the font-size

Since the whitespace between the inline elements is determined by the font-size, you could simply reset the font-size to 0, and thus remove the space between the elements.

Just set font-size: 0 on the parent elements, and then declare a new font-size for the children elements. This works, as demonstrated here (example)

#parent {
    font-size: 0;
}

#child {
    font-size: 16px;
}

This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size is declared using em units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline elements.

Method 3 - Set the parent element to display: flex

In some cases, you can also set the display of the parent element to flex. (example)

This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.

.parent {
    display: flex;
}
.parent > div {
    display: inline-block;
    padding: 1em;
    border: 2px solid #f00;
}

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
    display: inline-block;_x000D_
    padding: 1em;_x000D_
    border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Sides notes:

It is incredibly unreliable to use negative margins to remove the space between inline elements. Please don't use negative margins if there are other, more optimal, solutions.

A simple command line to download a remote maven2 artifact to the local repository?

Give them a trivial pom with these jars listed as dependencies and instructions to run:

mvn dependency:go-offline

This will pull the dependencies to the local repo.

A more direct solution is dependency:get, but it's a lot of arguments to type:

mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version

Opening a folder in explorer and selecting a file

Samuel Yang answer tripped me up, here is my 3 cents worth.

Adrian Hum is right, make sure you put quotes around your filename. Not because it can't handle spaces as zourtney pointed out, but because it will recognize the commas (and possibly other characters) in filenames as separate arguments. So it should look as Adrian Hum suggested.

string argument = "/select, \"" + filePath +"\"";

Selectors in Objective-C?

You have to be very careful about the method names. In this case, the method name is just "lowercaseString", not "lowercaseString:" (note the absence of the colon). That's why you're getting NO returned, because NSString objects respond to the lowercaseString message but not the lowercaseString: message.

How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:.

You can also look at the documentation and note the presence or absence of a trailing colon.

How can I concatenate a string within a loop in JSTL/JSP?

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Are you using JavaScript or jQuery besides the html? If you are, you can do something like:

HTML:

<select id='some_selector'></select>?

jQuery:

var select = '';
for (i=1;i<=100;i++){
    select += '<option val=' + i + '>' + i + '</option>';
}
$('#some_selector').html(select);

As you can see here.

Another option for compatible browsers instead of select, you can use is HTML5's input type=number:

<input type="number" min="1" max="100" value="1">

getActivity() returns null in Fragment function

commit schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready.

I'd suggest adding an

onAttach(Activity activity)

method to your Fragment and putting a break point on it and seeing when it is called relative to your call to asd(). You'll see that it is called after the method where you make the call to asd() exits. The onAttach call is where the Fragment is attached to its activity and from this point getActivity() will return non-null (nb there is also an onDetach() call).

Using GitLab token to clone without authentication

If you already has a repository and just changed the way you do authentication to MFA, u can change your remote origin HTTP URI to use your new api token as follows:

git remote set-url origin https://oauth2:TOKEN@ANY_GIT_PROVIDER_DOMAIN/YOUR_PROJECT/YOUR_REPO.git

And you wont need to re-clone the repository at all.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

Best XML parser for Java

In addition to SAX and DOM there is STaX parsing available using XMLStreamReader which is an xml pull parser.

What are the differences between the different saving methods in Hibernate?

This link explains in good manner :

http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate/

We all have those problems that we encounter just infrequently enough that when we see them again, we know we’ve solved this, but can’t remember how.

The NonUniqueObjectException thrown when using Session.saveOrUpdate() in Hibernate is one of mine. I’ll be adding new functionality to a complex application. All my unit tests work fine. Then in testing the UI, trying to save an object, I start getting an exception with the message “a different object with the same identifier value was already associated with the session.” Here’s some example code from Java Persistence with Hibernate.

            Session session = sessionFactory1.openSession();
            Transaction tx = session.beginTransaction();
            Item item = (Item) session.get(Item.class, new Long(1234));
            tx.commit();
            session.close(); // end of first session, item is detached

            item.getId(); // The database identity is "1234"
            item.setDescription("my new description");
            Session session2 = sessionFactory.openSession();
            Transaction tx2 = session2.beginTransaction();
            Item item2 = (Item) session2.get(Item.class, new Long(1234));
            session2.update(item); // Throws NonUniqueObjectException
            tx2.commit();
            session2.close();

To understand the cause of this exception, it’s important to understand detached objects and what happens when you call saveOrUpdate() (or just update()) on a detached object.

When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application’s memory, but Hibernate is no longer responsible for tracking changes to the objects.

If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.

Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.

So what are we to do? In Hibernate 3, we have merge() (in Hibernate 2, use saveOrUpdateCopy()). This method will force Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.

        Session session = sessionFactory1.openSession();
        Transaction tx = session.beginTransaction();
        Item item = (Item) session.get(Item.class, new Long(1234));
        tx.commit();
        session.close(); // end of first session, item is detached

        item.getId(); // The database identity is "1234"
        item.setDescription("my new description");
        Session session2 = sessionFactory.openSession();
        Transaction tx2 = session2.beginTransaction();
        Item item2 = (Item) session2.get(Item.class, new Long(1234));
        Item item3 = session2.merge(item); // Success!
        tx2.commit();
        session2.close();

It’s important to note that merge returns a reference to the newly updated version of the instance. It isn’t reattaching item to the Session. If you test for instance equality (item == item3), you’ll find it returns false in this case. You will probably want to work with item3 from this point forward.

It’s also important to note that the Java Persistence API (JPA) doesn’t have a concept of detached and reattached objects, and uses EntityManager.persist() and EntityManager.merge().

I’ve found in general that when using Hibernate, saveOrUpdate() is usually sufficient for my needs. I usually only need to use merge when I have objects that can have references to objects of the same type. Most recently, the cause of the exception was in the code validating that the reference wasn’t recursive. I was loading the same object into my session as part of the validation, causing the error.

Where have you encountered this problem? Did merge work for you or did you need another solution? Do you prefer to always use merge, or prefer to use it only as needed for specific cases

How to redirect in a servlet filter?

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

Create an array with random values

Refer below :-

let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */

Encode html entities in javascript

I had the same problem and created 2 functions to create entities and translate them back to normal characters. The following methods translate any string to HTML entities and back on String prototype

/**
 * Convert a string to HTML entities
 */
String.prototype.toHtmlEntities = function() {
    return this.replace(/./gm, function(s) {
        // return "&#" + s.charCodeAt(0) + ";";
        return (s.match(/[a-z0-9\s]+/i)) ? s : "&#" + s.charCodeAt(0) + ";";
    });
};

/**
 * Create string from HTML entities
 */
String.fromHtmlEntities = function(string) {
    return (string+"").replace(/&#\d+;/gm,function(s) {
        return String.fromCharCode(s.match(/\d+/gm)[0]);
    })
};

You can then use it as following:

var str = "Test´†®¥¨©??ø…ˆƒ?÷?™ƒ?æøp£¨ ƒ™en tést".toHtmlEntities();
console.log("Entities:", str);
console.log("String:", String.fromHtmlEntities(str));

Output in console:

Entities: &#68;&#105;&#116;&#32;&#105;&#115;&#32;&#101;&#180;&#8224;&#174;&#165;&#168;&#169;&#729;&#8747;&#248;&#8230;&#710;&#402;&#8710;&#247;&#8721;&#8482;&#402;&#8710;&#230;&#248;&#960;&#163;&#168;&#160;&#402;&#8482;&#101;&#110;&#32;&#116;&#163;&#101;&#233;&#115;&#116;
String: Dit is e´†®¥¨©??ø…ˆƒ?÷?™ƒ?æøp£¨ ƒ™en t£eést 

How to get the path of src/test/resources directory in JUnit?

Use .getAbsolutePath() on your File object.

getClass().getResource("somefile").getFile().getAbsolutePath()

What is Join() in jQuery?

join is not a jQuery function .Its a javascript function.

The join() method joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

http://www.w3schools.com/jsref/jsref_join.asp

os.walk without digging into directories below

root folder changes for every directory os.walk finds. I solver that checking if root == directory

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        if root == dir_name: #This only meet parent folder
            for f in files:
                if os.path.splitext(f)[1] in whitelist:
                    outputList.append(os.path.join(root, f))
                else:
                    self._email_to_("ignore")
    return outputList

How does one use the onerror attribute of an img element

This works:

<img src="invalid_link"
     onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>

Live demo: http://jsfiddle.net/oLqfxjoz/

As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;.

Credentials for the SQL Server Agent service are invalid

I found I had to be logged in as a domain user.

It gave me this error when I was logged in as local machine Administrator and trying to add domain service account.

Logged in as domain user (but admin on machine) and it accepted the credentials.

Creating multiple log files of different content with log4j

Demo link: https://github.com/RazvanSebastian/spring_multiple_log_files_demo.git

My solution is based on XML configuration using spring-boot-starter-log4j. The example is a basic example using spring-boot-starter and the two Loggers writes into different log files.

Adding CSRFToken to Ajax request

How about this,

$("body").bind("ajaxSend", function(elm, xhr, s){
   if (s.type == "POST") {
      xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
   }
});

Ref: http://erlend.oftedal.no/blog/?blogid=118

To pass CSRF as parameter,

        $.ajax({
            type: "POST",
            url: "file",
            data: { CSRF: getCSRFTokenValue()}
        })
        .done(function( msg ) {
            alert( "Data: " + msg );
        });

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

@James Jithin - such exception can appear also when you have two different versions of beans and security schema in xsi:schemaLocation. It's the case in the snippet you have pasted:

xsi:schemaLocation="http://www.springframework.org/schema/beans   
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
 http://www.springframework.org/schema/security  
 http://www.springframework.org/schema/security/spring-security-3.1.xsd"

In my case changing them both to 3.1 solved the problem

What is an example of the simplest possible Socket.io example?

Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.

I adapted this example from the example posted here: http://socket.io/get-started/chat/

First, start in an empty directory, and create a very simple file called package.json Place the following in it.

{
"dependencies": {}
}

Next, on the command line, use npm to install the dependencies we need for this example

$ npm install --save express socket.io

This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

Create a file called server.js This will obviously be our server run by node. Place the following code into it:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

Create the last file called index.html and place the following code into it.

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

You can now test this very simple example and see some output similar to the following:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

For my case, the culprit was the semicolon and double quotes in the password for prod DB. Our IT team use some tool to generate passwords, so it generated one with the semicolon and double quotes Connectionstring looks like

<add key="BusDatabaseConnectionString" value="Data Source=myserver;Initial Catalog=testdb;User Id=Listener;Password=BlaBla"';[]qrk/>

Got the password changed and it worked.

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:

Could not load file or assembly '..., Version=..., Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.

In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:

Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.

It turned out to be a result of the following actions on a Solution:

  1. NuGet Package Restore was turned on for the Solution.

  2. A Project was added, and a Nuget package was installed into it (AjaxMin in this case).

  3. The Project was moved to different folder in the Solution.

  4. The Nuget package was updated to a newer version.

And slowly but surely this bug started showing up for some users.

The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:

  <repository path="..\Old\packages.config" />

And this after the reorg:

  <repository path="..\Old\packages.config" />
  <repository path="..\New\packages.config" />

So the first line now refers to a Project that, while on disk, is no longer part of my Solution.

With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.

Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.

The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.

C# nullable string error

String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.

How to get a value from the last inserted row?

Since PostgreSQL JDBC driver version 8.4-701 the PreparedStatement#getGeneratedKeys() is finally fully functional. We use it here almost one year in production to our full satisfaction.

In "plain JDBC" the PreparedStatement needs to be created as follows to make it to return the keys:

statement = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);

You can download the current JDBC driver version here (which is at the moment still 8.4-701).

if (boolean == false) vs. if (!boolean)

The first form, when used with an API that returns Boolean and compared against Boolean.FALSE, will never throw a NullPointerException.

The second form, when used with the java.util.Map interface, also, will never throw a NullPointerException because it returns a boolean and not a Boolean.

If you aren't concerned about consistent coding idioms, then you can pick the one you like, and in this concrete case it really doesn't matter. If you do care about consistent coding, then consider what you want to do when you check a Boolean that may be NULL.

What does "fatal: bad revision" mean?

I had a "fatal : bad revision" with Idea / Webstorm because I had a git directory inside another, without using properly submodules or subtrees.

I checked for .git dirs with :

find ./ -name '.git' -print

How to color the Git console?

For example see https://web.archive.org/web/20080506194329/http://www.arthurkoziel.com/2008/05/02/git-configuration/

The interesting part is

Colorized output:

git config --global color.branch auto
git config --global color.diff auto
git config --global color.interactive auto
git config --global color.status auto

How to call a method in MainActivity from another class?

Simply, You can make this method static as below:

public static void startChronometer(){
    mChronometer.start();
    showElapsedTime();
} 

you can call this function in other class as below:

MainActivity.startChronometer();

what is Promotional and Feature graphic in Android Market/Play Store?

In market client on phones at least featured apps with high ratings get to display the promotional graphic.

This is the one that shows up on top even before you start searching the market for a specific app.

See this answer from Android market forum.

Edited: One of the google employee gives some clarifications here

Update: Both links above are now broken but the detailed information can be found here

Selected applications have the ability to be featured atop their respective categories. This is not a guaranteed feature, but uploading promotional graphics is something that we recommend.

Cannot import XSSF in Apache POI

Problem: While importing the " org.apache.poi.xssf.usermodel.XSSFWorkbook"class showing an error in eclipse.

Solution: Use This maven dependency to resolve this problem:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.15</version>
</dependency>

-Hari Krishna Neela

Difference between a script and a program?

For me, the main difference is that a script is interpreted, while a program is executed (i.e. the source is first compiled, and the result of that compilation is expected).


Wikipedia seems to agree with me on this :

Script :

"Scripts" are distinct from the core code of the application, which is usually written in a different language, and are often created or at least modified by the end-user.
Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code.

Program :

The program has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled)

HTML Input Box - Disable

<input type="text" disabled="disabled" />

See the W3C HTML Specification on the input tag for more information.

ASP.NET Core - Swashbuckle not creating swagger.json file

I don't know if this is useful for someone, but in my case the problem was that the name had different casing.

V1 in the service configuration - V capital letter
v1 in Settings -- v lower case

The only thing I did was to use the same casing and it worked.

version name with capital V

What is the correct way to free memory in C#

Let's answer your questions one by one.

  1. Yes, you make a new object whenever this statement is executed, however, it goes "out of scope" when you exit the method and it is eligible for garbage collection.
  2. Well this would be the same as #1, except that you've used a string type. A string type is immutable and you get a new object every time you make an assignment.
  3. Yes the garbage collector collects the out of scope objects, unless you assign the object to a variable with a large scope such as class variable.
  4. Yes.
  5. The using statement only applies to objects that implement the IDisposable interface. If that is the case, by all means using is best for objects within a method's scope. Don't put Foo o at a larger scope unless you have a good reason to do so. It is best to limit the scope of any variable to the smallest scope that makes sense.

Unable to Cast from Parent Class to Child Class

The instance that your base class reference is referring to is not an instance of your child class. There's nothing wrong.

More specifically:

Base derivedInstance = new Derived();
Base baseInstance = new Base();

Derived good = (Derived)derivedInstance; // OK
Derived fail = (Derived)baseInstance; // Throws InvalidCastException

For the cast to be successful, the instance that you're downcasting must be an instance of the class that you're downcasting to (or at least, the class you're downcasting to must be within the instance's class hierarchy), otherwise the cast will fail.

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

HTML img align="middle" doesn't align an image

just remove float: left and replace align with margin: 0 auto and it will be centered.

JSON to string variable dump

You can use console.log() in Firebug or Chrome to get a good object view here, like this:

$.getJSON('my.json', function(data) {
  console.log(data);
});

If you just want to view the string, look at the Resource view in Chrome or the Net view in Firebug to see the actual string response from the server (no need to convert it...you received it this way).

If you want to take that string and break it down for easy viewing, there's an excellent tool here: http://json.parser.online.fr/

How to determine device screen size category (small, normal, large, xlarge) using code?

Copy and paste this code into your Activity and when it is executed it will Toast the device's screen size category.

int screenSize = getResources().getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK;

String toastMsg;
switch(screenSize) {
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        toastMsg = "Large screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        toastMsg = "Normal screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        toastMsg = "Small screen";
        break;
    default:
        toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();

jQuery Datepicker onchange event issue

DatePicker selected value change event code below

/* HTML Part */
<p>Date: <input type="text" id="datepicker"></p>

/* jQuery Part */
$("#datepicker").change(function() {
                selectedDate= $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
                alert(selectedDate);        
            });

Difference between git pull and git pull --rebase

Suppose you have two commits in local branch:

      D---E master
     /
A---B---C---F origin/master

After "git pull", will be:

      D--------E  
     /          \
A---B---C---F----G   master, origin/master

After "git pull --rebase", there will be no merge point G. Note that D and E become different commits:

A---B---C---F---D'---E'   master, origin/master

SQL Server : How to test if a string has only digit characters

The selected answer does not work.

declare @str varchar(50)='79D136'
select 1 where @str NOT LIKE '%[^0-9]%'

I don't have a solution but know of this potential pitfall. The same goes if you substitute the letter 'D' for 'E' which is scientific notation.

C - function inside struct

As others have noted, embedding function pointers directly inside your structure is usually reserved for special purposes, like a callback function.

What you probably want is something more like a virtual method table.

typedef struct client_ops_t client_ops_t;
typedef struct client_t client_t, *pno;

struct client_t {
    /* ... */
    client_ops_t *ops;
};

struct client_ops_t {
    pno (*AddClient)(client_t *);
    pno (*RemoveClient)(client_t *);
};

pno AddClient (client_t *client) { return client->ops->AddClient(client); }
pno RemoveClient (client_t *client) { return client->ops->RemoveClient(client); }

Now, adding more operations does not change the size of the client_t structure. Now, this kind of flexibility is only useful if you need to define many kinds of clients, or want to allow users of your client_t interface to be able to augment how the operations behave.

This kind of structure does appear in real code. The OpenSSL BIO layer looks similar to this, and also UNIX device driver interfaces have a layer like this.

Pattern matching using a wildcard

If you want to examine elements inside a dataframe you should not be using ls() which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls() (unless of course you add an environment argument to the ls(.)-call). Try using grep() which is the workhorse function for pattern matching of character vectors:

result <- a[ grep("blue", a$x) , ]  # Note need to use `a$` to get at the `x`

If you want to use subset then consider the closely related function grepl() which returns a vector of logicals can be used in the subset argument:

subset(a, grepl("blue", a$x))
      x
2 blue1
3 blue2

Edit: Adding one "proper" use of glob2rx within subset():

result <- subset(a,  grepl(glob2rx("blue*") , x) )
result
      x
2 blue1
3 blue2

I don't think I actually understood glob2rx until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)

Setting a PHP $_SESSION['var'] using jQuery

You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:

HTML:

<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />

Javascript:

$("img.foo").onclick(function()
{
    // Get the src of the image
    var src = $(this).attr("src");

    // Send Ajax request to backend.php, with src set as "img" in the POST data
    $.post("/backend.php", {"img": src});
});

PHP (backend.php):

<?php
    // do any authentication first, then add POST variable to session
    $_SESSION['imgsrc'] = $_POST['img'];
?>

Trigger back-button functionality on button click in Android

If you are inside the fragment then you write the following line of code inside your on click listener, getActivity().onBackPressed(); this works perfectly for me.

Creating stored procedure and SQLite?

SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth

Source : Appropriate Uses For SQLite

Get method arguments using Spring AOP?

Yes, the value of any argument can be found using getArgs

@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {

   Object[] signatureArgs = thisJoinPoint.getArgs();
   for (Object signatureArg: signatureArgs) {
      System.out.println("Arg: " + signatureArg);
      ...
   }
}

x86 Assembly on a Mac

Forget about finding a IDE to write/run/compile assembler on Mac. But, remember mac is UNIX. See http://asm.sourceforge.net/articles/linasm.html. A decent guide (though short) to running assembler via GCC on Linux. You can mimic this. Macs use Intel chips so you want to look at Intel syntax.

Conda version pip install -r requirements.txt --target ./lib

would this work?

cat requirements.txt | while read x; do conda install "$x" -p ./lib ;done

or

conda install --file requirements.txt -p ./lib

Access restriction on class due to restriction on required library rt.jar?

I just had this problem too. Apparently I had set the JRE to 1.5 instead of 1.6 in my build path.

Using Position Relative/Absolute within a TD?

This is because according to CSS 2.1, the effect of position: relative on table elements is undefined. Illustrative of this, position: relative has the desired effect on Chrome 13, but not on Firefox 4. Your solution here is to add a div around your content and put the position: relative on that div instead of the td. The following illustrates the results you get with the position: relative (1) on a div good), (2) on a td(no good), and finally (3) on a div inside a td (good again).

On Firefox 4

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="position:relative;">_x000D_
        <span style="position:absolute; left:150px;">_x000D_
          Absolute span_x000D_
        </span>_x000D_
        Relative div_x000D_
      </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I disable the Maven Javadoc plugin from the command line?

Add to the release plugin config in the root-level pom.xml:

<configuration>
    <arguments>-Dmaven.javadoc.skip=true</arguments>
</configuration>

Simple export and import of a SQLite database on Android

Import and Export of a SQLite database on Android

Here is my function for export database into device storage

private void exportDB(){
    String DatabaseName = "Sycrypter.db";
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
    String backupDBPath = SAMPLE_DB_NAME;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

Here is my function for import database from device storage into android application

private void importDB(){
    String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
    File sd = new File(dir);
    File data = Environment.getDataDirectory();
    FileChannel source = null;
    FileChannel destination = null;
    String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
    String currentDBPath = "Sycrypter.db";
    File currentDB = new File(sd, currentDBPath);
    File backupDB = new File(data, backupDBPath);

    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

How can I install Apache Ant on Mac OS X?

MacPorts will install ant for you in MacOSX 10.9. Just use

$ sudo port install apache-ant

and it will install.

JPA entity without id

See the Java Persistence book: Identity and Sequencing

The relevant part for your question is the No Primary Key section:

Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object's row, so all of the matching rows will be updated or deleted.

If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

Edit a commit message in SourceTree Windows (already pushed to remote)

On Version 1.9.6.1. For UnPushed commit.

  1. Click on previously committed description
  2. Click Commit icon
  3. Enter new commit message, and choose "Ammend latest commit" from the Commit options dropdown.
  4. Commit your message.

PHP substring extraction. Get the string before the first '/' or the whole string

Use explode()

$arr = explode("/", $string, 2);
$first = $arr[0];

In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.

How to replace a character by a newline in Vim

\r can do the work here for you.

implement addClass and removeClass functionality in angular2

You can basically switch the class using [ngClass]

for example

<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

Efficient way to add spaces between characters in a string

A very pythonic and practical way to do it is by using the string join() method:

str.join(iterable)

The official Python documentations says:

Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.

How to use it?

Remember: this is a string method.

This method will be applied to the str above, which reflects the string that will be used as separator of the items in the iterable.

Let's have some practical example!

iterable = "BINGO"
separator = " " # A whitespace character.
                # The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'

In practice you would do it like this:

iterable = "BINGO"    
" ".join(iterable)
> 'B I N G O'

But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.

iterable = ['B', 'I', 'N', 'G', 'O']    
" ".join(iterable)
> 'B I N G O'

What happens if you use a hyphen as a string instead?

iterable = ['B', 'I', 'N', 'G', 'O']    
"-".join(iterable)
> 'B-I-N-G-O'

C# Dictionary get item by index

Your key is a string and your value is an int. Your code won't work because it cannot look up the random int you pass. Also, please provide full code

How to dynamically create CSS class in JavaScript and apply?

Here is Vishwanath's solution slightly rewritten with comments :

function setStyle(cssRules, aSelector, aStyle){
    for(var i = 0; i < cssRules.length; i++) {
        if(cssRules[i].selectorText && cssRules[i].selectorText.toLowerCase() == aSelector.toLowerCase()) {
            cssRules[i].style.cssText = aStyle;
            return true;
        }
    }
    return false;
}

function createCSSSelector(selector, style) {
    var doc = document;
    var allSS = doc.styleSheets;
    if(!allSS) return;

    var headElts = doc.getElementsByTagName("head");
    if(!headElts.length) return;

    var styleSheet, media, iSS = allSS.length; // scope is global in a function
    /* 1. search for media == "screen" */
    while(iSS){ --iSS;
        if(allSS[iSS].disabled) continue; /* dont take into account the disabled stylesheets */
        media = allSS[iSS].media;
        if(typeof media == "object")
            media = media.mediaText;
        if(media == "" || media=='all' || media.indexOf("screen") != -1){
            styleSheet = allSS[iSS];
            iSS = -1;   // indication that media=="screen" was found (if not, then iSS==0)
            break;
        }
    }

    /* 2. if not found, create one */
    if(iSS != -1) {
        var styleSheetElement = doc.createElement("style");
        styleSheetElement.type = "text/css";
        headElts[0].appendChild(styleSheetElement);
        styleSheet = doc.styleSheets[allSS.length]; /* take the new stylesheet to add the selector and the style */
    }

    /* 3. add the selector and style */
    switch (typeof styleSheet.media) {
    case "string":
        if(!setStyle(styleSheet.rules, selector, style));
            styleSheet.addRule(selector, style);
        break;
    case "object":
        if(!setStyle(styleSheet.cssRules, selector, style));
            styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length);
        break;
    }

How can I pass arguments to a batch file?

Accessing batch parameters can be simple with %1, %2, ... %9 or also %*,
but only if the content is simple.

There is no simple way for complex contents like "&"^&, as it's not possible to access %1 without producing an error.

set  var=%1
set "var=%1"
set  var=%~1
set "var=%~1"

The lines expand to

set  var="&"&
set "var="&"&"
set  var="&"&
set "var="&"&"

And each line fails, as one of the & is outside of the quotes.

It can be solved with reading from a temporary file a remarked version of the parameter.

@echo off
SETLOCAL DisableDelayedExpansion

SETLOCAL
for %%a in (1) do (
    set "prompt="
    echo on
    for %%b in (1) do rem * #%1#
    @echo off
) > param.txt
ENDLOCAL

for /F "delims=" %%L in (param.txt) do (
  set "param1=%%L"
)
SETLOCAL EnableDelayedExpansion
set "param1=!param1:*#=!"
set "param1=!param1:~0,-2!"
echo %%1 is '!param1!'

The trick is to enable echo on and expand the %1 after a rem statement (works also with %2 .. %*).
So even "&"& could be echoed without producing an error, as it is remarked.

But to be able to redirect the output of the echo on, you need the two for-loops.

The extra characters * # are used to be safe against contents like /? (would show the help for REM).
Or a caret ^ at the line end could work as a multiline character, even in after a rem.

Then reading the rem parameter output from the file, but carefully.
The FOR /F should work with delayed expansion off, else contents with "!" would be destroyed.
After removing the extra characters in param1, you got it.

And to use param1 in a safe way, enable the delayed expansion.

Find ALL tweets from a user (not just the first 3,200)

I've been in this (Twitter) industry for a long time and witnessed lots of changes in Twitter API and documentation. I would like to clarify one thing to you. There is no way to surpass 3200 tweets limit. Twitter doesn't provide this data even in its new premium API.

The only way someone can surpass this limit is by saving the tweets of an individual Twitter user.

There are tools available which claim to have a wide database and provide more than 3200 tweets. Few of them are followersanalysis.com, keyhole.co which I know of.

Truncating Text in PHP?

The obvious thing to do is read the documentation.

But to help: substr($str, $start, $end);

$str is your text

$start is the character index to begin at. In your case, it is likely 0 which means the very beginning.

$end is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:

<?php

$text = "long text that should be truncated";
echo substr($text, 0, 15);

?>

and you would get this:

long text that 

makes sense?

EDIT

The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:

function truncate($text, $chars = 25) {
    if (strlen($text) <= $chars) {
        return $text;
    }
    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

So in your case you would paste this function into the functions.php file and call it like this in your page:

$post = the_post();
echo truncate($post, 100);

This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

scp from Linux to Windows

Your code isn't working because c:/ or d:/ is totally wrong for linux just use /mnt/c or/mnt/c

From your local windows10-ubuntu bash use this command:

for download: (from your remote server folder to d:/ubuntu) :

scp username@ipaddress:/folder/file.txt /mnt/d/ubuntu

Then type your remote server password if there is need.

for upload: (from d:/ubuntu to remote server ) :

scp /mnt/d/ubuntu/file.txt username@ipaddress:/folder/file.txt 

Then type your remote server password if there is need. note: I tested and it worked.

Output an Image in PHP

header('Content-type: image/jpeg');
readfile($image);

CSS Equivalent of the "if" statement

CSS has become a very powerful tool over the years and it has hacks for a lot of things javaScript can do

There is a hack in CSS for using conditional statements/logic.

It involves using the symbol '~'

Let me further illustrate with an example.

Let's say you want a background to slide into the page when a button is clicked. All you need to do is use a radio checkbox. Style the label for the radio underneath the button so that when the button is pressed the checkbox is also pressed.

Then you use the code below

.checkbox:checked ~ .background{
opacity:1
width: 100%
}

This code simply states IF the checkbox is CHECKED then open up the background ELSE leave it as it is.

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

A great substitute for np.isnan() and pd.isnull() is

for i in range(0,a.shape[0]):
    if(a[i]!=a[i]):
       //do something here
       //a[i] is nan

since only nan is not equal to itself.

Unit testing void methods?

What ever instance you are using to call the void method , You can just use ,Verfiy

For Example:

In My case its _Log is the instance and LogMessage is the method to be tested:

try
{
    this._log.Verify(x => x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, "Created the Student with name as"), "Failure");
}
Catch 
{
    Assert.IsFalse(ex is Moq.MockException);
}

Is the Verify throws an exception due to failure of the method the test would Fail ?

Python speed testing - Time Difference - milliseconds

I know this is late, but I actually really like using:

import time
start = time.time()

##### your timed code here ... #####

print "Process time: " + (time.time() - start)

time.time() gives you seconds since the epoch. Because this is a standardized time in seconds, you can simply subtract the start time from the end time to get the process time (in seconds). time.clock() is good for benchmarking, but I have found it kind of useless if you want to know how long your process took. For example, it's much more intuitive to say "my process takes 10 seconds" than it is to say "my process takes 10 processor clock units"

>>> start = time.time(); sum([each**8.3 for each in range(1,100000)]) ; print (time.time() - start)
3.4001404476250935e+45
0.0637760162354
>>> start = time.clock(); sum([each**8.3 for each in range(1,100000)]) ; print (time.clock() - start)
3.4001404476250935e+45
0.05

In the first example above, you are shown a time of 0.05 for time.clock() vs 0.06377 for time.time()

>>> start = time.clock(); time.sleep(1) ; print "process time: " + (time.clock() - start)
process time: 0.0
>>> start = time.time(); time.sleep(1) ; print "process time: " + (time.time() - start)
process time: 1.00111794472

In the second example, somehow the processor time shows "0" even though the process slept for a second. time.time() correctly shows a little more than 1 second.

Hexadecimal string to byte array in C

Could it be simpler?!

uint8_t hex(char ch) {
    uint8_t r = (ch > 57) ? (ch - 55) : (ch - 48);
    return r & 0x0F;
}

int to_byte_array(const char *in, size_t in_size, uint8_t *out) {
    int count = 0;
    if (in_size % 2) {
        while (*in && out) {
            *out = hex(*in++);
            if (!*in)
                return count;
            *out = (*out << 4) | hex(*in++);
            *out++;
            count++;
        }
        return count;
    } else {
        while (*in && out) {
            *out++ = (hex(*in++) << 4) | hex(*in++);
            count++;
        }
        return count;
    }
}

int main() {
    char hex_in[] = "deadbeef10203040b00b1e50";
    uint8_t out[32];
    int res = to_byte_array(hex_in, sizeof(hex_in) - 1, out);

    for (size_t i = 0; i < res; i++)
        printf("%02x ", out[i]);

    printf("\n");
    system("pause");
    return 0;
}

How to read and write INI file with Python3?

ConfigObj is a good alternative to ConfigParser which offers a lot more flexibility:

  • Nested sections (subsections), to any level
  • List values
  • Multiple line values
  • String interpolation (substitution)
  • Integrated with a powerful validation system including automatic type checking/conversion repeated sections and allowing default values
  • When writing out config files, ConfigObj preserves all comments and the order of members and sections
  • Many useful methods and options for working with configuration files (like the 'reload' method)
  • Full Unicode support

It has some draw backs:

  • You cannot set the delimiter, it has to be =… (pull request)
  • You cannot have empty values, well you can but they look liked: fuabr = instead of just fubar which looks weird and wrong.

Change Active Menu Item on Page Scroll?

If you want the accepted answer to work in JQuery 3 change the code like this:

var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });

I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)

How to save all console output to file in R?

If you are able to use the bash shell, you can consider simply running the R code from within a bash script and piping the stdout and stderr streams to a file. Here is an example using a heredoc:

File: test.sh

#!/bin/bash
# this is a bash script
echo "Hello World, this is bash"

test1=$(echo "This is a test")

echo "Here is some R code:"

Rscript --slave --no-save --no-restore - "$test1" <<EOF
  ## R code
  cat("\nHello World, this is R\n")
  args <- commandArgs(TRUE)
  bash_message<-args[1]
  cat("\nThis is a message from bash:\n")
  cat("\n",paste0(bash_message),"\n")
EOF

# end of script 

Then when you run the script with both stderr and stdout piped to a log file:

$ chmod +x test.sh
$ ./test.sh
$ ./test.sh &>test.log
$ cat test.log
Hello World, this is bash
Here is some R code:

Hello World, this is R

This is a message from bash:

 This is a test

Other things to look at for this would be to try simply pipping the stdout and stderr right from the R heredoc into a log file; I haven't tried this yet but it will probably work too.

The name 'InitializeComponent' does not exist in the current context

Unload the entire solution and then reload it again. Then Rebuild the solution. This resolved the issue for me.

Check if a number has a decimal place/is a whole number

parseInt(num) === num

when passed a number, parseInt() just returns the number as int:

parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3     // true

Check free disk space for current partition in bash

Yes:

df -k .

for the current directory.

df -k /some/dir

if you want to check a specific directory.

You might also want to check out the stat(1) command if your system has it. You can specify output formats to make it easier for your script to parse. Here's a little example:

$ echo $(($(stat -f --format="%a*%S" .)))

Yes/No message box using QMessageBox

If you want to make it in python you need check this code in your workbench. also write like this. we created a popup box with python.

msgBox = QMessageBox()
msgBox.setText("The document has been modified.")
msgBox.setInformativeText("Do you want to save your changes?")
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Save)
ret = msgBox.exec_()

did you specify the right host or port? error on Kubernetes

Make sure your config is set to the project - gcloud config set project [PROJECT_ID]

  1. Run a checklist of the Clusters in the account: gcloud container clusters list

  2. Check the output : NAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VE. alpha-cluster asia-south1-a 1.9.7-gke.6 35.200.254.78 f1-micro 1.9.7- NUM_NODES STATUS gke.6 3 RUNNING

  3. Run the following cmd to fetch credentials for your running cluster:

gcloud container clusters get-credentials your-cluster-name --zone your-zone --project your-project

  1. The following output follows:

Fetching cluster endpoint and auth data. kubeconfig entry generated for alpha-cluster.

  1. Try checking details of the node running kubectl such as below to list all pods in the current namespace, with more details:

$ kubectl get nodes -o wide

Should be good to go.

How can I use interface as a C# generic type constraint?

You cannot do this in any released version of C#, nor in the upcoming C# 4.0. It's not a C# limitation, either - there's no "interface" constraint in the CLR itself.

How do you fade in/out a background color using jquery?

I know that the question was how to do it with Jquery, but you can achieve the same affect with simple css and just a little jquery...

For example, you have a div with 'box' class, add the following css

.box {
background-color: black;
-webkit-transition: background 0.5s linear;
-moz-transition: background 0.5s linear;
-ms-transition: background 0.5s linear;
-o-transition: background 0.5s linear;
transition: background 0.5s linear;
}

and then use AddClass function to add another class with different background color like 'box highlighted' or something like that with the following css:

.box.highlighted {
  background-color: white;
}

I am a beginner and maybe there are some disadvantages of this method but maybe it'll be helpful for somebody

Here's a codepen: https://codepen.io/anon/pen/baaLYB

Can an AJAX response set a cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

AngularJS - Access to child scope

Using $emit and $broadcast, (as mentioned by walv in the comments above)

To fire an event upwards (from child to parent)

$scope.$emit('myTestEvent', 'Data to send');

To fire an event downwards (from parent to child)

$scope.$broadcast('myTestEvent', {
  someProp: 'Sending you some data'
});

and finally to listen

$scope.$on('myTestEvent', function (event, data) {
  console.log(data);
});

For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Enjoy :)

What are the complexity guarantees of the standard containers?

I found the nice resource Standard C++ Containers. Probably this is what you all looking for.

VECTOR

Constructors

vector<T> v;              Make an empty vector.                                     O(1)
vector<T> v(n);           Make a vector with N elements.                            O(n)
vector<T> v(n, value);    Make a vector with N elements, initialized to value.      O(n)
vector<T> v(begin, end);  Make a vector and copy the elements from begin to end.    O(n)

Accessors

v[i]          Return (or set) the I'th element.                        O(1)
v.at(i)       Return (or set) the I'th element, with bounds checking.  O(1)
v.size()      Return current number of elements.                       O(1)
v.empty()     Return true if vector is empty.                          O(1)
v.begin()     Return random access iterator to start.                  O(1)
v.end()       Return random access iterator to end.                    O(1)
v.front()     Return the first element.                                O(1)
v.back()      Return the last element.                                 O(1)
v.capacity()  Return maximum number of elements.                       O(1)

Modifiers

v.push_back(value)         Add value to end.                                                O(1) (amortized)
v.insert(iterator, value)  Insert value at the position indexed by iterator.                O(n)
v.pop_back()               Remove value from end.                                           O(1)
v.assign(begin, end)       Clear the container and copy in the elements from begin to end.  O(n)
v.erase(iterator)          Erase value indexed by iterator.                                 O(n)
v.erase(begin, end)        Erase the elements from begin to end.                            O(n)

For other containers, refer to the page.

Converting list to *args when calling function

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

so:

>>> def printer(*args):
 print args


>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>> 

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

How to read a .xlsx file using the pandas Library in iPython?

Instead of using a sheet name, in case you don't know or can't open the excel file to check in ubuntu (in my case, Python 3.6.7, ubuntu 18.04), I use the parameter index_col (index_col=0 for the first sheet)

import pandas as pd
file_name = 'some_data_file.xlsx' 
df = pd.read_excel(file_name, index_col=0)
print(df.head()) # print the first 5 rows

What's in an Eclipse .classpath/.project file?

Complete reference is not available for the mentioned files, as they are extensible by various plug-ins.

Basically, .project files store project-settings, such as builder and project nature settings, while .classpath files define the classpath to use during running. The classpath files contains src and target entries that correspond with folders in the project; the con entries are used to describe some kind of "virtual" entries, such as the JVM libs or in case of eclipse plug-ins dependencies (normal Java project dependencies are displayed differently, using a special src entry).

How do I generate sourcemaps when using babel and webpack?

On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.

https://webpack.js.org/configuration/devtool

devtool best dev options

                                build   rebuild      quality                       look
eval-source-map                 slow    pretty fast  original source               worst
inline-source-map               slow    slow         original source               medium
cheap-module-eval-source-map    medium  fast         original source (lines only)  worst
inline-cheap-module-source-map  medium  pretty slow  original source (lines only)  best

lines only

Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author is this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.

REVISITING THIS

On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s

Bootstrap NavBar with left, center or right aligned items

<div class="d-flex justify-content-start">hello</div>    
<div class="d-flex justify-content-end">hello</div>
<div class="d-flex justify-content-center">hello</div>
<div class="d-flex justify-content-between">hello</div>
<div class="d-flex justify-content-around">hello</div>

Put the fields that you want to center, right or left according above division.

Call a PHP function after onClick HTML event

You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:

<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
    {
    $new = '{';
    $new .= '"fullname":"' . $_GET['fullname'] . '",';
    $new .= '"email":"' . $_GET['email'] . '",';
    $new .= '"phone":"' . $_GET['phone'] . '",';
    $new .= '}';
    return $new;
    }

function saveContact()
    {
    $datafile = fopen ("data/data.json", "a+");
    if(!$datafile){
        echo "<script>alert('Data not existed!')</script>";
        } 
    else{
        $contact_list = $contact_list . addNewContact();
        file_put_contents("data/data.json", $contact_list);
        }
    fclose($datafile);
    }

// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled

{ ?>

<form>
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact"/>
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->

Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...

Other thought, IE doesn't support placeholder.

Serializing with Jackson (JSON) - getting "No serializer found"?

I found at least three ways of doing this:

  1. Add public getters on your entity that you try to serialize;
  2. Add an annotation at the top of the entity, if you don't want public getters. This will change the default for Jackson from Visbility=DEFAULT to @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) where any access modifiers are accepted;
  3. Change your ObjectMapper globally by setting objectMapperInstance.setVisibility(JsonMethod.FIELD, Visibility.ANY);. This should be avoided if you don't need this functionality globally.

Choose based on your needs.

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

What is the easiest way to get the current day of the week in Android?

Use the Java Calendar class.

Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK); 

switch (day) {
    case Calendar.SUNDAY:
        // Current day is Sunday
        break;
    case Calendar.MONDAY:
        // Current day is Monday
        break;
    case Calendar.TUESDAY:
        // etc.
        break;
}

How do I run Selenium in Xvfb?

The easiest way is probably to use xvfb-run:

DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar

xvfb-run does the whole X authority dance for you, give it a try!

Open an image using URI in Android's default gallery image viewer

My solution

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/your_app_folder/"+"your_picture_saved_name"+".png")), "image/*");
context.startActivity(intent);

How to name and retrieve a stash by name in git?

git stash save is deprecated as of 2.15.x/2.16, instead you can use git stash push -m "message"

You can use it like this:

git stash push -m "message"

where "message" is your note for that stash.

In order to retrieve the stash you can use: git stash list. This will output a list like this, for example:

stash@{0}: On develop: perf-spike
stash@{1}: On develop: node v10

Then you simply use apply giving it the stash@{index}:

git stash apply stash@{1}

References git stash man page

How to select specific columns in laravel eloquent

ModelName::find($id, ['name', 'surname']);

How to escape single quotes in MySQL

In PHP, use mysqli_real_escape_string.

Example from the PHP Manual:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

How to print binary number via printf

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

  char buffer [33];
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);

Here's the origin:

itoa in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

Launch Pycharm from command line (terminal)

pycharm download & Open in UBUNTU

Download:

Open:

  1. Navigate to bin directory in the extracted folder.

  2. run : ./pycharm.sh

ListView item background via custom selector

The article "Why is my list black? An Android optimization" in the Android Developers Blog has a thorough explanation of why the list background turns black when scrolling. Simple answer: set cacheColorHint on your list to transparent (#00000000).

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Copy the contents of the PATH settings to a notepad and check if the location for the 1.4.2 comes before that of the 7. If so, remove the path to 1.4.2 in the PATH setting and save it.

After saving and applying "Environment Variables" close and reopen the cmd line. In XP the path does no get reflected in already running programs.

Android - set TextView TextStyle programmatically?

You may try this one

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                textView.setTextAppearance(R.style.Lato_Bold);
            } else {
                textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
            }

What is console.log?

It's not a jQuery feature but a feature for debugging purposes. You can for instance log something to the console when something happens. For instance:

$('#someButton').click(function() {
  console.log('#someButton was clicked');
  // do something
});

You'd then see #someButton was clicked in Firebug’s “Console” tab (or another tool’s console — e.g. Chrome’s Web Inspector) when you would click the button.

For some reasons, the console object could be unavailable. Then you could check if it is - this is useful as you don't have to remove your debugging code when you deploy to production:

if (window.console && window.console.log) {
  // console is available
}

Please run `npm cache clean`

This error can be due to many many things.

The key here seems the hint about error reading. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.

You could also try with sudo, that might solve a permission problem if that's the case.

Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...

how to set length of an column in hibernate with maximum length

You need to alter your table. Increase the column width using a DDL statement.

please see here

http://dba-oracle.com/t_alter_table_modify_column_syntax_example.htm

html div onclick event

You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway

Test the click on the div and examine the target

Live Demo

$(".expandable-panel-heading").on("click",function (e) {
    if (e.target.id =="ancherComplaint") { // or test the tag
        e.preventDefault(); // or e.stopPropagation()
        markActiveLink(e.target);
    }    
    else alert('123');
});
function markActiveLink(el) {   
    alert(el.id);
} 

Android Eclipse - Could not find *.apk

I tried all the above solutions. but it didn't work.

The solution was to restart eclipse !!!!!!!

hope this will help someone :)

How to view/delete local storage in Firefox?

From Firefox 34 onwards you now have an option for Storage Inspector, which you can enable it from developer tools settings

Once there, you can enable the Storage options under Default Firefox Developer tools

Updated 27-3-16

Firefox 48.0a1 now supports Cookies editing.

Updated 3-4-16

Firefox 48.0a1 now supports localStorage and sessionStorage editing.

Updated 02-08-16

Firefox 48 (stable release) and onward supports editing of all storage types, except IndexedDB

jQuery remove selected option from this

This should do the trick:

$('#some_select_box').click(function() {
  $('option:selected', this ).remove();
});

Better way to check variable for null or empty string?

to be more robust (tabulation, return…), I define:

function is_not_empty_string($str) {
    if (is_string($str) && trim($str, " \t\n\r\0") !== '')
        return true;
    else
        return false;
}

// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    var_export($value);
    if (is_not_empty_string($value)) 
        print(" is a none empty string!\n");
    else
        print(" is not a string or is an empty string\n");
}

sources:

Python: how can I check whether an object is of type datetime.date?

import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date

> True

Spring Boot - Cannot determine embedded database driver class for database type NONE

If you really need "spring-boot-starter-data-jpa" as your project dependency and at the same time you don't want to allow your app to access any database, you can simply exclude auto-configuration classes

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Remove empty lines in a text file via grep

with awk, just check for number of fields. no need regex

$ more file
hello

world

foo

bar

$ awk 'NF' file
hello
world
foo
bar

Get all dates between two dates in SQL Server

DECLARE @FirstDate DATE = '2018-01-01'
DECLARE @LastDate Date = '2018-12-31'
DECLARE @tbl TABLE(ID INT IDENTITY(1,1) PRIMARY KEY,CurrDate date)
INSERT @tbl VALUES( @FirstDate)
WHILE @FirstDate < @LastDate
BEGIN
SET @FirstDate = DATEADD( day,1, @FirstDate)
INSERT @tbl VALUES( @FirstDate)
END
INSERT @tbl VALUES( @LastDate) 

SELECT * FROM @tbl

Format numbers in django templates

Django's contributed humanize application does this:

{% load humanize %}
{{ my_num|intcomma }}

Be sure to add 'django.contrib.humanize' to your INSTALLED_APPS list in the settings.py file.

Cannot instantiate the type List<Product>

List can be instantiated by any class implementing the interface.By this way,Java provides us polymorphic behaviour.See the example below:

List<String> list = new ArrayList<String>();

Instead of instantiating an ArrayList directly,I am using a List to refer to ArrayList object so that we are using only the List interface methods and do not care about its actual implementation.

Examples of classes implementing List are ArrayList,LinkedList,Vector.You probably want to create a List depending upon your requirements.

Example:- a LinkedList is more useful when you hve to do a number of inertion or deletions .Arraylist is more performance intensive as it is backed by a fixed size array and array contents have to be changed by moving or regrowing the array.

Again,using a List we can simply change our object instantiation without changing any code further in your programs.

Suppose we are using ArrayList<String> value = new ArrayList<String>();

we may use a specific method of ArrrayList and out code will not be robust

By using List<String> value = new ArrayList<String>();

we are making sure we are using only List interface methods..and if we want to change it to a LinkedList we simply have to change the code :

List<String> value = new ArrayList<String>(); 

------ your code uses List interface methods.....

value = new LinkedList<String>(); 

-----your code still uses List interface methods and we do not have to change anything---- and we dont have to change anything in our code further

By the way a LinkedList also works a Deque which obviously also you cannot instantiate as it is also an interface

omp parallel vs. omp parallel for

There are obviously plenty of answers, but this one answers it very nicely (with source)

#pragma omp for only delegates portions of the loop for different threads in the current team. A team is the group of threads executing the program. At program start, the team consists only of a single member: the master thread that runs the program.

To create a new team of threads, you need to specify the parallel keyword. It can be specified in the surrounding context:

#pragma omp parallel
{
   #pragma omp for
   for(int n = 0; n < 10; ++n)
   printf(" %d", n);
}

and:

What are: parallel, for and a team

The difference between parallel, parallel for and for is as follows:

A team is the group of threads that execute currently. At the program beginning, the team consists of a single thread. A parallel construct splits the current thread into a new team of threads for the duration of the next block/statement, after which the team merges back into one. for divides the work of the for-loop among the threads of the current team.

It does not create threads, it only divides the work amongst the threads of the currently executing team. parallel for is a shorthand for two commands at once: parallel and for. Parallel creates a new team, and for splits that team to handle different portions of the loop. If your program never contains a parallel construct, there is never more than one thread; the master thread that starts the program and runs it, as in non-threading programs.

https://bisqwit.iki.fi/story/howto/openmp/

Difference between id and name attributes in HTML

The name attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different id attributes, but the same name. When submitted, there is just the one value in the response - the radio button you selected.

Of course, there's more to it than that, but it will definitely get you thinking in the right direction.

How do I check for vowels in JavaScript?

function findVowels(str) {
  return str.match(/[aeiou]/ig);
}

findVowels('abracadabra'); // 'aaaaa'

Basically it returns all the vowels in a given string.

How to get device make and model on iOS?

Below Function Perfectly Working on iOS7 or later version in Swift

func DeviceName()-> String {

        var myDeviceName : String = String()

        var systemInfo = [UInt8](count: sizeof(utsname), repeatedValue: 0)

        let model = systemInfo.withUnsafeMutableBufferPointer { (inout body: UnsafeMutableBufferPointer<UInt8>) -> String? in

            if uname(UnsafeMutablePointer(body.baseAddress)) != 0 {
                return nil
            }

            return String.fromCString(UnsafePointer(body.baseAddress.advancedBy(Int(_SYS_NAMELEN * 4))))
        }

        let deviceNamesByCode : [String: String] = ["iPod1,1":"iPod Touch 1",
                                                    "iPod2,1":"iPod Touch 2",
                                                    "iPod3,1":"iPod Touch 3",
                                                    "iPod4,1":"iPod Touch 4",
                                                    "iPod5,1":"iPod Touch 5",
                                                    "iPod7,1":"iPod Touch 6",
                                                    "iPhone1,1":"iPhone",
                                                    "iPhone1,2":"iPhone ",
                                                    "iPhone2,1":"iPhone ",
                                                    "iPhone3,1":"iPhone 4",
                                                    "iPhone3,2":"iPhone 4",
                                                    "iPhone3,3":"iPhone 4",
                                                    "iPhone4,1":"iPhone 4s",
                                                    "iPhone5,1":"iPhone 5",
                                                    "iPhone5,2":"iPhone 5",
                                                    "iPhone5,3":"iPhone 5c",
                                                    "iPhone5,4":"iPhone 5c",
                                                    "iPhone6,1":"iPhone 5s",
                                                    "iPhone6,2":"iPhone 5s",
                                                    "iPhone7,2":"iPhone 6",
                                                    "iPhone7,1":"iPhone 6 Plus",
                                                    "iPhone8,1":"iPhone 6s",
                                                    "iPhone8,2":"iPhone 6s Plus",
                                                    "iPhone8,4":"iPhone SE",
                                                    "iPad2,1":"iPad 2",
                                                    "iPad2,2":"iPad 2",
                                                    "iPad2,3":"iPad 2",
                                                    "iPad2,4":"iPad 2",
                                                    "iPad3,1":"iPad 3",
                                                    "iPad3,2":"iPad 3",
                                                    "iPad3,3":"iPad 3",
                                                    "iPad3,4":"iPad 4",
                                                    "iPad3,5":"iPad 4",
                                                    "iPad3,6":"iPad 4",
                                                    "iPad4,1":"iPad Air",
                                                    "iPad4,2":"iPad Air",
                                                    "iPad4,3":"iPad Air",
                                                    "iPad5,3":"iPad Air 2",
                                                    "iPad5,4":"iPad Air 2",
                                                    "iPad2,5":"iPad Mini",
                                                    "iPad2,6":"iPad Mini",
                                                    "iPad2,7":"iPad Mini",
                                                    "iPad4,4":"iPad Mini 2",
                                                    "iPad4,5":"iPad Mini 2",
                                                    "iPad4,6":"iPad Mini 2",
                                                    "iPad4,7":"iPad Mini 3",
                                                    "iPad4,8":"iPad Mini 3",
                                                    "iPad4,9":"iPad Mini 3",
                                                    "iPad5,1":"iPad Mini 4",
                                                    "iPad5,2":"iPad Mini 4",
                                                    "iPad6,3":"iPad Pro",
                                                    "iPad6,4":"iPad Pro",
                                                    "iPad6,7":"iPad Pro",
                                                    "iPad6,8":"iPad Pro",
                                                    "AppleTV5,3":"Apple TV",
                                                    "i386":"Simulator",
                                                    "x86_64":"Simulator"

        ]

        if model!.characters.count > 0 {
            myDeviceName = deviceNamesByCode[model!]!
        }else{
            myDeviceName = UIDevice.currentDevice().model
        }

        print("myDeviceName==\(myDeviceName)")
        return myDeviceName

    }

Python 2.7 getting user input and manipulating as string without quotations

The issue seems to be resolved in Python version 3.4.2.

testVar = input("Ask user for something.")

Will work fine.

Difference between 2 dates in SQLite

The SQLite documentation is a great reference and the DateAndTimeFunctions page is a good one to bookmark.

It's also helpful to remember that it's pretty easy to play with queries with the sqlite command line utility:

sqlite> select julianday(datetime('now'));
2454788.09219907
sqlite> select datetime(julianday(datetime('now')));
2008-11-17 14:13:55

What are the differences between B trees and B+ trees?

The principal advantage of B+ trees over B trees is they allow you to pack in more pointers to other nodes by removing pointers to data, thus increasing the fanout and potentially decreasing the depth of the tree.

The disadvantage is that there are no early outs when you might have found a match in an internal node. But since both data structures have huge fanouts, the vast majority of your matches will be on leaf nodes anyway, making on average the B+ tree more efficient.

Colorizing text in the console with C++

In Windows, you can use any combination of red green and blue on the foreground (text) and the background.

/* you can use these constants
FOREGROUND_BLUE
FOREGROUND_GREEN
FOREGROUND_RED
FOREGROUND_INTENSITY
BACKGROUND_BLUE
BACKGROUND_GREEN
BACKGROUND_RED
BACKGROUND_INTENSITY
*/

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
std::cout << "I'm cyan! Who are you?" << std::endl;

Source: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes

How do you attach and detach from Docker's process?

In the same shell, hold ctrl key and press keys p then q

How do you handle a form change in jQuery?

You can do this:

$("form :input").change(function() {
  $(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:

$('.checkChangedbutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

References: Updated

According to jQuery this is a filter to select all form controls.

http://api.jquery.com/input-selector/

The :input selector basically selects all form controls.

How to sum all column values in multi-dimensional array?

Use this snippet:

$key = 'gozhi';
$sum = array_sum(array_column($array,$key));

How to convert a SVG to a PNG with ImageMagick?

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"

Compiler error: "initializer element is not a compile-time constant"

You can certainly #define a macro as shown below. The compiler will replace "IMAGE_SEGMENT" with its value before compilation. While you will achieve defining a global lookup for your array, it is not the same as a global variable. When the macro is expanded, it works just like inline code and so a new image is created each time. So if you are careful in where you use the macro, then you would have effectively achieved creating a global variable.

#define IMAGE_SEGMENT [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];

Then use it where you need it as shown below. Each time the below code is executed, a new object is created with a new memory pointer.

imageSegment = IMAGE_SEGMENT

convert date string to mysql datetime field

Use DateTime::createFromFormat like this :

$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00');
$mysql_date_string = $date->format('Y-m-d H:i:s');

You can adapt this to any input format, whereas strtotime() will assume you're using the US date format if you use /, even if you're not.

The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don't precise it.

Where to get this Java.exe file for a SQL Developer installation

you can enter the jdk path required as th full path for java.exe in sql developer for oracle 11g.

I found the jdk at the following path in my system.

c:\app\sony\product\11.0.0\db_1\jdk

How to calculate the CPU usage of a process by PID in Linux from C?

Take a look at the "pidstat" command, sounds like exactly what you require.

How to loop through all enum values in C#?

foreach(Foos foo in Enum.GetValues(typeof(Foos)))

Best way to display data via JSON using jQuery

You can create a jQuery object from a JSON object:

$.getJSON(url, data, function(json) {
    $(json).each(function() {
        /* YOUR CODE HERE */
    });
});

How to correctly use "section" tag in HTML5?

The answer is in the current spec:

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.

The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.

Reference:

Also see:

It looks like there's been a lot of confusion about this element's purpose, but the one thing that's agreed upon is that it is not a generic wrapper, like <div> is. It should be used for semantic purposes, and not a CSS or JavaScript hook (although it certainly can be styled or "scripted").

A better example, from my understanding, might look something like this:

<div id="content">
  <article>
     <h2>How to use the section tag</h2>
     <section id="disclaimer">
         <h3>Disclaimer</h3>
         <p>Don't take my word for it...</p>
     </section>
     <section id="examples">
       <h3>Examples</h3>
       <p>But here's how I would do it...</p>
     </section>
     <section id="closing_notes">
       <h3>Closing Notes</h3>
       <p>Well that was fun. I wonder if the spec will change next week?</p>
     </section>
  </article>
</div>

Note that <div>, being completely non-semantic, can be used anywhere in the document that the HTML spec allows it, but is not necessary.

How to change the display name for LabelFor in razor in mvc3?

You can change the labels' text by adorning the property with the DisplayName attribute.

[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }

Or, you could write the raw HTML explicitly:

<label for="SomekingStatus" class="control-label">Someking Status</label>

What's the difference between TRUNCATE and DELETE in SQL

A big reason it is handy, is when you need to refresh the data in a multi-million row table, but don't want to rebuild it. "Delete *" would take forever, whereas the perfomance impact of Truncate would be negligible.

How to stop and restart memcached server?

As root on CentOS 7:

systemctl start memcached
systemctl stop memcached
systemctl restart memcached

To tell the service to start at reboot (ex chkconfig):

systemctl enable memcached

To tell the service to not start at reboot:

systemctl disable memcached

iOS: present view controller programmatically

You need to set storyboard Id from storyboard identity inspector

 AddTaskViewController *add=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboard_id"];
 [self presentViewController:add animated:YES completion:nil];

How do I set a fixed background image for a PHP file?

You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do

<head>
    <?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
    <title>Title</title>
</hea>

Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

How to set environment variable or system property in spring tests?

For Unit Tests, the System variable is not instantiated yet when I do "mvn clean install" because there is no server running the application. So in order to set the System properties, I need to do it in pom.xml. Like so:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.21.0</version>
    <configuration>
        <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <MY_ENV_VAR>newValue</MY_ENV_VAR>
            <ENV_TARGET>olqa</ENV_TARGET>
            <buildDirectory>${project.build.directory}</buildDirectory>
        </systemPropertyVariables>
    </configuration>
</plugin>

What is the maximum length of a Push Notification alert text?

According to updated Apple document (check my answer date):

"... When using the HTTP/2 provider API, maximum payload size is 4096 bytes. Using the legacy binary interface, maximum payload size is 2048 bytes. Apple Push Notification service (APNs) refuses any notification that exceeds the maximum size."

Angular 2 Hover event

If the mouse over for all over the component is your option, you can directly is @hostListener to handle the events to perform the mouse over al below.

  import {HostListener} from '@angular/core';

  @HostListener('mouseenter') onMouseEnter() {
    this.hover = true;
    this.elementRef.nativeElement.addClass = 'edit';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.hover = false;
    this.elementRef.nativeElement.addClass = 'un-edit';
  }

Its available in @angular/core. I tested it in angular 4.x.x

Webfont Smoothing and Antialiasing in Firefox and Opera

As Opera is powered by Blink since Version 15.0 -webkit-font-smoothing: antialiased does also work on Opera.

Firefox has finally added a property to enable grayscaled antialiasing. After a long discussion it will be available in Version 25 with another syntax, which points out that this property only works on OS X.

-moz-osx-font-smoothing: grayscale;

This should fix blurry icon fonts or light text on dark backgrounds.

.font-smoothing {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

You may read my post about font rendering on OSX which includes a Sass mixin to handle both properties.

jQuery duplicate DIV into another DIV

Put this on an event

$(function(){
    $('.package').click(function(){
       var content = $('.container').html();
       $(this).html(content);
    });
});

Move the mouse pointer to a specific position?

You can't move the mouse pointer using javascript, and thus for obvious security reasons. The best way to achieve this effect would be to actually place the control under the mouse pointer.

How to set NODE_ENV to production/development in OS X

Before running your app, you can do this in console,

export NODE_ENV=production

Or if you are in windows you could try this:

SET NODE_ENV=production

for PowerShell:

$env:NODE_ENV="production"

or you can run your app like this:

NODE_ENV=production node app.js

You can also set it in your js file:

process.env.NODE_ENV = 'production';

But I don't suggest to do it in your runtime file, since it's not easy to open up VIM in your server and change it to production. You can make a config.json file in your directory and everytime your app runs, it reads from it and sets the configuration.

Clearing my form inputs after submission

since you are using jquery library, i would advise you utilize the reset() method.

Firstly, add an id attribute to the form tag

<form id='myForm'>

Then on completion, clear your input fields as:

$('#myForm')[0].reset();