Programs & Examples On #Data warehouse

A data warehouse (DW) is a database specifically structured/designed to aid in querying, analyzing and reporting (generating reports out of) of current and historical data. DWs are central repositories of integrated data from one or more disparate sources. Basic difference between a data warehouse and a set of DB tables is how the data is organized/structured.

What is the difference between a database and a data warehouse?

Example: A house is worth $100,000, and it is appreciating at $1000 per year.

To keep track of the current house value, you would use a database as the value would change every year.

Three years later, you would be able to see the value of the house which is $103,000.

To keep track of the historical house value, you would use a data warehouse as the value of the house should be

$100,000 on year 0, 
$101,000 on year 1, 
$102,000 on year 2, 
$103,000 on year 3. 

Difference between Fact table and Dimension table?

In the simplest form, I think a dimension table is something like a 'Master' table - that keeps a list of all 'items', so to say.

A fact table is a transaction table which describes all the transactions. In addition, aggregated (grouped) data like total sales by sales person, total sales by branch - such kinds of tables also might exist as independent fact tables.

How do I prompt a user for confirmation in bash script?

Try the read shell builtin:

read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
  echo "yaaa";
else
  echo "booo";
fi

How can I find the number of years between two dates?

import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;

public static int getDiffYears(Date first, Date last) {
    Calendar a = getCalendar(first);
    Calendar b = getCalendar(last);
    int diff = b.get(YEAR) - a.get(YEAR);
    if (a.get(MONTH) > b.get(MONTH) || 
        (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
        diff--;
    }
    return diff;
}

public static Calendar getCalendar(Date date) {
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.setTime(date);
    return cal;
}

How to find pg_config path

I used :

export PATH=$PATH:/Library/PostgreSQL/9.6/bin

pip install psycopg2

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

If your project is Dll, then the case might be that linker wants to build a console program. Open the project properties. Select the General settings. Select configuration type Dynamic Library there(.dll).

Download a file with Android, and showing the progress in a ProgressDialog

Use Android Query library, very cool indeed.You can change it to use ProgressDialog as you see in other examples, this one will show progress view from your layout and hide it after completion.

File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
    public void callback(String url, File file, AjaxStatus status) {
        if (file != null) {
            // do something with file  
        } 
    }
});

How to display HTML in TextView?

Use below code to get the solution:

textView.setText(fromHtml("<Your Html Text>"))

Utitilty Method

public static Spanned fromHtml(String text)
{
    Spanned result;
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(text);
    }
    return result;
}

How to export a MySQL database to JSON?

This might be a more niche answer but if you are on windows and MYSQL Workbench you can just select the table you want and click Export/Import in the Result grid. This will give you multiple format options including .json

PostgreSQL delete with inner join

This worked for me:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Try this. For python 2.7.12 we need to define constructor or need to add self to each methods followed by defining an instance of an class called object.

import cv2

class calculator:

#   def __init__(self):

def multiply(self, a, b):
    x= a*b
    print(x)

def subtract(self, a,b):
    x = a-b
    print(x)

def add(self, a,b):
    x = a+b
    print(x)

def div(self, a,b):
    x = a/b
    print(x)

 calc = calculator()
 calc.multiply(2,3)
 calc.add(2,3)
 calc.div(10,5)
 calc.subtract(2,3)

How to specify more spaces for the delimiter using cut?

Another way if you must use cut command

ps axu | grep [j]boss |awk '$1=$1'|cut -d' ' -f5

In Solaris, replace awk with nawk or /usr/xpg4/bin/awk

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

This is the best way to enable/ disable swipe to pop view controller in iOS 10, Swift 3 :

For First Screen [ Where you want to Disable Swipe gesture ] :

class SignUpViewController : UIViewController,UIGestureRecognizerDelegate {

//MARK: - View initializers
override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    swipeToPop()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func swipeToPop() {

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
    self.navigationController?.interactivePopGestureRecognizer?.delegate = self;
}

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {

    if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
        return false
    }
    return true
} }

For middle screen [ Where you want to Enable Swipe gesture ] :

class FriendListViewController : UIViewController {

//MARK: - View initializers
override func viewDidLoad() {

    super.viewDidLoad()
    swipeToPop()
}

func swipeToPop() {

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
    self.navigationController?.interactivePopGestureRecognizer?.delegate = nil;
} }

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

How to handle calendar TimeZones using Java?

It looks like your TimeStamp is being set to the timezone of the originating system.

This is deprecated, but it should work:

cal.setTimeInMillis(ts_.getTime() - ts_.getTimezoneOffset());

The non-deprecated way is to use

Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)

but that would need to be done on the client side, since that system knows what timezone it is in.

How to find the minimum value in an ArrayList, along with the index number? (Java)

try this:

public int getIndexOfMin(List<Float> data) {
    float min = Float.MAX_VALUE;
    int index = -1;
    for (int i = 0; i < data.size(); i++) {
        Float f = data.get(i);
        if (Float.compare(f.floatValue(), min) < 0) {
            min = f.floatValue();
            index = i;
        }
    }
    return index;
}

A CSS selector to get last visible div

You could select and style this with JavaScript or jQuery, but CSS alone can't do this.

For example, if you have jQuery implemented on the site, you could just do:

var last_visible_element = $('div:visible:last');

Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like:

var last_visible_element = $('#some-wrapper div:visible:last');

Convert Pixels to Points

This works:

int pixels = (int)((dp) * Resources.System.DisplayMetrics.Density + 0.5f);

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

Difference between two dates in years, months, days in JavaScript

For quick and easy use I wrote this function some time ago. It returns the diff between two dates in a nice format. Feel free to use it (tested on webkit).

/**
 * Function to print date diffs.
 * 
 * @param {Date} fromDate: The valid start date
 * @param {Date} toDate: The end date. Can be null (if so the function uses "now").
 * @param {Number} levels: The number of details you want to get out (1="in 2 Months",2="in 2 Months, 20 Days",...)
 * @param {Boolean} prefix: adds "in" or "ago" to the return string
 * @return {String} Diffrence between the two dates.
 */
function getNiceTime(fromDate, toDate, levels, prefix){
    var lang = {
            "date.past": "{0} ago",
            "date.future": "in {0}",
            "date.now": "now",
            "date.year": "{0} year",
            "date.years": "{0} years",
            "date.years.prefixed": "{0} years",
            "date.month": "{0} month",
            "date.months": "{0} months",
            "date.months.prefixed": "{0} months",
            "date.day": "{0} day",
            "date.days": "{0} days",
            "date.days.prefixed": "{0} days",
            "date.hour": "{0} hour",
            "date.hours": "{0} hours",
            "date.hours.prefixed": "{0} hours",
            "date.minute": "{0} minute",
            "date.minutes": "{0} minutes",
            "date.minutes.prefixed": "{0} minutes",
            "date.second": "{0} second",
            "date.seconds": "{0} seconds",
            "date.seconds.prefixed": "{0} seconds",
        },
        langFn = function(id,params){
            var returnValue = lang[id] || "";
            if(params){
                for(var i=0;i<params.length;i++){
                    returnValue = returnValue.replace("{"+i+"}",params[i]);
                }
            }
            return returnValue;
        },
        toDate = toDate ? toDate : new Date(),
        diff = fromDate - toDate,
        past = diff < 0 ? true : false,
        diff = diff < 0 ? diff * -1 : diff,
        date = new Date(new Date(1970,0,1,0).getTime()+diff),
        returnString = '',
        count = 0,
        years = (date.getFullYear() - 1970);
    if(years > 0){
        var langSingle = "date.year" + (prefix ? "" : ""),
            langMultiple = "date.years" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (years > 1 ? langFn(langMultiple,[years]) : langFn(langSingle,[years]));
        count ++;
    }
    var months = date.getMonth();
    if(count < levels && months > 0){
        var langSingle = "date.month" + (prefix ? "" : ""),
            langMultiple = "date.months" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (months > 1 ? langFn(langMultiple,[months]) : langFn(langSingle,[months]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var days = date.getDate() - 1;
    if(count < levels && days > 0){
        var langSingle = "date.day" + (prefix ? "" : ""),
            langMultiple = "date.days" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (days > 1 ? langFn(langMultiple,[days]) : langFn(langSingle,[days]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var hours = date.getHours();
    if(count < levels && hours > 0){
        var langSingle = "date.hour" + (prefix ? "" : ""),
            langMultiple = "date.hours" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (hours > 1 ? langFn(langMultiple,[hours]) : langFn(langSingle,[hours]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var minutes = date.getMinutes();
    if(count < levels && minutes > 0){
        var langSingle = "date.minute" + (prefix ? "" : ""),
            langMultiple = "date.minutes" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (minutes > 1 ? langFn(langMultiple,[minutes]) : langFn(langSingle,[minutes]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    var seconds = date.getSeconds();
    if(count < levels && seconds > 0){
        var langSingle = "date.second" + (prefix ? "" : ""),
            langMultiple = "date.seconds" + (prefix ? ".prefixed" : "");
        returnString += (count > 0 ?  ', ' : '') + (seconds > 1 ? langFn(langMultiple,[seconds]) : langFn(langSingle,[seconds]));
        count ++;
    } else {
        if(count > 0)
            count = 99;
    }
    if(prefix){
        if(returnString == ""){
            returnString = langFn("date.now");
        } else if(past)
            returnString = langFn("date.past",[returnString]);
        else
            returnString = langFn("date.future",[returnString]);
    }
    return returnString;
}

How does one convert a HashMap to a List in Java?

Solution using Java 8 and Stream Api:

private static <K, V>  List<V> createListFromMapEntries (Map<K, V> map){
        return map.values().stream().collect(Collectors.toList());
    }

Usage:

  public static void main (String[] args)
    {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "one");
        map.put(2, "two");
        map.put(3, "three");

        List<String> result = createListFromMapEntries(map);
        result.forEach(System.out :: println);
    }

Definition of "downstream" and "upstream"

That's a bit of informal terminology.

As far as Git is concerned, every other repository is just a remote.

Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.

The terms are not restricted to Git repositories.

For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

Remove All Event Listeners of Specific Type

So this function gets rid of most of a specified listener type on an element:

function removeListenersFromElement(element, listenerType){
  const listeners = getEventListeners(element)[listenerType];
  let l = listeners.length;
  for(let i = l-1; i >=0; i--){
    removeEventListener(listenerType, listeners[i].listener);
  }
 }

There have been a few rare exceptions where one can't be removed for some reason.

How do I check what version of Python is running my script?

from sys import version_info, api_version, version, hexversion

print(f"sys.version: {version}")
print(f"sys.api_version: {api_version}")
print(f"sys.version_info: {version_info}")
print(f"sys.hexversion: {hexversion}")

output

sys.version: 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]
sys.api_version: 1013
sys.version_info: sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)
sys.hexversion: 50726384

Python socket receive - incoming packets always have a different size

Note that exact reason why your code is frozen is not because you set too high request.recv() buffer size. Here is explained What means buffer size in socket.recv(buffer_size)

This code will work until it'll receive an empty TCP message (if you'd print this empty message, it'd show b''):

while True:    
  data = self.request.recv(1024)
  if not data: break

And note, that there is no way to send empty TCP message. socket.send(b'') simply won't work.

Why? Because empty message is sent only when you type socket.close(), so your script will loop as long as you won't close your connection. As Hans L pointed out here are some good methods to end message.

Eclipse reported "Failed to load JNI shared library"

Yep, in Windows 7 64 bit you have C:\Program Files and C:\Program Files (x86). You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin to environment variable PATH.

How to upgrade Angular CLI project?

Remove :

npm uninstall -g angular-cli

Reinstall (with yarn)

# npm install --global yarn
yarn global add @angular/cli@latest
ng set --global packageManager=yarn  # This will help ng-cli to use yarn

Reinstall (with npm)

npm install --global @angular/cli@latest

Another way is to not use global install, and add /node_modules/.bin folder in the PATH, or use npm scripts. It will be softer to upgrade.

Java generating non-repeating random numbers

In Java 8, if you want to have a list of non-repeating N random integers in range (a, b), where b is exclusive, you can use something like this:

Random random = new Random();
List<Integer> randomNumbers = random.ints(a, b).distinct().limit(N).boxed().collect(Collectors.toList());

python: order a list of numbers without built-in sort, min, max function

l = [64, 25, 12, 22, 11, 1,2,44,3,122, 23, 34]

for i in range(len(l)):
    for j in range(i + 1, len(l)):

        if l[i] > l[j]:
           l[i], l[j] = l[j], l[i]

print l

Output:

[1, 2, 3, 11, 12, 22, 23, 25, 34, 44, 64, 122]

Selecting pandas column by location

You could use label based using .loc or index based using .iloc method to do column-slicing including column ranges:

In [50]: import pandas as pd

In [51]: import numpy as np

In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))

In [53]: df
Out[53]: 
          a         b         c         d
0  0.806811  0.187630  0.978159  0.317261
1  0.738792  0.862661  0.580592  0.010177
2  0.224633  0.342579  0.214512  0.375147
3  0.875262  0.151867  0.071244  0.893735

In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]: 
          a         b         d
0  0.806811  0.187630  0.317261
1  0.738792  0.862661  0.010177
2  0.224633  0.342579  0.375147
3  0.875262  0.151867  0.893735

In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

ASP.NET: Session.SessionID changes between requests

In my case I figured out that the session cookie had a domain that included www. prefix, while I was requesting page with no www..
Adding www. to the URL immediately fixed the problem. Later I changed cookie's domain to be set to .mysite.com instead of www.mysite.com.

how to have two headings on the same line in html

Check my sample solution

<h5 style="float: left; width: 50%;">Employee: Employee Name</h5>
<h5 style="float: right; width: 50%; text-align: right;">Employee: Employee Name</h5>

This will divide your page into two and insert the two header elements to the right and left part equally.

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Root certificates issued by CAs are just self-signed certificates (which may in turn be used to issue intermediate CA certificates). They have not much special about them, except that they've managed to be imported by default in many browsers or OS trust anchors.

While browsers and some tools are configured to look for the trusted CA certificates (some of which may be self-signed) in location by default, as far as I'm aware the openssl command isn't.

As such, any server that presents the full chain of certificate, from its end-entity certificate (the server's certificate) to the root CA certificate (possibly with intermediate CA certificates) will have a self-signed certificate in the chain: the root CA.

openssl s_client -connect myweb.com:443 -showcerts doesn't have any particular reason to trust Verisign's root CA certificate, and because it's self-signed you'll get "self signed certificate in certificate chain".

If your system has a location with a bundle of certificates trusted by default (I think /etc/pki/tls/certs on RedHat/Fedora and /etc/ssl/certs on Ubuntu/Debian), you can configure OpenSSL to use them as trust anchors, for example like this:

openssl s_client -connect myweb.com:443 -showcerts -CApath /etc/ssl/certs

How do you round a floating point number in Perl?

Following is a sample of five different ways to summate values. The first is a naive way to perform the summation (and fails). The second attempts to use sprintf(), but it too fails. The third uses sprintf() successfully while the final two (4th & 5th) use floor($value + 0.5).

 use strict;
 use warnings;
 use POSIX;

 my @values = (26.67,62.51,62.51,62.51,68.82,79.39,79.39);
 my $total1 = 0.00;
 my $total2 = 0;
 my $total3 = 0;
 my $total4 = 0.00;
 my $total5 = 0;
 my $value1;
 my $value2;
 my $value3;
 my $value4;
 my $value5;

 foreach $value1 (@values)
 {
      $value2 = $value1;
      $value3 = $value1;
      $value4 = $value1;
      $value5 = $value1;

      $total1 += $value1;

      $total2 += sprintf('%d', $value2 * 100);

      $value3 = sprintf('%1.2f', $value3);
      $value3 =~ s/\.//;
      $total3 += $value3;

      $total4 += $value4;

      $total5 += floor(($value5 * 100.0) + 0.5);
 }

 $total1 *= 100;
 $total4 = floor(($total4 * 100.0) + 0.5);

 print '$total1: '.sprintf('%011d', $total1)."\n";
 print '$total2: '.sprintf('%011d', $total2)."\n";
 print '$total3: '.sprintf('%011d', $total3)."\n";
 print '$total4: '.sprintf('%011d', $total4)."\n";
 print '$total5: '.sprintf('%011d', $total5)."\n";

 exit(0);

 #$total1: 00000044179
 #$total2: 00000044179
 #$total3: 00000044180
 #$total4: 00000044180
 #$total5: 00000044180

Note that floor($value + 0.5) can be replaced with int($value + 0.5) to remove the dependency on POSIX.

How to get current relative directory of your Makefile?

Solution found here : https://sourceforge.net/p/ipt-netflow/bugs-requests-patches/53/

The solution is : $(CURDIR)

You can use it like that :

CUR_DIR = $(CURDIR)

## Start :
start:
    cd $(CUR_DIR)/path_to_folder

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

Error importing Seaborn module in Python

I solved this problem by looking at sys.path (the path for finding modules) while in ipython and noticed that I was in a special environment (because I use conda).

so i went to my terminal and typed "source activate py27" is my python 2.7 environment. and then "conda update seaborn", restarted my jupyter kernel, and then all was good.

Render HTML in React Native

An iOS/Android pure javascript react-native component that renders your HTML into 100% native views. It's made to be extremely customizable and easy to use and aims at being able to render anything you throw at it.

react-native-render-html

use above library to improve your app performance level and easy to use.

Install

npm install react-native-render-html --save or yarn add react-native-render-html

Basic usage

import React, { Component } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import HTML from 'react-native-render-html';

const htmlContent = `
    <h1>This HTML snippet is now rendered with native components !</h1>
    <h2>Enjoy a webview-free and blazing fast application</h2>
    <img src="https://i.imgur.com/dHLmxfO.jpg?2" />
    <em style="textAlign: center;">Look at how happy this native cat is</em>
`;

export default class Demo extends Component {
    render () {
        return (
            <ScrollView style={{ flex: 1 }}>
                <HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />
            </ScrollView>
        );
    }
}

PROPS

you may user it's different different types of props (see above link) for the designing and customizable also using below link refer.

Customizable render html

How to check if a double is null?

Firstly, a Java double cannot be null, and cannot be compared with a Java null. (The double type is a primitive (non-reference) type and primitive types cannot be null.)

Next, if you call ResultSet.getDouble(...), that returns a double not a Double, the documented behaviour is that a NULL (from the database) will be returned as zero. (See javadoc linked above.) That is no help if zero is a legitimate value for that column.

So your options are:

The getObject method will deliver the value as a Double (assuming that the column type is double), and is documented to return null for a NULL. (For more information, this page documents the default mappings of SQL types to Java types, and therefore what actual type you should expect getObject to deliver.)

Should you always favor xrange() over range()?

Go with range for these reasons:

1) xrange will be going away in newer Python versions. This gives you easy future compatibility.

2) range will take on the efficiencies associated with xrange.

How to get a Char from an ASCII Character Code in c#

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

How can I get device ID for Admob

  • Is your app published on Play store -- with live ads:

If your app is on Play store showing live ads -- you can't use live ads for testing -- add your device ID in code to get test ads from Admob on your real device. Never use live ads during development or testing.

To get real device ID in logcat,

  1. Connect your device in USB debug mode to Android Studio

USB debug mode(Developer option)

  1. Open any app on your device which shows live ads from Admob: On the connected device, if you have your app downloaded from play store(showing live ads) open that app or else open any other app that shows live Admob ads. Your device should have an internet connection.

  2. Filter the logcat with 'device' as shown below to get test device

Test Device ID in logcat

Read Admob ad testing on device - device IDs can change for more

How do I echo and send console output to a file in a bat script?

My option was this:

Create a subroutine that takes in the message and automates the process of sending it to both console and log file.

setlocal
set logfile=logfile.log

call :screenandlog "%DATE% %TIME% This message goes to the screen and to the log"    

goto :eof

:screenandlog
set message=%~1
echo %message% & echo %message% >> %logfile%
exit /b

If you add a variable to the message, be sure to remove the quotes in it before sending it to the subroutine or it can screw your batch. Of course this only works for echoing.

Get protocol + host name from URL

You can simply use urljoin with relative root '/' as second argument:

import urllib.parse


url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
root_url = urllib.parse.urljoin(url, '/')
print(root_url)

Difference between frontend, backend, and middleware in web development

Here is one breakdown:

Front-end tier -> User Interface layer usually consisting of a mix of HTML, Javascript, CSS, Flash, and various server-side code like ASP.Net, classic ASP, PHP, etc. Think of this as being closest to the user in terms of code.

Middleware, middle-tier -> One tier back, generally referred to as the "plumbing" part of a system. Java and C# are common languages for writing this part that could be viewed as the glue between the UI and the data and can be webservices or WCF components or other SOA components possibly.

Back-end tier -> Databases and other data stores are generally at this level. Oracle, MS-SQL, MySQL, SAP, and various off-the-shelf pieces of software come to mind for this piece of software that is the final processing of the data.

Overlap can exist between any of these as you could have everything poured into one layer like an ASP.Net website that uses the built-in AJAX functionality that generates Javascript while the code behind may contain database commands making the code behind contain both middle and back-end tiers. Alternatively, one could use VBScript to act as all the layers using ADO objects and merging all three tiers into one.

Similarly, taking middleware and either front or back-end can be combined in some cases.

Bottlenecks generally have a few different levels to them:

1) Database or back-end processing -> This can vary from payroll or sales or other tasks where the throughput to the database is bogging things down.

2) Middleware bottlenecks -> This would be where some web service may be hitting capacity but the front and back ends have bandwidth to handle more traffic. Alternatively, there may be some server that is part of a system that isn't quite the UI part or the raw data that can be a bottleneck using something like Biztalk or MSMQ.

3) Front-end bottlenecks -> This could client or server-side issues. For example, if you took a low-end PC and had it load a web page that consisted of a lot of data being downloaded, the client could be where the bottleneck is. Similarly, the server could be queuing up requests if it is getting hammered with requests like what Amazon.com or other high-traffic websites may get at times.

Some of this is subject to interpretation, so it isn't perfect by any means and YMMV.


EDIT: Something to consider is that some systems can have multiple front-ends or back-ends. For example, a content management system will likely have a way for site visitors to view the content that is a front-end but what about how content editors are able to change the data on the site? The ability to pull up this data could be seen as front-end since it is a UI component or it could be seen as a back-end since it is used by internal users rather than the general public viewing the site. Thus, there is something to be said for context here.

Circular gradient in android

<!-- Drop Shadow Stack -->
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#00CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#10CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#20CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#30CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#50CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>

<!-- Background -->
<item>
    <shape android:shape="oval">
        <gradient
            android:startColor="@color/colorAccent_1"
            android:centerColor="@color/colorAccent_2"
            android:endColor="@color/colorAccent_3"
            android:angle="45"
            />
        <corners android:radius="3dp" />
    </shape>
</item>

<color name="colorAccent_1">#6f64d6</color>
<color name="colorAccent_2">#7668F8</color>
<color name="colorAccent_3">#6F63FF</color>

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How to modify WooCommerce cart, checkout pages (main theme portion)

    I've found this works well as a conditional within page.php that includes the WooCommerce cart and checkout screens.

    !is_page(array('cart', 'checkout'))
    

    How can I find out if an .EXE has Command-Line Options?

    This is what I get from console on Windows 10:

    C:\>find /?
    Searches for a text string in a file or files.
    
    FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]
    
      /V         Displays all lines NOT containing the specified string.
      /C         Displays only the count of lines containing the string.
      /N         Displays line numbers with the displayed lines.
      /I         Ignores the case of characters when searching for the string.
      /OFF[LINE] Do not skip files with offline attribute set.
      "string"   Specifies the text string to find.
      [drive:][path]filename
                 Specifies a file or files to search.
    
    If a path is not specified, FIND searches the text typed at the prompt
    or piped from another command.
    

    Python 2.7: %d, %s, and float()

    See String Formatting Operations:

    %d is the format code for an integer. %f is the format code for a float.

    %s prints the str() of an object (What you see when you print(object)).

    %r prints the repr() of an object (What you see when you print(repr(object)).

    For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

    >>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
            1.
    >>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
          1.12
    

    How to multiply a BigDecimal by an integer in Java

    You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

    public class Payment
    {
        BigDecimal itemCost  = BigDecimal.ZERO;
        BigDecimal totalCost = BigDecimal.ZERO;
    
        public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
        {
            itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
            totalCost = totalCost.add(itemCost);
            return totalCost;
        }
    }
    

    Determine Pixel Length of String in Javascript/jQuery?

    Based on vSync's answer, the pure javascript method is lightning fast for large amount of objects. Here is the Fiddle: https://jsfiddle.net/xeyq2d5r/8/

    [1]: https://jsfiddle.net/xeyq2d5r/8/ "JSFiddle"
    

    I received favorable tests for the 3rd method proposed, that uses the native javascript vs HTML Canvas

    Google was pretty competive for option 1 and 3, 2 bombed.

    FireFox 48:
    Method 1 took 938.895 milliseconds.
    Method 2 took 1536.355 milliseconds.
    Method 3 took 135.91499999999996 milliseconds.

    Edge 11 Method 1 took 4895.262839793865 milliseconds.
    Method 2 took 6746.622271896686 milliseconds.
    Method 3 took 1020.0315412885484 milliseconds.

    Google Chrome: 52
    Method 1 took 336.4399999999998 milliseconds.
    Method 2 took 2271.71 milliseconds.
    Method 3 took 333.30499999999984 milliseconds.

    How to check if any value is NaN in a Pandas DataFrame

    let df be the name of the Pandas DataFrame and any value that is numpy.nan is a null value.

    1. If you want to see which columns has nulls and which do not(just True and False)

      df.isnull().any()
      
    2. If you want to see only the columns that has nulls

      df.loc[:, df.isnull().any()].columns
      
    3. If you want to see the count of nulls in every column

      df.isna().sum()
      
    4. If you want to see the percentage of nulls in every column

      df.isna().sum()/(len(df))*100
      
    5. If you want to see the percentage of nulls in columns only with nulls:

    df.loc[:,list(df.loc[:,df.isnull().any()].columns)].isnull().sum()/(len(df))*100
    

    EDIT 1:

    If you want to see where your data is missing visually:

    import missingno
    missingdata_df = df.columns[df.isnull().any()].tolist()
    missingno.matrix(df[missingdata_df])
    

    Help with packages in java - import does not work

    Yes, this is a classpath issue. You need to tell the compiler and runtime that the directory where your .class files live is part of the CLASSPATH. The directory that you need to add is the parent of the "com" directory at the start of your package structure.

    You do this using the -classpath argument for both javac.exe and java.exe.

    Should also ask how the 3rd party classes you're using are packaged. If they're in a JAR, and I'd recommend that you have them in one, you add the .jar file to the classpath:

    java -classpath .;company.jar foo.bar.baz.YourClass
    

    Google for "Java classpath". It'll find links like this.

    One more thing: "import" isn't loading classes. All it does it save you typing. When you include an import statement, you don't have to use the fully-resolved class name in your code - you can type "Foo" instead of "com.company.thing.Foo". That's all it's doing.

    Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

    The solution is to add your variable to /etc/profile. Then everything works as expected! Of course you MUST do it as a root user with sudo nano /etc/profile. If you edit it with any other way the system will complain with a damaged /etc/profile, even if you change the permissions to root.

    Ruby function to remove all white spaces?

    I was trying to do this as I wanted to use a records "title" as an id in the view but the titles had spaces.

    a solution is:

    record.value.delete(' ') # Foo Bar -> FooBar
    

    How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

    Integer.parseInt(str) throws NumberFormatException if the string does not contain a parsable integer. You can hadle the same as below.

    int a;
    String str = "N/A";
    
    try {   
       a = Integer.parseInt(str);
    } catch (NumberFormatException nfe) {
      // Handle the condition when str is not a number.
    }
    

    How to count instances of character in SQL Column

    The second answer provided by nickf is very clever. However, it only works for a character length of the target sub-string of 1 and ignores spaces. Specifically, there were two leading spaces in my data, which SQL helpfully removes (I didn't know this) when all the characters on the right-hand-side are removed. Which meant that

    " John Smith"

    generated 12 using Nickf's method, whereas:

    " Joe Bloggs, John Smith"

    generated 10, and

    " Joe Bloggs, John Smith, John Smith"

    Generated 20.

    I've therefore modified the solution slightly to the following, which works for me:

    Select (len(replace(Sales_Reps,' ',''))- len(replace((replace(Sales_Reps, ' ','')),'JohnSmith','')))/9 as Count_JS
    

    I'm sure someone can think of a better way of doing it!

    How can I strip first X characters from string using sed?

    Another way, using cut instead of sed.

    result=`echo $pid | cut -c 5-`
    

    How to play video with AVPlayerViewController (AVKit) in Swift

    Swift 3:

    import UIKit
    import AVKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var viewPlay: UIView!
        var player : AVPlayer?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let url : URL = URL(string: "http://static.videokart.ir/clip/100/480.mp4")!
            player = AVPlayer(url: url)
            let playerLayer = AVPlayerLayer(player: player)
            playerLayer.frame = self.viewPlay.bounds
            self.viewPlay.layer.addSublayer(playerLayer)
    
        }
    
        @IBAction func play(_ sender: Any) {
            player?.play()
        }
    
        @IBAction func stop(_ sender: Any) {
            player?.pause()
        }
    
    }
    

    Bower: ENOGIT Git is not installed or not in the PATH

    Just use the Git Bash instead of node.js or command prompt

    As an Example for installing ReactJS, after opening Git Bash, execute the following command to install react:

    bower install --react
    

    PHP - Notice: Undefined index:

    You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

    if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

    Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

    Android java.lang.NoClassDefFoundError

    I fixed the issue by just adding private libraries of the main project to export here:

    Project Properties->Java Build Path->Order And Export
    

    And make sure Android Private Libraries are checked.

    Screenshot:

    enter image description here

    Make sure google-play-services_lib.jar and google-play-services.jar are checked. Clean the project and re-run and the classNotfound exception goes away.

    How to recursively list all the files in a directory in C#?

    I prefer to use DirectoryInfo because I can get FileInfo's, not just strings.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection<FileInfo> matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Select(x => x)
                .ToList();
    

    I do this in case in the future I need future filtering..based on the properties of FileInfo.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection<FileInfo> matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Where(x => x.LastWriteTimeUtc < DateTimeOffset.Now)
                .Select(x => x)
                .ToList();
    

    I can also resort back to strings if need be. (and still am future proofed for filters/where-clause stuff.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection<string> matchingFileNames = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Select(x => x.FullName)
                .ToList();
    

    Note that "." is a valid search pattern if you want to filer by extension.

    NuGet: 'X' already has a dependency defined for 'Y'

    1. Go to the link https://www.nuget.org/packages/ClosedXML/0.64.0
    2. Search your NuGet packages
    3. See the all version of related packages
    4. Install the lower version of packages

    implementing merge sort in C++

    Based on the code here: http://cplusplus.happycodings.com/algorithms/code17.html

    // Merge Sort
    
    #include <iostream>
    using namespace std;
    
    int a[50];
    void merge(int,int,int);
    void merge_sort(int low,int high)
    {
     int mid;
     if(low<high)
     {
      mid = low + (high-low)/2; //This avoids overflow when low, high are too large
      merge_sort(low,mid);
      merge_sort(mid+1,high);
      merge(low,mid,high);
     }
    }
    void merge(int low,int mid,int high)
    {
     int h,i,j,b[50],k;
     h=low;
     i=low;
     j=mid+1;
    
     while((h<=mid)&&(j<=high))
     {
      if(a[h]<=a[j])
      {
       b[i]=a[h];
       h++;
      }
      else
      {
       b[i]=a[j];
       j++;
      }
      i++;
     }
     if(h>mid)
     {
      for(k=j;k<=high;k++)
      {
       b[i]=a[k];
       i++;
      }
     }
     else
     {
      for(k=h;k<=mid;k++)
      {
       b[i]=a[k];
       i++;
      }
     }
     for(k=low;k<=high;k++) a[k]=b[k];
    }
    int main()
    {
     int num,i;
    
    cout<<"*******************************************************************
    *************"<<endl;
     cout<<"                             MERGE SORT PROGRAM
    "<<endl;
    
    cout<<"*******************************************************************
    *************"<<endl;
     cout<<endl<<endl;
     cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN 
    PRESS
    ENTER]:"<<endl;
     cin>>num;
     cout<<endl;
     cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN
    PRESS ENTER]:"<<endl;
     for(i=1;i<=num;i++)
     {
      cin>>a[i] ;
     }
     merge_sort(1,num);
     cout<<endl;
     cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
     cout<<endl<<endl;
    
     for(i=1;i<=num;i++)
     cout<<a[i]<<"  ";
    
     cout<<endl<<endl<<endl<<endl;
    return 1;
    
    }
    

    Where can I find the .apk file on my device, when I download any app and install?

    You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup

    How do I put my website's logo to be the icon image in browser tabs?

    It is called 'favicon' and you need to add below code to the header section of your website.

    Simply add this to the <head> section.

    <link rel="icon" href="/your_path_to_image/favicon.jpg">
    

    How to quit android application programmatically

    Is quitting an application frowned upon?. Go through this link. It answers your question. The system does the job of killing an application.

    Suppose you have two activities A an B. You navigate from A to B. When you click back button your activity B is popped form the backstack and destroyed. Previous activity in back stack activity A takes focus.

    You should leave it to the system to decide when to kill the application.

    public void finish()

    Call this when your activity is done and should be closed.

    Suppose you have many activities. you can use Action bar. On click of home icon naviagate to MainActivity of your application. In MainActivity click back button to quit from the application.

    Python conversion from binary string to hexadecimal

    bstr = '0000 0100 1000 1101'.replace(' ', '')
    hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))
    

    what is the difference between json and xml

    XML uses a tag structures for presenting items, like <tag>item</tag>, so an XML document is a set of tags nested into each other. And JSON syntax looks like a construction from Javascript language, with all stuff like lists and dictionaries:

    {
     'attrib' : 'value',
     'array' : [1, 2, 3]
    }
    

    So if you use JSON it's really simple to use a JSON strings in many script languages, especially Javascript and Python.

    super() in Java

    For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:

    public class DeveloperSteps extends ScenarioSteps {
    
    public DeveloperSteps(Pages pages) {
        super(pages);
    }........
    

    How to execute logic on Optional if not present?

    ifPresentOrElse can handle cases of nullpointers as well. Easy approach.

       Optional.ofNullable(null)
                .ifPresentOrElse(name -> System.out.println("my name is "+ name),
                        ()->System.out.println("no name or was a null pointer"));
    

    Date Comparison using Java

    Use java.util.Calendar if you have extensive date related processing.

    Date has before(), after() methods. you could use them as well.

    How can I turn a List of Lists into a List in Java 8?

    Method to convert a List<List> to List :

    listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());
    

    See this example:

    public class Example {
    
        public static void main(String[] args) {
            List<List<String>> listOfLists = Collections.singletonList(Arrays.asList("a", "b", "v"));
            List<String> list = listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());
    
            System.out.println("listOfLists => " + listOfLists);
            System.out.println("list => " + list);
        }
    
    }       
    

    It prints:

    listOfLists => [[a, b, c]]
    list => [a, b, c]
    

    In Python this can be done using List Comprehension.

    list_of_lists = [['Roopa','Roopi','Tabu', 'Soudipta'],[180.0, 1231, 2112, 3112], [130], [158.2], [220.2]]
    
    flatten = [val for sublist in list_of_lists for val in sublist]
    
    print(flatten)
    
    ['Roopa', 'Roopi', 'Tabu', 'Soudipta', 180.0, 1231, 2112, 3112, 130, 158.2, 220.2]
    

    How do I redirect to the previous action in ASP.NET MVC?

    For ASP.NET Core You can use asp-route-* attribute:

    <form asp-action="Login" asp-route-previous="@Model.ReturnUrl">
    

    Other in details example: Imagine that you have a Vehicle Controller with actions

    Index

    Details

    Edit

    and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

    //In your viewmodel add the ReturnUrl Property
    public class VehicleViewModel
    {
         ..............
         ..............
         public string ReturnUrl {get;set;}
    }
    
    
    
    Details.cshtml
    <a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>
    
    Index.cshtml
    <a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>
    
    Edit.cshtml
    <form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
            <div class="box-footer">
                <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
                <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
            </div>
        </form>
    

    In your controller:

    // GET: Vehicle/Edit/5
        public ActionResult Edit(int id,string previous)
        {
                var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
                var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
        //or by this code if you are not use automapper
        var viewModel = new VehicleViewModel();
    
        if (!string.IsNullOrWhiteSpace(previous)
                    viewModel.ReturnUrl = previous;
                else
                    viewModel.ReturnUrl = "Index";
                return View(viewModel);
            }
    
    
    
    [HttpPost]
        public IActionResult Edit(VehicleViewModel model, string previous)
        {
                if (!string.IsNullOrWhiteSpace(previous))
                    model.ReturnUrl = previous;
                else
                    model.ReturnUrl = "Index";
                ............. 
                .............
                return RedirectToAction(model.ReturnUrl);
        }
    

    Set background colour of cell to RGB value of data in cell

    Setting the Color property alone will guarantee an exact match. Excel 2003 can only handle 56 colors at once. The good news is that you can assign any rgb value at all to those 56 slots (which are called ColorIndexs). When you set a cell's color using the Color property this causes Excel to use the nearest "ColorIndex". Example: Setting a cell to RGB 10,20,50 (or 3281930) will actually cause it to be set to color index 56 which is 51,51,51 (or 3355443).

    If you want to be assured you got an exact match, you need to change a ColorIndex to the RGB value you want and then change the Cell's ColorIndex to said value. However you should be aware that by changing the value of a color index you change the color of all cells already using that color within the workbook. To give an example, Red is ColorIndex 3. So any cell you made Red you actually made ColorIndex 3. And if you redefine ColorIndex 3 to be say, purple, then your cell will indeed be made purple, but all other red cells in the workbook will also be changed to purple.

    There are several strategies to deal with this. One way is to choose an index not yet in use, or just one that you think will not be likely to be used. Another way is to change the RGB value of the nearest ColorIndex so your change will be subtle. The code I have posted below takes this approach. Taking advantage of the knowledge that the nearest ColorIndex is assigned, it assigns the RGB value directly to the cell (thereby yielding the nearest color) and then assigns the RGB value to that index.

    Sub Example()
        Dim lngColor As Long
        lngColor = RGB(10, 20, 50)
        With Range("A1").Interior
            .Color = lngColor
            ActiveWorkbook.Colors(.ColorIndex) = lngColor
        End With
    End Sub
    

    How to set the text color of TextView in code?

    Try this:

    textView.setTextColor(getResources().getColor(R.color.errorColor, null));
    

    Difference between JSON.stringify and JSON.parse

    They are opposing each other. JSON.Stringify() converts JSON to string and JSON.Parse() parses a string into JSON.

    DIV height set as percentage of screen?

    If you want it based on the screen height, and not the window height:

    const height = 0.7 * screen.height
    
    // jQuery
    $('.header').height(height)
    
    // Vanilla JS
    document.querySelector('.header').style.height = height + 'px'
    
    // If you have multiple <div class="header"> elements
    document.querySelectorAll('.header').forEach(function(node) {
      node.style.height = height + 'px'
    })
    

    Differentiate between function overloading and function overriding

    Function overloading is same name function but different arguments. Function over riding means same name function and same as arguments

    How do I use jQuery to redirect?

    Via Jquery:

    $(location).attr('href','http://example.com/Registration/Success/');
    

    Show space, tab, CRLF characters in editor of Visual Studio

    The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.

    Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.

    Web-scraping JavaScript page with Python

    Using PyQt5

    from PyQt5.QtWidgets import QApplication
    from PyQt5.QtCore import QUrl
    from PyQt5.QtWebEngineWidgets import QWebEnginePage
    import sys
    import bs4 as bs
    import urllib.request
    
    
    class Client(QWebEnginePage):
        def __init__(self,url):
            global app
            self.app = QApplication(sys.argv)
            QWebEnginePage.__init__(self)
            self.html = ""
            self.loadFinished.connect(self.on_load_finished)
            self.load(QUrl(url))
            self.app.exec_()
    
        def on_load_finished(self):
            self.html = self.toHtml(self.Callable)
            print("Load Finished")
    
        def Callable(self,data):
            self.html = data
            self.app.quit()
    
    # url = ""
    # client_response = Client(url)
    # print(client_response.html)
    

    checking if a number is divisible by 6 PHP

    Assuming $foo is an integer:

    $answer = (int) (floor(($foo + 5) / 6) * 6)
    

    How to add hours to current date in SQL Server?

    DATEADD (datepart , number , date )

    declare @num_hours int; 
        set @num_hours = 5; 
    
    select dateadd(HOUR, @num_hours, getdate()) as time_added, 
           getdate() as curr_date  
    

    Replace all spaces in a string with '+'

    You need to look for some replaceAll option

    str = str.replace(/ /g, "+");
    

    this is a regular expression way of doing a replaceAll.

    function ReplaceAll(Source, stringToFind, stringToReplace) {
        var temp = Source;
        var index = temp.indexOf(stringToFind);
    
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
    
        return temp;
    }
    
    String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
        var temp = this;
        var index = temp.indexOf(stringToFind);
    
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
    
        return temp;
    
    };
    

    HTTP Get with 204 No Content: Is that normal

    Http GET returning 204 is perfectly fine, and so is returning 404.

    The important thing is that you define the design standards/guidelines for your API, so that all your endpoints use status codes consistently.

    For example:

    • you may indicate that a GET endpoint that returns a collection of resources will return 204 if the collection is empty. In this case GET /complaints/year/2019/month/04 may return 204 if there are no complaints filed in April 2019. This is not an error on the client side, so we return a success status code (204). OTOH, GET /complaints/12345 may return 404 if complaint number 12345 doesn't exist.
    • if your API uses HATEOAS, 204 is probably a bad idea because the response should contain links to navigate to other states.

    SQL Stored Procedure: If variable is not null, update statement

    Use a T-SQL IF:

    IF @ABC IS NOT NULL AND @ABC != -1
        UPDATE [TABLE_NAME] SET XYZ=@ABC
    

    Take a look at the MSDN docs.

    How do I copy to the clipboard in JavaScript?

    This is the best. So much winning.

    var toClipboard = function(text) {
        var doc = document;
    
        // Create temporary element
        var textarea = doc.createElement('textarea');
        textarea.style.position = 'absolute';
        textarea.style.opacity  = '0';
        textarea.textContent    = text;
    
        doc.body.appendChild(textarea);
    
        textarea.focus();
        textarea.setSelectionRange(0, textarea.value.length);
    
        // Copy the selection
        var success;
        try {
            success = doc.execCommand("copy");
        }
        catch(e) {
            success = false;
        }
    
        textarea.remove();
    
        return success;
    }
    

    find files by extension, *.html under a folder in nodejs

    The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with .html

    var fs = require('fs');
    var path = require('path');
    
    var searchRecursive = function(dir, pattern) {
      // This is where we store pattern matches of all files inside the directory
      var results = [];
    
      // Read contents of directory
      fs.readdirSync(dir).forEach(function (dirInner) {
        // Obtain absolute path
        dirInner = path.resolve(dir, dirInner);
    
        // Get stats to determine if path is a directory or a file
        var stat = fs.statSync(dirInner);
    
        // If path is a directory, scan it and combine results
        if (stat.isDirectory()) {
          results = results.concat(searchRecursive(dirInner, pattern));
        }
    
        // If path is a file and ends with pattern then push it onto results
        if (stat.isFile() && dirInner.endsWith(pattern)) {
          results.push(dirInner);
        }
      });
    
      return results;
    };
    
    var files = searchRecursive('./', '.html'); // replace dir and pattern
                                                    // as you seem fit
    
    console.log(files);
    

    How to declare and add items to an array in Python?

    {} represents an empty dictionary, not an array/list. For lists or arrays, you need [].

    To initialize an empty list do this:

    my_list = []
    

    or

    my_list = list()
    

    To add elements to the list, use append

    my_list.append(12)
    

    To extend the list to include the elements from another list use extend

    my_list.extend([1,2,3,4])
    my_list
    --> [12,1,2,3,4]
    

    To remove an element from a list use remove

    my_list.remove(2)
    

    Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

    To initialize an empty dictionary use {} or dict()

    Dictionaries have keys and values

    my_dict = {'key':'value', 'another_key' : 0}
    

    To extend a dictionary with the contents of another dictionary you may use the update method

    my_dict.update({'third_key' : 1})
    

    To remove a value from a dictionary

    del my_dict['key']
    

    Upgrade to python 3.8 using conda

    You can update your python version to 3.8 in conda using the command

    conda install -c anaconda python=3.8
    

    as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running

    conda update --all
    

    may resolve some dependency failures. You can also create a new environment called py38 using this command

    conda create -n py38 python=3.8
    

    Edit - note that the conda install option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).

    ASP.NET Custom Validator Client side & Server Side validation not firing

    Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via

     Page.Validate({Insert validation group name here});
    

    How can I display the current branch and folder path in terminal?

    To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfiles project.

    https://github.com/mathiasbynens/dotfiles


    enter image description here


    Installation is dead simple on OSX and Linux. Run the following command in Terminal.

    git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh
    

    This is going to:

    1. Git clone the repo.
    2. cd into the folder.
    3. Run the installation bash script.

    Difference between Hive internal tables and external tables?

    In Hive We can also create an external table. It tells Hive to refer to the data that is at an existing location outside the warehouse directory. Dropping External tables will delete metadata but not the data.

    How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

    Easy with recursion.

    public static string GetStandardExcelColumnName(int columnNumberOneBased)
    {
      int baseValue = Convert.ToInt32('A');
      int columnNumberZeroBased = columnNumberOneBased - 1;
    
      string ret = "";
    
      if (columnNumberOneBased > 26)
      {
        ret = GetStandardExcelColumnName(columnNumberZeroBased / 26) ;
      }
    
      return ret + Convert.ToChar(baseValue + (columnNumberZeroBased % 26) );
    }
    

    Stopping a JavaScript function when a certain condition is met

    if(condition){
        // do something
           return false;
    
    }
    

    Compile to a stand-alone executable (.exe) in Visual Studio

    I don't think it is possible to do what the questioner asks which is to avoid dll hell by merging all the project files into one .exe.

    The framework issue is a red herring. The problem that occurs is that when you have multiple projects depending on one library it is a PITA to keep the libraries in sync. Each time the library changes, all the .exes that depend on it and are not updated will die horribly.

    Telling people to learn C as one response did is arrogant and ignorant.

    Is there an opposite to display:none?

    The best "opposite" would be to return it to the default value which is:

    display: inline
    

    PHP file_get_contents() and setting request headers

    Unfortunately, it doesn't look like file_get_contents() really offers that degree of control. The cURL extension is usually the first to come up, but I would highly recommend the PECL_HTTP extension (http://pecl.php.net/package/pecl_http) for very simple and straightforward HTTP requests. (it's much easier to work with than cURL)

    Can I do Android Programming in C++, C?

    You should look at MoSync too, MoSync gives you standard C/C++, easy-to-use well-documented APIs, and a full-featured Eclipse-based IDE. Its now a open sourced IDE still pretty cool but not maintained anymore.

    How to query between two dates using Laravel and Eloquent?

    If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.

    $list=  (new LeaveApplication())
                ->whereDate('from','<=', $today)
                ->whereDate('to','>=', $today)
                ->get();
    

    Load image with jQuery and append it to the DOM

    I imagine that you define your image something like this:

    <img id="image_portrait" src="" alt="chef etat"  width="120" height="135"  />
    

    You can simply load/update image for this tag and chage/set atts (width,height):

    var imagelink;
    var height;
    var width;
    $("#image_portrait").attr("src", imagelink);
    $("#image_portrait").attr("width", width);
    $("#image_portrait").attr("height", height);
    

    Convert NSDate to String in iOS Swift

    Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.

    extension DateFormatter {
    
        static var sharedDateFormatter: DateFormatter = {
            let dateFormatter = DateFormatter()   
            // Add your formatter configuration here     
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            return dateFormatter
        }()
    }
    

    Usage:

    let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
    

    How can I force gradle to redownload dependencies?

    You can do it like this

    https://marschall.github.io/2017/04/17/disabling-gradle-cache.html
    

    To quote from Disabling the Gradle Build Cache

    The Gradle build cache may be a great thing when you’re regularly building >large projects with Gradle. However when only occasionally building open source >projects it can quickly become large.

    To disable the Gradle build cache add the following line to ~/.gradle/gradle.properties

    org.gradle.caching=false
    

    You can clean the existing cache with

    rm -rf $HOME/.gradle/caches/
    rm -rf $HOME/.gradle/wrapper/
    

    Is there any method to get the URL without query string?

    How about this: location.href.slice(0, - ((location.search + location.hash).length))

    Difference between single and double quotes in Bash

    Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.

    Example:

    $ echo "$(echo "upg")"
    upg
    $ echo '$(echo "upg")'
    $(echo "upg")
    

    The Bash manual has this to say:

    3.1.2.2 Single Quotes

    Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

    3.1.2.3 Double Quotes

    Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

    The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

    Change Select List Option background colour on hover

    I realise this is an older question, but I recently came across this need and came up with the following solution using jQuery and CSS:

    jQuery('select[name*="lstDestinations"] option').hover(
            function() {
                jQuery(this).addClass('highlight');
            }, function() {
                jQuery(this).removeClass('highlight');
            }
        );
    

    and the css:

    .highlight {
        background-color:#333;
        cursor:pointer;
    }
    

    Perhaps this helps someone else.

    How to generate a random string of 20 characters

    Here you go. Just specify the chars you want to allow on the first line.

    char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    StringBuilder sb = new StringBuilder(20);
    Random random = new Random();
    for (int i = 0; i < 20; i++) {
        char c = chars[random.nextInt(chars.length)];
        sb.append(c);
    }
    String output = sb.toString();
    System.out.println(output);
    

    If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

    Add custom headers to WebView resource requests - android

    Maybe my response quite late, but it covers API below and above 21 level.

    To add headers we should intercept every request and create new one with required headers.

    So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+

        webView.setWebViewClient(new WebViewClient() {
    
            // Handle API until level 21
            @SuppressWarnings("deprecation")
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    
                return getNewResponse(url);
            }
    
            // Handle API 21+
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    
                String url = request.getUrl().toString();
    
                return getNewResponse(url);
            }
    
            private WebResourceResponse getNewResponse(String url) {
    
                try {
                    OkHttpClient httpClient = new OkHttpClient();
    
                    Request request = new Request.Builder()
                            .url(url.trim())
                            .addHeader("Authorization", "YOU_AUTH_KEY") // Example header
                            .addHeader("api-key", "YOUR_API_KEY") // Example header
                            .build();
    
                    Response response = httpClient.newCall(request).execute();
    
                    return new WebResourceResponse(
                            null,
                            response.header("content-encoding", "utf-8"),
                            response.body().byteStream()
                    );
    
                } catch (Exception e) {
                    return null;
                }
    
            }
       });
    

    If response type should be processed you could change

            return new WebResourceResponse(
                    null, // <- Change here
                    response.header("content-encoding", "utf-8"),
                    response.body().byteStream()
            );
    

    to

            return new WebResourceResponse(
                    getMimeType(url), // <- Change here
                    response.header("content-encoding", "utf-8"),
                    response.body().byteStream()
            );
    

    and add method

            private String getMimeType(String url) {
                String type = null;
                String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    
                if (extension != null) {
    
                    switch (extension) {
                        case "js":
                            return "text/javascript";
                        case "woff":
                            return "application/font-woff";
                        case "woff2":
                            return "application/font-woff2";
                        case "ttf":
                            return "application/x-font-ttf";
                        case "eot":
                            return "application/vnd.ms-fontobject";
                        case "svg":
                            return "image/svg+xml";
                    }
    
                    type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                }
    
                return type;
            }
    

    PHP Composer behind http proxy

    Try this:

    export HTTPS_PROXY_REQUEST_FULLURI=false
    

    solved this issue for me working behind a proxy at a company few weeks ago.

    How can I select from list of values in SQL Server

    Simplest way to get the distinct values of a long list of comma delimited text would be to use a find an replace with UNION to get the distinct values.

    SELECT 1
    UNION SELECT 1
    UNION SELECT 1
    UNION SELECT 2
    UNION SELECT 5
    UNION SELECT 1
    UNION SELECT 6
    

    Applied to your long line of comma delimited text

    • Find and replace every comma with UNION SELECT
    • Add a SELECT in front of the statement

    You now should have a working query

    map function for objects (instead of arrays)

    Use following map function to define myObject.map

    o => f=> Object.keys(o).reduce((a,c)=> c=='map' ? a : (a[c]=f(o[c],c),a), {})
    

    _x000D_
    _x000D_
    let map = o => f=> Object.keys(o).reduce((a,c)=> c=='map' ? a : (a[c]=f(o[c],c),a), {})
    
    
    
    // TEST init
    
    myObject = { 'a': 1, 'b': 2, 'c': 3 }
    myObject.map = map(myObject);        
    
    // you can do this instead above line but it is not recommended 
    // ( you will see `map` key any/all objects)
    // Object.prototype.map = map(myObject);
    
    // OP desired interface described in question
    newObject = myObject.map(function (value, label) {
        return  value * value;
    });
    
    console.log(newObject);
    _x000D_
    _x000D_
    _x000D_

    How do you read scanf until EOF in C?

    Your code loops until it reads a single word, then exits. So if you give it multiple words it will read the first and exit, while if you give it an empty input, it will loop forever. In any case, it will only print random garbage from uninitialized memory. This is apparently not what you want, but what do you want? If you just want to read and print the first word (if it exists), use if:

    if (scanf("%15s", word) == 1)
        printf("%s\n", word);
    

    If you want to loop as long as you can read a word, use while:

    while (scanf("%15s", word) == 1)
        printf("%s\n", word);
    

    Also, as others have noted, you need to give the word array a size that is big enough for your scanf:

    char word[16];
    

    Others have suggested testing for EOF instead of checking how many items scanf matched. That's fine for this case, where scanf can't fail to match unless there's an EOF, but is not so good in other cases (such as trying to read integers), where scanf might match nothing without reaching EOF (if the input isn't a number) and return 0.

    edit

    Looks like you changed your question to match my code which works fine when I run it -- loops reading words until EOF is reached and then exits. So something else is going on with your code, perhaps related to how you are feeding it input as suggested by David

    AWK: Access captured group from line pattern

    I struggled a bit with coming up with a bash function that wraps Peter Tillemans' answer but here's what I came up with:

    function regex { perl -n -e "/$1/ && printf \"%s\n\", "'$1' }

    I found this worked better than opsb's awk-based bash function for the following regular expression argument, because I do not want the "ms" to be printed.

    '([0-9]*)ms$'
    

    Get selected value in dropdown list using JavaScript

    If you have a select element that looks like this:

    <select id="ddlViewBy">
      <option value="1">test1</option>
      <option value="2" selected="selected">test2</option>
      <option value="3">test3</option>
    </select>
    

    Running this code:

    var e = document.getElementById("ddlViewBy");
    var strUser = e.value;
    

    Would make strUser be 2. If what you actually want is test2, then do this:

    var e = document.getElementById("ddlViewBy");
    var strUser = e.options[e.selectedIndex].text;
    

    Which would make strUser be test2

    jQuery Datepicker localization

    You can do like this

     $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
        closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
        prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
        nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
        currentText: 'Courant', currentStatus: 'Voir le mois courant',
        monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
        'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
        monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
        'Jul','Aoû','Sep','Oct','Nov','Déc'],
        monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
        weekHeader: 'Sm', weekStatus: '',
        dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
        dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
        dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
        dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
        dateFormat: 'dd/mm/yy', firstDay: 0, 
        initStatus: 'Choisir la date', isRTL: false};
     $.datepicker.setDefaults($.datepicker.regional['fr']);
    

    Set Google Chrome as the debugging browser in Visual Studio

    Click on the arrow near by start button there you will get list of browser. Select the browser you want your application to be run with and click on "Set as Default" Click ok and you are done with this.

    Draw on HTML5 Canvas using a mouse

    Googled this ("html5 canvas paint program"). Looks like what you need.

    http://dev.opera.com/articles/view/html5-canvas-painting/

    iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

    In my case (an iOS Phonegap app), applying translate3d to relative child elements did not resolve the issue. My scrollable element didn't have a set height as it was absolutely positioned and I was defining the top and bottom positions. What fixed it for me was adding a min-height (of 100px).

    How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

    On Windows only, you can get the motherboard ID using WMI, through a COM bridge such as JACOB.

    Example:

    import java.util.Enumeration;
    import com.jacob.activeX.ActiveXComponent;
    import com.jacob.com.ComThread;
    import com.jacob.com.EnumVariant;
    import com.jacob.com.Variant;
    
    public class Test {
        public static void main(String[] args) {
            ComThread.InitMTA();
            try {
                ActiveXComponent wmi = new ActiveXComponent("winmgmts:\\\\.");
                Variant instances = wmi.invoke("InstancesOf", "Win32_BaseBoard");
                Enumeration<Variant> en = new EnumVariant(instances.getDispatch());
                while (en.hasMoreElements())
                {
                    ActiveXComponent bb = new ActiveXComponent(en.nextElement().getDispatch());
                    System.out.println(bb.getPropertyAsString("SerialNumber"));
                    break;
                }
            } finally {
                ComThread.Release();
            }
        }
    }
    

    And if you choose to use the MAC address to identify the machine, you can use WMI to determine whether an interface is connected via USB (if you want to exclude USB adapters.)

    It's also possible to get a hard drive ID via WMI but this is unreliable.

    Spring Boot application.properties value not populating

    follow these steps. 1:- create your configuration class like below you can see

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.beans.factory.annotation.Value;
    
    @Configuration
    public class YourConfiguration{
    
        // passing the key which you set in application.properties
        @Value("${some.pro}")
        private String somePro;
    
       // getting the value from that key which you set in application.properties
        @Bean
        public String getsomePro() {
            return somePro;
        }
    }
    

    2:- when you have a configuration class then inject in the variable from a configuration where you need.

    @Component
    public class YourService {
    
        @Autowired
        private String getsomePro;
    
        // now you have a value in getsomePro variable automatically.
    }
    

    Hide Twitter Bootstrap nav collapse on click

    Mobile view: how to hide toggle navigation in bootstrap + dropdown + jquery + scrollto with navigation items that points to anchors/ids on the same page, one page template

    The issue I was experimenting with any of the above solutions was that they are collapsing only the submenu items, while the navigation menu doesn't collapse.

    So I did my thought.. and what can we observe? Well, every time we/the users click an scrollto link, we want the page to scroll to that position and contemporaneously, collapse the menu to restore the page view.

    Well... why not to assign this job to the scrollto functions? Easy :-)

    So in the two codes

    // scroll to top action
    $('.scroll-top').on('click', function(event) {
        event.preventDefault();
        $('html, body').animate({scrollTop:0}, 'slow');
    

    and

    // scroll function
    function scrollToID(id, speed){
    var offSet = 67;
    var targetOffset = $(id).offset().top - offSet;
    var mainNav = $('#main-nav');
        $('html,body').animate({scrollTop:targetOffset}, speed);
    if (mainNav.hasClass("open")) {
        mainNav.css("height", "1px").removeClass("in").addClass("collapse");
        mainNav.removeClass("open");
    }
    

    I've just added the same command in both the functions

        if($('.navbar-toggle').css('display') !='none'){
        $(".navbar-toggle").trigger( "click" );
    }
    

    (kudos to one of the above contributors)

    like this (the same should be added to both the scrolls)

    $('.scroll-top').on('click', function(event) {
        event.preventDefault();
        $('html, body').animate({scrollTop:0}, 'slow');
    if($('.navbar-toggle').css('display') !='none'){
        $(".navbar-toggle").trigger( "click" );
    }
    });
    

    if you wanna see it in action just check it out recupero dati da NAS

    Random number between 0 and 1 in python

    My variation that I find to be more flexible.

    str_Key           = ""
    str_FullKey       = "" 
    str_CharacterPool = "01234ABCDEFfghij~-)"
    for int_I in range(64): 
        str_Key = random.choice(str_CharacterPool) 
        str_FullKey = str_FullKey + str_Key 
    

    Windows shell command to get the full path to the current directory?

    This has always worked for me:

    SET CurrentDir="%~dp0"
    
    ECHO The current file path this bat file is executing in is the following:
    
    ECHO %CurrentDir%
    
    Pause
    

    What does "The following object is masked from 'package:xxx'" mean?

    The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

    When two functions have the same name, which one gets called?

    R will look through the search path to find functions, and will use the first one that it finds.

    search()
     ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
     ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
     ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
     ## [10] "package:methods"   "Autoloads"         "package:base"
    

    In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

    is_true
    ## function (x, .xname = get_name_in_parent(x)) 
    ## {
    ##     x <- coerce_to(x, "logical", .xname)
    ##     call_and_name(function(x) {
    ##         ok <- x & !is.na(x)
    ##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
    ##     }, x)
    ## }
    <bytecode: 0x0000000004fc9f10>
    <environment: namespace:assertive.base>
    

    The functions in testthat are not accessible in the usual way; that is, they have been masked.

    What if I want to use one of the masked functions?

    You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

    testthat::is_true
    ## function () 
    ## {
    ##     function(x) expect_true(x)
    ## }
    ## <environment: namespace:testthat>
    

    How do I suppress the message?

    If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

    library(testthat)
    library(assertive, warn.conflicts = FALSE)
    # No output this time
    

    Alternatively, suppress the message with suppressPackageStartupMessages:

    library(testthat)
    suppressPackageStartupMessages(library(assertive))
    # Also no output
    

    Impact of R's Startup Procedures on Function Masking

    If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

    For example, the documentation there says:

    Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

    Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

    How do I list all the masked functions?

    First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

    library(dplyr)
    envs <- search() %>% setNames(., .)
    

    For each environment, get the exported functions (and other variables).

    fns <- lapply(envs, ls)
    

    Turn this into a data frame, for easy use with dplyr.

    fns_by_env <- data_frame(
      env = rep.int(names(fns), lengths(fns)),
      fn  = unlist(fns)
    )
    

    Find cases where the object appears more than once.

    fns_by_env %>% 
      group_by(fn) %>% 
      tally() %>% 
      filter(n > 1) %>% 
      inner_join(fns_by_env)
    

    To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

    How do I prevent name conflict bugs?

    The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

    library(conflicted)
    library(Hmisc)
    units
    ## Error: units found in 2 packages. You must indicate which one you want with ::
    ##  * Hmisc::units
    ##  * base::units
    

    Can't install any packages in Node.js using "npm install"

    The repository is not down, it looks like they've changed how they host files (I guess they have restored some old code):

    Now you have to add the /package-name/ before the -

    Eg:

    http://registry.npmjs.org/-/npm-1.1.48.tgz
    http://registry.npmjs.org/npm/-/npm-1.1.48.tgz
    

    There are 3 ways to solve it:

    • Use a complete mirror:
    • Use a public proxy:

      --registry http://165.225.128.50:8000

    • Host a local proxy:

      https://github.com/hughsk/npm-quickfix

    git clone https://github.com/hughsk/npm-quickfix.git
    cd npm-quickfix
    npm set registry http://localhost:8080/
    node index.js
    

    I'd personally go with number 3 and revert to npm set registry http://registry.npmjs.org/ as soon as this get resolved.

    Stay tuned here for more info: https://github.com/isaacs/npm/issues/2694

    How to automatically reload a page after a given period of inactivity

    var bd = document.getElementsByTagName('body')[0];
    var time = new Date().getTime();
    
    bd.onmousemove = goLoad;
    function goLoad() {
    if(new Date().getTime() - time >= 1200000) {
        time = new Date().getTime();
        window.location.reload(true);
        }else{
            time = new Date().getTime();
        }
    }
    

    Each time you move the mouse it will check the last time you moved the mouse. If the time interval is greater than 20' it will reload the page, else it will renew the last-time-you-moved-the-mouse.

    List(of String) or Array or ArrayList

    Sometimes I don't want to add items to a list when I instantiate it.

    Instantiate a blank list

    Dim blankList As List(Of String) = New List(Of String)
    

    Add to the list

    blankList.Add("Dis be part of me list") 'blankList is no longer blank, but you get the drift
    

    Loop through the list

    For Each item in blankList
      ' write code here, for example:
      Console.WriteLine(item)
    Next
    

    Add animated Gif image in Iphone UIImageView

    Here is an interesting library: https://github.com/Flipboard/FLAnimatedImage

    I tested the demo example and it's working great. It's a child of UIImageView. So I think you can use it in your Storyboard directly as well.

    Cheers

    Excel SUMIF between dates

    You haven't got your SUMIF in the correct order - it needs to be range, criteria, sum range. Try:

    =SUMIF(A:A,">="&DATE(2012,1,1),B:B)
    

    How to open adb and use it to send commands

    The short answer is adb is used via command line. find adb.exe on your machine, add it to the path and use it from cmd on windows.

    "adb devices" will give you a list of devices adb can talk to. your emulation platform should be on the list. just type adb to get a list of commands and what they do.

    How to apply CSS to iframe?

    Here, There are two things inside the domain

    1. iFrame Section
    2. Page Loaded inside the iFrame

    So you want to style those two sections as follows,

    1. Style for the iFrame Section

    It can style using CSS with that respected id or class name. You can just style it in your parent Style sheets also.

    <style>
    #my_iFrame{
    height: 300px;
    width: 100%;
    position:absolute;
    top:0;
    left:0;
    border: 1px black solid;
    }
    </style>
    
    <iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>
    

    2. Style the Page Loaded inside the iFrame

    This Styles can be loaded from the parent page with the help of Javascript

    var cssFile  = document.createElement("link") 
    cssFile.rel  = "stylesheet"; 
    cssFile.type = "text/css"; 
    cssFile.href = "iFramePage.css"; 
    

    then set that CSS file to the respected iFrame section

    //to Load in the Body Part
    frames['my_iFrame'].document.body.appendChild(cssFile); 
    //to Load in the Head Part
    frames['my_iFrame'].document.head.appendChild(cssFile);
    

    Here, You can edit the Head Part of the Page inside the iFrame using this way also

    var $iFrameHead = $("#my_iFrame").contents().find("head");
    $iFrameHead.append(
       $("<link/>",{ 
          rel: "stylesheet", 
          href: urlPath, 
          type: "text/css" }
         ));
    

    Java Array, Finding Duplicates

    On the nose answer..

    duplicates=false;
    for (j=0;j<zipcodeList.length;j++)
      for (k=j+1;k<zipcodeList.length;k++)
        if (k!=j && zipcodeList[k] == zipcodeList[j])
          duplicates=true;
    

    Edited to switch .equals() back to == since I read somewhere you're using int, which wasn't clear in the initial question. Also to set k=j+1, to halve execution time, but it's still O(n2).

    A faster (in the limit) way

    Here's a hash based approach. You gotta pay for the autoboxing, but it's O(n) instead of O(n2). An enterprising soul would go find a primitive int-based hash set (Apache or Google Collections has such a thing, methinks.)

    boolean duplicates(final int[] zipcodelist)
    {
      Set<Integer> lump = new HashSet<Integer>();
      for (int i : zipcodelist)
      {
        if (lump.contains(i)) return true;
        lump.add(i);
      }
      return false;
    }
    

    Bow to HuyLe

    See HuyLe's answer for a more or less O(n) solution, which I think needs a couple of add'l steps:

    static boolean duplicates(final int[] zipcodelist)
    {
       final int MAXZIP = 99999;
       boolean[] bitmap = new boolean[MAXZIP+1];
       java.util.Arrays.fill(bitmap, false);
       for (int item : zipcodeList)
         if (!bitmap[item]) bitmap[item] = true;
         else return true;
       }
       return false;
    }
    

    Or Just to be Compact

    static boolean duplicates(final int[] zipcodelist)
    {
       final int MAXZIP = 99999;
       boolean[] bitmap = new boolean[MAXZIP+1];  // Java guarantees init to false
       for (int item : zipcodeList)
         if (!(bitmap[item] ^= true)) return true;
       return false;
    }
    

    Does it Matter?

    Well, so I ran a little benchmark, which is iffy all over the place, but here's the code:

    import java.util.BitSet;
    
    class Yuk
    {
      static boolean duplicatesZero(final int[] zipcodelist)
      {
        boolean duplicates=false;
        for (int j=0;j<zipcodelist.length;j++)
          for (int k=j+1;k<zipcodelist.length;k++)
            if (k!=j && zipcodelist[k] == zipcodelist[j])
              duplicates=true;
    
        return duplicates;
      }
    
    
      static boolean duplicatesOne(final int[] zipcodelist)
      {
        final int MAXZIP = 99999;
        boolean[] bitmap = new boolean[MAXZIP + 1];
        java.util.Arrays.fill(bitmap, false);
        for (int item : zipcodelist) {
          if (!(bitmap[item] ^= true))
            return true;
        }
        return false;
      }
    
      static boolean duplicatesTwo(final int[] zipcodelist)
      {
        final int MAXZIP = 99999;
    
        BitSet b = new BitSet(MAXZIP + 1);
        b.set(0, MAXZIP, false);
        for (int item : zipcodelist) {
          if (!b.get(item)) {
            b.set(item, true);
          } else
            return true;
        }
        return false;
      }
    
      enum ApproachT { NSQUARED, HASHSET, BITSET};
    
      /**
       * @param args
       */
      public static void main(String[] args)
      {
        ApproachT approach = ApproachT.BITSET;
    
        final int REPS = 100;
        final int MAXZIP = 99999;
    
        int[] sizes = new int[] { 10, 1000, 10000, 100000, 1000000 };
        long[][] times = new long[sizes.length][REPS];
    
        boolean tossme = false;
    
        for (int sizei = 0; sizei < sizes.length; sizei++) {
          System.err.println("Trial for zipcodelist size= "+sizes[sizei]);
          for (int rep = 0; rep < REPS; rep++) {
            int[] zipcodelist = new int[sizes[sizei]];
            for (int i = 0; i < zipcodelist.length; i++) {
              zipcodelist[i] = (int) (Math.random() * (MAXZIP + 1));
            }
            long begin = System.currentTimeMillis();
            switch (approach) {
            case NSQUARED :
              tossme ^= (duplicatesZero(zipcodelist));
              break;
            case HASHSET :
              tossme ^= (duplicatesOne(zipcodelist));
              break;
            case BITSET :
              tossme ^= (duplicatesTwo(zipcodelist));
              break;
    
            }
            long end = System.currentTimeMillis();
            times[sizei][rep] = end - begin;
    
    
          }
          long avg = 0;
          for (int rep = 0; rep < REPS; rep++) {
            avg += times[sizei][rep];
          }
          System.err.println("Size=" + sizes[sizei] + ", avg time = "
                + avg / (double)REPS + "ms");
        }
      }
    
    }
    

    With NSQUARED:

    Trial for size= 10
    Size=10, avg time = 0.0ms
    Trial for size= 1000
    Size=1000, avg time = 0.0ms
    Trial for size= 10000
    Size=10000, avg time = 100.0ms
    Trial for size= 100000
    Size=100000, avg time = 9923.3ms
    

    With HashSet

    Trial for zipcodelist size= 10
    Size=10, avg time = 0.16ms
    Trial for zipcodelist size= 1000
    Size=1000, avg time = 0.15ms
    Trial for zipcodelist size= 10000
    Size=10000, avg time = 0.0ms
    Trial for zipcodelist size= 100000
    Size=100000, avg time = 0.16ms
    Trial for zipcodelist size= 1000000
    Size=1000000, avg time = 0.0ms
    

    With BitSet

    Trial for zipcodelist size= 10
    Size=10, avg time = 0.0ms
    Trial for zipcodelist size= 1000
    Size=1000, avg time = 0.0ms
    Trial for zipcodelist size= 10000
    Size=10000, avg time = 0.0ms
    Trial for zipcodelist size= 100000
    Size=100000, avg time = 0.0ms
    Trial for zipcodelist size= 1000000
    Size=1000000, avg time = 0.0ms
    

    BITSET Wins!

    But only by a hair... .15ms is within the error for currentTimeMillis(), and there are some gaping holes in my benchmark. Note that for any list longer than 100000, you can simply return true because there will be a duplicate. In fact, if the list is anything like random, you can return true WHP for a much shorter list. What's the moral? In the limit, the most efficient implementation is:

     return true;
    

    And you won't be wrong very often.

    Post an object as data using Jquery Ajax

    Just pass the object as is. Note you can create the object as follows

    var data0 = {numberId: "1", companyId : "531"};
    
    $.ajax({
     type: "POST",
     url: "TelephoneNumbers.aspx/DeleteNumber",
     data: dataO,
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function(msg) {
     alert('In Ajax');
     }
    });
    

    UPDATE seems an odd issue with the serializer, maybe it is expecting a string, out of interest can you try the following.

    data: "{'numberId':'1', 'companyId ':'531'}",

    Alter a MySQL column to be AUTO_INCREMENT

    Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):

    ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY
    

    JavaScript CSS how to add and remove multiple CSS classes to an element

    Perhaps:

    document.getElementById("myEle").className = "class1 class2";
    

    Not tested, but should work.

    Mercurial stuck "waiting for lock"

    I am very familiar with Mercurial's locking code (as of 1.9.1). The above advice is good, but I'd add that:

    1. I've seen this in the wild, but rarely, and only on Windows machines.
    2. Deleting lock files is the easiest fix, BUT you have to make sure nothing else is accessing the repository. (If the lock is a string of zeros, this is almost certainly true).

    (For the curious: I haven't yet been able to catch the cause of this problem, but suspect it's either an older version of Mercurial accessing the repository or a problem in Python's socket.gethostname() call on certain versions of Windows.)

    Add new element to an existing object

    Just do myFunction.foo = "bar" and it will add it. myFunction is the name of the object in this case.

    Spark DataFrame groupBy and sort in the descending order (pyspark)

    By far the most convenient way is using this:

    df.orderBy(df.column_name.desc())
    

    Doesn't require special imports.

    Configure Log4net to write to multiple files

    Yes, just add multiple FileAppenders to your logger. For example:

    <log4net>
        <appender name="File1Appender" type="log4net.Appender.FileAppender">
            <file value="log-file-1.txt" />
            <appendToFile value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date %message%newline" />
            </layout>
        </appender>
        <appender name="File2Appender" type="log4net.Appender.FileAppender">
            <file value="log-file-2.txt" />
            <appendToFile value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date %message%newline" />
            </layout>
        </appender>
    
        <root>
            <level value="DEBUG" />
            <appender-ref ref="File1Appender" />
            <appender-ref ref="File2Appender" />
        </root>
    </log4net>
    

    Delete newline in Vim

    J deletes extra leading spacing (if any), joining lines with a single space. (With some exceptions: after /[.!?]$/, two spaces may be inserted; before /^\s*)/, no spaces are inserted.)

    If you don't want that behavior, gJ simply removes the newline and doesn't do anything clever with spaces at all.

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

    Using Javascript

    I created a working demo that shows how to use the Google Maps API Directions Service in Javascript through a

    • DirectionsService object to send and receive direction requests
    • DirectionsRenderer object to render the returned route on the map

    _x000D_
    _x000D_
    function initMap() {_x000D_
      var pointA = new google.maps.LatLng(51.7519, -1.2578),_x000D_
        pointB = new google.maps.LatLng(50.8429, -0.1313),_x000D_
        myOptions = {_x000D_
          zoom: 7,_x000D_
          center: pointA_x000D_
        },_x000D_
        map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),_x000D_
        // Instantiate a directions service._x000D_
        directionsService = new google.maps.DirectionsService,_x000D_
        directionsDisplay = new google.maps.DirectionsRenderer({_x000D_
          map: map_x000D_
        }),_x000D_
        markerA = new google.maps.Marker({_x000D_
          position: pointA,_x000D_
          title: "point A",_x000D_
          label: "A",_x000D_
          map: map_x000D_
        }),_x000D_
        markerB = new google.maps.Marker({_x000D_
          position: pointB,_x000D_
          title: "point B",_x000D_
          label: "B",_x000D_
          map: map_x000D_
        });_x000D_
    _x000D_
      // get route from A to B_x000D_
      calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);_x000D_
    _x000D_
    }_x000D_
    _x000D_
    _x000D_
    _x000D_
    function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {_x000D_
      directionsService.route({_x000D_
        origin: pointA,_x000D_
        destination: pointB,_x000D_
        travelMode: google.maps.TravelMode.DRIVING_x000D_
      }, function(response, status) {_x000D_
        if (status == google.maps.DirectionsStatus.OK) {_x000D_
          directionsDisplay.setDirections(response);_x000D_
        } else {_x000D_
          window.alert('Directions request failed due to ' + status);_x000D_
        }_x000D_
      });_x000D_
    }_x000D_
    _x000D_
    initMap();
    _x000D_
        html,_x000D_
        body {_x000D_
          height: 100%;_x000D_
          margin: 0;_x000D_
          padding: 0;_x000D_
        }_x000D_
        #map-canvas {_x000D_
          height: 100%;_x000D_
          width: 100%;_x000D_
        }
    _x000D_
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>_x000D_
    _x000D_
    <div id="map-canvas"></div>
    _x000D_
    _x000D_
    _x000D_

    Also on Jsfiddle: http://jsfiddle.net/user2314737/u9no8te4/

    Using Google Maps Web Services

    You can use the Web Services using an API_KEY issuing a request like this:

    https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY

    An API_KEY can be obtained in the Google Developer Console with a quota of 2,500 free requests/day.

    A request can return JSON or XML results that can be used to draw a path on a map.

    Official documentation for Web Services using the Google Maps Directions API are here

    A full list of all the new/popular databases and their uses?

    To file under both 'established' and 'key-value store': Berkeley DB.

    Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).

    Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.

    Static Initialization Blocks

    If your static variables need to be set at runtime then a static {...} block is very helpful.

    For example, if you need to set the static member to a value which is stored in a config file or database.

    Also useful when you want to add values to a static Map member as you can't add these values in the initial member declaration.

    See whether an item appears more than once in a database column

    How about:

    select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;
    

    concatenate two database columns into one resultset column

    Normal behaviour with NULL is that any operation including a NULL yields a NULL...

    - 9 * NULL  = NULL  
    - NULL + '' = NULL  
    - etc  
    

    To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..

    SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
    

    How to pip install a package with min and max version range?

    You can do:

    $ pip install "package>=0.2,<0.3"
    

    And pip will look for the best match, assuming the version is at least 0.2, and less than 0.3.

    This also applies to pip requirements files. See the full details on version specifiers in PEP 440.

    Connecting to Postgresql in a docker container from outside

    I tried to connect from localhost (mac) to a postgres container. I changed the port in the docker-compose file from 5432 to 3306 and started the container. No idea why I did it :|

    Then I tried to connect to postgres via PSequel and adminer and the connection could not be established.

    After switching back to port 5432 all works fine.

      db:
        image: postgres
        ports:
          - 5432:5432
        restart: always
        volumes:
          - "db_sql:/var/lib/mysql"
        environment:
          POSTGRES_USER: root
          POSTGRES_PASSWORD: password
          POSTGRES_DB: postgres_db
    

    This was my experience I wanted to share. Perhaps someone can make use of it.

    Use grep to report back only line numbers

    I recommend the answers with sed and awk for just getting the line number, rather than using grep to get the entire matching line and then removing that from the output with cut or another tool. For completeness, you can also use Perl:

    perl -nE '/pattern/ && say $.' filename
    

    or Ruby:

    ruby -ne 'puts $. if /pattern/' filename
    

    How do I select text nodes with jQuery?

    For some reason contents() didn't work for me, so if it didn't work for you, here's a solution I made, I created jQuery.fn.descendants with the option to include text nodes or not

    Usage


    Get all descendants including text nodes and element nodes

    jQuery('body').descendants('all');
    

    Get all descendants returning only text nodes

    jQuery('body').descendants(true);
    

    Get all descendants returning only element nodes

    jQuery('body').descendants();
    

    Coffeescript Original:

    jQuery.fn.descendants = ( textNodes ) ->
    
        # if textNodes is 'all' then textNodes and elementNodes are allowed
        # if textNodes if true then only textNodes will be returned
        # if textNodes is not provided as an argument then only element nodes
        # will be returned
    
        allowedTypes = if textNodes is 'all' then [1,3] else if textNodes then [3] else [1]
    
        # nodes we find
        nodes = []
    
    
        dig = (node) ->
    
            # loop through children
            for child in node.childNodes
    
                # push child to collection if has allowed type
                nodes.push(child) if child.nodeType in allowedTypes
    
                # dig through child if has children
                dig child if child.childNodes.length
    
    
        # loop and dig through nodes in the current
        # jQuery object
        dig node for node in this
    
    
        # wrap with jQuery
        return jQuery(nodes)
    

    Drop In Javascript Version

    var __indexOf=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++){if(t in this&&this[t]===e)return t}return-1}; /* indexOf polyfill ends here*/ jQuery.fn.descendants=function(e){var t,n,r,i,s,o;t=e==="all"?[1,3]:e?[3]:[1];i=[];n=function(e){var r,s,o,u,a,f;u=e.childNodes;f=[];for(s=0,o=u.length;s<o;s++){r=u[s];if(a=r.nodeType,__indexOf.call(t,a)>=0){i.push(r)}if(r.childNodes.length){f.push(n(r))}else{f.push(void 0)}}return f};for(s=0,o=this.length;s<o;s++){r=this[s];n(r)}return jQuery(i)}
    

    Unminified Javascript version: http://pastebin.com/cX3jMfuD

    This is cross browser, a small Array.indexOf polyfill is included in the code.

    how to set mongod --dbpath

    First you will have a config file in /etc/mongodb.conf, therefore this sounds like a homebrew install which will use some more standardized paths. The whole /data/db/ thing is referenced in a lot of manual install documentation.

    So basically from your log the server is not running, it's shutting down, so there is nothing for the shell to connect to. Seems like you have had some unclean shutdowns/restarts which has led to the inconsistency.

    Clear the files in the journal /usr/local/var/mongodb/journal/ on your config.

    Also:

    sudo rm /var/lib/mongodb/mongod.lock
    

    Just in case, even though that part looks clean. And then restart.

    Copy data from one column to other column (which is in a different table)

    Hope you have key field is two tables.

     UPDATE tblindiantime t
       SET CountryName = (SELECT c.BusinessCountry 
                         FROM contacts c WHERE c.Key = t.Key 
                         )
    

    How to turn NaN from parseInt into 0 for an empty string?

    You can also use the isNaN() function:

    var s = ''
    var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
    

    How to disable input conditionally in vue.js

    Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.

    How to make a checkbox checked with jQuery?

    from jQuery v1.6 use prop

    to check that is checkd or not

    $('input:radio').prop('checked') // will return true or false
    

    and to make it checkd use

    $("input").prop("checked", true);
    

    react hooks useEffect() cleanup for only componentWillUnmount?

    useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html

    enter image description here

    Optional query string parameters in ASP.NET Web API

    It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.

    The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    public class BooksController : ApiController
      {
        // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
        public string GetFindBooks([FromUri]BookQuery query)
        {
          // ...
        }
      }
    
      public class BookQuery
      {
        public string Author { get; set; }
        public string Title { get; set; }
        public string ISBN { get; set; }
        public string SomethingElse { get; set; }
        public DateTime? Date { get; set; }
      }
    

    It even supports multiple parameters, as long as the properties don't conflict.

    // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
    public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
    {
      // ...
    }
    
    public class Paging
    {
      public string Sort { get; set; }
      public int Skip { get; set; }
      public int Take { get; set; }
    }
    

    Update:
    In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.

    Changing text color onclick

    Do something like this:

    <script>
    function changeColor(id)
    {
      document.getElementById(id).style.color = "#ff0000"; // forecolor
      document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
    }
    </script>
    
    <div id="myid">Hello There !!</div>
    
    <a href="#" onclick="changeColor('myid'); return false;">Change Color</a>
    

    Remove all child elements of a DOM node in JavaScript

    Using a range loop feels the most natural to me:

    for (var child of node.childNodes) {
        child.remove();
    }
    

    According to my measurements in Chrome and Firefox, it is about 1.3x slower. In normal circumstances, this will perhaps not matter.

    Implement touch using Python?

    This tries to be a little more race-free than the other solutions. (The with keyword is new in Python 2.5.)

    import os
    def touch(fname, times=None):
        with open(fname, 'a'):
            os.utime(fname, times)
    

    Roughly equivalent to this.

    import os
    def touch(fname, times=None):
        fhandle = open(fname, 'a')
        try:
            os.utime(fname, times)
        finally:
            fhandle.close()
    

    Now, to really make it race-free, you need to use futimes and change the timestamp of the open filehandle, instead of opening the file and then changing the timestamp on the filename (which may have been renamed). Unfortunately, Python doesn't seem to provide a way to call futimes without going through ctypes or similar...


    EDIT

    As noted by Nate Parsons, Python 3.3 will add specifying a file descriptor (when os.supports_fd) to functions such as os.utime, which will use the futimes syscall instead of the utimes syscall under the hood. In other words:

    import os
    def touch(fname, mode=0o666, dir_fd=None, **kwargs):
        flags = os.O_CREAT | os.O_APPEND
        with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:
            os.utime(f.fileno() if os.utime in os.supports_fd else fname,
                dir_fd=None if os.supports_fd else dir_fd, **kwargs)
    

    Automatic prune with Git fetch or pull

    git config --global fetch.prune true

    To always --prune for git fetch and git pull in all your Git repositories:

    git config --global fetch.prune true
    

    This above command appends in your global Git configuration (typically ~/.gitconfig) the following lines. Use git config -e --global to view your global configuration.

    [fetch]
        prune = true
    

    git config remote.origin.prune true

    To always --prune but from one single repository:

    git config remote.origin.prune true
                     #^^^^^^
                     #replace with your repo name
    

    This above command adds in your local Git configuration (typically .git/config) the below last line. Use git config -e to view your local configuration.

    [remote "origin"]
        url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        fetch = +refs/heads/*:refs/remotes/origin/*
        prune = true
    

    You can also use --global within the second command or use instead --local within the first command.


    git config --global gui.pruneDuringFetch true

    If you use git gui you may also be interested by:

    git config --global gui.pruneDuringFetch true
    

    that appends:

    [gui]
        pruneDuringFetch = true
    

    References

    The corresponding documentations from git help config:

    --global

      For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t.

     

    --local

      For writing options: write to the repository .git/config file. This is the default behavior.

     

    fetch.prune

      If true, fetch will automatically behave as if the --prune option was given on the command line. See also remote.<name>.prune.

     

    gui.pruneDuringFetch

      "true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".

     

    remote.<name>.prune

      When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the --prune option was given on the command line). Overrides fetch.prune settings, if any.

    Can you pass parameters to an AngularJS controller on creation?

    I'm very late to this and I have no idea if this is a good idea, but you can include the $attrs injectable in the controller function allowing the controller to be initialized using "arguments" provided on an element, e.g.

    app.controller('modelController', function($scope, $attrs) {
        if (!$attrs.model) throw new Error("No model for modelController");
    
        // Initialize $scope using the value of the model attribute, e.g.,
        $scope.url = "http://example.com/fetch?model="+$attrs.model;
    })
    
    <div ng-controller="modelController" model="foobar">
      <a href="{{url}}">Click here</a>
    </div>
    

    Again, no idea if this is a good idea, but it seems to work and is another alternative.

    Output in a table format in Java's System.out

    Use System.out.format . You can set lengths of fields like this:

    System.out.format("%32s%10d%16s", string1, int1, string2);
    

    This pads string1, int1, and string2 to 32, 10, and 16 characters, respectively.

    See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).

    C dynamically growing array

    To create an array of unlimited items of any sort of type:

    typedef struct STRUCT_SS_VECTOR {
        size_t size;
        void** items;
    } ss_vector;
    
    
    ss_vector* ss_init_vector(size_t item_size) {
        ss_vector* vector;
        vector = malloc(sizeof(ss_vector));
        vector->size = 0;
        vector->items = calloc(0, item_size);
    
        return vector;
    }
    
    void ss_vector_append(ss_vector* vec, void* item) {
        vec->size++;
        vec->items = realloc(vec->items, vec->size * sizeof(item));
        vec->items[vec->size - 1] = item;
    };
    
    void ss_vector_free(ss_vector* vec) {
        for (int i = 0; i < vec->size; i++)
            free(vec->items[i]);
    
        free(vec->items);
        free(vec);
    }
    

    and how to use it:

    // defining some sort of struct, can be anything really
    typedef struct APPLE_STRUCT {
        int id;
    } apple;
    
    apple* init_apple(int id) {
        apple* a;
        a = malloc(sizeof(apple));
        a-> id = id;
        return a;
    };
    
    
    int main(int argc, char* argv[]) {
        ss_vector* vector = ss_init_vector(sizeof(apple));
    
        // inserting some items
        for (int i = 0; i < 10; i++)
            ss_vector_append(vector, init_apple(i));
    
    
        // dont forget to free it
        ss_vector_free(vector);
    
        return 0;
    }
    

    This vector/array can hold any type of item and it is completely dynamic in size.

    Bash script - variable content as a command to run

    Your are probably looking for eval $var.

    How to configure PostgreSQL to accept all incoming connections

    Configuration all files with postgres 12 on centos:

    step 1: search and edit file

    sudo vi /var/lib/pgsql/12/data/pg_hba.conf

    press "i" and at line IPv4 change

    host    all             all             0.0.0.0/0            md5
    

    step 2: search and edit file postgresql.conf

    sudo vi /var/lib/pgsql/12/data/postgresql.conf

    add last line: listen_addresses = '*' :wq! (save file) - step 3: restart

    systemctl restart postgresql-12.service
    

    How to show what a commit did?

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

    git log -p commit1 commit2
    

    Is there a way to programmatically scroll a scroll view to a specific edit text?

    I think I have found more elegant and less error prone solution using

    ScrollView.requestChildRectangleOnScreen

    There is no math involved, and contrary to other proposed solutions, it will handle correctly scrolling both up and down.

    /**
     * Will scroll the {@code scrollView} to make {@code viewToScroll} visible
     * 
     * @param scrollView parent of {@code scrollableContent}
     * @param scrollableContent a child of {@code scrollView} whitch holds the scrollable content (fills the viewport).
     * @param viewToScroll a child of {@code scrollableContent} to whitch will scroll the the {@code scrollView}
     */
    void scrollToView(ScrollView scrollView, ViewGroup scrollableContent, View viewToScroll) {
        Rect viewToScrollRect = new Rect(); //coordinates to scroll to
        viewToScroll.getHitRect(viewToScrollRect); //fills viewToScrollRect with coordinates of viewToScroll relative to its parent (LinearLayout) 
        scrollView.requestChildRectangleOnScreen(scrollableContent, viewToScrollRect, false); //ScrollView will make sure, the given viewToScrollRect is visible
    }
    

    It is a good idea to wrap it into postDelayed to make it more reliable, in case the ScrollView is being changed at the moment

    /**
     * Will scroll the {@code scrollView} to make {@code viewToScroll} visible
     * 
     * @param scrollView parent of {@code scrollableContent}
     * @param scrollableContent a child of {@code scrollView} whitch holds the scrollable content (fills the viewport).
     * @param viewToScroll a child of {@code scrollableContent} to whitch will scroll the the {@code scrollView}
     */
    private void scrollToView(final ScrollView scrollView, final ViewGroup scrollableContent, final View viewToScroll) {
        long delay = 100; //delay to let finish with possible modifications to ScrollView
        scrollView.postDelayed(new Runnable() {
            public void run() {
                Rect viewToScrollRect = new Rect(); //coordinates to scroll to
                viewToScroll.getHitRect(viewToScrollRect); //fills viewToScrollRect with coordinates of viewToScroll relative to its parent (LinearLayout) 
                scrollView.requestChildRectangleOnScreen(scrollableContent, viewToScrollRect, false); //ScrollView will make sure, the given viewToScrollRect is visible
            }
        }, delay);
    }
    

    The default XML namespace of the project must be the MSBuild XML namespace

    I ran into this issue while opening the Service Fabric GettingStartedApplication in Visual Studio 2015. The original solution was built on .NET Core in VS 2017 and I got the same error when opening in 2015.

    Here are the steps I followed to resolve the issue.

    • Right click on (load Failed) project and edit in visual studio.
    • Saw the following line in the Project tag: <Project Sdk="Microsoft.NET.Sdk.Web" >

    • Followed the instruction shown in the error message to add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to this tag

    It should now look like:

    <Project Sdk="Microsoft.NET.Sdk.Web" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
    • Reloading the project gave me the next error (yours may be different based on what is included in your project)

    "Update" element <None> is unrecognized

    • Saw that None element had an update attribute as below:

      <None Update="wwwroot\**\*;Views\**\*;Areas\**\Views">
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </None>
      
    • Commented that out as below.

      <!--<None Update="wwwroot\**\*;Views\**\*;Areas\**\Views">
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </None>-->
      
    • Onto the next error: Version in Package Reference is unrecognized Version in element <PackageReference> is unrecognized

    • Saw that Version is there in csproj xml as below (Additional PackageReference lines removed for brevity)

    • Stripped the Version attribute

      <PackageReference Include="Microsoft.AspNetCore.Diagnostics" />
      <PackageReference Include="Microsoft.AspNetCore.Mvc" />
      
    • I now get the following: VS Auto Upgrade

    Bingo! The visual Studio One-way upgrade kicked in! Let VS do the magic!

    • The Project loaded but with reference lib errors. enter image description here

    • Fixed the reference lib errors individually, by removing and replacing in NuGet to get the project working!

    Hope this helps another code traveler :-D

    LISTAGG function: "result of string concatenation is too long"

    A new feature added in 12cR2 is the ON OVERFLOW clause of LISTAGG. The query including this clause would look like:

    SELECT pid, LISTAGG(Desc, ' ' ON OVERFLOW TRUNCATE ) WITHIN GROUP (ORDER BY seq) AS desc
    FROM B GROUP BY pid;
    

    The above will restrict the output to 4000 characters but will not throw the ORA-01489 error.

    These are some of the additional options of ON OVERFLOW clause:

    • ON OVERFLOW TRUNCATE 'Contd..' : This will display 'Contd..' at the end of string (Default is ... )
    • ON OVERFLOW TRUNCATE '' : This will display the 4000 characters without any terminating string.
    • ON OVERFLOW TRUNCATE WITH COUNT : This will display the total number of characters at the end after the terminating characters. Eg:- '...(5512)'
    • ON OVERFLOW ERROR : If you expect the LISTAGG to fail with the ORA-01489 error ( Which is default anyway ).

    LISTAGG Enhancements in 12c R2

    Iterating through a golang map

    For example,

    package main
    
    import "fmt"
    
    func main() {
        type Map1 map[string]interface{}
        type Map2 map[string]int
        m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
        //m = map[foo:map[first: 1] boo: map[second: 2]]
        fmt.Println("m:", m)
        for k, v := range m {
            fmt.Println("k:", k, "v:", v)
        }
    }
    

    Output:

    m: map[boo:map[second:2] foo:map[first:1]]
    k: boo v: map[second:2]
    k: foo v: map[first:1]
    

    How to iterate over a TreeMap?

    Using Google Collections, assuming K is your key type:

    Maps.filterKeys(treeMap, new Predicate<K>() {
      @Override
      public boolean apply(K key) {
        return false; //return true here if you need the entry to be in your new map
      }});
    

    You can use filterEntries instead if you need the value as well.

    android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

    Another thing to note is Environment.getExternalStorageDirectory() has been deprecated in API 29, so change this if you're using this to get the database path:

    https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()

    This method was deprecated in API level 29.

    To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.

    How to remove trailing whitespaces with sed?

    To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):

    sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"
    

    Is there a way to comment out markup in an .ASPX page?

    While this works:

    <%-- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ht_tv1.Default" %> --%>
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Blank._Default" %>
    

    This won't.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" <%--Inherits="ht_tv1.Default"--%> Inherits="Blank._Default" %>
    

    So you can't comment out part of something which is what I want to do 99.9995% of the time.

    why $(window).load() is not working in jQuery?

    <script type="text/javascript">
       $(window).ready(function () {
          alert("Window Loaded");
       });
    </script>
    

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

    A much cleaner, safer answer to this problem (you really shouldn't hard code Strings):

    public void openInGallery(String imageId) {
      Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(imageId).build();
      Intent intent = new Intent(Intent.ACTION_VIEW, uri);
      startActivity(intent);
    }
    

    All you have to do is append the image id to the end of the path for the EXTERNAL_CONTENT_URI. Then launch an Intent with the View action, and the Uri.

    The image id comes from querying the content resolver.

    How to get everything after a certain character?

    strtok is an overlooked function for this sort of thing. It is meant to be quite fast.

    $s = '233718_This_is_a_string';
    $firstPart = strtok( $s, '_' );
    $allTheRest = strtok( '' ); 
    

    Empty string like this will force the rest of the string to be returned.

    NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.

    How to correctly implement custom iterators and const_iterators?

    I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.

    You can find it on Github

    Here are the simple steps to creating and using custom iterators:

    1. Create your "custom iterator" class.
    2. Define typedefs in your "custom container" class.
      • e.g. typedef blRawIterator< Type > iterator;
      • e.g. typedef blRawIterator< const Type > const_iterator;
    3. Define "begin" and "end" functions
      • e.g. iterator begin(){return iterator(&m_data[0]);};
      • e.g. const_iterator cbegin()const{return const_iterator(&m_data[0]);};
    4. We're Done!!!

    Finally, onto defining our custom iterator classes:

    NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.

    In this example, I define a random access iterator and a reverse random access iterator:

    1. //-------------------------------------------------------------------
      // Raw iterator with random access
      //-------------------------------------------------------------------
      template<typename blDataType>
      class blRawIterator
      {
      public:
      
          using iterator_category = std::random_access_iterator_tag;
          using value_type = blDataType;
          using difference_type = std::ptrdiff_t;
          using pointer = blDataType*;
          using reference = blDataType&;
      
      public:
      
          blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
          blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
          ~blRawIterator(){}
      
          blRawIterator<blDataType>&                  operator=(const blRawIterator<blDataType>& rawIterator) = default;
          blRawIterator<blDataType>&                  operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
      
          operator                                    bool()const
          {
              if(m_ptr)
                  return true;
              else
                  return false;
          }
      
          bool                                        operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
          bool                                        operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
      
          blRawIterator<blDataType>&                  operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
          blRawIterator<blDataType>&                  operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
          blRawIterator<blDataType>&                  operator++(){++m_ptr;return (*this);}
          blRawIterator<blDataType>&                  operator--(){--m_ptr;return (*this);}
          blRawIterator<blDataType>                   operator++(int){auto temp(*this);++m_ptr;return temp;}
          blRawIterator<blDataType>                   operator--(int){auto temp(*this);--m_ptr;return temp;}
          blRawIterator<blDataType>                   operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
          blRawIterator<blDataType>                   operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
      
          difference_type                             operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
      
          blDataType&                                 operator*(){return *m_ptr;}
          const blDataType&                           operator*()const{return *m_ptr;}
          blDataType*                                 operator->(){return m_ptr;}
      
          blDataType*                                 getPtr()const{return m_ptr;}
          const blDataType*                           getConstPtr()const{return m_ptr;}
      
      protected:
      
          blDataType*                                 m_ptr;
      };
      //-------------------------------------------------------------------
      
    2. //-------------------------------------------------------------------
      // Raw reverse iterator with random access
      //-------------------------------------------------------------------
      template<typename blDataType>
      class blRawReverseIterator : public blRawIterator<blDataType>
      {
      public:
      
          blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
          blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
          blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
          ~blRawReverseIterator(){}
      
          blRawReverseIterator<blDataType>&           operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
          blRawReverseIterator<blDataType>&           operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
          blRawReverseIterator<blDataType>&           operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
      
          blRawReverseIterator<blDataType>&           operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
          blRawReverseIterator<blDataType>&           operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
          blRawReverseIterator<blDataType>&           operator++(){--this->m_ptr;return (*this);}
          blRawReverseIterator<blDataType>&           operator--(){++this->m_ptr;return (*this);}
          blRawReverseIterator<blDataType>            operator++(int){auto temp(*this);--this->m_ptr;return temp;}
          blRawReverseIterator<blDataType>            operator--(int){auto temp(*this);++this->m_ptr;return temp;}
          blRawReverseIterator<blDataType>            operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
          blRawReverseIterator<blDataType>            operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
      
          difference_type                             operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
      
          blRawIterator<blDataType>                   base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
      };
      //-------------------------------------------------------------------
      

    Now somewhere in your custom container class:

    template<typename blDataType>
    class blCustomContainer
    {
    public: // The typedefs
    
        typedef blRawIterator<blDataType>              iterator;
        typedef blRawIterator<const blDataType>        const_iterator;
    
        typedef blRawReverseIterator<blDataType>       reverse_iterator;
        typedef blRawReverseIterator<const blDataType> const_reverse_iterator;
    
                                .
                                .
                                .
    
    public:  // The begin/end functions
    
        iterator                                       begin(){return iterator(&m_data[0]);}
        iterator                                       end(){return iterator(&m_data[m_size]);}
    
        const_iterator                                 cbegin(){return const_iterator(&m_data[0]);}
        const_iterator                                 cend(){return const_iterator(&m_data[m_size]);}
    
        reverse_iterator                               rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
        reverse_iterator                               rend(){return reverse_iterator(&m_data[-1]);}
    
        const_reverse_iterator                         crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
        const_reverse_iterator                         crend(){return const_reverse_iterator(&m_data[-1]);}
    
                                .
                                .
                                .
        // This is the pointer to the
        // beginning of the data
        // This allows the container
        // to either "view" data owned
        // by other containers or to
        // own its own data
        // You would implement a "create"
        // method for owning the data
        // and a "wrap" method for viewing
        // data owned by other containers
    
        blDataType*                                    m_data;
    };
    

    What is the purpose of the word 'self'?

    self is inevitable.

    There was just a question should self be implicit or explicit. Guido van Rossum resolved this question saying self has to stay.

    So where the self live?

    If we would just stick to functional programming we would not need self. Once we enter the Python OOP we find self there.

    Here is the typical use case class C with the method m1

    class C:
        def m1(self, arg):
            print(self, ' inside')
            pass
    
    ci =C()
    print(ci, ' outside')
    ci.m1(None)
    print(hex(id(ci))) # hex memory address
    

    This program will output:

    <__main__.C object at 0x000002B9D79C6CC0>  outside
    <__main__.C object at 0x000002B9D79C6CC0>  inside
    0x2b9d79c6cc0
    

    So self holds the memory address of the class instance. The purpose of self would be to hold the reference for instance methods and for us to have explicit access to that reference.


    Note there are three different types of class methods:

    • static methods (read: functions),
    • class methods,
    • instance methods (mentioned).

    How to cast Object to boolean?

    Assuming that yourObject.toString() returns "true" or "false", you can try

    boolean b = Boolean.valueOf(yourObject.toString())
    

    Search an Oracle database for tables with specific column names?

    To find all tables with a particular column:

    select owner, table_name from all_tab_columns where column_name = 'ID';
    

    To find tables that have any or all of the 4 columns:

    select owner, table_name, column_name
    from all_tab_columns
    where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS');
    

    To find tables that have all 4 columns (with none missing):

    select owner, table_name
    from all_tab_columns
    where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS')
    group by owner, table_name
    having count(*) = 4;
    

    How to force link from iframe to be opened in the parent window

    Yah I found

    <base target="_parent" />
    

    This useful for open all iframe links open in iframe.

    And

    $(window).load(function(){
        $("a").click(function(){
            top.window.location.href=$(this).attr("href");
            return true;
        })
    })
    

    This we can use for whole page or specific part of page.

    Thanks all for your help.

    How can I concatenate two arrays in Java?

    Object[] obj = {"hi","there"};
    Object[] obj2 ={"im","fine","what abt u"};
    Object[] obj3 = new Object[obj.length+obj2.length];
    
    for(int i =0;i<obj3.length;i++)
        obj3[i] = (i<obj.length)?obj[i]:obj2[i-obj.length];
    

    How can I retrieve a table from stored procedure to a datatable?

    string connString = "<your connection string>";
    string sql = "name of your sp";
    
    using(SqlConnection conn = new SqlConnection(connString)) 
    {
        try 
        {
            using(SqlDataAdapter da = new SqlDataAdapter()) 
            {
                da.SelectCommand = new SqlCommand(sql, conn);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
    
                DataSet ds = new DataSet();   
                da.Fill(ds, "result_name");
    
                DataTable dt = ds.Tables["result_name"];
    
                foreach (DataRow row in dt.Rows) {
                    //manipulate your data
                }
            }    
        } 
        catch(SQLException ex) 
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch(Exception e) 
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    

    Modified from Java Schools Example

    What is the difference between '@' and '=' in directive scope in AngularJS?

    Even when the scope is local, as in your example, you may access the parent scope through the property $parent. Assume in the code below, that title is defined on the parent scope. You may then access title as $parent.title:

    link : function(scope) { console.log(scope.$parent.title) },
    template : "the parent has the title {{$parent.title}}"
    

    However in most cases the same effect is better obtained using attributes.

    An example of where I found the "&" notation, which is used "to pass data from the isolated scope via an expression and to the parent scope", useful (and a two-way databinding could not be used) was in a directive for rendering a special datastructure inside an ng-repeat.

    <render data = "record" deleteFunction = "dataList.splice($index,1)" ng-repeat = "record in dataList" > </render>
    

    One part of the rendering was a delete button and here it was useful to attach a deletefunction from the outside scope via &. Inside the render-directive it looks like

    scope : { data = "=", deleteFunction = "&"},
    template : "... <button ng-click = "deleteFunction()"></button>"
    

    2-way databinding i.e. data = "=" can not be used as the delete function would run on every $digest cycle, which is not good, as the record is then immediately deleted and never rendered.

    Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

    Just add

    spring.flyway.enabled=false
    

    in application.properties file if you do not want flyway to check the checksum every time you run the application.

    Regex expressions in Java, \\s vs. \\s+

    The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

    Greedy quantifiers
    X?  X, once or not at all
    X*  X, zero or more times
    X+  X, one or more times
    X{n}    X, exactly n times
    X{n,}   X, at least n times
    X{n,m}  X, at least n but not more than m times
    
    Reluctant quantifiers
    X?? X, once or not at all
    X*? X, zero or more times
    X+? X, one or more times
    X{n}?   X, exactly n times
    X{n,}?  X, at least n times
    X{n,m}? X, at least n but not more than m times
    
    Possessive quantifiers
    X?+ X, once or not at all
    X*+ X, zero or more times
    X++ X, one or more times
    X{n}+   X, exactly n times
    X{n,}+  X, at least n times
    X{n,m}+ X, at least n but not more than m times
    

    What does the 'Z' mean in Unix timestamp '120314170138Z'?

    "Z" doesn't stand for "Zulu"

    I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):

    Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.

    Hiding elements in responsive layout?

    Bootstrap 4 Beta Answer:

    d-block d-md-none to hide on medium, large and extra large devices.

    d-none d-md-block to hide on small and extra-small devices.

    enter image description here

    Note that you can also inline by replacing d-*-block with d-*-inline-block


    Old answer: Bootstrap 4 Alpha

    • You can use the classes .hidden-*-up to hide on a given size and larger devices

      .hidden-md-up to hide on medium, large and extra large devices.

    • The same goes with .hidden-*-down to hide on a given size and smaller devices

      .hidden-md-down to hide on medium, small and extra-small devices

    • visible-* is no longer an option with bootstrap 4

    • To display only on medium devices, you can combine the two:

      hidden-sm-down and hidden-xl-up

    The valid sizes are:

    • xs for phones in portrait mode (<34em)
    • sm for phones in landscape mode (=34em)
    • md for tablets (=48em)
    • lg for desktops (=62em)
    • xl for desktops (=75em)

    This was as of Bootstrap 4, alpha 5 (January 2017). More details here: http://v4-alpha.getbootstrap.com/layout/responsive-utilities/

    On Bootstrap 4.3.x: https://getbootstrap.com/docs/4.3/utilities/display/

    Escaping Strings in JavaScript

    Use encodeURI()

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

    Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.

    How to remove "disabled" attribute using jQuery?

    Use like this,

    HTML:

    <input type="text" disabled="disabled" class="inputDisabled" value="">
    
    <div id="edit">edit</div>
    

    JS:

     $('#edit').click(function(){ // click to
                $('.inputDisabled').attr('disabled',false); // removing disabled in this class
     });
    

    lexical or preprocessor issue file not found occurs while archiving?

    I had this problem after changed project name. I used all the methods mentioned on the internet but still doesn't work. Then I realized that all the header files not found was from cocoapods, so I re-installed the cocoapods using pod install, and thus solved the problem.

    Hope this could help.

    How can I get Docker Linux container information from within the container itself?

    I've found that in 17.09 there is a simplest way to do it within docker container:

    $ cat /proc/self/cgroup | head -n 1 | cut -d '/' -f3
    4de1c09d3f1979147cd5672571b69abec03d606afcc7bdc54ddb2b69dec3861c
    

    Or like it has already been told, a shorter version with

    $ cat /etc/hostname
    4de1c09d3f19
    

    Or simply:

    $ hostname
    4de1c09d3f19
    

    TypeError: $ is not a function WordPress

    Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.

    1. Wrap your code using:

      <script> 
      jQuery(function($) {
      
      YOUR CODE GOES HERE
      
      });
      </script>
      
    2. You can also use jQuery's API using noConflict();

      <script>
      $.noConflict();
      jQuery( document ).ready(function( $ ) {
      // Code that uses jQuery's $ can follow here.
      });
      // Code that uses other library's $ can follow here.
      </script>
      
    3. Another example of using noConflict without using document ready:

      <script>
      jQuery.noConflict();
          (function( $ ) {
              $(function() { 
                  // YOUR CODE HERE
              });
           });
      </script>
      
    4. You could even choose to create your very alias to avoid conflicts like so:

      var jExample = jQuery.noConflict();
      // Do something with jQuery
      jExample( "div p" ).hide();
      
    5. Yet another longer solution is to rename all referances of $ to jQuery:

      $( "div p" ).hide(); to jQuery( "div p" ).hide();

    compareTo with primitives -> Integer / int

    May I propose a third

    ((Integer) a).compareTo(b)  
    

    I want to show all tables that have specified column name

    Pretty simple on a per database level

    Use DatabaseName
    Select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'ColName'