text:
Q: Firebase Cloud Functions to send an HTTP request on a user sign-in trigger? I'm sorry, but I've watched all seven of Jennifer Person's videos, read the documentation, and worked through the tutorials but I still don't see how to write my function. I'm trying to write a function that gets an IBM Watson Speech-to-text token, which is obtained with this CURL script:
curl -X GET --user username:password --output token
"https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"

I.e., send an HTTP GET request to the URL, provide my username and password, and then write the output to the file /javascript/services/token.
This is my guess as to the function. An authentication trigger wraps a Nodejs HTTP GET request, and a NodeJs file save fs.writefile.
const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.getWatsonToken = functions.auth.user().onCreate(event => { // authentication trigger

  var https = require('https');  // Nodejs http.request

  var options = {
    host: 'stream.watsonplatform.net',
    path: '/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api',
    username: groucho,
    password: swordfish
  };

  callback = function(response) {
    response.on('end', function () {
      console.log(response);
      fs.writeFile("/javascript/services/token", response);
    });
  }

  http.request(options, callback).end();

});

A: This function works:
// Node modules
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request'); // node module to send HTTP requests
const fs = require('fs');

admin.initializeApp(functions.config().firebase);

exports.getWatsonToken = functions.database.ref('userLoginEvent').onUpdate(event => { // authentication trigger when user logs in

  var username = 'groucho',
      password = 'swordfish',
      url = 'https://' + username + ':' + password + '@stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api';

  request({url: url}, function (error, response, body) {

    var tokenService = "app.value('watsonToken','" + body + "');";

    fs.writeFile('../public/javascript/services/watsonTokenValue.js', tokenService, (err) => {
      if (err) throw err;
        console.log('The file has been saved!');
    }); // close fs.writeFile

  }); // close request

}); // close getWatsonToken

In the controller:
 firebase.auth().onAuthStateChanged(function(user) { // this runs on login
    if (user) { // user is signed in
      console.log("User signed in!");
      $scope.authData = user;
      firebase.database().ref('userLoginEvent').update({'user': user.uid}); // update Firebase database to trigger Cloud Function to get a new IBM Watson token
    } // end if user is signed in
    else { // User is signed out
      console.log("User signed out.");
    }
  }); // end onAuthStateChanged

Walking through the Cloud Function, it injects four Node modules, including request for sending HTTP requests, and fs for writing the results to a file. Then the trigger is set for an update to a location userLoginEvent in the Firebase database (which I created from the console). Next, the HTTP request goes out. The response (the token) is called body.app.value('watsonToken','" + body + "'); is an Angular value service to wrap the token. Then fs writes all this to a location in my project.
In the AngularJS controller, onAuthStateChanged triggers when a user logins in. The user.uid is then updated to the location userLoginEvent in the Firebase database, and the Cloud Function triggers, the HTTP request goes out, and the response is written to an Angular service.


text:
Q: Reading data from a website passing parameters import requests
from lxml import html
from bs4 import BeautifulSoup

session_requests = requests.session()

sw_url = "https://www.southwest.com"
sw_url2 = "https://www.southwest.com/flight/select-flight.html?displayOnly=&int=HOMEQBOMAIR"
#result = session_requests.get(sw_url)

#tree = html.fromstring(result.text)

payload = {"name":"AirFormModel","origin":"MCI","destination":"DAL","departDate":"2018-02-28T06:00:00.000Z","returnDate":"2018-03-03T06:00:00.000Z","tripType":"true","priceType":"DOLLARS","adult":1,"senior":0,"promoCode":""}

#{
#    'origin': 'MCI',
#   'destination': 'DAL',
#   'departDate':'2018-02-28T06:00:00.000Z',
#   'returnDate':'2018-03-01T06:00:00.000Z',
#   'adult':'1'
#}

p = requests.post(sw_url,params=payload)
#print(p.text)
print(p.content)
p1 = requests.get(sw_url2)
soup = BeautifulSoup(p.text,'html.parser')

print(soup.find("div",{"class":"productPricing"}))
pr = soup.find_all("span",{"class":"currency_symbol"})

for tag in pr:
    print(tag)
    print('++++')
    print(tag.next_sibling)

print(soup.find("div",{"class":"twoSegments"}))

soup = BeautifulSoup(p1.text,'html.parser')

print(soup.find("div",{"class":"productPricing"}))
pr = soup.find_all("span",{"class":"currency_symbol"})

for tag in pr:
    print(tag)
    print('++++')
    print(tag.next_sibling)

print(soup.find("div",{"class":"twoSegments"}))

I need to retrieve prices for flights between 2 locations on specific dates. I identified the parameters by looking at the session info from inspector of the browser and included them in the post request.
I am not sure what I'm doing wrong here, but I am unable to read the data from the tags correctly. It's printing none.

Edit : 4/25/2018
I'm using the following code now, but it doesn't seem to help. Please advise.
import threading
from lxml import html
from bs4 import BeautifulSoup
import time
import datetime
import requests

def worker(oa,da,ods):
    """thread worker function"""
    print (oa + ' ' + da + ' ' + ods + ' ' +  str(datetime.datetime.now()))
    url = "https://www.southwest.com/api/air-booking/v1/air-booking/page/air/booking/shopping"
    rh = {
    'accept': 'application/json,text/javascript,*/*;q=0.01',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.5',
    'cache-control': 'max-age=0',
    'content-length': '454',
    'content-type': 'application/json',
    'referer': 'https://www.southwest.com/air/booking/select.html?originationAirportCode=MCI&destinationAirportCode=LAS&returnAirportCode=&departureDate=2018-05-29&departureTimeOfDay=ALL_DAY&returnDate=&returnTimeOfDay=ALL_DAY&adultPassengersCount=1&seniorPassengersCount=0&fareType=USD&passengerType=ADULT&tripType=oneway&promoCode=&reset=true&redirectToVision=true&int=HOMEQBOMAIR&leapfrogRequest=true',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
    }

    fd = {
    'returnAirport':'',
    'twoWayTrip':'false',
    'fareType':'DOLLARS',
    'originAirport':oa,
    'destinationAirport':da,
    'outboundDateString':ods,
    'returnDateString':'',
    'adultPassengerCount':'1',
    'seniorPassengerCount':'0',
    'promoCode':'',
    'submitButton':'true'
    }
    with requests.Session() as s:
        r = s.post(url,headers = rh )
#        soup = BeautifulSoup(r.content,'html.parser')
#        soup = BeautifulSoup(r.content,'lxml')
        print(r)
        print(r.content)
    print (oa + ' ' + da + ' ' + ods + ' ' + str(datetime.datetime.now()))
    return

#db = MySQLdb.connect(host="localhost",user="root",passwd="vikram",db="garmin")
rcount = 0

tdelta = 55
#print(strt_date)
threads = []
count = 1
thr_max = 2
r = ["MCI","DEN","MCI","MDW","MCI","DAL"]

strt_date = (datetime.date.today() + datetime.timedelta(days=tdelta)).strftime("%m/%d/%Y")

while count < 2:
    t = threading.Thread(name=r[count-1]+r[count],target=worker,args=(r[count-1],r[count],strt_date))
    threads.append(t)
    t.start()
    count = count + 2

A: When you say looked at the session info from inspector of the browser, I'm assuming you meant the network tab. If that's the case, are you sure you noted the data being sent properly?
Here's the URL that gets sent by the browser, following which the page you required is fetched:
url = 'https://www.southwest.com/flight/search-flight.html'

You didn't use headers in your request, which, in my opinion, should be passed compulsorily in some cases. Here are the headers that the browser passes:
:authority:www.southwest.com
:method:POST
:path:/flight/search-flight.html
:scheme:https
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.9
cache-control:max-age=0
content-length:564
content-type:application/x-www-form-urlencoded
origin:https://www.southwest.com
referer:https://www.southwest.com/flight/search-flight.html?int=HOMEQBOMAIR
upgrade-insecure-requests:1
user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36

Note:

*

*I removed the cookie header, because that would be taken care of by requests if you're using session.

*The first four headers (those that begin with a colon (':')) cannot be passed in Python's requests; so, I skipped them.
Here's the dict that I used to pass the headers:
rh = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'cache-control': 'max-age=0',
    'content-length': '564',
    'content-type': 'application/x-www-form-urlencoded',
    'origin': 'https://www.southwest.com',
    'referer': 'https://www.southwest.com/flight/search-flight.html?int=HOMEQBOMAIR',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
}

And here is the form data sent by browser:
fd = {
    'toggle_selfltnew': '',
    'toggle_AggressiveDrawers': '',
    'transitionalAwardSelected': 'false',
    'twoWayTrip': 'true',
    'originAirport': 'MCI',
    # 'originAirport_displayed': 'Kansas City, MO - MCI',
    'destinationAirport': 'DAL',
    # 'destinationAirport_displayed': 'Dallas (Love Field), TX - DAL',
    'airTranRedirect': '',
    'returnAirport': 'RoundTrip',
    'returnAirport_displayed': '',
    'outboundDateString': '02/28/2018',
    'outboundTimeOfDay': 'ANYTIME',
    'returnDateString': '03/01/2018',
    'returnTimeOfDay': 'ANYTIME',
    'adultPassengerCount': '1',
    'seniorPassengerCount': '0',
    'promoCode': '',
    'fareType': 'DOLLARS',
    'awardCertificateToggleSelected': 'false',
    'awardCertificateProductId': ''
}

Note that I commented out two of the items above, but it didn't make any difference. I assumed you'd be having only the location codes and not the full name. If you do have them or if you can extract them from the page, you can send those as well along with other data.
I don't know if it makes any difference, but I used data instead of params:
with requests.Session() as s:
    r = s.post(url, headers = rh, data = fd)
    soup = BeautifulSoup(r.content, 'lxml')

Finally, here is the result:
>>> soup.find('span', {'class': 'currency_symbol'}).text
'$'

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have defined a function to rank schools by the sat_score criteria, but this function doesn't work def score(school):
    school = combined['SCHOOL NAME']
    for row in school:
        schools = combined[combined['SCHOOL NAME'] == row]
        if schools['sat_score'].iloc[0]>= 1500.0:
            return 'high score'
        elif (schools['sat_score'].iloc[0] > 1100.0) & (schools['sat_score'].iloc[0]< 1500.0):
            return 'medium_score'

        else:
            schools['sat_score'].iloc[0] <=1100.0
            return 'poor_score'

combined['ranking_school'] = combined['sat_score'].apply(score)

This function yield only 'medium_score' in all the numbers of the data series combined['ranking_school']. Instead, have to outcome the 3 possibilities that are: high_score, medium_score, and poor_score.
If someone could help with this, it will be so nice!!!
Regards


text:
Q: Why isn't my if statement working properly? I'm writing a program that finds whether a word/phrase up to 8 characters is a palindrome. No matter what I put in as input, even if it is a palindrome, my program prints my else statement. I checked and made sure the code I wrote actually prints the input in reverse and it does. So I'm not quite sure what the problem is.
import java.util.Scanner;
public class hw5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word, newWord;
int lengthOfWord;
char lc;//last character

    System.out.print("Enter word/phrase of 8 characters or less: ");
    word = in.nextLine();

    word = word.toLowerCase();
    newWord = word;
    lengthOfWord = word.length();
    lc = word.charAt(lengthOfWord -1);

    lc = word.charAt(lengthOfWord -1);

    if (word.length() == 2)
        newWord = lc+word.substring(0,1);
    else if (word.length() == 3)
        newWord = lc+word.substring(1,2)+word.substring(0,1);
    else if (word.length() == 4)
        newWord = lc+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
    else if (word.length() == 5)
        newWord = lc+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
    else if (word.length() == 6)
        newWord = lc+word.substring(4,5)+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
    else if (word.length() == 7)
        newWord = lc+word.substring(5,6)+word.substring(4,5)+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
    else if (word.length() == 8)
        newWord = lc+word.substring(6,7)+word.substring(5,6)+word.substring(4,5)+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
    else
        newWord = "error, not enough or too many characters";

    if (newWord == word)
        System.out.println("it is a palindrome");
    else
        System.out.println("it is not a palindrome");

    System.out.println(newWord);

A: You could make it a lot simpler.
word = word.toLowerCase();
newWord = new StringBuilder(word).reverse().toString();

if (newWord.equals(word))
     System.out.println("it is a palindrome");
 else
      System.out.println("it is not a palindrome");

A: == means the runtime will check if they are pointing to the same address, equals will check if the two objects have the same content. So try to use the equals method to compare Strings and == for numbers.

A: Strings are objects.  And the string variables are merely pointers to the string object.  So, when you do if(newWord==word), you're not comparing the contents of the strings, rather you're comparing the value in these pointers (the memory location the pointers point too).  You need to use String's equals method in order to compare the contents of two strings.

A: if (newWord.equals(word))
        System.out.println("it is a palindrome");
else
        System.out.println("it is not a palindrome");

When you use ==, the words are not compared, what is compared is the index of the two variables in memory.


text:
Q: BufferedReader no longer buffering after a while? Sorry I can't post code but I have a bufferedreader with 50000000 bytes set as the buffer size. It works as you would expect for half an hour, the HDD light flashing every two minutes or so, reading in the big chunk of data, and then going quiet again as the CPU processes it. But after about half an hour (this is a very big file), the HDD starts thrashing as if it is reading one byte at a time. It is still in the same loop and I think I checked free ram to rule out swapping (heap size is default).
Probably won't get any helpful answers, but worth a try.
OK I have changed heap size to 768mb and still nothing. There is plenty of free memory and java.exe is only using about 300mb.
Now I have profiled it and heap stays at about 200MB, well below what is available. CPU stays at 50%. Yet the HDD starts thrashing like crazy. I have.. no idea. I am going to rewrite the whole thing in c#, that is my solution.
Here is the code (it is just a throw-away script, not pretty):
    BufferedReader s = null;
    HashMap<String, Integer> allWords = new HashMap<String, Integer>();
    HashSet<String> pageWords = new HashSet<String>();
    long[] pageCount = new long[78592];
    long pages = 0;

    Scanner wordFile = new Scanner(new BufferedReader(new FileReader("allWords.txt")));
    while (wordFile.hasNext()) {
        allWords.put(wordFile.next(), Integer.parseInt(wordFile.next()));
    }
    s = new BufferedReader(new FileReader("wikipedia/enwiki-latest-pages-articles.xml"), 50000000);
    StringBuilder words = new StringBuilder();
    String nextLine = null;
    while ((nextLine = s.readLine()) != null) {
        if (a.matcher(nextLine).matches()) {
            continue;
        }
        else if (b.matcher(nextLine).matches()) {
            continue;
        }
        else if (c.matcher(nextLine).matches()) {
            continue;
        }
        else if (d.matcher(nextLine).matches()) {
            nextLine = s.readLine();
            if (e.matcher(nextLine).matches()) {
                if (f.matcher(s.readLine()).matches()) {
                    pageWords.addAll(Arrays.asList(words.toString().toLowerCase().split("[^a-zA-Z]")));
                    words.setLength(0);
                    pages++;
                    for (String word : pageWords) {
                        if (allWords.containsKey(word)) {
                            pageCount[allWords.get(word)]++;
                        }
                        else if (!word.isEmpty() && allWords.containsKey(word.substring(0, word.length() - 1))) {
                            pageCount[allWords.get(word.substring(0, word.length() - 1))]++;
                        }
                    }
                    pageWords.clear();
                }
            }
        }
        else if (g.matcher(nextLine).matches()) {
            continue;
        }
        words.append(nextLine);
        words.append(" ");
    }

A: Have you tried removing the buffer size and trying it out with the defaults?

A: It may be not that the file buffering isn't working, but that your program is using up enough memory that your virtual memory system is page swapping to disk. What happens if you try with a smaller buffer size? What about larger?

A: I'd bet that you are running out of heap space and you are getting stuck doing back to back GC's.  Have you profiled the app to see what is going on during that time?  Also, try running with -verbose:gc to see garbage collection as it happens.  You could also try starting with a larger heap like"
-Xms1000m -Xmx1000m
That will give you 1gb of heap so if you do use that all up, it should be much later than it is currently happening.

A: It appears to me that if the file you are reading is very large, then the following lines could result in a large portion of the file being copied to memory via a StringBuilder.  If the process' memory footprint becomes too large, you will likely swap and/or throw your garbage collector into a spin.
...
words.append(nextLine);
words.append(" ");

A: Hopefully this may help: http://www.velocityreviews.com/forums/t131734-bufferedreader-and-buffer-size.html

A: Before you assume there is something wrong with Java and reading IO, I suggest you write a simple program which just reads the file as fast as it can.  You should be able to read the file at 20 MB/s or more regardless of file size with default buffering.  You should be able to do this by stripping down your application to just read the file.  Then you can prove to yourself how long it takes to read the file.
You have used quite a lot of expensive operations.  Perhaps you should look at how you can make your parser more efficient using a profiler.  e.g.
word.substring(0, word.length() - 1)

is the same as
word

so the first if clause and the second are the same.


text:
Q: "-k" option for "ls -l" commnad I can not use "-k" option for ls -l commnad.
   -k, --kibibytes
          use 1024-byte blocks

There is an option explanation in man ls like above.
So I guess that this option is valid.
However, there is no difference of output between ls -l and ls -lk.
Could anyone teach me how to validate "-k" option?

A: Older versions of ls(1) have a different description of the -k option, which I find more accurate:

-k     like --block-size=1K

--block-size=SIZE
          scale   sizes   by   SIZE   before   printing    them.     E.g.,
          `--block-size=M'  prints sizes in units of 1,048,576 bytes.  See
          SIZE format below.

That means -k will lead to ls displaying all file sizes divided by 1024. This may be overridden by other (implicit) options like -h (which displays file sizes "human readable", i. e. scaled depending on their size and with a scale suffix (K, M, G, T, …)).
You can determine, whether ls is an alias with default command line arguments with alias ls. You can circumvent the alias and run the command directly with command ls -l.


text:
Q: Detecting Missing Objects I want to detect missing objects of an image. Here is the situation

*

*You have an image of a room. There is a ball in the room.

*You have another image of the same room (Light conditions similar). The only difference is, the ball is missing.

*Now I need to opencv to compare these 2 images and find what is missing.

I know the first step of doing this, and that is calculating the histogram of both the images and comparing them . If something is missing from the second image, then the histogram values will differ.
Now, how to detect that "ball" is missing? Using template matching?

A: As stated in comments, you can easily subtract those 2 images. IIRC Mat has overloaded - [minus] operator. So sub = img1 - img2; should be enough as long as imgs are cv::Mat objects.
About the blobs take a look at following tutorials at OpenCV website:
http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html
http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/hull/hull.html
http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html


text:
Q: How to use PURGE option in Pyspark Snowflake Connector? How to use the PURGE option in pyspark-snowflake connector options? I am using the below configurations-
df.write.mode('overwrite') \
        .format(SNOWFLAKE_SOURCE_NAME) \
        .options(sfURL=[url],
                 sfUser=[user],
                 sfDatabase=[database],
                 sfSchema=[schema],
                 sfWarehouse=[warehouse],
                 sfRole=[role],
                 pem_private_key=pkb) \
        .option('truncate_table', 'ON') \
        .option('usestagingtable', 'OFF') \
        .option('continue_on_error', 'on') \
        .option('purge', 'off') \
        .option('dbtable', [dbtable]) \
        .save()

But it seems like the temporary file that is being generated while loading data from py-spark to snowflake is getting deleted every time we are loading the data.
I read it in the snowflake documentation that if the purge option is off then it should not delete that file.
Please let me know how to use this option in spark snowflake connector.
Thanks

A: df.write.mode('overwrite')  change this to df.write.mode('append')  // overwrite will by default delete the existing files first and save the new files


text:
Q: How to show the profile (user,super user,Admin) information based on the user type in dashboard page using angular Project In my angular application I have created the Dashboard page ,super user dashboard and admin dashboard pages. Super user and admin dashboard pages having the same data as dashboard page and some extra tables on it.That's why I have created the admin and components page as and some tables data in component.html page
And I have used the same navigation links(about,notifications,profile,logout) bar for all the dashboards which I have placed in basic Dashboard page.
Now I want to show the profile information based on the usertype(user,superuser,admin)when we click on the profile link.
I have created the page for profile link in navbar.something like:
profile.component.html

Username:

EmailId:

First name:

Last name:

Last login:

And I have called the user profile with GET method,I have got the details as
usertype,firstname,lastname,email-id,last-login details.
Now I want to place the details of user or super user or admin details in profile page when we click on that profile link based on the usertype from the get method API.
Navigation links in dashboard page:
dashboard.component.html

          Home (current)

           About

           Notifications {{ncount}}

        Profile

        Logout

I have tried many ways but not working Can anyone help me regarding this.

A: Create a separate section for each type of user profile, and check conditions.
profile.component.html

 // Super User profile section.

Username:

  ...
 //etc

 // Admin profile section.

Username:

  ...
 //etc

 // User profile section.

Username:

  ...
 //etc


text:
Q: How to Run chokidar in the background (persistent: true)? I am writing a node.js program that needs to watch for (add/delete/update) files in a folder. I am using chokidar for watching the files. Here's the code
async function updateIndexFile() {
    console.log({ path });
    const pathArray = []

    // Chokidar Code
    const options = {
      ignored: /(^|[\/\\])\../, // ignore dotfiles
      persistent: true
    }

    // Initialize watcher.
    const watcher = chokidar.watch(path, options);

    watcher
      .on('add', async (path) => {
        console.log(`File ${path} has been added`)
        let answer = await prompt({
          type: 'list',
          name: 'adventure',  // * Key
          message: 'Choose your own adventure',
          choices: ['Indexify', 'Undo'] // * Add Feature Names Here
        })
        console.log(answer);
      })  // Run indexify again on these files
      .on('change', path => console.log(`File ${path} has been changed`)) // Run indexify again on these files
      .on('unlink', path => console.log(`File ${path} has been removed`));  // Run indexify again on these files

But, I cant use the terminal as chokidar is watching the files. So, I want chokidar to watch files in the background. So, I can still prompt the user for more questions and do my stuff.

A: I know i am 3 months late , and you probably had found you answer by now, but this is for anyone who is visiting later.
You can use spawn child process using node module called.
simple put your code in a file and execute that file using below code
 const {spawn}=require(child_prcoess);
let detached_process = spawn(process.argv[0], ["program_name", "arg1","arg2","arg3"], { detached: true}); //launch program_name and detach it from program_name with args provided

            detached_process.unref(); //tell main program to do not wait for the completion of program_name


text:
Q: If inflater is not blocking, then how do I know when it's done? I have a situation where my inflation is fairly tasking (I'm populating a custom date module, that has 3 spinners filled with cusom views, for Month, Date, Year) and as a result the ViewFlipper that this RelativeLayout is being inflated into skips 90% of its animation (the view is supposed to slide in from the right, but instead just appears almost entirely finished in its motion and just animates the last few pixels to the Left).
I'm looking around and not seeing anything in the way of onCompletedInflation or anything like that.  But clearly either the the inflate() or the addView() call is async because if it wasn't then there would simply be a pause while it did its work and then the View would animate in smoothly (as it does if the View is simply included in the XML).
So, my question is, how do I prevent the animation from starting until I know for sure that all the inflation and view addition has completed, so that I can get a smooth Flipper animation, rather than just seeing the last few "frames" of the animation after the Main thread has caught up with all it's trying to do?


text:
Q: When is Spring @Conditional checked We are using Spring Boot 2.6.13 with Java 11 and our application has to connect to an external service. On some environments, we have to use a corporate proxy.
In order to make the application flexible, I thought of creating 2 beans. One with a proxy, the other without.
@Bean
public HttpHost getProxyHost() {
    return null;
}

@Bean
@Primary
@ConditionalOnProperty(name = "application.proxy-url")
public HttpHost getProxyHost(
        ApplicationConfiguration applicationConfiguration
) {
    return new HttpHost(
            applicationConfiguration.getProxyUrl(),
            applicationConfiguration.getProxyPort(),
            applicationConfiguration.getProxyScheme()
    );
}

I would think that Spring only makes the second bean if the proxy-url field is filled in. However, it creates the bean every time. Problem there is that if applicationConfiguration.getProxyUrl() returns null, a NullPointerException is thrown and the application is unable to startup.
There is a solution where I use an if statement, check the value and return null if the url is null. But I thought this IoC way would look cleaner.
I have tried searching online on how/when Spring is checking the @Conditional annotations, but haven't found much (without going through it's source code).
Thanks in advance!


text:
Q: Saxon/X PHP API Stylesheet compilation failed - get useful error notice I use in my PHP the Saxon/C API as XSLT 2.0 Processor version 1.0.0. I used Version 0.3, which compiled my Stylesheets perfectly. Unfortunately 0.3 had a bug in one function I needed, so I upgraded to 1.0.0. The bug is gone but now it does not compile my XSTL and says
net.sf.saxon.s9api.SaxonApiException : Stylesheet compilation failed: 1 error reported

which is absolutely not helpful. The stylesheet includes dozens of files and is really complex (otherwise I would use libxml) so I don't have the slightiest chance to find out what's wrong (or post it here) without a proper error message.
So, how can I get an error Message I could work with?
Thanks in advance!
--
My PHP code (rather the example mentioned here):
$saxonProc = new \Saxon\SaxonProcessor();
$saxon = $saxonProc->newXsltProcessor();
$saxon->setSourceFromFile('source.xml');
$saxon->compileFromFile('style.xml');
$result = $saxon->transformToString();

if($result == NULL) {
    $errCount = $saxon->getExceptionCount();
    if($errCount > 0 ){
        for($i = 0; $i < $errCount; $i++) {
            $errCode = $saxon->getErrorCode(intval($i));
            $errMessage = $saxon->getErrorMessage(intval($i));
            echo 'Error: Code='.$errCode.' Message='.$errMessage;
        }
        $saxon->exceptionClear();
    }
}

echo $result;

$saxon->clearParameters();
$saxon->clearProperties();

The  beginning of the stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:t="http://www.tei-c.org/ns/1.0"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   exclude-result-prefixes="t" version="2.0">
   <xsl:output method="xml" encoding="UTF-8"/>

   <xsl:include href="global-varsandparams.xsl"/>

A: The exact error details should appear in apache log file. Also the cumulated errors should be accessible via the getErrorCode and getErrorMessage. I see you have calls to that in your example. If it is not appearing here then I suspect this is a bug worth submitting.


text:
Q: Python PyQt dynamic widget generation using multithread I am writing a simple program that reads new input being written to a file and displays it in popup windows.
I am using PyQt5 for:
A) File changes (QtCore)
B) Window (QtWidgets)

Note that I do actually have a working model using signals as per PyQt reference guide. But couldn't figured out the below, therefore I am not understanding how things works.

While testing implementations i came across with multi-thread issues.
This is a simplified example of my problem:
from PyQt5 import QtWidgets
import sys
import threading

def additem(window):
    """ generates label in window at bottom """
    print("Adding label to window on thread {}".format(threading.currentThread()))
    row = window.layout().rowCount() + 1
    btn = QtWidgets.QPushButton('button_' + str(row), window)
    window.layout().addWidget(btn,row,1)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    w.setLayout(QtWidgets.QGridLayout())
    # set to timers after 3,6 will generate label in window
    threading.Timer(3,additem,args=(w,)).start()
    threading.Timer(6,additem,args=(w,)).start()
    w.show()
    sys.exit(app.exec_())

Output:

Adding label to window
  QObject::setParent: Cannot set parent, new parent is in different thread

I tried setting global queue to pass around objects but still same error.
Although I now why the exception is raised, I do not understand how to avoid it.
One attempt was to directly pass the top object "app" and then getting the window by index (app is the top parent):
...
threading.Timer(3,additem,args=(app,)).start()
...

def additem(app):
    w = app.allWidgets()[0]
    ...

I know PyQt is a C library wrapped in python but I am not familiar with C. The app object is a pointer to the object in the memory heap,
why it can't manipulate the object?
is the object being copied in a new thread? (thought I could still "update" that object)


text:
Q: Recommended Fonts for Programming? What fonts do you use for programming, and for what language/IDE?  I use Consolas for all my Visual Studio work, any other recommendations?

A: Inconsolata 14pt in TextMate

A: I like Profont, I first came across it when Jeff blogged about programming fonts

A: I've really fallen in love with Droid Sans Mono.

A: I like Consolas too, but I also like Anonymous:  http://www.ms-studio.com/FontSales/anonymous.html

A: Adding a vote for Consolas. It feels very easy on my eyes.

A: I never found a reason to stray from Courier New. I don't think I'd have a problem with any font so long as it's sans-serif. Mono-spaced fonts are nice for coding, too.

A: I use a proportional font too.  They seem good for the same reasons they work in books and magazines: the more variation between characters, the easier it is for the brain to distinguish them; and you can fit more on the screen.  Indentation still works fine: 6 leading spaces is still twice as wide as 3 leading spaces.
I use a version of Georgia that I hacked to make the lower case "l" look less like the digit "1", and put a slash through the zero.

A: I really really like DejaVu Sans Mono. It is very clean and easy on the eyes.

A: +1 for Monaco
alt text http://img.skitch.com/20080908-nmjji28uerreqpprs1h86gxna9.png
Just beautiful and I find I can read it for hours on end.

A: I think the anti-aliasing blur on Consolas is caused by monitors which do not have ClearType enabled. Consolas was designed for ClearType.
[Jeff A: indeed, you can see screenshots of this in a post I wrote on this topic.]

A: Two pages where there's a long list of programming fonts are these pages on keithdevens.com and lowing.org (dead link, but it's in the internet archive)
Some other discussions of programming fonts that may have more suggestions are the comments to this blog post on typographica and this topic on a text editor's forum.
Personally I like Triskweline:
alt text http://www.netalive.org/tinkering/triskweline/shot.gif

A: Instead of just chiming in with another vote for a particular font, I'd recommend reading these comparisons of programming fonts where you can learn a little more:
Jeff Atwood's excellent "round-up":
http://www.codinghorror.com/blog/archives/000157.html
Another review of 5 fonts with nice screenshots:
http://blog.hamstu.com/2008/02/03/the-typography-of-code/

A: I use Consolas for everything, including Notepad++, SQL Studio, Eclipse, etc. I wish there was a Mac version. Also, if you notice, the text area field on Stack Overflow uses Consolas, so we have some other fans out there as well :p

A: DejaVu Sans Mono (sometimes known as Panic Sans), size 11, anti-alised. Previously I only used fonts that weren't anti-aliased, but it just seems to work for this font.

A: I like Envy Code R.

A: Verdana - Variable width and easy to read on screen at small sizes.

A: Back in my Mac LC days I swore by Monaco 9pt, mostly for it's slashed 0. I never quite got used to the default line-height though.
monaco sample http://www.k8zt.com/ham_fonts/monaco.jpg
It's a little hard to track down in the original non-OS-X version.

A: +1 for Consolas, together with a proper Color Scheme (I use the white one at the first screenshot)

A:
I never found a reason to stray from Courier New. I don't think I'd have a problem with any font so long as it's sans-serif. Mono-spaced fonts are nice for coding, too.

Courier New has serifs.

A: Lucida Sans Typewriter

A: Another vote for Consolas.  My favorite IDE font at the moment.

A: Raize Font

The Raize Font is a clean, crisp, fixed-pitched sans serif screen font that is much easier to read than the fixed pitched fonts that come with Windows. Ideally suited for programming, scripting, html writing, etc., the Raize Font can be used in any IDE or text editor.

A: Monaco, 11pt, antialias, on Mac OS X. Looks ever better, and crisper on darker backgrounds.
alt text http://www.fabernitor.net/ayaz/monaco11pt.png

A: Consolas. Italic for comments. Only way. Nahh just kidding, the best programming font is this! Here's your first C program:
The image link must not be working, tell me in a comment http://img40.imageshack.us/img40/8008/picture1iqv.png

Recommended for high readability.

A: +1 for Monaco, although this blog post is making me think about switching to Inconsolata.
I'm curious as to what point size y'all use, I use the TextMate default size of 12pt.

A: I use Bitstream Vera Sans Mono, but you need to activate ClearType to get it readable .
I like the 'Illegal1 = O0' readablility test, mentioned earlier in this thread, thanks for that.

A: Anarch, 32 points, ofcourse. Code with style!
anarch http://img525.imageshack.us/img525/1584/ss42po1.jpg

A: For UltraEdit and anything for that matter, I use the good old Courier New.
alt text http://www.identifont.com/samples/microsoft/CourierNew.gif
I've found Consolas to difficult to read with it's over anti-aliasing.

A: I use Lucida Console for years and never find anything better.
However I tried a few times Consolas fonts and simply -- I prefer Lucida Console.

A: I like Terminus for some command line stuff, at least scrolling log files and irssi/irc (TTF versions available). Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled).
Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled). http://misc.nybergh.net/pub/fonts/terminus/2008-09-08_terminus_ttf_in_gnu_nano_putty_windows_xp_cleartype_screenshot.png

A: I'm going to make some enemies with this, but I actually use -- gasp -- a non-monospace font! I occasionally switch back to a monospace to disambiguate something, but mostly find that a good clean sans-serif font is easiest to read and doesn't waste screen estate.
An IDE with good syntax colouring helps.

A: I second Consolas, Inconsolata, DejaVu Sans Mono, and Droid Sans Mono, with my preference going towards the Droid one.

A: Neep Alt 13/17 is very good.

A: My favourite is ProggyClean at 11px. I've been using it for 2-3 years and it's great for getting lots on screen without being painful to read. It deserves even more attention than the couple of mentions it's had so far:
Proggy Clean http://www.proggyfonts.com/download/example_proggy_clean.gif
The site has many variations including slashed zeroes, bold for function marks etc:
Proggy Square http://www.proggyfonts.com/download/example_proggy_square_bp.gif
(As an aside, my most-loved favourite text editor, TextPad, allows you to have different fonts and font sizes for different file types, which is a really great feature.)

A: Until I found ProggyTiny, I always made my own fonts using Softy. It's surprisingly easy, and might increase your productivity if you're annoyed by some features of your current font (like "Q is too similiar to 0").

A: Bitstream vera sans, a Gnome font. I find its much clearer than Consolas, which is pretty good too.

A: I use Terminuse in almost everything (Eclipse, putty and other terminals): http://fractal.csie.org/~eric/wiki/Terminus_font
I must say that I don't get it why most people use small fonts like 9pt, do you have 14" monitors or what?
For me the best way is to use font size that makes my monitor display at most one 30-40 line method, this way I need to create smaller methods :)

A: I use MonteCarlo, which is based on ProFont but has a bold face too. That way IDEs/editors that use bold as part of their syntax highlighting leave your text still properly fixed width.
java example http://bok.net.nyud.net/MonteCarlo/images/java-example.png
quick brown fox example http://bok.net.nyud.net/MonteCarlo/images/screenshot-small.gif
Like ProFont, Proggy & others, its quite small (& being bitmap based, obviously doesn't scale), but I like a small font for coding and its still extremely clear and easy on the eyes.

A: Either Consolas (download) or Andale Mono (download). I mostly use Andale Mono. I wrote an article about programming fonts a long time ago, I think Consolas wasn't even out yet.
http://www.deadprogrammer.com/photos/fonts.gif
I find that typing Illegal1 = O0 is a good test of suitability.

A: I use Consolas on my mac, BTW; here's a link to download the consolas TTF files if you want to install this (Mac/Win/Linux).
/mp

A: I don't use Consolas, though it does look good on LCD, but sometimes I'm not on LCD, like when I'm giving presentations and then it looks crap.
My current font of choice for programming is the Liberation Mono font.
Oh man, just discovered why the text on Stack Overflow looks like crap, it forces Consolas which is a cleartype font, and on my current setup which didn't have cleartype enabled, it looks very bad.
Going to make a bugreport on uservoice.

A: I have been using the Dina - http://www.donationcoder.com/Software/Jibz/Dina/index.html - font for awhile now for text editing and it seems to be doing the job nicely.

A: ProFont.  Am I the only one still using it?

A: I like Fixedsys in Visual Studio.  It's a classic.  No anti-aliasing blur.

A: I'm amazed nobody has mentioned Pragmata. It's the BMW of programming fonts. Condensed, readable, and the pinnacle of simple elegance.
alt text http://www.fsd.it/fonts/imm/pr_abc.gif
There is now a fundraising project going on for PragmataPro (which covers a larger portion of Unicode than Pragmata) to make it available for free under a Creative Commons license!

A: A excellent CodeProject article that list 33 fonts for programming (With examples of each)
http://www.codeproject.com/KB/work/FontSurvey.aspx

A: I use Inconsolata with UltraEdit on Windows. With TextMate (on the Mac) I prefer Monaco (it's the default font).

A: I have to agree with Kevin Kenny, Proggy fonts all the way, though I prefer Proggy Clean. But either way you have to go with a font that clearly shows the difference between the number 0 and the letter O. Which the preview font here doesn't really show that.

A: I'm on PanicSans 12pt w/ AA on TextMate, but loving Inconsolata on Terminal/vim... (debating changing my TM font to this one... but point size 14pt) :)

A: Consolas for me as well

A: I just tried Consolas and Envy - Envy seems "too narrow" to my eyes, but Consolas looks great (I am on a mac). Thanks for the tips !

A: Courier New for me as well, it's well spaced.

A: Another vote for Consolas for code editing, and Dina for console output.

A: Lucida Console every time.
I've never found a font that can pack as many lines of code onto the screen at the same point size without looking cramped.
And it looks nice too.

A: I just recently switched from Bitstream Vera Sans Mono to Inconsolata, but reading the answers here, I'm going to give Consolas a chance for a bit. Looks really nice so far.

A: I love consolas, especially with italics for comments. The little italic curlicues are so cute :P

A: @modesty:

I wish there was a Mac version.

You can install the font on a Mac. I use it all the time, everywhere, without any problem. The only thing to pay attention for is to set nomacatsui when working with GVIM, or better yet, switch to MacVim.

A: Another vote up for Dina. As long as you use it at its optimum size (9 pt), it looks great.

A: For quite some time I've been using ProFont, mainly because it allows a lot of lines fit into a given height (a lot more than say Consolas or others). Consolas is not bad either, though...

A: I never considered changing my font, I have always been happy with Courier. This thread has truely opened my eyes, if only I could upvote it!
Went with Droid Sans Mono.

A: I like Consolas myself, but when it comes to monospaced fonts there are quite a few other options to choose from:

A: Don't forget the colours!
For some reason Delphi 7 in Twilight does not render Droid Sans Mono well, but in Visual Studio with an orange on black theme it is excellent. Deja Vu Sans Mono is the best all rounder. I use it almost everywhere. Consolas would be excellent apart from its ugly Q glyph.
One other thing I have found since I entered the world of work is that even though I have great eyesight I like to keep my code font around 12 or 13pt size both to reduce eye strain and to make sure I can't put too much text on screen. It's sort of an incentive to keep code blocks vertically short.
I note that this edit box does not respect my browser's default monospaced font. It's giving me Monaco (I'm on OSX). Monaco is horrible. It's glyphs have poorly angled elements and it's capitals are not well proportioned.
Oh, and it almost doesn't matter on Windows because your font will not look right anyway. /me dons flame retardent suit

A: Tahoma is very readable.

If you need it larger then use Verdana.

A: ProFont is a great font for code, Consolas a 2nd runner up.  You could always go retro with a little Terminal font for a little nostalgia (customize the background color to black and foreground font to green for the full effect!).

A: In bash and vim I use Lucida Typewriter, but in Kate, Scintilla, Eclipse, and Netbeans I (currently) use Lucida Casual, i.e., a proportional font. Ten years ago I started using proportional fonts in Visual Studio (MS Comic Sans) and it works very well for me. Colored syntax highlighting in said IDEs provides excellent readability and for text-heavy languages like HTML and LaTeX a proportional font is a natural choice.

A: I like consolas too.

A: Consolas, works great for various font sizes, and I can't find anything better.

A: Consolas - recently switched over to it and it's lovely.

A: Consolas and Courier New under Windows, Inconsola under *nix. I really miss the old IBM terminal fonts, though. The one from green/orange terminals.

A: I'd also have to add another vote for Android's "Droid Sans Mono". It's a very crisp, clear coding font.

A: I experimented with Myriad until I realised using a variable-width font was a fools game.
Courier New here, although I am going to try out Envy after seeing it here.

A: Consolas for Visual Studio.  It is the first thing I change when getting a new install setup.  The second is inverting the main colors, white text on black background is much easier to stare at for hours in my opinion.
Black text on white background http://college-code.com/stackoverflow/black_on_white.PNG
Versus
White text on black background http://college-code.com/stackoverflow/white_on_black.PNG
The second one tends to make my eyes bleed less after long coding sessions.  Could be my code however.

A: Consolas all the way.

A: Lucida Console or Lucida Sans Typewriter, as small as possible so I can maximize the amount of code on the screen. Occasionally Courier or Monaco (e.g. Monaco in TextMate).

A: I'm a happy user of ProFont originally available on the Mac, now available for everyone.

A: If you're like me and only swear by serifs try Kourier with a K, a somewhat more compact Courier .

A: It must be noted that the text editor/IDE that you use determines how good a font will look.  I love UltraEdit, but the only font it renders properly is Courier New.  It blurs out about all other useful monospace fonts.  However, Visual Studio does a great job rendering any font accurately.
Currently, I will vote Consolas.  Though, I will try some of the others listed in the responses.  Thank you.  Btw, please post links to download!

A: I'm digging the DejaVu Sans Mono (it's supposed to be the same as Panic Sans) on my Mac.

A: +1 Verdana -- agree with pauldoo
A variable width font for coding is probably not to everyone's taste but I really like Verdana's legibility with ClearType.

A: I have been using Proggy Clean TT with Visual Studio for a couple of years now. I like the ability to choose a zero slashed font so when management decides to program instead of manage they don't confuse 0101 with 0101(zeros).
http://www.proggyfonts.com/

A: Consolas unless I'm runing over a slow RDP connection with font smoothing turned off, then Lucida Console.

A: Its already been said a few times but http://www.proggyfonts.com/ is just awesome. Im a big fan of the Proggy Clean Slashed Zero Bold Punctuation. I do most my work in c# so the bold punctuation is very nice for it.

A: I like ProFont TT >tweaked< It's clean and there is a clear difference between 1, l and I and 0 and O.It works best at 9pt. It doesn't scale up very well.

A: Verdana.
Easy to read, and, very imporetant, easy to distinguish similar characters like O and 0, ( and {, 1 and I and l etc.

A: Consolas for me. These were specially developped for LCD + MS hint engine. Also you might find ClearType tuner (MS PowerToy) a great addition as it gives you more control over how your fonts look.

A: For VS nothing beat  Fixedsys.

A: I prefer Profont.

A: I actually bought The Sans Mono Condensed, which is (was) the goto code font in O'Reilly titles. It's by the same guy as did Consolas for Microsoft (but Consolas wasn't available when I bought it).
It's a really nice, tight, clear face - works really well on slides if you're doing that sort of thing as well.

A: I'd never heard of Droid Sans Mono before, but I installed it and tried it at 9 points, and I must say it's by far the highest quality mono font I've seen on Linux.
On my Mac it's Panic Sans all the way, using it at 11 or 12 points allow anti-aliasing that actually works on monospace, which I've never seen before.

A: Monaco 10pt for me.

A: I've been hanging on to this link for more than a year, it's an article entitled "Five great programming fonts". The five are good fonts, but the article includes comments with a dozen more interesting answers.
http://forums.programming-designs.com/viewtopic.php?pid=3338

A: I recommend Lucida Console for Windows users and Adobe Courier for Linux/Unix, with a size of 10pt these fonts looks great! and very legible
Edit:
I've been saying that using Lucida Console was a real good option, well, now I know Consolas :)

A: I use Inconsolata in both Linux and Mac OS X.

A: 6x13.  You can get two terminal or editor windows across a 1024x768 and three onto a 1600x1200 screen.  A windows version of this font can be found Here.

A: I prefer Consolas as well, and obviously cleartype helps when using other fonts.

A: Lucida Console isn't so good because the bold text takes up more room than the non-bold text.  Consolas overcomes this.

A: monaco 12pt, is there any other way?

A: I use Bitstream Vera http://www.gnome.org/fonts/ for Visual Studio 2008 paired with the Darkness Theme because my eyes can't deal with white backgrounds.

A: Verdana - Once I realised that I didn't HAVE to use a mono-spaced font ;-)

A: Consolas
I use it everywhere, I use it for everything.
Advice: stick to it.

A: I've been using Anonymous, but I'll need to check out some of these other fonts.

A: I just use Courier New, or whatever monospace font I have available.
However, I sometimes like using sans-serif (currently Comic Sans MS) for comments in Notepad++. (However, I now tend more to switch everything to monospace just for consistency in spacing and such.)

A: Nobody's mentioned it yet, so let me just mention DejaVu Sans Mono, which is a fork of Vera Sans Mono, and is included in most Linux distribs. It supports most of Unicode.

A: Yet another vote from me for Consolas. I use it since I learned about it from Jeff's blog post. Thanks to you for this advice.
It made me improve an aspect of my daily programming life, which I didn't think about much before.

A: Bitstream Vera Sans Mono. [http://www.dafont.com/bitstream-vera-mono.font]

A: bitstream vera sans mono

A: Any monospace font, really. I honestly don't find it matters too much past that.

A: arial is best

A: I use ForMateKonaVe, which is a merge of Bitstream Vera Sans Mono and a half-width'd Konatsu. I use a lot of Japanese here and there and this is the best way to display it in TextMate.

A: Fixedsys Excelsior 2.00, Raize, and the usuals.
http://kaishaku.org/codefonts/

A: try Lucida Grande..
Amazing!!

A: -2 for Bitstream Vera Sans Mono -- it has an dotted zero - released this font as an free download after an modification.
+2 for Prima Sans Mono -- lacks an dotted zero - need an free download for RapidShare to extend the font to an terminal.

A: I swear by DejaVu Sans Mono

A: Any sans-serif.


text:
Q: React Js ErrorBoundary only working for the main layout components and not for nested components I am using errorboundaries in my code and when I use it in the file where I am rendering my main layout components it works, Eg.:
<ErrorBoundary>

</ErrorBoundary>
<ErrorBoundary>
 //this component has an error
</ErrorBoundary>
<ErrorBoundary>

</ErrorBoundary>

The above code works and the fallback UI is shown for the error that is in the main component. But when I use errorboundary component inside the main component file it does not work,
Eg of errorboundary that does not work:
class main extends React.Component {
//code
<ErrorBoundary>
{object}
</ErrorBoundary>
//more code

This does not work and the whole app crashes instead, displaying only a blank page. Why might this be happening and how to deal with it? Thank you.

A: I figured it out. Errorboundary catches the error in components. So it wasn't working earlier, but when I rendered a faulty component in between the ErrorBoundary instead, it worked.
<ErrorBoundary>
<FaultyComponent/>
</ErrorBoundary>

it worked.


text:
Q: Change complete URL in adress bar, without reloading the page What I need is for a webpage to completely alter the users adressbar on visit.
For instance: I visit www.X.com, but my adress bar displays www.Z.com.
I have already looked at history.pushState / history.replaceState, but using them I get results like this: www.X.com/www.Z.com.
Is there a way, preferably using history.pushState/replaceState, to accomplish this effect?

A: function changeUrl(page, url) {
    if (typeof (history.pushState) != "undefined") {
        var obj = { Page: page, Url: url };
        history.pushState(obj, obj.Page, obj.Url);
    } else {
        alert("Browser does not support HTML5.");
    }
}
$(function () {
    $("#button1").click(function () {
        changeUrl('Page1', 'Page1.htm');
    });
    $("#button2").click(function () {
        changeUrl('Page2', 'Page2.htm');
    });
    $("#button3").click(function () {
        changeUrl('Page3', 'Page3.htm');
    });
});

A: I fixed the issue with my hosting provider.


text:
Q: The difference between PopupMenuItem Click and MouseOver When a Menu Item has a sub Menu hovering the mouse expands the sub-menu it fires a click event.
Is there any difference between this click event and if the user actually clicks?
I'm using a TPopupMenu as dropdown property of a cxButton.
EDIT
Delphi 2007

A: No there isn't. If the user clicks the item or hover it, the same OnClick event is fired.
I've checked this for Delphi 2009.

A: Well, if the user actually clicks a MenuItem with sub menu items, the OnClick event is not fired. So the distinction is made by:
procedure TForm1.MenuFileOpenClick(Sender: TObject);
var
  ActuallyClicked: Boolean;
begin
  ActuallyCLicked := TMenuItem(Sender).Count = 0;
end;

And if the menu item has a linked action:
procedure TForm1.FileOpenExecute(Sender: TObject);
var
  ActuallyClicked: Boolean;
begin
  if Sender is TBasicAction then
    Sender := TBasicAction(Sender).ActionComponent;
  ActuallyCLicked := TMenuItem(Sender).Count = 0;
end;

A: Not sure this will work with D2007; it does in D7. Can you try the following?
type
  THackPopupList = class(TPopupList)
  private
    FActuallyClicked: Boolean;
  protected
    procedure WndProc(var Message: TMessage); override;
  public
    property ActuallyClicked: Boolean read FActuallyClicked;
  end;

{ THackPopupList }

procedure THackPopupList.WndProc(var Message: TMessage);
begin
  FActuallyClicked := Message.Msg = WM_COMMAND;
  inherited WndProc(Message);
end;

{ TForm1 }

procedure TForm1.MenuFileOpenClick(Sender: TObject);
var
  ActuallyClicked: Boolean;
begin
  ActuallyClicked := THackPopupList(PopupList).ActuallyClicked;
  ...
end;

initialization
  PopupList.Free;
  PopupList := THackPopupList.Create;

end.

Explanation: The OnClick which is triggered by a hover is initiated by a WM_INITMENUPOPUP, but the OnClick which is triggered by a mouse click is initiated by this WM_COMMAND.
This depends on Menus.pas already having been initialized. But as I understand from Delphi unit initialization order, that is guaranteed even if you put this code in an auxiliary unit.


text:
Q: Push DIV below first fold? Jquery? Is there a way to "push" a div below the first fold so that it never shows up on page load unless the user scrolls down?  I know there is something called Jquery viewport but not sure how to use it.  I don't want the DIV to be "hidden" with CSS either.

A: How about using jQuery to set a top or margin-top CSS property for your element that is equal to the height of the viewport:
$(function () {
    $('#my-under-the-fold-element').css({
        top : $(window).height()
    });
});

Then you just need to make your element absolutely positioned.
Here is a demo: http://jsfiddle.net/CtgUB/2/

A: You don't need any javascript! Just good 'ole CSS. Set the element that is a child of the <body> to position:absolute; top:100%; and you've got your below-the-fold-element.
.below {
    position: absolute;
    top:100%;
}

Plus, unlike setting a static top or margin with javascript, this will work even after you resize your browser window.
Here's a jsFiddle with the full markup: http://jsfiddle.net/ubhBL/


text:
Q: How can I cut connected graph lines?

I'm gonna draw a graph that shows Time per speed.
But the lines are connect each other at the end to start like picture.
How can i cut connected graph lines??

A: This bug is likely because the data you're plotting on the x-axis isn't sorted and your data for the y-axis isn't paired to the sorted x data.
To illustrate this, consider trying to plot y=x^2
x = np.array([1,3,5,6,2,4,8,7])
y = np.array([1,9,25,36,4,16,64,49])

plt.plot(x,y)

Python is plotting the points according to their index in the array and connecting the lines between consecutive points. To get the data in the correct order, you can np.argsort, which sorts the elements in an array and returns the indices of the sorted elements.
xnew = x[np.argsort(x)]
ynew = y[np.argsort(x)]

plt.plot(xnew, ynew)

It's important to note that we want to sort the y values according to their x values, which is why np.sort isn't used.
For your dataset, I would create a variable for the sorted indices
indx = np.argsort(mean_spd_per_time_array[:, 0])

Then create new x and y variables to plot
# Sort the data according to x values
x = mean_spd_per_time_array[:, 0][indx]
y = mean_spd_per_time_array[:, 1][indx]


text:
Q: certificate signed by unknown authority when connect to remote kubernetes cluster using kubectl I am using kubectl to connect remote kubernetes cluster(v1.15.2),I am copy config from remote server to local macOS:
scp -r root@ip:~/.kube/config ~/.kube

and change the url to https://kube-ctl.example.com,I exposed the api server to the internet:
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURvakNDQW9xZ0F3SUJBZ0lVU3FpUlZSU3FEOG1PemRCT1MyRzlJdGE0R2Nrd0RRWUpLb1pJaHZjTkFRRUwKQlFB92FERUxNQWtHQTFVRUJoTUNRMDR4RURBT0JnTlZCQWdUQjBKbGFVcHBibWN4RURBT0JnTlZCQWNUQjBKbAphVXBwYm1jeEREQUtCZ05WQkFvVEEyczRjekVTTUJBR0ExVUVDeE1KTkZCaGNtRmthV2R0TVJNd0VRWURWUVFECkV3cHJkV0psY201bGRHVnpNQ0FYR3RFNU1Ea3hNekUxTkRRd01Gb1lEekl4TVRrd09ESXdNVFUwTkRBd1dqQm8KTVFzd0NRWURWUVFHRXdKRFRqRVFNQTRHQTFVRUNCTUhRbVZwU21sdVp6RVFNQTRHQTFVRUJ4TUhRbVZwU21sdQpaekVNTUFvR0ExVUVDaE1EYXpoek1SSXdFQVlEVlFRTEV3azBVR0Z5WVdScFoyMHhFekFSQmdOVkJBTVRDbXQxClltVnlibVYwWlhNd2dnRWlNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0SUJEd0F3Z2dFS0FvSUJBUUNzOGFFR2R2TUgKb0E1eTduTjVydnAvQkEyTVM1RG1TNWwzQ0p4S3VMOGJ1bkF3alF1c0lTalUxVWlqeVdGOW03VzA3elZJaVJpRwpiYzZGT3JkSEJ2QXgzazBpT2pPRlduTHp1UjdaSFhqQ3lTbDJRam9YN3gzL0l1MERQelNHTXJLSzZETGpTRTk4CkdadEpjUi9OSmpiVFFJc3FXbWFEdUIyc3dmcEc1ZmlZU1A1KzVpcld1TG1pYjVnWnJYeUJJNlJ0dVV4K1NvdW0KN3RDKzJaVG5QdFF0QnFUZHprT3p3THhwZ0Zhd1kvSU1mbHBsaUlMTElOamcwRktxM21NOFpUa0xvNXcvekVmUApHT25GNkNFWlR6bkdrTWc2aUVGenNBcDU5N2lMUDBNTkR4YUNjcTRhdTlMdnMzYkdOZmpqdDd3WkxIVklLa0lGCm44Mk92cExGaElq2kFnTUJBQUdqUWpCQU1BNEdBMVVkRHdFQi93UUVBd0lCQmpBUEJnTlZIUk1CQWY4RUJUQUQKQVFIL01CMEdBMVVkRGdRV0JCUm0yWHpJSHNmVzFjMEFGZU9SLy9Qakc4dWdzREFOQmdrcWhraUc5dzBCQVFzRgpBQU9DQVFFQW1mOUozN3RYTys1dWRmT2RLejdmNFdMZyswbVJUeTBRSEVIblk5VUNLQi9vN2hLUVJHRXI3VjNMCktUeGloVUhvbHY1QzVUdG8zbUZJY2FWZjlvZlp0VVpvcnpxSUFwNE9Od1JpSnQ1Yk94K1d6SW5qN2JHWkhnZjkKSk8rUmNxQnQrUWsrejhTMmJKRG04WFdvMW5WdjJRNU1pUndPdnRIbnRxd3MvTlJ2bHBGV25ISHBEVExjOU9kVwpoMllzWVpEMmV4d0FRVDkxSlExVjRCdklrZGFPeW9USHZ6U2oybThSTzh6b3JBd09kS1NTdG9TZXdpOEhMeGI2ClhmaTRFbjR4TEE3a3pmSHFvcDZiSFF1L3hCa0JzYi9hd29kdDJKc2FnOWFZekxEako3S1RNYlQyRW52MlllWnIKSUhBcjEyTGVCRGRHZVd1eldpZDlNWlZJbXJvVnNRPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://k8s-ctl.example.com
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    namespace: kube-system
    user: admin
  name: kubernetes
current-context: kubernetes
kind: Config
preferences: {}
users:
- name: admin
  user:

when I get cluster pod info in my local Mac:
kubectl get pods --all-namespaces

give this error:
Unable to connect to the server: x509: certificate signed by unknown authority

when I access https://k8s-ctl.example.com in google chrome,the result is:
{
kind: "Status",
apiVersion: "v1",
metadata: { },
status: "Failure",
message: "Unauthorized",
reason: "Unauthorized",
code: 401
}

what should I do to make access remote k8s cluster sucess using kubectl client?
One way I have tried to using this .kube/config generate by command,but get the same result:
apiVersion: v1
clusters:
- cluster:
    certificate-authority: ssl/ca.pem
    server: https://k8s-ctl.example.com
  name: default
contexts:
- context:
    cluster: default
    user: admin
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate: ssl/admin.pem
    client-key: ssl/admin-key.pem

A: When kubectl interacts with kube API server it will validate the kube API server certificate as well as send the certificate in client-certificate  to the kube API server for mutual TLS authentication. I believe the problem is either of below.

*

*the ca that you have used to generate the  client-certificate is not the ca that has been used to startup the kube API server.

*The ca in certificate-authority-data is not the ca used to generate kube API server certificate.

If you make sure that you are using same ca to generate all the certificates consistently across the board then it should work.

A: I've reproduced your problem and as you created your cluster following kubernetes-the-hard-way, you need to follow these steps to be able to access your cluster from a different console.
First you have to copy the following certificates created while you was bootstraping your cluster to ~/.kube/ directory in your local machine:
ca.pem
admin.pem
admin-key.pem

After copying these files to your local machine, execute the following commands:
kubectl config set-cluster kubernetes-the-hard-way \
  --certificate-authority=~/.kube/ca.pem \
  --embed-certs=true \
  --server=https://${KUBERNETES_PUBLIC_ADDRESS}:6443

kubectl config set-credentials admin \
  --client-certificate=~/.kube/admin.pem \
  --client-key=~/.kube/admin-key.pem

kubectl config set-context kubernetes-the-hard-way \
  --cluster=kubernetes-the-hard-way \
  --user=admin

kubectl config use-context kubernetes-the-hard-way

Notice that you have to replace the ${KUBERNETES_PUBLIC_ADDRESS} variable with the remote address to your cluster.


text:
Q: Request promise Unhandled rejection RequestError I am working on Facebook Graph Api using Node.js . i am using request-promise for this but when i send request for my response  i am getting this error "Unhandled rejection Request Error: Error".
This is my code

var express = require('express');
var app = express();

const request = require('request-promise');

app.get('/url', (req, res) => {

  const userFieldSet = 'id,name,about,email';

  const options = {
    method: 'GET',
    uri: 'https://graph.facebook.com/v7.0/2423438197947713',
    params: {
      access_token:"my access token ",
      fields: userFieldSet
    }
  };
  request(options)
  .then(fbRes => {

    const parsedRes = JSON.parse(fbRes).data;
    res.json(parsedRes);
  })

});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

can anyone help me how to fix this ?

A: change params to qs
qs: {
      access_token:"my access token ",
      fields: userFieldSet
    }


text:
Q: Is leaving property blank same as "all" for transitions? Is the following exactly the same?  If not, what's the difference?
div {
  transition: all 3s;
}

vs
div {
  transition: 3s;
}

A: Yes, they are the same:

Definition and Usage
The transition-property property specifies the name of the CSS
  property the transition effect is for (the transition effect will
  start when the specified CSS property changes).
Tip: A transition effect could typically occur when a user hover over
  an element.
Note: Always specify the transition-duration property, otherwise the
  duration is 0, and the transition will have no effect.
Default value: all

Source:
http://www.w3schools.com/cssref/css3_pr_transition-property.asp

A: It's doing the same thing.
http://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
I changed the css to:
div {
    width: 100px;
    height: 100px;
    background: red;
    -webkit-transition: 3s;
    transition: 3s;
}

.div2 {
    width: 100px;
    height: 100px;
    background: red;
    -webkit-transition:all 3s;
    transition:all 3s;
}

and added this:

I believe that the default is "all" if you don't specify it but you can target the transition to just a specific property like width, height, font-size, color, etc. I always put "all" though in my code though.

A: Yes, they are equal.
If you don't declare any value and the cascade is empty, the specified value will be the result of the defaulting processes.

When the cascade does not result in a value, the specified
  value must be found some other way. Inherited properties draw
  their defaults from their parent element through inheritance; all
  other properties take their initial value.

Since transition-property is not inheritable, defaulting will yield its initial value, which is all.


text:
Q: Change color of notification icon like actual color of mediastyle notification bar I created mediaStyle Notification in my app. This notification is colored depending on the actual playing song. I set .setColor(color) in NotificationCompat.Builderso that I get also a colored program Icon while drawing the notification bar. This color is one of my program colors.
What I want:
How can I set the color of the program icon like the mediastyle notification color while drawing (swiping) the notification bar. I want to change the Icon color dynamically, depending on the actual notification color.
Is that possible?
Thanks,


text:
Q: How to empty sqlite3 database in django Running through the polls tutorial I ran this line:
q = Question(question_text="What's new?", pub_date=timezone.now())

Now, I've already ran:
python manage.py flush

But when I save and check the ID, I noticed that the id is still incrementing.
>>> q.save()
>>>q.id
3

Why is the id value not 1? Why are the id values preserved even though the db was destroyed?

A: You can try by deleting all tables using manage.py sqlclear before using manage.py flush which empties the data in all tables.
Then you can re-sync the tables according to your defined model with manage.py syncdb.
Maybe it would make your life easier to use south to make database migrations or some Django Extensions.


text:
Q: RadGrid not updating after Filter and Rebind My problem is that I have 2 radgrids on a page and I cannot filter the columns.
One table is created like this:
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>

                                    <telerik:RadGrid ID="mdegGrid" runat="server"
                                        AllowPaging="True" AllowCustomPaging="true"
                                        AllowSorting="True"
                                        AllowFilteringByColumn="True"
                                        OnNeedDataSource="mdegGrid_NeedDataSource"
                                        OnItemCommand="mdegGrid_ItemCommand"
                                        OnItemCreated="mdegGrid_ItemCreated"
                                        OnItemDataBound="mdegGrid_ItemDataBound"
                                        OnPreRender="mdegGrid_PreRender"
                                        CellSpacing="0" GridLines="None"
                                        EnableLinqExpressions="false"
                                        PageSize="12"
                                        PagerStyle-AlwaysVisible="true"
                                        EnableEmbeddedSkins="False"
                                        Skin="_HBB"
                                        CellPadding="0"
                                        MasterTableView-CellSpacing="0" >
                                        <GroupingSettings CaseSensitive="false" />
                                        <MasterTableView AutoGenerateColumns="false" TableLayout="Auto" HierarchyLoadMode="ServerOnDemand"
                                            DataKeyNames="ImportID" CommandItemDisplay="None" InsertItemPageIndexAction="ShowItemOnFirstPage">
                                            <CommandItemSettings ShowRefreshButton="false" />
                                            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
                                                <HeaderStyle Width="20px" />
                                            </RowIndicatorColumn>
                                            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
                                                <HeaderStyle Width="20px" />
                                            </ExpandCollapseColumn>
                                            <Columns>
                                                <telerik:GridBoundColumn UniqueName="ImportID" HeaderText="<%$ Resources:HBS, Import_ID %>" DataField="ImportID_Filter"
                                                    SortExpression="ImportID"
                                                    FilterControlWidth="99%" ShowFilterIcon="false"
                                                    AutoPostBackOnFilter="true" CurrentFilterFunction="Contains">
                                                    <HeaderStyle ForeColor="Silver" Height="20px" Width="7%" HorizontalAlign="Left"></HeaderStyle>
                                                    <ItemStyle ForeColor="Gray" Height="20px" Width="7%" HorizontalAlign="Left"></ItemStyle>
                                                </telerik:GridBoundColumn>

In the code behind in the mdeGrid_PreRender funtion I have the following code:
mdegGrid.MasterTableView.FilterExpression = string.Format("([{0}] LIKE N\'%{1}%\') ", _columnNameImports, txt.Text);
GridColumn column = mdegGrid.MasterTableView.GetColumnSafe(_columnNameImports);
column.CurrentFilterFunction = GridKnownFunction.Contains;
column.CurrentFilterValue = txt.Text;

mdegGrid.MasterTableView.Rebind();
UpdatePanel2.Update();

The problem is that nothing is happening. The grid becomes disabled with a Please wait loading message but after that, no filtering is happening.


text:
Q: Send Intent Each Day Using AlarmManager? I want the following:

*

*The AlarmManager sends a daily intent to my AppWidgetProvider at midnight EXACTLY.

*The Alarm must wake up the device.

Here is how I did it:
In my AppWidgetProvider subclass:
@Override
public void onEnabled(Context context) {
    super.onEnabled(context);
    Log.d(LOG_TAG, "Widget Provider enabled.  Starting timer");

    //Setting the Calender object to midnight time.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 0);
    calendar.add(Calendar.MINUTE, 0);
    calendar.add(Calendar.HOUR, 0);

    //The fired Intent
    Intent intent = new Intent(CLOCK_WIDGET_UPDATE); //custom intent name
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(), 1000*60*60*24, pendingIntent);
}

Although I think I did it right, this code doesn't work!
To test it, I changed 1000*60*60*24 with 10000 (10 sec) and updated a textView in the widget with random number. The random number never changed.
Any help will be appreciated !

A: I finally found the problem !
It seems that I need to set the AM_PM value too. When I print the calender using getTime().toLocaleString(), it was set to the next day but 12 hours later (12:00:00 PM).
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.add(Calendar.DAY_OF_MONTH, 1);

This is a perfect setup for the Calender instance that will set the alarm to the next day at midnight (i.e. the nearest midnight). You just pass it to the setRepeating() method.
Thanks @CommonsWare

A: First, what you want is not strictly possible. Android is not a RTOS; you may not get control "at midnight EXACTLY"
Second, your Calendar object represents a time in the past (unless it happens to be midnight at the time you are executing that code, in which case it represents the present). Try a start time in the future.


text:
Q: What would happen when USB devices draw more power than the hub can provide? I am going to buy a 7-port USB 3.0 hub, and connect 7 portable HDDs to it, in order to build a RAID 6 array. The hub comes with an upstream micro-USB 3.0 type B port, along with an auxiliary power adapter rated at 5V 2A (micro-USB 2.0 type B connector).

Each 2.5 inch HDD can easily consume 5V 0.9A which is the maximum for a single USB 3.0 port. And now I am going to connect 7 of them to all available ports.
My questions are:

*

*Are the power from the upstream USB port (0.9A) and the auxiliary port (2.0A) combined? I am confused, because I can always plug another hub into this one, and cascade this USB network -- and that hub can be either host-powered or self-powered. How does the power flow in this case?

*If a 2.5" HDD receives less than its required power (2A / 7 = 286mA), will it work at lower speed or won't work at all? Does it try to draw more power and overload the 5V 2A adapter?

*Can I replace the stock power adapter with higher current ones, e.g 5V 10A?

A: This very much seems to be an XY problem. What you're actually trying to achieve based on comments is scaling up storage capacity for a file server in an inexpensive way.
The issue here is that USB is horrendous for any situation where reliability is important for a couple of reasons:

*

*Power distribution over USB is generally problematic. You can mitigate this by only using powered hubs and powered peripherals, but that doesn't solve any of the other issues.

*The 'bus' is asymmetrical from a latency and efficiency perspective. The further down the chain of hubs something is, the worse it's latency and throughput will be. This can kind of be mitigated by utilizing a balanced tree topology so that everything is at the same nesting depth, but that's not exactly trivial, especially since the USB ports on most computers are actually connected to hubs internally themselves and not directly to the host controller, and it's also not exactly cheap.

*USB connectors are actually rather mechanically unstable. This is actually really important for the original intended use of USB so that you don't damage the ports when you trip over a cable, but it's a very bad thing for storage systems where reliability is needed.

*It's very easy to trigger a bus reset by accident. This isn't an issue for the input devices USB was intended to be used with, but it's a serious problem for storage devices (seeing link resets for SCSI or SATA devices is one of the times you start replacing hardware if you're doing things right).

*Because of how the MSC and UAS standards work, you have t reinitialize the whole device every time you have to reset the bus, which in turn can cause all kinds of nasty behavioral problems when dealing with a RAID array of any type.

There are a few 'correct' approaches to this depending on exactly how much you can spend:

*

*Look into getting some SATA Port Multipliers (essentially, these are like USB hubs for SATA devices). You will need support in the OS for this to work, but it's probably the least expensive option that's likely to be sufficiently reliable (just don't chain the port multipliers, it technically works but it causes serious performance issues in most cases).

*Just get a proper SAS HBA for the file server. SAS controllers work just fine with SATA disks (they have to) but are far more efficient than SATA controllers and usually have more ports (the small ones will typically have 8 ports). If doing this, put the server's OS on the SATA connectors on the MB. If you have to keep this as a specific system, this is what I would do.

*Get a dedicated NAS system. For a good one, you'd e looking at maybe 4-5 digits in terms of cost, but it would probably outlast whatever else you have, and would almost certainly scale well beyond what you actually need. FreeNAS is the OS I'd suggest here (iXsystems, the company backing FreeNAS, does reasonably priced semi-custom systems that are high-end enterprise quality). From there, you can either use iSCSI to expand the file server's storage, or you could just use the NAS directly.

*Buy a bunch of small inexpensive systems, throw a big storage device in each, and then set up a clustered filesystem. GlusterFS would be my specific recommendation here (as long as you don't need really fast storage, you can throw together individual GlusterFS nodes for under 500 USD each). This will give you the best long-term scalability (it can easily go into the thousands of TB range without issue provided your networking hardware is good), but puts significant limitations on other choices you might make about your infrastructure. I've done this before myself with both Intel NUC systems and Raspberry Pi's.

*Shell out probably hundreds of thousands on a proper SAN. Unless you're dealing with a big company, just don't, it's usually a waste.

A: The hub, as any USB device, is either "bus" or "self" powered.
Devices are enumerated normally, and come up in configuration 0, where no interfaces are implemented and power is limited to 100 mA.
The OS may only enable configurations with higher power requirements if the power budget allows.
A bus powered USB 1.1 or 2.0 hub asks for 500 mA for its working configuration, which is enough to give 100 mA each to itself and four downstream devices (which is why USB hubs always have four ports), and downstream devices are powered only when that request was granted.
A self powered USB hub asks for 4 mA, which is pretty much a symbolic value -- this configuration uses less power than the inactive configuration, so it is always inside the power budget. The hub must refuse the configuration switch if the power adapter is not connected.
Hubs offer both self-powered and bus-powered configurations, and the OS will try them in turn. If the power adapter is not present, the self-powered configuration is rejected, and the OS checks if the power budget is sufficient for a bus-powered configuration.
So, in a tree with an arbitrary number of hubs, there is either enough power for all devices, or there is a device for which the OS knows that the power budget does not allow activating a "working" configuration, which causes a message to be displayed in the UI.
A seven port USB 1.1 or 2.0 hub consists of two four port hubs, where one is downstream of the other, so insufficient power to that hub would leave four downstream ports completely unpowered, and the OS would request the user to plug in the hub's power supply.
With USB 3.0, the numbers change a bit because it is now possible to request more power, but the general idea remains the same: if the power budget doesn't allow it, devices will not be activated.
The hub is aware that the total power budget for its downstream ports is 2 A, and reports that fact to the OS. The OS will refuse to activate more disks than that budget allows, so expect only a few of the disks to spin up.
In theory, the disks could attempt to start without permission, which would be a violation of the USB specification. What happens then depends on whether the hub actively limits port power. I would not entrust data to any disk that does not wait to be explicitly switched into an active configuration.

A: I think gronostay is on the money with his "TL;DR: Don't do this" for fundamental reasons.
That said, I suppose you could simply supply your own 5V to the drives. Ignore the hub power, cut the cables (or better: connectors) to the drives open and connect the VCC and GND pins to a sufficient 5V power supply. You can even provide simple switches for switching them on separately in order to avoid an initial power surge.
There are a few details which others may be able to answer: Do you need a common ground with the hub? What quality must the 5V supply have (ripple, voltage precision)?

A: It's been a while since I've worked with the USB spec, but USB-compliant devices go through device enumeration where they are basically asked by the host how much power they will need.  Before enumeration is complete, they are allowed 100mA of current.  The request for current is part of the negotiation process.  The top-level USB Host manages the overall current draw on the bus and my understanding is it will deny a new device's requests for power when the budget won't allow it.  When the budget is spent, even modest requests should get denied.  Somebody else can confirm if I remember this correctly.
Best case situation (USB2.0) they can be allowed up to 500mA, depending on who else is on the bus.  With USB3.0 that amount went up to 900mA.

A: This is a terrible idea; don't do this!
With electronics, total power in always equals total power out. You have two power sources: up to 2 A from power supply and 0.9 A from upstream port, that's up to 2.9 A total. What happens if drives try to pull more than that?

*

*If the power supply is of good quality, it won't provide more than its rated 2 A and (at least some) drives won't spin up/will stop abruptly.

*If the power supply is not reliable, it will catch fire.

With daisy-chained hubs:

*

*If hubs have a diode that prevents backpowering, things get confusing: the power supply of the first hub powers all hubs down the chain, but the last one powers only the last hub. This is super unreliable.

*If they don't, all power supplies are shared between all hubs. This would be preferable.

What's more, HDDs will draw significantly more than rated current for a moment when they spin up. And they spin up as soon as they get power, i.e. simultaneously. Servers deal with this by starting drives one by one in intervals. You can't do this here because you don't have an advanced drive controller; each drive has one in its integrated SATA-to-USB adapter. More powerful power supplies will improve things, but it will still be super unreliable.
Power issues aside, this is still a terrible idea
I don't know how you intend to use this peculiar RAID array, but it's fundamentally flawed.
RAID is not about backup, RAID is about reliability. If you want protection against data loss, RAID is not what you need. So I assume the goal of this project is reliability and availability. Your array is very unreliable, so it doesn't serve its sole purpose.
Once a single drive fails or drops from array for whatever reason, it has to be brought back into the array and rebuilt. Rebuild of a single dozen-TB drive will take days. You want to use 2.5" drives, so we're probably in 500 GB - 5 TB range. Such drives will take between three hours and two days, probably. Now consider this:

*

*Your power solution is sketchy

*USB is not meant for permanent attachment - drives do disconnect accidentally every now and then

*We're not sure how well this hub will deal with plenty of drives

*These drives either take plenty of desk space with a rat's nest of cables or are neatly stacked, ready to be knocked down

*Neither of them was designed to work with vibrations amplified seven-fold (drive vibrations travel through case, desk, etc.)

With RAID 6 you can lose two drives without data loss, including drives that are pending rebuild. Considering these problems I wouldn't be surprised if you'd be losing drives faster than you can rebuild them. This will be a disaster waiting to happen.
Solution
You need a DAS (direct-attached storage). It's an enclosure in which you can put your drives, configure them as an array and have them presented as a single device. RAID is entirely managed by the DAS itself. NAS (network-attached storage) is also an option, but it will be available over the network rather than directly attached.
DAS and NAS devices are built with multiple drives in mind. Power problems are already solved for you, and disks are attached using SATA connectors and screwed in (3.5" disks are preferable, but you could go with 2.5" + adapters if you prefer them for some reason). Using drives designed for NAS is recommended.
This will cost a lot more, but it will work reliably which is the whole point.
You can reduce the price by buying external drives (they are cheaper than internal ones) and taking them out of their USB enclosures ("shucking"). But you may lose the warranty, you get drives that are not certified for arrays (vibration problem) and you must know what to buy: for example some 2.5" portable drives have USB ports soldered directly into their PCB, without any SATA port.
Some popular DAS brands are TerraMaster and Drobo.
TL;DR: Don't do this.
If you're on a tight budget, scale down and go for a DAS.


text:
Q: Close dropdown on click anywhere So I have the below code that works on clicking dropdowns and opening them, but then when I click on another dropdown, it doesn't close the previous one - How could I adjust my JS code to close the previous dropdown and keep the current dropdown open only?

function dropdowns() {
    var dropdowns = document.querySelectorAll('.dropdown:not(.is-hoverable)');

    if (dropdowns.length > 0) {
        dropdowns.forEach(function (el) {
            el.addEventListener('click', function (event) {
                event.stopPropagation();
                el.classList.toggle('is-active');
            });
        });

        document.addEventListener('click', function (event) {
            closeDropdowns();
        });
    }

    function closeDropdowns() {
        dropdowns.forEach(function (el) {
            el.classList.remove('is-active');
        });
    }
}
<link href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css" rel="stylesheet"/>

    <button class="button" aria-haspopup="true" aria-controls="dropdown-menu">
      Dropdown button

    </button>

        Dropdown item

        Other dropdown item

        Active dropdown item

        Other dropdown item

        With a divider

A: Call closeDropdowns() before you toggle the is-active class in your event handler.
function dropdowns() {
    var dropdowns = document.querySelectorAll('.dropdown:not(.is-hoverable)');

    if (dropdowns.length > 0) {
        dropdowns.forEach(function (el) {
            el.addEventListener('click', function (event) {
                event.stopPropagation();

                closeDropdowns(); // <== HERE
                el.classList.toggle('is-active');
            });
        });

        document.addEventListener('click', function (event) {
            closeDropdowns();
        });
    }

    function closeDropdowns() {
        dropdowns.forEach(function (el) {
            el.classList.remove('is-active');
        });
    }
}

However, you should add a check to test if the dropdown is currently open and if so - skip the toggling of the class as this will close and reopen it again.
el.addEventListener('click', function (event) {
    const isActive = el.classList.contains('is-active');

    closeDropdowns();

    if (!isActive) {
        el.classList.toggle('is-active'); // or simply el.classList.add('is-active');
    }

    event.stopPropagation();
});


text:
Q: Would an oracle for Rayo's function let you compute a model of $(V, \in)$? Working in Kelly-morse set theory, let $R$ be an oracle that can compute Rayo's function. Can $R$ compute a countable model $M = (\mathbb N,\in_M)$ that is elementary equivalent to $(V, \in)$?

A: This is an excellent question!
Here are some steps in the positive direction. I claim that the Rayo function can compute
the theory of true arithmetic. Indeed, I claim more, that we can push this into the hyperarithmetic hierarchy.
To see this, let's consider just true arithmetic first. Let $R$ be the Rayo function; so $R(n)$ is
the smallest number not first-order definable in $V$ in the
language of set theory by an expression of size at most $n$. [This
definition is made relative to a fixed truth predicate, and it is
not sensible to speak of the Rayo function in contexts where there
isn't such a truth predicate. For example, we cannot refer to the
Rayo function in ZFC, but it is fine in GBC+ETR or KM.]
Now, I claim that we can compute recursively whether a given statement $\sigma$
in the language of arithmetic is true or not in the standard model
$\langle\mathbb{N},+,\cdot,0,1,<\rangle$. The same idea appears in my solution to the question, The set of
largest numbers definable by formulas in different
lengths.
The algorithm is this: we
can compute atomic assertions directly, and we can reduce via
Boolean combinations. The only difficult case is to
check quantifiers $\exists m\ \varphi(m)$. But for this, I claim that it
is sufficient to check whether $\varphi(k)$ holds for any $k$ up to
$R(n)$, where $n$ is large enough to express the definition, "m is
the least natural number for which $\varphi(m)$ holds in
$\mathbb{N}$.'' The point is that if $\exists m\ \varphi(m)$ is
true, then the least such $m$ will be definable and therefore will
be smaller than $R(n)$ for that value of $n$. So we can use the Rayo function to reduce the infinite process of an existential quantifier into finitely many cases, since if none of those numbers works then we can be sure that there is no witness.
So the Rayo function $R$ computes $0^{(\omega)}$.
But actually, we can now push this further into the hyperarithmetic hierarchy. For example, we can compute $0^{(\omega+\omega)}$, which is the theory of the structure $\langle\mathbb{N},+,\cdot,0,1,<,0^{(\omega)}\rangle$. We just described how to compute atomic assertions in this structure, and now we can do the same trick again to get the theory of this structure, by using $R$ to bound the existential witnesses.
It seems to me that we can push this method much further, well into the hyperarithmetic hierarchy. But I'm not sure exactly how far. You want to push it all the way to $\text{Th}(V,\in)$,
which is quite a bit farther indeed.


text:
Q: Handling unused disk space in sql server db I have one database whose size is growing very fast. Curruntly its size is aruond 60GB however after executing db_spaceused stored procedure i could verify that more that 40 GB is unused(unused space is different, not reserved space which i unsderstand is for table growth). And actual data size is around 10-12 GB and few GB's in reserved space.
Now to collect that unsused space i tried to use the shrink operation but it turned out to be not helping. After searching further i also found not to use the shrink DB as that causes the data fragments to get genrated resulting in the dealay while disk operation. Now i am really not sure what other operation i should try to recollect the space and recollect the DB. I unsertand that due to the size queries might be taking longer that expected and reclaiming this space could help with the performance (not sure ).
While investigating i also come across Gererate Scripts feature. It helps exporting data, schema also but i am not sure if it also help creating script(everying user, permission and other things also) so that script will help creat as is replica(deep copy/clone) of DB using create scema and then populating it with data to other db/server ?
Any pointer would be helpful.

A: If your database is 60Gb it means it had grown to 60gb. Even if the data is only 20Gb, you probably have operations that grow the data from time to time (eg. nightly index maintenance jobs). The recommendation is to leave the database at 60Gb. Do not attempt to reclaim the space, you will only cause harm and whatever caused the database to grow to 60Gb to start with it will likely occur again and trigger database growth.
In fact, you should to the opposite. Try to identify why it grew to 60Gb and extrapolate what will happen when your data reaches 30Gb. Will the database grow to 90Gb? If yes, the you should grow it now to 90Gb. The last thing you want is for growth to occur randomly, and possibly run out of disk space at a critical moment. In fact you should check right now if your server has Instant File initialization enabled.
Now of course, the question is: what would cause 3x data size growth, and how to identify it? I don't know of any easy method. I would recommend start by looking at your SQL Agent jobs. Check your maintenance scripts. Look into the application itself, does it has a pattern of growth and delete for data? Look at past backups (you do have them, right?) and compare.
BTW I assume due diligence and you checked that the data file has grown to 60Gb. If is the LOG file that has grown then is easy, it means you enabled full recovery model and forgot to backup the log.


text:
Q: Is there any real time paypal ipn service PayPal has explicitly stated that their IPN service should not be relied on during the user checkout process. I believe the idea here is that IPN should be a tracking mechanism to keep our back end data in sync with PayPal's data. What I want to do is to use express checkout but enforce an "IPN" to hit my server, and for my server to appropriately respond, before anything is finalized.
I can then ensure that I only give out content to users once they've paid, and that if a user does pay for a piece of content they do not have to refresh or wait for the IPN to come in. One of the problems with doing this using a return url and query string, is that i have a single page website on the firefox phone. The phone gets data from our API web service. So i need this endpoint to be hit regardless of the return url.
I know there are some more features with PayPal advanced developer, at a fee. I'm fine with that if that's the case, but i just want to know my options first.

A: As the name implies, IPN is instant.  There are rare occasions where it may be slightly delayed, but that doesn't happen often, especially on the live servers.
You can build your IPN listener to do whatever you need as far as updating a database, generating custom email notifications, hitting 3rd party web services, etc. and those actions will be triggered in real-time.
You just need to get your listener created and configured in the PayPal IPN settings, or you can also pass the IPN URL in the NotifyURL parameter of your Express Checkout API calls.
If you happen to be using WordPress you may be interested in my PayPal IPN for WordPress plugin.  It gets you up-and-running with IPN very quickly, and then you can hook into the plugin to trigger your own functions based on different IPN types or payment statuses.
Extra Info from Comments
As mentioned, IPN is a post-transaction thing.  What you could do, though, is setup Auth and Capture on your checkout system.  When the order comes through you would run it as an Authorization, and when you're ready to "finalize" you would run the capture.
You would get an IPN for both the authorization and the capture.  So, one thing you could do, if it suits you, would be to run the order as an Authorization, and then within your IPN script, go ahead and run the capture.  That way you could do whatever checks you want to do and only capture if they pass.
In passing cases, the capture would take place "almost" instantly when the order takes place.  Cases where it doesn't pass, you could either void the Auth or let it sit there in a pending state.


text:
Q: Azure AD Differential query - Detect change in Directory role assignment for a user I am using differential query (AzureAD graph API) to detect changes in Azure AD from the last sync. I am getting all users, group memberships, manager changes. Only missing information is Directory Role assignment (e.g Billing administrator, SharePoint administrator etc).
How can I detect a change in roles of any user?
API - https://graph.windows.net/{org}/directoryObjects?api-version=1.5&deltaLink=xxxxxttttxxxxxxxx

A: First, if you have enabled those Directory Roles, you can use AAD Graph API operations on directory roles to list  members of those roles.
GET https://graph.windows.net/myorganization/directoryRoles/{object_id}/$links/members?api-version=1.6

But, This API can also list service principals which assigned this role.