Programs & Examples On #Rft

Acronym for Rational Functional Tester, an IBM Rational product for automated GUI testing

"The page has expired due to inactivity" - Laravel 5.5

Sign in to connect to the server.

Search Error

An error has occurred: search false You don't have the peais.

Search request is longer.

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

TokenMismatchException in VerifyCsrfToken.php Line 67

Use like this

<form>
<input type="hidden" name="_token" value="<?= csrf_token(); ?>" />

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Datetime current year and month in Python

Late answer, but you can also use:

import time
ym = time.strftime("%Y-%m")

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Inspired by @aaronpenne and @Soumyaansh

f = open("file.txt", "rb")
text = f.read().decode(errors='replace')

Adding CSRFToken to Ajax request

If you are working in node.js with lusca try also this:

$.ajax({
url: "http://test.com",
type:"post"
headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
})

converting epoch time with milliseconds to datetime

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

ValueError: unconverted data remains: 02:05

You have to parse all of the input string, you cannot just ignore parts.

from datetime import date, datetime

for item in j:
    st = datetime.strptime(item['start'], '%A %d %B %H:%M')

    if st.date() == date.today():
        item['start'] = st.time()

Here, we compare the date to today's date by using more datetime objects instead of trying to use strings.

The alternative is to only pass in part of the item['start'] string (splitting out just the time), but there really is no point here, not when you could just parse everything in one step first.

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

try it:

const cors = require('cors')

const corsOptions = {
    origin: 'http://localhost:4200',
    credentials: true,

}
app.use(cors(corsOptions));

403 Forbidden error when making an ajax Post request in Django framework

The fastest solution if you are not embedding js into your template is:

Put <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> before your reference to script.js file in your template, then add csrfmiddlewaretoken into your data dictionary:

$.ajax({
            type: 'POST',
            url: somepathname + "do_it/",
            data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
            success: function() {
                console.log("Success!");
            }
        })

If you do embed your js into the template, it's as simple as: data: {csrfmiddlewaretoken: '{{ csrf_token }}'}

Auto-loading lib files in Rails 4

Though this does not directly answer the question, but I think it is a good alternative to avoid the question altogether.

To avoid all the autoload_paths or eager_load_paths hassle, create a "lib" or a "misc" directory under "app" directory. Place codes as you would normally do in there, and Rails will load files just like how it will load (and reload) model files.

How to stop a looping thread in Python?

Threaded stoppable function

Instead of subclassing threading.Thread, one can modify the function to allow stopping by a flag.

We need an object, accessible to running function, to which we set the flag to stop running.

We can use threading.currentThread() object.

import threading
import time


def doit(arg):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        print ("working on %s" % arg)
        time.sleep(1)
    print("Stopping as you wish.")


def main():
    t = threading.Thread(target=doit, args=("task",))
    t.start()
    time.sleep(5)
    t.do_run = False
    t.join()

if __name__ == "__main__":
    main()

The trick is, that the running thread can have attached additional properties. The solution builds on assumptions:

  • the thread has a property "do_run" with default value True
  • driving parent process can assign to started thread the property "do_run" to False.

Running the code, we get following output:

$ python stopthread.py                                                        
working on task
working on task
working on task
working on task
working on task
Stopping as you wish.

Pill to kill - using Event

Other alternative is to use threading.Event as function argument. It is by default False, but external process can "set it" (to True) and function can learn about it using wait(timeout) function.

We can wait with zero timeout, but we can also use it as the sleeping timer (used below).

def doit(stop_event, arg):
    while not stop_event.wait(1):
        print ("working on %s" % arg)
    print("Stopping as you wish.")


def main():
    pill2kill = threading.Event()
    t = threading.Thread(target=doit, args=(pill2kill, "task"))
    t.start()
    time.sleep(5)
    pill2kill.set()
    t.join()

Edit: I tried this in Python 3.6. stop_event.wait() blocks the event (and so the while loop) until release. It does not return a boolean value. Using stop_event.is_set() works instead.

Stopping multiple threads with one pill

Advantage of pill to kill is better seen, if we have to stop multiple threads at once, as one pill will work for all.

The doit will not change at all, only the main handles the threads a bit differently.

def main():
    pill2kill = threading.Event()
    tasks = ["task ONE", "task TWO", "task THREE"]

    def thread_gen(pill2kill, tasks):
        for task in tasks:
            t = threading.Thread(target=doit, args=(pill2kill, task))
            yield t

    threads = list(thread_gen(pill2kill, tasks))
    for thread in threads:
        thread.start()
    time.sleep(5)
    pill2kill.set()
    for thread in threads:
        thread.join()

Django CSRF Cookie Not Set

In your view are you using the csrf decorator??

from django.views.decorators.csrf import csrf_protect

@csrf_protect def view(request, params): ....

How to print current date on python3?

I always use this code, which print the year to second in a tuple

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

How to disable Django's CSRF validation?

If you just need some views not to use CSRF, you can use @csrf_exempt:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

You can find more examples and other scenarios in the Django documentation:

Django DoesNotExist

Nice way to handle not found error in Django.

https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#get-object-or-404

from django.shortcuts import get_object_or_404

def get_data(request):
    obj = get_object_or_404(Model, pk=1)

Python datetime strptime() and strftime(): how to preserve the timezone information

Unfortunately, strptime() can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

strftime() doesn't officially support %z.

You are stuck with python-dateutil to support timezone parsing, I am afraid.

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

Convert python datetime to epoch with strftime

if you just need a timestamp in unix /epoch time, this one line works:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

and depends only on datetime works in python2 and python3

TypeError: sequence item 0: expected string, int found

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)

How to create a file name with the current date & time in Python?

Change this line

filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")

To

filename1 = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")

Note the extra datetime. Alternatively, change your import datetime to from datetime import datetime

python date of the previous month

Building on bgporter's answer.

def prev_month_range(when = None): 
    """Return (previous month's start date, previous month's end date)."""
    if not when:
        # Default to today.
        when = datetime.datetime.today()
    # Find previous month: https://stackoverflow.com/a/9725093/564514
    # Find today.
    first = datetime.date(day=1, month=when.month, year=when.year)
    # Use that to find the first day of this month.
    prev_month_end = first - datetime.timedelta(days=1)
    prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year)
    # Return previous month's start and end dates in YY-MM-DD format.
    return (prev_month_start.strftime('%Y-%m-%d'), prev_month_end.strftime('%Y-%m-%d'))

Plotting dates on the x-axis with Python's matplotlib

As @KyssTao has been saying, help(dates.num2date) says that the x has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102 is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).

Use datestr2num instead (see help(dates.datestr2num)):

new_x = dates.datestr2num(date) # where date is '01/02/1991'

Python IndentationError: unexpected indent

Simply copy your script and put under """ your entire code """ ...

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that's it

Difference between two dates in Python

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])

Using %f with strftime() in Python to get microseconds

You can use datetime's strftime function to get this. The problem is that time's strftime accepts a timetuple that does not carry microsecond information.

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

Should do the trick!

Python logging: use milliseconds in time format

If you are using arrow or if you don't mind using arrow. You can substitute python's time formatting for arrow's one.

import logging

from arrow.arrow import Arrow


class ArrowTimeFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)


logger = logging.getLogger(__name__)

default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
    fmt='%(asctime)s',
    datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))

logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)

Now you can use all of arrow's time formatting in datefmt attribute.

C - gettimeofday for computing time?

If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>

int main()
{
   clock_t start = clock();
   //... do work here
   clock_t end = clock();
   double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
   return 0;
}

hth

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

Get the current time in C

If you just need the time without the date.

  time_t rawtime;
  struct tm * timeinfo;
  time( &rawtime );
  timeinfo = localtime( &rawtime );
  printf("%02d:%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min, 
    timeinfo->tm_sec);

Django CSRF check failing with an Ajax POST request

If you use the $.ajax function, you can simply add the csrf token in the data body:

$.ajax({
    data: {
        somedata: 'somedata',
        moredata: 'moredata',
        csrfmiddlewaretoken: '{{ csrf_token }}'
    },

get UTC timestamp in python with datetime

Naïve datetime versus aware datetime

Default datetime objects are said to be "naïve": they keep time information without the time zone information. Think about naïve datetime as a relative number (ie: +4) without a clear origin (in fact your origin will be common throughout your system boundary).

In contrast, think about aware datetime as absolute numbers (ie: 8) with a common origin for the whole world.

Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4 targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp() method. (cf: http://bugs.python.org/issue1457227)

To check if your datetime dt is naïve, check dt.tzinfo, if None, then it's naïve:

datetime.now()        ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1)  ## returns naïve datetime pointing on user given time

I have naïve datetimes, what can I do ?

You must make an assumption depending on your particular context: The question you must ask yourself is: was your datetime on UTC ? or was it local time ?

  • If you were using UTC (you are out of trouble):

    import calendar
    
    def dt2ts(dt):
        """Converts a datetime object to UTC timestamp
    
        naive datetime will be considered UTC.
    
        """
    
        return calendar.timegm(dt.utctimetuple())
    
  • If you were NOT using UTC, welcome to hell.

    You have to make your datetime non-naïve prior to using the former function, by giving them back their intended timezone.

    You'll need the name of the timezone and the information about if DST was in effect when producing the target naïve datetime (the last info about DST is required for cornercases):

    import pytz     ## pip install pytz
    
    mytz = pytz.timezone('Europe/Amsterdam')             ## Set your timezone
    
    dt = mytz.normalize(mytz.localize(dt, is_dst=True))  ## Set is_dst accordingly
    

    Consequences of not providing is_dst:

    Not using is_dst will generate incorrect time (and UTC timestamp) if target datetime was produced while a backward DST was put in place (for instance changing DST time by removing one hour).

    Providing incorrect is_dst will of course generate incorrect time (and UTC timestamp) only on DST overlap or holes. And, when providing also incorrect time, occuring in "holes" (time that never existed due to forward shifting DST), is_dst will give an interpretation of how to consider this bogus time, and this is the only case where .normalize(..) will actually do something here, as it'll then translate it as an actual valid time (changing the datetime AND the DST object if required). Note that .normalize() is not required for having a correct UTC timestamp at the end, but is probably recommended if you dislike the idea of having bogus times in your variables, especially if you re-use this variable elsewhere.

    and AVOID USING THE FOLLOWING: (cf: Datetime Timezone conversion using pytz)

    dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))  ## BAD !!
    

    Why? because .replace() replaces blindly the tzinfo without taking into account the target time and will choose a bad DST object. Whereas .localize() uses the target time and your is_dst hint to select the right DST object.

OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):

Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.

By using time.mktime we can create an utc_mktime:

def utc_mktime(utc_tuple):
    """Returns number of seconds elapsed since epoch

    Note that no timezone are taken into consideration.

    utc tuple must be: (year, month, day, hour, minute, second)

    """

    if len(utc_tuple) == 6:
        utc_tuple += (0, 0, 0)
    return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))

def datetime_to_timestamp(dt):
    """Converts a datetime object to UTC timestamp"""

    return int(utc_mktime(dt.timetuple()))

You must make sure that your datetime object is created on the same timezone than the one that has created your datetime.

This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).

How do I format a date in Jinja2?

There is a jinja2 extension you can use just need pip install (https://github.com/hackebrot/jinja2-time)

How to get the seconds since epoch from the time + date output of gmtime()?

There are two ways, depending on your original timestamp:

mktime() and timegm()

http://docs.python.org/library/time.html

Remove the newline character in a list read from a file

You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.

with open("grades.dat") as input:
    grades = [line.split(",") for line in input.read().splitlines()]
etc...

Converting unix timestamp string to readable date

Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:

Timestamps can be in two formats:

  1. 13 digits(milliseconds) - To convert milliseconds to date, use:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
    
  2. 10 digits(seconds) - To convert seconds to date, use:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'
    

Python base64 data decode

(I know this is old but I wanted to post this for people like me who stumble upon it in the future) I personally just use this python code to decode base64 strings:

print open("FILE-WITH-STRING", "rb").read().decode("base64")

So you can run it in a bash script like this:

python -c 'print open("FILE-WITH-STRING", "rb").read().decode("base64")' > outputfile
file -i outputfile

twneale has also pointed out an even simpler solution: base64 -d So you can use it like this:

cat "FILE WITH STRING" | base64 -d > OUTPUTFILE
#Or You Can Do This
echo "STRING" | base64 -d > OUTPUTFILE

That will save the decoded string to outputfile and then attempt to identify file-type using either the file tool or you can try TrID. The following command will decode the string into a file and then use TrID to automatically identify the file's type and add the extension.

echo "STRING" | base64 -d > OUTPUTFILE; trid -ce OUTPUTFILE

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

How can I account for period (AM/PM) using strftime?

Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ?

Iterating through a range of dates in Python

This function has some extra features:

  • can pass a string matching the DATE_FORMAT for start or end and it is converted to a date object
  • can pass a date object for start or end
  • error checking in case the end is older than the start

    import datetime
    from datetime import timedelta
    
    
    DATE_FORMAT = '%Y/%m/%d'
    
    def daterange(start, end):
          def convert(date):
                try:
                      date = datetime.datetime.strptime(date, DATE_FORMAT)
                      return date.date()
                except TypeError:
                      return date
    
          def get_date(n):
                return datetime.datetime.strftime(convert(start) + timedelta(days=n), DATE_FORMAT)
    
          days = (convert(end) - convert(start)).days
          if days <= 0:
                raise ValueError('The start date must be before the end date.')
          for n in range(0, days):
                yield get_date(n)
    
    
    start = '2014/12/1'
    end = '2014/12/31'
    print list(daterange(start, end))
    
    start_ = datetime.date.today()
    end = '2015/12/1'
    print list(daterange(start, end))
    

Python strftime - date without leading 0?

Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to http://docs.python.org/library/time.html -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

Sending mail from Python using SMTP

Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

Regular expression to limit number of characters to 10

You can use curly braces to control the number of occurrences. For example, this means 0 to 10:

/^[a-z]{0,10}$/

The options are:

  • {3} Exactly 3 occurrences;
  • {6,} At least 6 occurrences;
  • {2,5} 2 to 5 occurrences.

See the regular expression reference.

Your expression had a + after the closing curly brace, hence the error.

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

View a file in a different Git branch without changing branches

A simple, newbie friendly way for looking into a file: git gui browser <branch> which lets you explore the contents of any file.

It's also there in the File menu of git gui. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.

Bash command line and input limit

Ok, Denizens. So I have accepted the command line length limits as gospel for quite some time. So, what to do with one's assumptions? Naturally- check them.

I have a Fedora 22 machine at my disposal (meaning: Linux with bash4). I have created a directory with 500,000 inodes (files) in it each of 18 characters long. The command line length is 9,500,000 characters. Created thus:

seq 1 500000 | while read digit; do
    touch $(printf "abigfilename%06d\n" $digit);
done

And we note:

$ getconf ARG_MAX
2097152

Note however I can do this:

$ echo * > /dev/null

But this fails:

$ /bin/echo * > /dev/null
bash: /bin/echo: Argument list too long

I can run a for loop:

$ for f in *; do :; done

which is another shell builtin.

Careful reading of the documentation for ARG_MAX states, Maximum length of argument to the exec functions. This means: Without calling exec, there is no ARG_MAX limitation. So it would explain why shell builtins are not restricted by ARG_MAX.

And indeed, I can ls my directory if my argument list is 109948 files long, or about 2,089,000 characters (give or take). Once I add one more 18-character filename file, though, then I get an Argument list too long error. So ARG_MAX is working as advertised: the exec is failing with more than ARG_MAX characters on the argument list- including, it should be noted, the environment data.

Good tutorial for using HTML5 History API (Pushstate?)

I benefited a lot from 'Dive into HTML 5'. The explanation and demo are easier and to the point. History chapter - http://diveintohtml5.info/history.html and history demo - http://diveintohtml5.info/examples/history/fer.html

String comparison in Python: is vs. ==

The logic is not flawed. The statement

if x is y then x==y is also True

should never be read to mean

if x==y then x is y

It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

Use the DATEDIFF to return value in milliseconds, seconds, minutes, hours, ...

DATEDIFF(interval, date1, date2)

interval REQUIRED - The time/date part to return. Can be one of the following values:

year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond

date1, date2 REQUIRED - The two dates to calculate the difference between

Filtering Pandas Dataframe using OR statement

You can do like below to achieve your result:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()


#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()

Why do we have to normalize the input for an artificial neural network?

It's explained well here.

If the input variables are combined linearly, as in an MLP [multilayer perceptron], then it is rarely strictly necessary to standardize the inputs, at least in theory. The reason is that any rescaling of an input vector can be effectively undone by changing the corresponding weights and biases, leaving you with the exact same outputs as you had before. However, there are a variety of practical reasons why standardizing the inputs can make training faster and reduce the chances of getting stuck in local optima. Also, weight decay and Bayesian estimation can be done more conveniently with standardized inputs.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Handy little helper method to keep this process DRY:

function safeApply(scope, fn) {
    (scope.$$phase || scope.$root.$$phase) ? fn() : scope.$apply(fn);
}

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

CSS - How to Style a Selected Radio Buttons Label?

Here's an accessible solution

_x000D_
_x000D_
label {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
label input {_x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
label:focus-within {_x000D_
  outline: 1px solid orange;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <label><input type="radio" value="all" checked>All</label>_x000D_
  <label><input type="radio" value="false">Open</label>_x000D_
  <label><input type="radio" value="true">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use regex in file find

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
  1. -name uses globular expressions, aka wildcards. What you want is -regex
  2. To use intervals as you intend, you need to tell find to use Extended Regular Expressions via the -regextype posix-extended flag
  3. You need to escape out the periods because in regex a period has the special meaning of any single character. What you want is a literal period denoted by \.
  4. To match only those files that are greater than 3 days old, you need to prefix your number with a + as in -mtime +3.

Proof of Concept

$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
./test.log.1234-12-12.zip

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

Merge trunk to branch in Subversion

Last revision merged from trunk to branch can be found by running this command inside the working copy directory:

svn log -v --stop-on-copy

How can I disable ARC for a single file in a project?

Note: if you want to disable ARC for many files, you have to:

  1. open "Build phases" -> "Compile sources"
  2. select files with "left_mouse" + "cmd" (for separated files) or + "shift" (for grouped files - select first and last)
  3. press "enter"
  4. paste -fno-objc-arc
  5. press "enter" again
  6. profit!

Strings and character with printf

You're confusing the dereference operator * with pointer type annotation *. Basically, in C * means different things in different places:

  • In a type, * means a pointer. int is an integer type, int* is a pointer to integer type
  • As a prefix operator, * means 'dereference'. name is a pointer, *name is the result of dereferencing it (i.e. getting the value that the pointer points to)
  • Of course, as an infix operator, * means 'multiply'.

Where does this come from: -*- coding: utf-8 -*-

# -*- coding: utf-8 -*- is a Python 2 thing. In Python 3+, the default encoding of source files is already UTF-8 and that line is useless.

See: Should I use encoding declaration in Python 3?

pyupgrade is a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object.

Defining Z order of views of RelativeLayout in Android

In Android starting from API level 21, items in the layout file get their Z order both from how they are ordered within the file, as described in correct answer, and from their elevation, a higher elevation value means the item gets a higher Z order.

This can sometimes cause problems, especially with buttons that often appear on top of items that according to the order of the XML should be below them in Z order. To fix this just set the android:elevation of the the items in your layout XML to match the Z order you want to achieve.

I you set an elevation of an element in the layout it will start to cast a shadow. If you don't want this effect you can remove the shadow with code like so:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   myView.setOutlineProvider(null);
}

I haven't found any way to remove the shadow of a elevated view through the layout xml.

Creating a "Hello World" WebSocket example

WebSockets are implemented with a protocol that involves handshake between client and server. I don't imagine they work very much like normal sockets. Read up on the protocol, and get your application to talk it. Alternatively, use an existing WebSocket library, or .Net4.5beta which has a WebSocket API.

Examples of good gotos in C or C++

I don't use goto's myself, however I did work with a person once that would use them in specific cases. If I remember correctly, his rationale was around performance issues - he also had specific rules for how. Always in the same function, and the label was always BELOW the goto statement.

How permission can be checked at runtime without throwing SecurityException?

Sharing my methods in case someone needs them:

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

    int res = context.checkCallingOrSelfPermission(permission);

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

    return res == PackageManager.PERMISSION_GRANTED;

}

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

    boolean hasAllPermissions = true;

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

    return hasAllPermissions;

}

And to call it:

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

How to force maven update?

I had this problem for a different reason. I went to the maven repository https://mvnrepository.com looking for the latest version of spring core, which at the time was 5.0.0.M3/ The repository showed me this entry for my pom.xml:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.0.0.M3</version>
</dependency>

Naive fool that I am, I assumed that the comment was telling me that the jar is located in the default repository.

However, after a lot of head-banging, I saw a note just below the xml saying "Note: this artifact it located at Alfresco Public repository (https://artifacts.alfresco.com/nexus/content/repositories/public/)"

So the comment in the XML is completely misleading. The jar is located in another archive, which was why Maven couldn't find it!

How to implement a simple scenario the OO way

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:

books

  • id
  • book specific info
  • etc

chapters

  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

Is "else if" faster than "switch() case"?

Far more important than the performance benefits of switch (which are relatively slight, but worth noting) are the readability issues.

I for one find a switch statement extremely clear in intent and pure whitespace, compared to chains of ifs.

IF...THEN...ELSE using XML

<IF id="if-1">
   <TIME from="5pm" to="9pm" />
<ELSE>
   <something else />
</ELSE>
</IF>

I don't know if this makes any sense to anyone else or it is actually usable in your program, but I would do it like this.

My point of view: You need to have everything related to your "IF" inside your IF-tag, otherwise you won't know what ELSE belongs to what IF. Secondly, I'd skip the THEN tag because it always follows an IF.

Play audio file from the assets directory

Fix of above function for play and pause

  public void playBeep ( String word )
{
    try
    {
        if ( ( m == null ) )
        {

            m = new MediaPlayer ();
        }
        else if( m != null&&lastPlayed.equalsIgnoreCase (word)){
            m.stop();
            m.release ();
            m=null;
            lastPlayed="";
            return;
        }else if(m != null){
            m.release ();
            m = new MediaPlayer ();
        }
        lastPlayed=word;

        AssetFileDescriptor descriptor = context.getAssets ().openFd ( "rings/" + word + ".mp3" );
        long                start      = descriptor.getStartOffset ();
        long                end        = descriptor.getLength ();

        // get title
        // songTitle=songsList.get(songIndex).get("songTitle");
        // set the data source
        try
        {
            m.setDataSource ( descriptor.getFileDescriptor (), start, end );
        }
        catch ( Exception e )
        {
            Log.e ( "MUSIC SERVICE", "Error setting data source", e );
        }

        m.prepare ();
        m.setVolume ( 1f, 1f );
        // m.setLooping(true);
        m.start ();
    }
    catch ( Exception e )
    {
        e.printStackTrace ();
    }
}

ORA-12560: TNS:protocol adaptor error

After searching alot got a simple way to solve it. Just follow the steps.

  1. Check status of your listener.
    1. open command prompt and type lsnrctl status
    2. You will get no listener.
  2. Now open listener.ora file which is present in following directory: C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN

    1. Open that file and change the host parameter with you computer name
    2. You can get your computer name by right click on My Computer and check you computer name, and replace host parameter with your computer name as follows:

      LISTENER = (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1)) (ADDRESS = (PROTOCOL = TCP)(HOST = Electron-PC)(PORT = 1521) ) ) )

      So here you can observe HOST = Electron-PC, which is my computer name.

    3. Save the listener.ora file and again return to cammand propt

    3.Type the following in command prompt lsnrctl start

This will start the OracleTNSListner.

you can check it in the service by opening services tab of Task Manager. if not started automatically you can start it.

Just this much and you are ready to work again on oracle.

Best of Luck.

Python, how to check if a result set is empty?

For reference, cursor.rowcount will only return on CREATE, UPDATE and DELETE statements:

 |  rowcount
 |      This read-only attribute specifies the number of rows the last DML statement
 |      (INSERT, UPDATE, DELETE) affected.  This is set to -1 for SELECT statements.

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

How to tar certain file types in all subdirectories?

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -I 'pigz -9' -cf target.tgz

for multicore or just for one core:

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -czf target.tgz

How to register ASP.NET 2.0 to web server(IIS7)?

Open Control Panel - Programs - Turn Windows Features on or off expand - Internet Information Services expand - World Wide Web Services expand - Application development Features check - ASP.Net

Its advisable you check other feature to avoid future problem that might not give direct error messages Please don't forget to mark this question as answered if it solves your problem for the purpose of others

How to send email to multiple address using System.Net.Mail

I think you can use this code in order to have List of outgoing Addresses having a display Name (also different):

//1.The ACCOUNT
MailAddress fromAddress = new MailAddress("[email protected]", "my display name");
String fromPassword = "password";

//2.The Destination email Addresses
MailAddressCollection TO_addressList = new MailAddressCollection();

//3.Prepare the Destination email Addresses list
foreach (var curr_address in mailto.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    MailAddress mytoAddress = new MailAddress(curr_address, "Custom display name");
    TO_addressList.Add(mytoAddress);
}

//4.The Email Body Message
String body = bodymsg;

//5.Prepare GMAIL SMTP: with SSL on port 587
var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 30000
};


//6.Complete the message and SEND the email:
using (var message = new MailMessage()
        {
            From = fromAddress,
            Subject = subject,
            Body = body,
        })
{
    message.To.Add(TO_addressList.ToString());
    smtp.Send(message);
}

Spring CORS No 'Access-Control-Allow-Origin' header is present

Following on Omar's answer, I created a new class file in my REST API project called WebConfig.java with this configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*");
  }
} 

This allows any origin to access the API and applies it to all controllers in the Spring project.

Transform DateTime into simple Date in Ruby on Rails

I recently wrote a gem to simplify this process and to neaten up your views, etc etc.

Check it out at: http://github.com/platform45/easy_dates

TypeScript, Looping through a dictionary

To get the keys:

function GetDictionaryKeysAsArray(dict: {[key: string]: string;}): string[] {
  let result: string[] = [];
  Object.keys(dict).map((key) =>
    result.push(key),
  );
  return result;
}

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

how to remove the bold from a headline?

<h1><span>This is</span> a Headline</h1>

h1 { font-weight: normal; text-transform: uppercase; }
h1 span { font-weight: bold; }

I'm not sure if it was just for the sake of showing us, but as a side note, you should always set uppercase text with CSS :)

automating telnet session using bash scripts

This worked for me..

I was trying to automate multiple telnet logins which require a username and password. The telnet session needs to run in the background indefinitely since I am saving logs from different servers to my machine.

telnet.sh automates telnet login using the 'expect' command. More info can be found here: http://osix.net/modules/article/?id=30

telnet.sh

#!/usr/bin/expect
set timeout 20
set hostName [lindex $argv 0]
set userName [lindex $argv 1]
set password [lindex $argv 2]

spawn telnet $hostName

expect "User Access Verification"
expect "Username:"
send "$userName\r"
expect "Password:"
send "$password\r";
interact

sample_script.sh is used to create a background process for each of the telnet sessions by running telnet.sh. More information can be found in the comments section of the code.

sample_script.sh

#!/bin/bash
#start screen in detached mode with session-name 'default_session' 
screen -dmS default_session -t screen_name 
#save the generated logs in a log file 'abc.log' 
screen -S default_session -p screen_name -X stuff "script -f /tmp/abc.log $(printf \\r)"
#start the telnet session and generate logs
screen -S default_session -p screen_name -X stuff "expect telnet.sh hostname username password $(printf \\r)"
  1. Make sure there is no screen running in the backgroud by using the command 'screen -ls'.
  2. Read http://www.gnu.org/software/screen/manual/screen.html#Stuff to read more about screen and its options.
  3. '-p' option in sample_script.sh preselects and reattaches to a specific window to send a command via the ‘-X’ option otherwise you get a 'No screen session found' error.

How To Change DataType of a DataColumn in a DataTable?

Puedes agregar una columna con tipo de dato distinto , luego copiar los datos y eliminar la columna anterior

TB.Columns.Add("columna1", GetType(Integer))    
TB.Select("id=id").ToList().ForEach(Sub(row) row("columna1") = row("columna2"))    
TB.Columns.Remove("columna2")

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.

How to enable CORS in AngularJs

Answered by myself.

CORS angular js + restEasy on POST

Well finally I came to this workaround: The reason it worked with IE is because IE sends directly a POST instead of first a preflight request to ask for permission. But I still don't know why the filter wasn't able to manage an OPTIONS request and sends by default headers that aren't described in the filter (seems like an override for that only case ... maybe a restEasy thing ...)

So I created an OPTIONS path in my rest service that rewrites the reponse and includes the headers in the response using response header

I'm still looking for the clean way to do it if anybody faced this before.

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

How to: Install Plugin in Android Studio

if you are on Linux (Ubuntu)... the go to File-> Settings-> Plugin and select plugin from respective location.

If you are on Mac OS... the go to File-> Preferences-> Plugin and select plugin from respective location.

How can I check for existence of element in std::vector, in one line?

Try std::find

vector<int>::iterator it = std::find(v.begin(), v.end(), 123);

if(it==v.end()){

    std::cout<<"Element not found";
}

grep using a character vector with multiple patterns

In addition to @Marek's comment about not including fixed==TRUE, you also need to not have the spaces in your regular expression. It should be "A1|A9|A6".

You also mention that there are lots of patterns. Assuming that they are in a vector

toMatch <- c("A1", "A9", "A6")

Then you can create your regular expression directly using paste and collapse = "|".

matches <- unique (grep(paste(toMatch,collapse="|"), 
                        myfile$Letter, value=TRUE))

How do I manually configure a DataSource in Java?

One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.

Edit:

If you want to configure a BasicDataSource for MySQL, you would do something like this:

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");

Code that needs a DataSource can then use that.

Assert a function/method was not called using Mock

With python >= 3.5 you can use mock_object.assert_not_called().

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

git rebase: "error: cannot stat 'file': Permission denied"

I just stumbled upon this thread of answers - this error is such a Bogus error.# error: cannot stat 'reddit/app/views/links': Permission denied

That's all I got - when trying to merge. I read a few of the answers and then came to the realization - all I had to do was close my code editor which happens to be Atom.

Once closing the editor - I ran "git merge" again and boom , it worked.

What a pointless error:(

Merge 2 arrays of objects

var newArray = yourArray.concat(otherArray); console.log('Concatenated newArray: ', newArray);

How to search images from private 1.0 registry in docker?

Modifying the answer from @mre to get the list just from one command (valid at least for Docker Registry v2).

docker exec -it <your_registry_container_id> ls -a /var/lib/registry/docker/registry/v2/repositories/

Understanding colors on Android (six characters)

Android Material Design

These are the conversions for setting the text color opacity levels.

  • 100%: FF
  • 87%: DE
  • 70%: B3
  • 54%: 8A
  • 50%: 80
  • 38%: 61
  • 12%: 1F

Dark text on light backgrounds

enter image description here

  • Primary text: DE000000
  • Secondary text: 8A000000
  • Disabled text, hint text, and icons: 61000000
  • Dividers: 1F000000

White text on dark backgrounds

enter image description here

  • Primary text: FFFFFFFF
  • Secondary text: B3FFFFFF
  • Disabled text, hint text, and icons: 80FFFFFF
  • Dividers: 1FFFFFFF

See also

  • Look up any percentage here.

Can I write into the console in a unit test? If yes, why doesn't the console window open?

Visual Studio For Mac

None of the other solutions worked on Visual Studio for Mac

If you are using NUnit, you can add a small .NET Console Project to your solution, and then reference the project you wish to test in the References of that new Console Project.

Whatever you were doing in your [Test()] methods can be done in the Main of the console application in this fashion:

class MainClass
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Console");

        // Reproduce the unit test
        var classToTest = new ClassToTest();
        var expected = 42;
        var actual = classToTest.MeaningOfLife();
        Console.WriteLine($"Pass: {expected.Equals(actual)}, expected={expected}, actual={actual}");
    }
}

You are free to use Console.Write and Console.WriteLine in your code under these circumstances.

powershell mouse move does not prevent idle mode

I had a similar situation where a download needed to stay active overnight and required a key press that refreshed my connection. I also found that the mouse move does not work. However, using notepad and a send key function appears to have done the trick. I send a space instead of a "." because if there is a [yes/no] popup, it will automatically click the default response using the spacebar. Here is the code used.

param($minutes = 120)

$myShell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 30
  $myShell.sendkeys(" ")
}

This function will work for the designated 120 minutes (2 Hours), but can be modified for the timing desired by increasing or decreasing the seconds of the input, or increasing or decreasing the assigned value of the minutes parameter.

Just run the script in powershell ISE, or powershell, and open notepad. A space will be input at the specified interval for the desired length of time ($minutes).

Good Luck!

How to read a file into a variable in shell?

In cross-platform, lowest-common-denominator sh you use:

#!/bin/sh
value=`cat config.txt`
echo "$value"

In bash or zsh, to read a whole file into a variable without invoking cat:

#!/bin/bash
value=$(<config.txt)
echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker's Wiki - Command substitution - Specialities.

mysql datetime comparison

But this is obviously performing a 'string' comparison

No. The string will be automatically cast into a DATETIME value.

See 11.2. Type Conversion in Expression Evaluation.

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

This error can be resolved by adding MessageBoxOptions.ServiceNotification.

MessageBox.Show(msg, "Print Error", System.Windows.Forms.MessageBoxButtons.YesNo, 
   System.Windows.Forms.MessageBoxIcon.Error,     
   System.Windows.Forms.MessageBoxDefaultButton.Button1, 
   System.Windows.Forms.MessageBoxOptions.ServiceNotification); 

But it is not going to show any dialog box if your web application is installed on IIS or server.Because in IIS or server it is hosted on worker process which dont have any desktop.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Blue and Purple Default links, how to remove?

<a href="https://www." style="color: inherit;"target="_blank">

For CSS inline style, this worked best for me.

Angular 2 ngfor first, last, index loop

By this you can get any index in *ngFor loop in ANGULAR ...

<ul>
  <li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
    <div *ngIf="first">
       // write your code...
    </div>

    <div *ngIf="last">
       // write your code...
    </div>
  </li>
</ul>

We can use these alias in *ngFor

  • index : number : let i = index to get all index of object.
  • first : boolean : let first = first to get first index of object.
  • last : boolean : let last = last to get last index of object.
  • odd : boolean : let odd = odd to get odd index of object.
  • even : boolean : let even = even to get even index of object.

Intersect Two Lists in C#

public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
    return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
                .Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}

What's the proper value for a checked attribute of an HTML checkbox?

Strictly speaking, you should put something that makes sense - according to the spec here, the most correct version is:

<input name=name id=id type=checkbox checked=checked>

For HTML, you can also use the empty attribute syntax, checked="", or even simply checked (for stricter XHTML, this is not supported).

Effectively, however, most browsers will support just about any value between the quotes. All of the following will be checked:

<input name=name id=id type=checkbox checked>
<input name=name id=id type=checkbox checked="">
<input name=name id=id type=checkbox checked="yes">
<input name=name id=id type=checkbox checked="blue">
<input name=name id=id type=checkbox checked="false">

And only the following will be unchecked:

<input name=name id=id type=checkbox>

See also this similar question on disabled="disabled".

Can dplyr package be used for conditional mutating?

Since you ask for other better ways to handle the problem, here's another way using data.table:

require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]

Note the order of conditional statements is reversed to get g correctly. There's no copy of g made, even during the second assignment - it's replaced in-place.

On larger data this would have better performance than using nested if-else, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.


Here's a benchmark on relatively bigger data:

# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT) 
# [1] 10000000        6
DF <- as.data.frame(DT)

DT_fun <- function(DT) {
    DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
    DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
    mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

BASE_fun <- function(DF) { # R v3.1.0
    transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

system.time(ans1 <- DT_fun(DT))
#   user  system elapsed 
#  2.659   0.420   3.107 

system.time(ans2 <- DPLYR_fun(DF))
#   user  system elapsed 
# 11.822   1.075  12.976 

system.time(ans3 <- BASE_fun(DF))
#   user  system elapsed 
# 11.676   1.530  13.319 

identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE

identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE

Not sure if this is an alternative you'd asked for, but I hope it helps.

Step-by-step debugging with IPython

From python 3.2, you have the interact command, which gives you access to the full python/ipython command space.

Testing two JSON objects for equality ignoring child order in Java

Looking at the answers, I tried JSONAssert but it failed. So I used Jackson with zjsonpatch. I posted details in the SO answer here.

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

What is git fast-forwarding?

In Git, to "fast forward" means to update the HEAD pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...

Fast forwarding is not possible when the new HEAD is in a diverged state relative to the stream you want to integrate. For instance, you are on master and have local commits, and git fetch has brought new upstream commits into origin/master. The branch now diverges from its upstream and cannot be fast forwarded: your master HEAD commit is not an ancestor of origin/master HEAD. To simply reset master to the value of origin/master would discard your local commits. The situation requires a rebase or merge.

If your local master has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master. Usually, no special steps are needed to do fast-forwarding; it is done by merge or rebase in the situation when there are no local commits.

Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?

No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)

jQuery: If this HREF contains

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

jquery simple image slideshow tutorial

This is by far the easiest example I have found on the net. http://jonraasch.com/blog/a-simple-jquery-slideshow

Summaring the example, this is what you need to do a slideshow:

HTML:

<div id="slideshow">
    <img src="img1.jpg" style="position:absolute;" class="active" />
    <img src="img2.jpg" style="position:absolute;" />
    <img src="img3.jpg" style="position:absolute;" />
</div>

Position absolute is used to put an each image over the other.

CSS

<style type="text/css">
    .active{
        z-index:99;
    }
</style>

The image that has the class="active" will appear over the others, the class=active property will change with the following Jquery code.

<script>
    function slideSwitch() {
        var $active = $('div#slideshow IMG.active');
        var $next = $active.next();    

        $next.addClass('active');

        $active.removeClass('active');
    }

    $(function() {
        setInterval( "slideSwitch()", 5000 );
    });
</script>

If you want to go further with slideshows I suggest you to have a look at the link above (to see animated oppacity changes - 2n example) or at other more complex slideshows tutorials.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

This solution worked for me

1) Click the "Export" tab for the database

2) Click the "Custom" radio button

3) Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

4) Scroll to the bottom and click "GO".

If it's related to wordpress, more info on why it is happening.

Search All Fields In All Tables For A Specific Value (Oracle)

Yes you can and your DBA will hate you and will find you to nail your shoes to the floor because that will cause lots of I/O and bring the database performance really down as the cache purges.

select column_name from all_tab_columns c, user_all_tables u where c.table_name = u.table_name;

for a start.

I would start with the running queries, using the v$session and the v$sqlarea. This changes based on oracle version. This will narrow down the space and not hit everything.

Is it ok to scrape data from Google results?

Google will eventually block your IP when you exceed a certain amount of requests.

Eclipse projects not showing up after placing project files in workspace/projects

This problems comes while .metadata of current workspace has been corrupted due to shut down Eclipse Unexpectedly. So if you face this problem just do the following steps:

  • Create a new workspace. Import your existing projects to your new workspace.

you made it!

arranging div one below the other

The default behaviour of divs is to take the full width available in their parent container.
This is the same as if you'd give the inner divs a width of 100%.

By floating the divs, they ignore their default and size their width to fit the content. Everything behind it (in the HTML), is placed under the div (on the rendered page).
This is the reason that they align theirselves next to each other.

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/float

Get rid of the float, and the divs will be aligned under each other.
If this does not happen, you'll have some other css on divs or children of wrapper defining a floating behaviour or an inline display.

If you want to keep the float, for whatever reason, you can use clear on the 2nd div to reset the floating properties of elements before that element.
clear has 5 valid values: none | left | right | both | inherit. Clearing no floats (used to override inherited properties), left or right floats or both floats. Inherit means it'll inherit the behaviour of the parent element

Also, because of the default behaviour, you don't need to set the width and height on auto.
You only need this is you want to set a hardcoded height/width. E.g. 80% / 800px / 500em / ...

<div id="wrapper">
    <div id="inner1"></div>
    <div id="inner2"></div>
</div>

CSS is

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; // this is not needed, as parent container, this div will size automaticly
    width:auto; // this is not needed, as parent container, this div will size automaticly
}

/*
You can get rid of the inner divs in the css, unless you want to style them.
If you want to style them identicly, you can use concatenation
*/
#inner1, #inner2 {
    border: 1px solid black;
}

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

What is the ellipsis (...) for in this method signature?

The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on".

As for its use in Java, it stands for varargs, meaning that any number of arguments can be added to the method call. The only limitations are that the varargs must be at the end of the method signature and there can only be one per method.

Javascript swap array elements

If you don't want to use temp variable in ES5, this is one way to swap array elements.

var swapArrayElements = function (a, x, y) {
  if (a.length === 1) return a;
  a.splice(y, 1, a.splice(x, 1, a[y])[0]);
  return a;
};

swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]

Javascript to convert UTC to local time

To format your date try the following function:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

Chris

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

I faced the same issue while running my project: I found out that if your project is using specific version of any thing in package.json find out that and install the specific version of that dependencies like for me, npm install @angular/cli@^4.0.0.

Show which git tag you are on?

This worked for me git describe --tags --abbrev=0

Edit 2020: As mentioned by some of the comments below, this might, or might not work for you, so be careful!

How to convert a string with Unicode encoding to a string of letters

This simple method will work for most cases, but would trip up over something like "u005Cu005C" which should decode to the string "\u0048" but would actually decode "H" as the first pass produces "\u0048" as the working string which then gets processed again by the while loop.

static final String decode(final String in)
{
    String working = in;
    int index;
    index = working.indexOf("\\u");
    while(index > -1)
    {
        int length = working.length();
        if(index > (length-6))break;
        int numStart = index + 2;
        int numFinish = numStart + 4;
        String substring = working.substring(numStart, numFinish);
        int number = Integer.parseInt(substring,16);
        String stringStart = working.substring(0, index);
        String stringEnd   = working.substring(numFinish);
        working = stringStart + ((char)number) + stringEnd;
        index = working.indexOf("\\u");
    }
    return working;
}

How to create a directive with a dynamic template in AngularJS?

If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.

http://www.w3docs.com/snippets/angularjs/dynamically-change-template-url-in-angularjs-directives.html

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

how to check if a datareader is null or empty

This

Example:

objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

Swift: Display HTML data in a label or textView

Swift 3

extension String {


var html2AttributedString: NSAttributedString? {
    guard
        let data = data(using: String.Encoding.utf8)
        else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
 }
}

compression and decompression of string data in java

You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

Mismatch Detected for 'RuntimeLibrary'

(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)

This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)

To correct this error, you need to go into your Project Properties (and/or those of the libraries you are using,) then into C/C++, then Code Generation, and check the value of Runtime Library; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)

There are currently four options for this setting:

  1. Multithreaded Debug
  2. Multithreaded Debug DLL
  3. Multithreaded Release
  4. Multithreaded Release DLL

Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.

Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.

For (some) more information, you can see these (linked from a comment above):

  1. Linker Tools Warning LNK4098 on MSDN
  2. /MD, /ML, /MT, /LD (Use Run-Time Library) on MSDN
  3. Build errors with VC11 Beta - mixing MTd libs with MDd exes fail to link on Bugzilla@Mozilla

UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)

If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)

The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.

Consider for example that the above two pieces of code are called A and B. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)

Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)

The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.

All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)

This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.

What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!

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

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

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

Get index of a key in json

What you are after are numerical indexes in the way classic arrays work, however there is no such thing with json object/associative arrays.

"key1", "key2" themeselves are the indexes and there is no numerical index associated with them. If you want to have such functionality you have to assiciate them yourself.

Generate class from database table

Set @TableName to the name of your table.

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'double'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'float'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'long'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

Adding double quote delimiters into csv file

Here's a way to do it without formulas or macros:

  1. Save your CSV as Excel
  2. Select any cells that might have commas
  3. Open to the Format menu and click on Cells
  4. Pick the Custom format
  5. Enter this => \"@\"
  6. Click OK
  7. Save the file as CSV

(from http://www.lenashore.com/2012/04/how-to-add-quotes-to-your-cells-in-excel-automatically/)

Google Chrome form autofill and its yellow background

The following CSS removes the yellow background color and replaces it with a background color of your choosing. It doesn't disable auto-fill and it requires no jQuery or Javascript hacks.

input:-webkit-autofill {
    -webkit-box-shadow:0 0 0 50px white inset; /* Change the color to your own background color */
    -webkit-text-fill-color: #333;
}
input:-webkit-autofill:focus {
    -webkit-box-shadow: /*your box-shadow*/,0 0 0 50px white inset;
    -webkit-text-fill-color: #333;
}

Solution copied from: Override browser form-filling and input highlighting with HTML/CSS

CSS Outside Border

Why not simply using background-clip?

-webkit-background-clip: padding;
   -moz-background-clip: padding;
        background-clip: padding-box;

See:
http://caniuse.com/#search=background-clip
https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip
https://css-tricks.com/almanac/properties/b/background-clip

Check/Uncheck a checkbox on datagridview

// here is a simple way to do so

//irate through the gridview
            foreach (DataGridViewRow row in PifGrid.Rows)
            {
//store the cell (which is checkbox cell) in an object
                DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;

//check if the checkbox is checked or not
                bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);

//if its checked then uncheck it other wise check it
                if (!bChecked)
                {
                    row.Cells["Check"].Value = true;

                }
                else
                {
                    row.Cells["Check"].Value = false;

                }
            }

What's the best practice for putting multiple projects in a git repository?

Solution 3

This is for using a single directory for multiple projects. I use this technique for some closely related projects where I often need to pull changes from one project into another. It's similar to the orphaned branches idea but the branches don't need to be orphaned. Simply start all the projects from the same empty directory state.

Start all projects from one committed empty directory

Don't expect wonders from this solution. As I see it, you are always going to have annoyances with untracked files. Git doesn't really have a clue what to do with them and so if there are intermediate files generated by a compiler and ignored by your .gitignore file, it is likely that they will be left hanging some of the time if you try rapidly swapping between - for example - your software project and a PH.D thesis project.

However here is the plan. Start as you ought to start any git projects, by committing the empty repository, and then start all your projects from the same empty directory state. That way you are certain that the two lots of files are fairly independent. Also, give your branches a proper name and don't lazily just use "master". Your projects need to be separate so give them appropriate names.

Git commits (and hence tags and branches) basically store the state of a directory and its subdirectories and Git has no idea whether these are parts of the same or different projects so really there is no problem for git storing different projects in the same repository. The problem is then for you clearing up the untracked files from one project when using another, or separating the projects later.

Create an empty repository

cd some_empty_directory
git init
touch .gitignore
git add .gitignore
git commit -m empty
git tag EMPTY

Start your projects from empty.

Work on one project.

git branch software EMPTY
git checkout software
echo "array board[8,8] of piece" > chess.prog

git add chess.prog 
git commit -m "chess program"

Start another project

whenever you like.

git branch thesis EMPTY
git checkout thesis
echo "the meaning of meaning" > philosophy_doctorate.txt
git add philosophy_doctorate.txt 
git commit -m "Ph.D"

Switch back and forth

Go back and forwards between projects whenever you like. This example goes back to the chess software project.

git checkout software
echo "while not end_of_game do make_move()" >> chess.prog
git add chess.prog 
git commit -m "improved chess program"

Untracked files are annoying

You will however be annoyed by untracked files when swapping between projects/branches.

touch untracked_software_file.prog
git checkout thesis 
ls
    philosophy_doctorate.txt  untracked_software_file.prog

It's not an insurmountable problem

Sort of by definition, git doesn't really know what to do with untracked files and it's up to you to deal with them. You can stop untracked files from being carried around from one branch to another as follows.

git checkout EMPTY 
ls
    untracked_software_file.prog
rm -r *
    (directory is now really empty, apart from the repository stuff!)
git checkout thesis
ls
    philosophy_doctorate.txt

By ensuring that the directory was empty before checking out our new project we made sure there were no hanging untracked files from another project.

A refinement

$ GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01T01:01:01' git commit -m empty

If the same dates are specified whenever committing an empty repository, then independently created empty repository commits can have the same SHA1 code. This allows two repositories to be created independently and then merged together into a single tree with a common root in one repository later.

Example

# Create thesis repository. 
# Merge existing chess repository branch into it

mkdir single_repo_for_thesis_and_chess
cd single_repo_for_thesis_and_chess
git init
touch .gitignore
git add .gitignore
GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01:T01:01:01' git commit -m empty
git tag EMPTY
echo "the meaning of meaning" > thesis.txt
git add thesis.txt
git commit -m "Wrote my PH.D"
git branch -m master thesis

# It's as simple as this ...
git remote add chess ../chessrepository/.git
git fetch chess chess:chess

Result

Diagram of merged repositories

Use subdirectories per project?

It may also help if you keep your projects in subdirectories where possible, e.g. instead of having files

chess.prog
philosophy_doctorate.txt 

have

chess/chess.prog
thesis/philosophy_doctorate.txt 

In this case your untracked software file will be chess/untracked_software_file.prog. When working in the thesis directory you should not be disturbed by untracked chess program files, and you may find occasions when you can work happily without deleting untracked files from other projects.

Also, if you want to remove untracked files from other projects, it will be quicker (and less prone to error) to dump an unwanted directory than to remove unwanted files by selecting each of them.

Branch names can include '/' characters

So you might want to name your branches something like

project1/master
project1/featureABC
project2/master
project2/featureXYZ

TypeError: $ is not a function when calling jQuery function

Use

jQuery(document).

instead of

$(document).

or

Within the function, $ points to jQuery as you would expect

(function ($) {
   $(document).
}(jQuery));

How to connect to LocalDb

Use (localdb)\MSSQLLocalDBwith Windows Auth

How to remove a row from JTable?

The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns.

What's the best way to generate a UML diagram from Python source code?

Certain classes of well-behaved programs may be diagrammable, but in the general case, it can't be done. Python objects can be extended at run time, and objects of any type can be assigned to any instance variable. Figuring out what classes an object can contain pointers to (composition) would require a full understanding of the runtime behavior of the program.

Python's metaclass capabilities mean that reasoning about the inheritance structure would also require a full understanding of the runtime behavior of the program.

To prove that these are impossible, you argue that if such a UML diagrammer existed, then you could take an arbitrary program, convert "halt" statements into statements that would impact the UML diagram, and use the UML diagrammer to solve the halting problem, which as we know is impossible.

Python: Get relative path from comparing two absolute paths

Edit : See jme's answer for the best way with Python3.

Using pathlib, you have the following solution :

Let's say we want to check if son is a descendant of parent, and both are Path objects. We can get a list of the parts in the path with list(parent.parts). Then, we just check that the begining of the son is equal to the list of segments of the parent.

>>> lparent = list(parent.parts)
>>> lson = list(son.parts)
>>> if lson[:len(lparent)] == lparent:
>>> ... #parent is a parent of son :)

If you want to get the remaining part, you can just do

>>> ''.join(lson[len(lparent):])

It's a string, but you can of course use it as a constructor of an other Path object.

Combine Date and Time columns using python pandas

First make sure to have the right data types:

df["Date"] = pd.to_datetime(df["Date"])
df["Time"] = pd.to_timedelta(df["Time"])

Then you easily combine them:

df["DateTime"] = df["Date"] + df["Time"]

How to convert Java String into byte[]?

It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:

Bool DmgrGetVersion (String szVersion);

Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010

How do I use reflection to invoke a private method?

Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):

obj.GetType().GetTypeInfo().GetDeclaredMethod("MethodName").Invoke(obj, yourArgsHere);

Or as an extension method:

public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)
{
    var type = typeof(T);
    var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
    return method.Invoke(obj, args);
}

Note:

  • If the desired method is in a superclass of obj the T generic must be explicitly set to the type of the superclass.

  • If the method is asynchronous you can use await (Task) obj.InvokeMethod(…).

Set default time in bootstrap-datetimepicker

By using Moment.js, i able to set the default time

var defaultStartTime = moment(new Date());
var _startTimeStr = "02:00 PM"


    if (moment(_startTimeStr, 'HH:mm a').isValid()) {
        var hr = moment(_startTimeStr, 'HH:mm a').hour();
        var min = moment(_startTimeStr, 'HH:mm a').minutes();

        defaultStartTime = defaultStartTime.hours(hr).minutes(min);
    }

$('#StartTime').datetimepicker({
    pickDate: false,
    defaultDate: defaultStartTime
});

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

How to clear cache of Eclipse Indigo

If you are asking about cache where eclipse stores your project and workspace information right click on your project(s) and choose refresh. Then go to project in the menu on top of the window and click "clean".

This typically does what you need.

If it does not try to remove project from the workspace (just press "delete" on the project and then say that you DO NOT want to remove the sources). Then open project again.

If this does not work too, do the same with the workspace. If this still does not work, perform fresh checkout of your project from source control and create new workspace.

Well, this should work.

Pass a password to ssh in pure bash

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

sshpass -f <(printf '%s\n' your_password) ssh user@hostname

instead of using sshpass -p your_password. As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

BTW, a little explanation for the <(command) syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe

Delayed function calls

Building upon the answer from David O'Donoghue here is an optimized version of the Delayed Delegate:

using System.Windows.Forms;
using System.Collections.Generic;
using System;

namespace MyTool
{
    public class DelayedDelegate
    {
       static private DelayedDelegate _instance = null;

        private Timer _runDelegates = null;

        private Dictionary<MethodInvoker, DateTime> _delayedDelegates = new Dictionary<MethodInvoker, DateTime>();

        public DelayedDelegate()
        {
        }

        static private DelayedDelegate Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DelayedDelegate();
                }

                return _instance;
            }
        }

        public static void Add(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay * 1000);
        }

        public static void AddMilliseconds(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay);
        }

        private void AddNewDelegate(MethodInvoker pMethod, int pDelay)
        {
            if (_runDelegates == null)
            {
                _runDelegates = new Timer();
                _runDelegates.Tick += RunDelegates;
            }
            else
            {
                _runDelegates.Stop();
            }

            _delayedDelegates.Add(pMethod, DateTime.Now + TimeSpan.FromMilliseconds(pDelay));

            StartTimer();
        }

        private void StartTimer()
        {
            if (_delayedDelegates.Count > 0)
            {
                int delay = FindSoonestDelay();
                if (delay == 0)
                {
                    RunDelegates();
                }
                else
                {
                    _runDelegates.Interval = delay;
                    _runDelegates.Start();
                }
            }
        }

        private int FindSoonestDelay()
        {
            int soonest = int.MaxValue;
            TimeSpan remaining;

            foreach (MethodInvoker invoker in _delayedDelegates.Keys)
            {
                remaining = _delayedDelegates[invoker] - DateTime.Now;
                soonest = Math.Max(0, Math.Min(soonest, (int)remaining.TotalMilliseconds));
            }

            return soonest;
        }

        private void RunDelegates(object pSender = null, EventArgs pE = null)
        {
            try
            {
                _runDelegates.Stop();

                List<MethodInvoker> removeDelegates = new List<MethodInvoker>();

                foreach (MethodInvoker method in _delayedDelegates.Keys)
                {
                    if (DateTime.Now >= _delayedDelegates[method])
                    {
                        method();

                        removeDelegates.Add(method);
                    }
                }

                foreach (MethodInvoker method in removeDelegates)
                {
                    _delayedDelegates.Remove(method);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                StartTimer();
            }
        }
    }
}

The class could be slightly more improved by using a unique key for the delegates. Because if you add the same delegate a second time before the first one fired, you might get a problem with the dictionary.

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

HttpClient does not exist in .net 4.0: what can I do?

Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here

However, the text is very confusion and contradicts itself.

This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.

But underneath it states that these are the supported platforms.

Supported Platforms:

  • .NET Framework 4

  • Windows 8

  • Windows Phone 8.1

  • Windows Phone Silverlight 7.5

  • Silverlight 4

  • Portable Class Libraries

Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.

Missing artifact com.sun:tools:jar

Problem is system is not able to find the file tools.jar

So first check that the file is there in the JDK installation of the directory.

enter image description here

Make the below entry in POM.xml as rightly pointed by others

<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.8.0_241\lib\tools.jar</systemPath>
</dependency> 

then Follow the below steps also to remove the problem

1) Right Click on your project

2) Click on Build path

As per the below image, select the workspace default JRE and click on finish.

enter image description here

How can I get the selected VALUE out of a QCombobox?

The member function QComboBox::currentData has been added since this question was asked, see this commit

Installing Bower on Ubuntu

on Ubuntu 12.04 and the packaged version of NodeJs is too old to install Bower using the PPA

sudo add-apt-repository ppa:chris-lea/node.js 
sudo apt-get update
sudo apt-get -y install nodejs

When this has installed, check the version:

npm --version
1.4.3

Now install Bower:

sudo npm install -g bower

This will fetch and install Bower globally.

What is the difference between HTML tags and elements?

lets put this in a simple term. An element is a set of opening and closing tags in use.

Element

<h1>...</h1>

Tag H1 opening tag

<h1>

H1 closing tag

</h1>

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.

  • this is against Facebook policy, so depending on the country where you live, this may not be legal
  • you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
  • when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
  • this is bypassing the OAuth concept
  • on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API

Sample implementation using WatiN:

class FacebookUser
{
  public string Name { get; set; }
  public long Id { get; set; }
}

public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
  var users = new List<FacebookUser>();
  Settings.Instance.MakeNewIeInstanceVisible = false;
  using (var browser = new IE("https://www.facebook.com"))
  {
    try
    {
      browser.TextField(Find.ByName("email")).Value = email;
      browser.TextField(Find.ByName("pass")).Value = password;
      browser.Form(Find.ById("login_form")).Submit();
      browser.WaitForComplete();
    }
    catch (ElementNotFoundException)
    {
      // We're already logged in
    }
    browser.GoTo("https://www.facebook.com/friends");
    var watch = new Stopwatch();
    watch.Start();

    Link previousLastLink = null;
    while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
    {
      var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
                       && l.GetAttributeValue("data-hovercard").Contains("user.php")
                       && l.Text != null
                     ).LastOrDefault();

      if (lastLink == null || previousLastLink == lastLink)
      {
        break;
      }

      var ieElement = lastLink.NativeElement as IEElement;
      if (ieElement != null)
      {
        var htmlElement = ieElement.AsHtmlElement;
        htmlElement.scrollIntoView();
        browser.WaitForComplete();
      }

      previousLastLink = lastLink;
    }

    var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
      && l.GetAttributeValue("data-hovercard").Contains("user.php")
      && l.Text != null
    ).ToList();

    var idRegex = new Regex("id=(?<id>([0-9]+))");
    foreach (var link in links)
    {
      string hovercard = link.GetAttributeValue("data-hovercard");
      var match = idRegex.Match(hovercard);
      long id = 0;
      if (match.Success)
      {
        id = long.Parse(match.Groups["id"].Value);
      }
      users.Add(new FacebookUser
      {
        Name = link.Text,
        Id = id
      });
    }
  }
  return users;
}

Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.

setup.py examples?

Here you will find the simplest possible example of using distutils and setup.py:

https://docs.python.org/2/distutils/introduction.html#distutils-simple-example

This assumes that all your code is in a single file and tells how to package a project containing a single module.

Pretty-Print JSON Data to a File using Python

If you already have existing JSON files which you want to pretty format you could use this:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

Spring MVC + JSON = 406 Not Acceptable

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

That should be the problem. JSON is served as application/json. If you set the Accept header accordingly, you should get the proper response. (There are browser plugins that let you set headers, I like "Poster" for Firefox best)

Find an object in SQL Server (cross-database)

Easiest way is to hit up the information_schemas...

SELECT *
FROM information_schema.Tables
WHERE [Table_Name]='????'

SELECT *
FROM information_schema.Views
WHERE [Table_Name]='????'

SELECT *
FROM information_schema.Routines
WHERE [Routine_Name]='????'

Permutations between two lists of unequal length

May be simpler than the simplest one above:

>>> a = ["foo", "bar"]
>>> b = [1, 2, 3]
>>> [(x,y) for x in a for y in b]  # for a list
[('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)]
>>> ((x,y) for x in a for y in b)  # for a generator if you worry about memory or time complexity.
<generator object <genexpr> at 0x1048de850>

without any import

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

Case insensitive access for generic dictionary

There is much simpler way:

using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

Pass command parameter to method in ViewModel in WPF?

Just using Data Binding syntax. For example,

<Button x:Name="btn" 
         Content="Click" 
         Command="{Binding ClickCmd}" 
         CommandParameter="{Binding ElementName=btn,Path=Content}" /> 

Not only can we use Data Binding to get some data from View Models, but also pass data back to View Models. In CommandParameter, must use ElementName to declare binding source explicitly.

How to set a primary key in MongoDB?

This is the syntax of creating primary key

db.< collection >.createIndex( < key and index type specification>, { unique: true } )

Let's take that our database have collection named student and it's document have key named student_id which we need to make a primary key. Then the command should be like below.

db.student.createIndex({student_id:1},{unique:true})

You can check whether this student_id set as primary key by trying to add duplicate value to the student collection.

prefer this document for further informations https://docs.mongodb.com/manual/core/index-unique/#create-a-unique-index

How do I expand the output display to see more columns of a pandas DataFrame?

Only using these 3 lines worked for me:

pd.set_option('display.max_columns', None)  
pd.set_option('display.expand_frame_repr', False)
pd.set_option('max_colwidth', -1)

Anaconda / Python 3.6.5 / pandas: 0.23.0 / Visual Studio Code 1.26

Split text with '\r\n'

The problem is not with the splitting but rather with the WriteLine. A \n in a string printed with WriteLine will produce an "extra" line.

Example

var text = 
  "somet interesting text\n" +
  "some text that should be in the same line\r\n" +
  "some text should be in another line";

string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
   Console.WriteLine(s); //But will print 3 lines in total.
}

To fix the problem remove \n before you print the string.

Console.WriteLine(s.Replace("\n", ""));

Writing a list to a file with Python

I thought it would be interesting to explore the benefits of using a genexp, so here's my take.

The example in the question uses square brackets to create a temporary list, and so is equivalent to:

file.writelines( list( "%s\n" % item for item in list ) )

Which needlessly constructs a temporary list of all the lines that will be written out, this may consume significant amounts of memory depending on the size of your list and how verbose the output of str(item) is.

Drop the square brackets (equivalent to removing the wrapping list() call above) will instead pass a temporary generator to file.writelines():

file.writelines( "%s\n" % item for item in list )

This generator will create newline-terminated representation of your item objects on-demand (i.e. as they are written out). This is nice for a couple of reasons:

  • Memory overheads are small, even for very large lists
  • If str(item) is slow there's visible progress in the file as each item is processed

This avoids memory issues, such as:

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(I triggered this error by limiting Python's max. virtual memory to ~100MB with ulimit -v 102400).

Putting memory usage to one side, this method isn't actually any faster than the original:

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(Python 2.6.2 on Linux)

Using PHP with Socket.io

For 'long-lived connection' you mentioned, you can use Ratchet for PHP. It's a library built based on Stream Socket functions that PHP has supported since PHP 5.

For client side, you need to use WebSocket that HTML5 supported instead of Socket.io (since you know, socket.io only works with node.js).

In case you still want to use Socket.io, you can try this way: - find & get socket.io.js for client to use - work with Ratchet to simulate the way socket.io does on server

Hope this helps!

Docker official registry (Docker Hub) URL

For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be

docker.io/<dockerimagename>:version

The suggestion above of registry.hub.docker.com/library/<dockerimagename> did not work for me.

I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

checked = "checked" vs checked = true

document.getElementById('myRadio').checked is a boolean value. It should be true or false

document.getElementById('myRadio').checked = "checked"; casts the string to a boolean, which is true.

document.getElementById('myRadio').checked = true; just assigns true without casting.

Use true as it is marginally more efficient and is more intention revealing to maintainers.

How to kill a nodejs process in Linux?

In order to kill use: killall -9 /usr/bin/node

To reload use: killall -12 /usr/bin/node

How to convert map to url query string?

Another 'one class'/no dependency way of doing it, handling single/multiple:

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class UrlQueryString {
  private static final String DEFAULT_ENCODING = "UTF-8";

  public static String buildQueryString(final LinkedHashMap<String, Object> map) {
    try {
      final Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      while (it.hasNext()) {
        final Map.Entry<String, Object> entry = it.next();
        final String key = entry.getKey();
        if (key != null) {
          sb.append(URLEncoder.encode(key, DEFAULT_ENCODING));
          sb.append('=');
          final Object value = entry.getValue();
          final String valueAsString = value != null ? URLEncoder.encode(value.toString(), DEFAULT_ENCODING) : "";
          sb.append(valueAsString);
          if (it.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static String buildQueryStringMulti(final LinkedHashMap<String, List<Object>> map) {
    try {
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      for (final Iterator<Entry<String, List<Object>>> mapIterator = map.entrySet().iterator(); mapIterator.hasNext();) {
        final Entry<String, List<Object>> entry = mapIterator.next();
        final String key = entry.getKey();
        if (key != null) {
          final String keyEncoded = URLEncoder.encode(key, DEFAULT_ENCODING);
          final List<Object> values = entry.getValue();
          sb.append(keyEncoded);
          sb.append('=');
          if (values != null) {
            for (final Iterator<Object> listIt = values.iterator(); listIt.hasNext();) {
              final Object valueObject = listIt.next();
              sb.append(valueObject != null ? URLEncoder.encode(valueObject.toString(), DEFAULT_ENCODING) : "");
              if (listIt.hasNext()) {
                sb.append('&');
                sb.append(keyEncoded);
                sb.append('=');
              }
            }
          }
          if (mapIterator.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static void main(final String[] args) {
    // Examples: could be turned into unit tests ...
    {
      final LinkedHashMap<String, Object> queryItems = new LinkedHashMap<String, Object>();
      queryItems.put("brand", "C&A");
      queryItems.put("count", null);
      queryItems.put("misc", 42);
      final String buildQueryString = buildQueryString(queryItems);
      System.out.println(buildQueryString);
    }
    {
      final LinkedHashMap<String, List<Object>> queryItems = new LinkedHashMap<String, List<Object>>();
      queryItems.put("usernames", new ArrayList<Object>(Arrays.asList(new String[] { "bob", "john" })));
      queryItems.put("nullValue", null);
      queryItems.put("misc", new ArrayList<Object>(Arrays.asList(new Integer[] { 1, 2, 3 })));
      final String buildQueryString = buildQueryStringMulti(queryItems);
      System.out.println(buildQueryString);
    }
  }
}

You may use either simple (easier to write in most cases) or multiple when required. Note that both can be combined by adding an ampersand... If you find any problems let me know in the comments.

How to Truncate a string in PHP to the word closest to a certain number of characters?

By using the wordwrap function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:

substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));

One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:

if (strlen($string) > $your_desired_width) 
{
    $string = wordwrap($string, $your_desired_width);
    $string = substr($string, 0, strpos($string, "\n"));
}

The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:

function tokenTruncate($string, $your_desired_width) {
  $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
  $parts_count = count($parts);

  $length = 0;
  $last_part = 0;
  for (; $last_part < $parts_count; ++$last_part) {
    $length += strlen($parts[$last_part]);
    if ($length > $your_desired_width) { break; }
  }

  return implode(array_slice($parts, 0, $last_part));
}

Also, here is the PHPUnit testclass used to test the implementation:

class TokenTruncateTest extends PHPUnit_Framework_TestCase {
  public function testBasic() {
    $this->assertEquals("1 3 5 7 9 ",
      tokenTruncate("1 3 5 7 9 11 14", 10));
  }

  public function testEmptyString() {
    $this->assertEquals("",
      tokenTruncate("", 10));
  }

  public function testShortString() {
    $this->assertEquals("1 3",
      tokenTruncate("1 3", 10));
  }

  public function testStringTooLong() {
    $this->assertEquals("",
      tokenTruncate("toooooooooooolooooong", 10));
  }

  public function testContainingNewline() {
    $this->assertEquals("1 3\n5 7 9 ",
      tokenTruncate("1 3\n5 7 9 11 14", 10));
  }
}

EDIT :

Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:

$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);

Merge two json/javascript arrays in to one array

Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2); will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.

What you seek is a simple javascript function known as .concat. Which would work like:

var finalObj = json1.concat(json2);

While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:

;(function($) {
    if (!$.concat) {
        $.extend({
            concat: function() {
                return Array.prototype.concat.apply([], arguments);
            }
        });
    }
})(jQuery);

And then recall it as desired like:

var finalObj = $.concat(json1, json2);

You can also use it for multiple array objects of this type with a like:

var finalObj = $.concat(json1, json2, json3, json4, json5, ....);

And if you really want it jQuery style and very short and sweet (aka minified)

;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

_x000D_
_x000D_
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);_x000D_
_x000D_
$(function() {_x000D_
    var json1 = [{id:1, name: 'xxx'}],_x000D_
        json2 = [{id:2, name: 'xyz'}],_x000D_
        json3 = [{id:3, name: 'xyy'}],_x000D_
        json4 = [{id:4, name: 'xzy'}],_x000D_
        json5 = [{id:5, name: 'zxy'}];_x000D_
    _x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3));_x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3, json4, json5));_x000D_
    console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json4, json1, json2, json5));_x000D_
});
_x000D_
center { padding: 3em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<center>See Console Log</center>
_x000D_
_x000D_
_x000D_

jsFiddle

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';

SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
       SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2

Show or hide element in React

I was able to use css property "hidden". Don't know about possible drawbacks.

export default function App() {
    const [hidden, setHidden] = useState(false);
    return (
      <div>
        <button onClick={() => setHidden(!hidden)}>HIDE</button>
        <div hidden={hidden}>hidden component</div>
      </div>
    );
  }

Promise.all().then() resolve?

But that doesn't seem like the proper way to do it..

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("First handler", data);_x000D_
    return data.map(entry => entry * 10);_x000D_
  })_x000D_
  .then(data => {_x000D_
    console.log("Second handler", data);_x000D_
  });
_x000D_
_x000D_
_x000D_

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

The output we see from that is:

First handler [1,2]
Second handler [10,20]

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

If the additional work you're doing is synchronous, you can also put it in the first handler:

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("Initial data", data);_x000D_
    data = data.map(entry => entry * 10);_x000D_
    console.log("Updated data", data);_x000D_
    return data;_x000D_
  });
_x000D_
_x000D_
_x000D_

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

Resolve build errors due to circular dependency amongst classes

Here is the solution for templates: How to handle circular dependencies with templates

The clue to solving this problem is to declare both classes before providing the definitions (implementations). It’s not possible to split the declaration and definition into separate files, but you can structure them as if they were in separate files.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

For other people where the accepted answer does not solve this issue...

As of September 2018, AndroidX has replaced the Android Support Libraries, which includes the appcompat-v7 library.

'com.android.support:appcompat-v7' becomes 'androidx.appcompat:appcompat:1.0.0'

'com.android.support:design' becomes 'com.google.android.material:material:1.0.0'

References:

https://developer.android.com/jetpack/androidx/migrate List of Support Libraries to AndroidX mappings

How to redirect user's browser URL to a different page in Nodejs?

If you are using Express, the cleanest complete answer is this

const express = require('express')
const app     = express()

app.get('*', (req, res) => {
  // REDIRECT goes here
  res.redirect('https://www.YOUR_URL.com/')
})

app.set('port', (process.env.PORT || 3000))
const server = app.listen(app.get('port'), () => {})

Cannot connect to Database server (mysql workbench)

Try opening services.msc from the start menu search box and try manually starting the MySQL service or directly write services.msc in Run box

Simple dictionary in C++

While using a std::map is fine or using a 256-sized char table would be fine, you could save yourself an enormous amount of space agony by simply using an enum. If you have C++11 features, you can use enum class for strong-typing:

// First, we define base-pairs. Because regular enums
// Pollute the global namespace, I'm using "enum class". 
enum class BasePair {
    A,
    T,
    C,
    G
};

// Let's cut out the nonsense and make this easy:
// A is 0, T is 1, C is 2, G is 3.
// These are indices into our table
// Now, everything can be so much easier
BasePair Complimentary[4] = {
    T, // Compliment of A
    A, // Compliment of T
    G, // Compliment of C
    C, // Compliment of G
};

Usage becomes simple:

int main (int argc, char* argv[] ) {
    BasePair bp = BasePair::A;
    BasePair complimentbp = Complimentary[(int)bp];
}

If this is too much for you, you can define some helpers to get human-readable ASCII characters and also to get the base pair compliment so you're not doing (int) casts all the time:

BasePair Compliment ( BasePair bp ) {
    return Complimentary[(int)bp]; // Move the pain here
}

// Define a conversion table somewhere in your program
char BasePairToChar[4] = { 'A', 'T', 'C', 'G' };
char ToCharacter ( BasePair bp ) {
    return BasePairToChar[ (int)bp ];
}

It's clean, it's simple, and its efficient.

Now, suddenly, you don't have a 256 byte table. You're also not storing characters (1 byte each), and thus if you're writing this to a file, you can write 2 bits per Base pair instead of 1 byte (8 bits) per base pair. I had to work with Bioinformatics Files that stored data as 1 character each. The benefit is it was human-readable. The con is that what should have been a 250 MB file ended up taking 1 GB of space. Movement and storage and usage was a nightmare. Of coursse, 250 MB is being generous when accounting for even Worm DNA. No human is going to read through 1 GB worth of base pairs anyhow.

Oracle "(+)" Operator

In practice, the + symbol is placed directly in the conditional statement and on the side of the optional table (the one which is allowed to contain empty or null values within the conditional).

throw checked Exceptions from mocks with Mockito

There is the solution with Kotlin :

given(myObject.myCall()).willAnswer {
    throw IOException("Ooops")
}

Where given comes from

import org.mockito.BDDMockito.given

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.

The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

XML Schema How to Restrict Attribute by Enumeration

New answer to old question

None of the existing answers to this old question address the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD. The fix is to use xs:simpleContent first. Details follow...


Your XML,

<price currency="euros">20000.00</price>

will be valid against either of the following corrected XSDs:

Locally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Globally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="currencyType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="pounds" />
      <xs:enumeration value="euros" />
      <xs:enumeration value="dollars" />
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency" type="currencyType"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Notes

  • As commented by @Paul, these do change the content type of price from xs:string to xs:decimal, but this is not strictly necessary and was not the real problem.
  • As answered by @user998692, you could separate out the definition of currency, and you could change to xs:decimal, but this too was not the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD; xs:simpleContent is needed first.

A related matter (that wasn't asked but may have confused other answers):

How could price be restricted given that it has an attribute?

In this case, a separate, global definition of priceType would be needed; it is not possible to do this with only local type definitions.

How to restrict element content when element has attribute

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="priceType">  
    <xs:restriction base="xs:decimal">  
      <xs:minInclusive value="0.00"/>  
      <xs:maxInclusive value="99999.99"/>  
    </xs:restriction>  
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="priceType">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

How to count the frequency of the elements in an unordered list?

In Python 2.7+, you could use collections.Counter to count items

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]

The located assembly's manifest definition does not match the assembly reference

Is possible you have a wrong nugget versions in assemblyBinding try:

  1. Remove all assembly binding content in web.config / app.config:
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.1.3.0" newVersion="3.1.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.1.3.0" newVersion="3.1.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
  </dependentAssembly>
</assemblyBinding>
  1. Type in Package Manager Console: Add-BindingRedirect
  2. All necessary binding redirects are generated
  3. Run your application and see if it works properly. If not, add any missing binding redirects that the package console missed.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

If you're using Nedit under Cygwin-X (or any platform for that matter), hold down the Ctrl key while selecting text with the left mouse.

Additionally, you can then drag the selected "box" around in an insert mode using the depressed left-mouse button or in overwrite mode by using Ctrl+left-mouse button.

What does "static" mean in C?

I hate to answer an old question, but I don't think anybody has mentioned how K&R explain it in section A4.1 of "The C Programming Language".

In short, the word static is used with two meanings:

  1. Static is one of the two storage classes (the other being automatic). A static object keeps its value between invocations. The objects declared outside all blocks are always static and cannot be made automatic.
  2. But, when the static keyword (big emphasis on it being used in code as a keyword) is used with a declaration, it gives that object internal linkage so it can only be used within that translation unit. But if the keyword is used in a function, it changes the storage class of the object (the object would only be visible within that function anyway). The opposite of static is the extern keyword, which gives an object external linkage.

Peter Van Der Linden gives these two meanings in "Expert C Programming":

  • Inside a function, retains its value between calls.
  • At the function level, visible only in this file.

How do I find Waldo with Mathematica?

I've found Waldo!

waldo had been found

How I've done it

First, I'm filtering out all colours that aren't red

waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];

Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.

corr = ImageCorrelate[red, 
   Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]], 
   NormalizedSquaredEuclideanDistance];

I use Binarize to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation

pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];

I had to play around a little with the level. If the level is too high, too many false positives are picked out.

Finally I'm combining this result with the original image to get the result above

found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]

How to add certificate chain to keystore?

I solved the problem by cat'ing all the pems together:

cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD

(keytool didn't know what to do with a PKCS7 formatted key)

I got all the pems from letsencrypt

JavaScript - Get Browser Height

I prefer the way I just figured out... No JS... 100% HTML & CSS:

(Will center it perfectly in the middle, regardless of the content size.

HTML FILE

<html><head>
<link href="jane.css" rel="stylesheet" />
</head>
<body>
<table id="container">
<tr>
<td id="centerpiece">
123
</td></tr></table>
</body></html>

CSS FILE

#container{
    border:0;
    width:100%;
    height:100%;
}
#centerpiece{
    vertical-align:middle;
    text-align:center;
}

for centering images / div's held within the td, you may wish to try margin:auto; and specify a div dimension instead. -Though, saying that... the 'text-align' property will align much more than just a simple text element.

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

I have occurred the same error look following example-

async.waterfall([function(waterCB) {
    waterCB(null);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.

Cheak your function parameters Below are a correct example.

async.waterfall([function(waterCB) {
    waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

Thanks

Check if current directory is a Git repository

Another solution is to check for the command's exit code.

git rev-parse 2> /dev/null; [ $? == 0 ] && echo 1

This will print 1 if you're in a git repository folder.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

Update:

According @noraj's answer and @Niels Kristian's comment, the following command should do the job.

gem update --system
bundle install

I wrote this in case someone gets into an issue like mine.

gem install bundler shows that everythings installs well.

Fetching: bundler-1.16.0.gem (100%)
Successfully installed bundler-1.16.0
Parsing documentation for bundler-1.16.0
Installing ri documentation for bundler-1.16.0
Done installing documentation for bundler after 7 seconds
1 gem installed

When I typed bundle there was an error:

/Users/nikkov/.rvm/gems/ruby-2.4.0/bin/bundle:23:in `load': cannot load such file -- /Users/nikkov/.rvm/rubies/ruby-2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/exe/bundle (LoadError)
    from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/bundle:23:in `<main>'
    from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:in `eval'
    from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:in `<main>'

And in the folder /Users/nikkov/.rvm/rubies/ruby-2.4.0/lib/ruby/gems/2.4.0/gems/ there wasn't a bundler-1.16.0 folder.

I fixed this with sudo gem install bundler

Is there a way to specify a default property value in Spring XML?

Are you looking for the PropertyOverrideConfigurer documented here

http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-overrideconfigurer

The PropertyOverrideConfigurer, another bean factory post-processor, is similar to the PropertyPlaceholderConfigurer, but in contrast to the latter, the original definitions can have default values or no values at all for bean properties. If an overriding Properties file does not have an entry for a certain bean property, the default context definition is used.

Remote Procedure call failed with sql server 2008 R2

start SQL Server Agent from the command prompt using:

SQLAGENT90 -C -V>C:\SQLAGENT.OUT

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

You must use OpenSSL and keytool.

OpenSSL for CER & PVK file > P12

openssl pkcs12 -export -name servercert -in selfsignedcert.crt -inkey serverprivatekey.key -out myp12keystore.p12

Keytool for p12 > JKS

keytool -importkeystore -destkeystore mykeystore.jks -srckeystore myp12keystore.p12 -srcstoretype pkcs12 -alias servercert

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

converting a javascript string to a html object

You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..

string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call

but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.

You would need to use append or appendTo or after etc.. to put it in the dom first..

Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..

How can I get the index from a JSON object with value?

Traverse through the array and find the index of the element which contains a key name and has the value as the passed param.

_x000D_
_x000D_
var data = [{_x000D_
  "name": "placeHolder",_x000D_
  "section": "right"_x000D_
}, {_x000D_
  "name": "Overview",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "ByFunction",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "Time",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allFit",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allbMatches",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allOffers",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allInterests",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allResponses",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "divChanged",_x000D_
  "section": "right"_x000D_
}];_x000D_
_x000D_
Array.prototype.getIndexOf = function(el) {_x000D_
_x000D_
  var arr = this;_x000D_
_x000D_
  for (var i=0; i<arr.length; i++){_x000D_
     console.log(arr[i].name);_x000D_
     if(arr[i].name==el){_x000D_
       return i;_x000D_
     }_x000D_
     _x000D_
  }_x000D_
  _x000D_
  return -1;_x000D_
_x000D_
}_x000D_
_x000D_
alert(data.getIndexOf("allResponses"));
_x000D_
_x000D_
_x000D_

Capitalize the first letter of both words in a two word string

The base R function to perform capitalization is toupper(x). From the help file for ?toupper there is this function that does what you need:

simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
      sep="", collapse=" ")
}

name <- c("zip code", "state", "final count")

sapply(name, simpleCap)

     zip code         state   final count 
   "Zip Code"       "State" "Final Count" 

Edit This works for any string, regardless of word count:

simpleCap("I like pizza a lot")
[1] "I Like Pizza A Lot"

Get paragraph text inside an element

Try this:

<li onclick="myfunction(this)">

function myfunction(li) {
    var TextInsideLi = li.getElementsByTagName('p')[0].innerHTML;
}

Live demo

Adding asterisk to required fields in Bootstrap 3

This works for me:

CSS

.form-group.required.control-label:before{
   content: "*";
   color: red;
}

OR

.form-group.required.control-label:after{
   content: "*";
   color: red;
}

Basic HTML

<div class="form-group required control-label">
  <input class="form-control" />
</div>

Convert String to double in Java

You only need to parse String values using Double

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);

List directory in Go

ioutil.ReadDir is a good find, but if you click and look at the source you see that it calls the method Readdir of os.File. If you are okay with the directory order and don't need the list sorted, then this Readdir method is all you need.

How to create a library project in Android Studio and an application project that uses the library project

In my case, using MAC OS X 10.11 and Android 2.0, and by doing exactly what Aqib Mumtaz has explained.

But, each time, I had this message : "A problem occurred configuring project ':app'. > Cannot evaluate module xxx : Configuration with name 'default' not found."

I found that the reason of this message is that Android 2.0 doesn't allow to create a library directly. So, I have decided first to create an app projet and then to modify the build.gradle in order to transform it as a library.

This solution doesn't work, because a Library project is very different than an app project.

So, I have resolved my problem like this :

  • First create an standard app (if needed) ;
  • Then choose 'File/Create Module'
  • Go to the finder and move the folder of the module freshly created in your framework directory

Then continue with the solution proposed by Aqib Mumtaz.

As a result, your library source will be shared without needing to duplicate source files each time (it was an heresy for me!)

Hoping that this help you.

How to hide collapsible Bootstrap 4 navbar on click

The easiest way to do it using only Angular 2/4 template with no coding:

<nav class="navbar navbar-default" aria-expanded="false">
  <div class="container-wrapper">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div class="navbar-collapse collapse no-transition" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
      <ul class="nav navbar-nav" (click)="isCollapsed = !isCollapsed">
        <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}"><a routerLink="/">Home</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/about">About</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/portfolio">Portfolio</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/contacts">Contacts</a></li>
      </ul>
    </div>

  </div>
</nav>

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Select N random elements from a List<T> in C#

I just ran into this problem, and some more google searching brought me to the problem of randomly shuffling a list: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle

To completely randomly shuffle your list (in place) you do this:

To shuffle an array a of n elements (indices 0..n-1):

  for i from n - 1 downto 1 do
       j ? random integer with 0 = j = i
       exchange a[j] and a[i]

If you only need the first 5 elements, then instead of running i all the way from n-1 to 1, you only need to run it to n-5 (ie: n-5)

Lets say you need k items,

This becomes:

  for (i = n - 1; i >= n-k; i--)
  {
       j = random integer with 0 = j = i
       exchange a[j] and a[i]
  }

Each item that is selected is swapped toward the end of the array, so the k elements selected are the last k elements of the array.

This takes time O(k), where k is the number of randomly selected elements you need.

Further, if you don't want to modify your initial list, you can write down all your swaps in a temporary list, reverse that list, and apply them again, thus performing the inverse set of swaps and returning you your initial list without changing the O(k) running time.

Finally, for the real stickler, if (n == k), you should stop at 1, not n-k, as the randomly chosen integer will always be 0.

Convert Json String to C# Object List

Try to change type of ScoreIfNoMatch, like this:

   public class MatrixModel
        {
            public string S1 { get; set; }
            public string S2 { get; set; }
            public string S3 { get; set; }
            public string S4 { get; set; }
            public string S5 { get; set; }
            public string S6 { get; set; }
            public string S7 { get; set; }
            public string S8 { get; set; }
            public string S9 { get; set; }
            public string S10 { get; set; }
            // the type should be string
            public string ScoreIfNoMatch { get; set; }
        }

What does InitializeComponent() do, and how does it work in WPF?

Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.

Qt: How do I handle the event of the user pressing the 'X' (close) button?

Well, I got it. One way is to override the QWidget::closeEvent(QCloseEvent *event) method in your class definition and add your code into that function. Example:

class foo : public QMainWindow
{
    Q_OBJECT
private:
    void closeEvent(QCloseEvent *bar);
    // ...
};


void foo::closeEvent(QCloseEvent *bar)
{
    // Do something
    bar->accept();
}

Objective-C Static Class Level variables

u can rename the class as classA.mm and add C++ features in it.

How can I create a Java method that accepts a variable number of arguments?

The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.

void print(final String format, final String... arguments) {
    System.out.format( format, arguments );
}

Node Express sending image files as API response

There is an api in Express.

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

Android Viewpager as Image Slide Gallery

Just use this https://gist.github.com/8cbe094bb7a783e37ad1 for make surrounding pages visible and http://viewpagerindicator.com/ this, for indicator. That's pretty cool, i'm using it for a gallery.

A field initializer cannot reference the nonstatic field, method, or property

private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; is a field initializer and executes first (before any field without an initializer is set to its default value and before the invoked instance constructor is executed). Instance fields that have no initializer will only have a legal (default) value after all instance field initializers are completed. Due to the initialization order, instance constructors are executed last, which is why the instance is not created yet the moment the initializers are executed. Therefore the compiler cannot allow any instance property (or field) to be referenced before the class instance is fully constructed. This is because any access to an instance variable like reminder implicitly references the instance (this) to tell the compiler the concrete memory location of the instance to use.

This is also the reason why this is not allowed in an instance field initializer.

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple_name.

The only type members that are guaranteed to be initialized before instance field initializers are executed are class (static) field initializers and class (static) constructors and class methods. Since static members are instance independent, they can be referenced at any time:

class SomeOtherClass
{
  private static Reminders reminder = new Reminders();

  // This operation is allowed,
  // since the compiler can guarantee that the referenced class member is already initialized
  // when this instance field initializer executes
  private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

That's why instance field initializers are only allowed to reference a class member (static member). This compiler initialization rules will ensure a deterministic type instantiation.

For more details I recommend this document: Microsoft Docs: Class declarations.

This means that an instance field that references another instance member to initialize its value, must be initialized from the instance constructor or the referenced member must be declared static.

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

Can you check if this code works for you? Maybe something overwrites them later?

RelativeLayout center vertical

        <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginHorizontal="5dp"
        android:layout_marginBottom="5dp"
        android:background="@drawable/default_button">

        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:layout_marginStart="15dp"
            android:src="@drawable/google" />

        <Button
            android:id="@+id/btnGmailLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:paddingHorizontal="15dp"
            android:text="@string/gmail_login_button_text"
            android:textAllCaps="false"
            android:textColor="@color/black" />
    </RelativeLayout>

Scripting Language vs Programming Language

Scripted languages

Scripting languages are interpreted within another program. JavaScript is embedded within a browser and interpreted by that browser.

Examples of scripting languages

  1. JavaScript
  2. Perl
  3. Python

Advantages of Scripting languages:

  1. Simple – Scripting languages are easier to write than programming language.

  2. Fewer Lines of Code (LOC)

Programmed languages

Programming languages like Java are compiled and not interpreted by another application in the same way.

Examples programming languages

  1. C
  2. C++ and
  3. Java

More Details

How do I reload a page without a POSTDATA warning in Javascript?

You can't refresh without the warning; refresh instructs the browser to repeat the last action. It is up to the browser to choose whether to warn the user if repeating the last action involves resubmitting data.

You could re-navigate to the same page with a fresh session by doing:

window.location = window.location.href;

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

AWS4-HMAC-SHA256, also known as Signature Version 4, ("V4") is one of two authentication schemes supported by S3.

All regions support V4, but US-Standard¹, and many -- but not all -- other regions, also support the other, older scheme, Signature Version 2 ("V2").

According to http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html ... new S3 regions deployed after January, 2014 will only support V4.

Since Frankfurt was introduced late in 2014, it does not support V2, which is what this error suggests you are using.

http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html explains how to enable V4 in the various SDKs, assuming you are using an SDK that has that capability.

I would speculate that some older versions of the SDKs might not support this option, so if the above doesn't help, you may need a newer release of the SDK you are using.


¹US Standard is the former name for the S3 regional deployment that is based in the us-east-1 region. Since the time this answer was originally written, "Amazon S3 renamed the US Standard Region to the US East (N. Virginia) Region to be consistent with AWS regional naming conventions." For all practical purposes, it's only a change in naming.

How to loop and render elements in React.js without an array of objects to map?

Updated: As of React > 0.16

Render method does not necessarily have to return a single element. An array can also be returned.

var indents = [];
for (var i = 0; i < this.props.level; i++) {
  indents.push(<span className='indent' key={i}></span>);
}
return indents;

OR

return this.props.level.map((item, index) => (
    <span className="indent" key={index}>
        {index}
    </span>
));

Docs here explaining about JSX children


OLD:

You can use one loop instead

var indents = [];
for (var i = 0; i < this.props.level; i++) {
  indents.push(<span className='indent' key={i}></span>);
}
return (
   <div>
    {indents}
    "Some text value"
   </div>
);

You can also use .map and fancy es6

return (
   <div>
    {this.props.level.map((item, index) => (
       <span className='indent' key={index} />
    ))}
    "Some text value"
   </div>
);

Also, you have to wrap the return value in a container. I used div in the above example

As the docs say here

Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.

How do I find a stored procedure containing <text>?

select * from sys.system_objects
where name like '%cdc%'

How to use RANK() in SQL Server

You have to use DENSE_RANK rather than RANK. The only difference is that it doesn't leave gaps. You also shouldn't partition by contender_num, otherwise you're ranking each contender in a separate group, so each is 1st-ranked in their segregated groups!

SELECT contendernum,totals, DENSE_RANK() OVER (ORDER BY totals desc) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a
order by contendernum

A hint for using StackOverflow, please post DDL and sample data so people can help you using less of their own time!

create table Cat1GroupImpersonation (
contendernum int,
criteria1 int,
criteria2 int,
criteria3 int,
criteria4 int);

insert Cat1GroupImpersonation select
1,196,0,0,0 union all select
2,181,0,0,0 union all select
3,192,0,0,0 union all select
4,181,0,0,0 union all select
5,179,0,0,0;

How to fix a collation conflict in a SQL Server query?

I had problems with collations as I had most of the tables with Modern_Spanish_CI_AS, but a few, which I had inherited or copied from another Database, had SQL_Latin1_General_CP1_CI_AS collation.

In my case, the easiest way to solve the problem has been as follows:

  1. I've created a copy of the tables which were 'Latin American, using script table as...
  2. The new tables have obviously acquired the 'Modern Spanish' collation of my database
  3. I've copied the data of my 'Latin American' table into the new one, deleted the old one and renamed the new one.

I hope this helps other users.