SecPKCS12Import leak under arc?

Question: I was found memory leaks by iOS instruments on all SecPKCS12Import lines of that code under arc:
    SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, 0);
    CFStringRef certSummary = SecCertificateCopySubjectSummary(certRef);
    NSData *data = (__bridge_transfer NSData *) SecCertificateCopyData(certRef);
    NSURL *indexURL = [[NSBundle mainBundle] URLForResource:@"cert1" withExtension:@"p12"];
    NSData *localP12 = [NSData dataWithContentsOfURL:indexURL];
    NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
    NSString *password = ///
    [options setObject:password forKey:(__bridge id)kSecImportExportPassphrase];
    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) localP12,(__bridge CFDictionaryRef)options, &items);
    if (securityError == noErr) { };/// good } else { //bad }
    CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
    CFArrayRef certificates =
    (CFArrayRef)CFDictionaryGetValue(identityDict,kSecImportItemCertChain);
    SecCertificateRef localCert = (SecCertificateRef)CFArrayGetValueAtIndex(certificates,0);
    CFDataRef dataLocal = SecCertificateCopyData(localCert);
    NSData *local = (__bridge NSData *)dataLocal;
    //NSLog(@"local:%@",local);
    NSURL *indexURLmac3 = [[NSBundle mainBundle] URLForResource:@"cert2" withExtension:@"p12"];
    NSData *localP12mac3 = [NSData dataWithContentsOfURL:indexURLmac3];
    NSMutableDictionary * optionsMac3 = [[NSMutableDictionary alloc] init];
    NSString *passwordMac3 = //
    [optionsMac3 setObject:passwordMac3 forKey:(__bridge id)kSecImportExportPassphrase];
    CFArrayRef itemsMac3 = CFArrayCreate(NULL, 0, 0, NULL);
    securityError = SecPKCS12Import((__bridge CFDataRef) localP12mac3, (__bridge CFDictionaryRef)optionsMac3, &itemsMac3);
    if (securityError == noErr) { };/// good } else { //bad }
    CFDictionaryRef identityDictMac3 = CFArrayGetValueAtIndex(itemsMac3, 0);
    CFArrayRef certificatesMac3 =
    (CFArrayRef)CFDictionaryGetValue(identityDictMac3, kSecImportItemCertChain);
    SecCertificateRef localCertMac3 = (SecCertificateRef)CFArrayGetValueAtIndex(certificatesMac3,0);
    CFDataRef dataLocalMac3 = SecCertificateCopyData(localCertMac3);
    NSData *localMac3 = (__bridge NSData *)dataLocalMac3;
    NSURL *indexURLwebcob3 = [[NSBundle mainBundle] URLForResource:@"cert3" withExtension:@"p12"];
    NSData *localP12wwebcob3 = [NSData dataWithContentsOfURL:indexURLwebcob3];
    NSMutableDictionary * optionsWebcob3 = [[NSMutableDictionary alloc] init];
    NSString *passwordWebcob3 = //
    [optionsWebcob3 setObject:passwordWebcob3 forKey:(__bridge id)kSecImportExportPassphrase];
    CFArrayRef itemsWebcob3 = CFArrayCreate(NULL, 0, 0, NULL);
    securityError = SecPKCS12Import((__bridge CFDataRef) localP12wwebcob3, (__bridge CFDictionaryRef)optionsWebcob3, &itemsWebcob3);
    if (securityError == noErr) { };/// good } else { //bad }
    CFDictionaryRef identityDictWebcob3 = CFArrayGetValueAtIndex(itemsWebcob3, 0);
    CFArrayRef certificatesWebcob3 =
    (CFArrayRef)CFDictionaryGetValue(identityDictWebcob3,
                                     kSecImportItemCertChain);
    SecCertificateRef localCertWebcob3 = (SecCertificateRef)CFArrayGetValueAtIndex(certificatesWebcob3,0);
    CFDataRef dataLocalWebcob3 = SecCertificateCopyData(localCertWebcob3);
    NSData *localWebcob3 = (__bridge NSData *)dataLocalWebcob3;
    if ([data isEqualToData:local] || [data isEqualToData:localMac3] || [data isEqualToData:localWebcob3]) trust = YES;

    CFRelease(certSummary);
    CFRelease((CFDataRef) dataLocal);
    CFRelease((CFDataRef) dataLocalMac3);
    CFRelease((CFDataRef) dataLocalWebcob3);

where i'm wrong?
Comment: You could at least format your code nicely...
Answer: Wow. That code is really hard to follow. You seem to be doing three different PKCS12 imports, you may want to make that a single method that's called three times. Just saying.
Anyway, without even following your code I know what the issue may be - because I have seen this before. The Security methods you are using follow the CoreFoundation memory management patterns defined here. More than once I have found the PKCS12 identity import process leaking because someone did not realize that, or thought that bridge casts to ARC would just make it work.
But here is what you should look at - in addition to whatever Instruments is trying to tell you, of course:

You need to release the items passed as the last argument to SecPKCS12Import (the CFArrayRef in the documentation). Look at Apple's example for guidance.
I see something even more obvious - you are calling CFArrayCreate without a corresponding release.
Comment: The ARC transition guide also provides some guidance on using ARC with CoreFoundation: http://developer.apple.com/library/mac/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html
Comment: perfect explanation, tnx. sorry for code, no time to formatting, i just copy/paste

SecPKCS12Import leak under arc?


Creating a table to show averages on python

Question: I am trying to figure out the code to generate a table that shows average retail price, average wholesale price, and the average market share. I am being asked to use df and groupby
]
The image shows the gas stations I am looking at and lists the name, ID, Address, Latitude, Longitude, date, Price, Wholesale, Tax, mkshare, and brand.
Comment: What's your question?  What have you tried so far?
Comment: Check this question out https://stackoverflow.com/questions/64506283/create-a-pandas-table.  This is the reference documentation https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
Comment: This is my first time using python so I am trying to create a code to make a table. I haven't tried anything yet because I am not sure where to start
Comment: Hello! It may help us help you to further define your scenario, show sample input data, and give some example/expected output
Answer: IIUC this is what you want:
df.groupby("Name")[["Price", "Wholesale", "mkshare"]].mean()

Basically, you have to group by the gas stations names, select the necessary columns and get the mean of them.
It's always good to take a look at the documentation:

pandas.DataFrame.groupby
pandas.core.groupby.GroupBy.mean


How do I call API using postman for requesting token for large scale matrix routing in HERE API

Question: I am not able to figure out the exact API request format in Postman for requesting token for large scale matrix routing in HERE API. Below is the official document page which is not clear of course.
https://developer.here.com/documentation/large-matrix/dev_guide/topics/get-started/request-a-token.html
Any pointers would be appreciated.
Thank you.
Answer: The steps to using the Large-Scale Matrix Routing API is to first generate an OAuth 1.0 signature using your access key id and access key secret. See this page for how to create the credentials:
https://developer.here.com/documentation/authentication/dev_guide/topics/token.html
See how you can generate your signature and use the signature to request a token:
https://developer.here.com/documentation/authentication/dev_guide/topics/using-aaa-javasdk-or-3rd-party-libraries.html#using-aaa-javasdk-or-3rd-party-libraries
Comment: Thank you for your reply. I have done both already. Main concern is, how do i call REST API to get token using Postman?
Comment: Check this https://developer.here.com/documentation/authentication/dev_guide/topics/using-postman.html
Comment: @HEREDeveloperSupport  After following all this steps still getting this error in postman ~  "error_description": "errorCode: '401202'. Invalid Client Authorization header, expecting signed request format."


How To Retrieve specific node using Xpath c#

Question: I have an xml file
<BookLib>
  <Book Id="1">
    <Title>Title1</Title>
    <Author>Author1</Author>
    <Publisher>Publisher1</Publisher>
    <Subject />
  </Book>
  <Book Id="2">
    <Title>Title2</Title>
    <Author>Author2</Author>
    <Publisher>Publisher2</Publisher>
    <Subject />
  </Book>
  <Book Id="3">
    <Title>Title3</Title>
    <Author>Author3</Author>
    <Publisher>Author3</Publisher>
    <Subject />
  </Book>
</BookLib>

I want to select book id. I tried using this
@"/BookLib/Book/Title[contains(translate(text(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'" + searchText + "')]/@Id";

in XPathExpression
how can i retrieve 'id' using xpath in c#
Comment: Your XML seems malformed for me: Id=1 => `Id="1"`
Comment: And your second and third Title havea wrong end tag.
Comment: Also, you'd said what you tried - but not what the result was. (And do you have to use XPath? I'd personally use LINQ to XML...)
Answer: Since @Id is below Book, not Id, you have to move back up to get it:
@"/BookLib/Book/Title[contains(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'"
      + searchText.ToLower() + "')]/../@Id";

or do the comparison without moving down to Title in the first place:
@"/BookLib/Book[contains(translate(Title,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'"
      + searchText.ToLower() + "')]/@Id";

I personally prefer the latter because it seems a bit cleaner.
Answer: First you can use fn:lower-case() which is better than fn:translate as it use Unicode mapping to change the case. So it will work with accent like É->é, À->à, etc.
Then you can simplify by using XPath axes.
So, to get the @Id, you can use the following XPath (adapt to C#) :
@"//Book/Title[contains(lower-case(./text()),'" + searchText.ToLower() + "' )]/@Id";

Comment: `lower-case()` _would be_ better, if .NET supported XPath 2.0, which it does not.


DynamoDB: When does 1MB limit for queries apply

Question: In the docs for DynamoDB it says:

In a Query operation, DynamoDB retrieves the items in sorted order, and then processes the items using KeyConditionExpression and any FilterExpression that might be present.

And:

A single Query operation can retrieve a maximum of 1 MB of data. This limit applies before any FilterExpression is applied to the results.

Does this mean, that KeyConditionExpression is applied before this 1MB limit?
Comment: @error404 Are you sure? I understand it X has to be <= 1MB, then X gets filtered to Y and is especially < 1MB.
Comment: this means that for a query if the `FilterExpression` alone has an output of 1MB then this limit is applied
Comment: @J.Hesters — Your understanding has always been my impression and how I interpret the docs: `KeyConditionExpression` produces at most 1MB of data, and is further filtered to return you less than 1MB.
Comment: @readyornot that's how I understand it, too.
Answer: Indeed, your interpretation is correct. With KeyConditionExpression, DynamoDB can  efficiently fetch only the data matching its criteria, and you only pay for this matching data and the 1MB read size applies to the matching data. But with FilterExpression the story is different: DynamoDB has no efficient way of filtering out the non-matching items before actually fetching all of it then filtering out the items you don't want. So you pay for reading the entire unfiltered data (before FilterExpression), and the 1MB maximum also corresponds to the unfiltered data.
If you're still unconvinced that this is the way it should be, here's another issue to consider: Imagine that you have 1 gigabyte of data in your database to be Scan'ed (or in a single key to be Query'ed), and after filtering, the result will be just 1 kilobyte. Were you to make this query and expect to get the 1 kilobyte back, Dynamo would need to read and process the entire 1 gigabyte of data before returning. This could take a very long time, and you would have no idea how much, and will likely timeout while waiting for the result. So instead, Dynamo makes sure to return to you after every 1MB of data it reads from disk (and for which you pay ;-)). Control will return to you 1000 (=1 gigabyte / 1 MB) times during the long query, and you won't have a chance to timeout. Whether a 1MB limit actually makes sense here or it should have been more, I don't know, and maybe we should have had a different limit for the response size and the read amount - but definitely some sort of limit was needed on the read amount, even if it doesn't translate to large responses.
By the way, the Scan documentation includes a slightly differently-worded version of the explanation of the 1MB limit, maybe you will find it clearer than the version in the Query documentation:

A single Scan operation will read up to the maximum number of items set (if using the Limit parameter) or a maximum of 1 MB of data and then apply any filtering to the results using FilterExpression.


There's a matrix cookbook. Is there a set cookbook?

Question: There's a matrix cookbook. Is there a set cookbook?
I'm looking for a comprehensive list of properties, formulas, inclusions or lack thereof on the algebra of sets, De Morgan's laws,  Cartesian products, infinite (countable or uncountable) intersections or unions, etc.
For example, in topology, real analysis, probability theory or measure theory, I see a lot of expressions like $$\bigcup_{k=1}^{\infty} (A_k \cap B_k)$$ $$ (A \cup B) \times (C \cup D)$$ $$ \bigcap_{x \in X} (A_x \times B_x)^c$$
Sometimes I wonder if we can do things like put/remove a $\cap B$ or $\cup A$ to both sides of a set inclusion. If it's a set equality, I think there are cases where it's a no longer equality but merely an inclusion or sometimes not an inclusion at all.
Expressions similar to the ones aforementioned don't always equal to something, they're usually just subsets or supersets of something else, and sometimes there's no (or no relevant) set inclusion. These are not difficult to prove; I'd just like to have a reference much like the matrix cookbook please.

I'm interested mainly in the basics and not necessarily about open/closed, non-/measurable, counterexamples, etc. If a set inclusion is true and the reverse doesn't hold, I'll take the cookbook's word for it.
I think this can be found in some appendix of some textbook. For example, a Calculus textbook appendix might have a list of trigonometric identities, without proofs, counterexamples or exercises. That's what I'm looking for.
Wiki is helpful but doesn't have a lot of the properties. For example, the Cartesian products page doesn't have the second expression above (other than explaining what the second expression is not) and whether or not an empty Cartesian product implies one of the Cartesian factors is empty, but I was able to find both and more on stackexchange.
There are books on these, but a lot of the properties are in exercises, some of which are determining true/false rather than dis/proving, so I'd have to try them myself or look up the solutions manual.

I wish there was some compilation of all these folklores.
Comment: Chapter I of "Foundations of Modern Analysis" by Dieudonne. But if these things don't become natural, doing practice exercises will be more useful than memorizing rules or looking them up all the time.
Answer: The book " Naive Set Theory " by Paul Halmos is very informative and readable book.
Comment: Correct me if I'm wrong. the author may be Paul Halmos, not Paul Halmus.
Comment: @LeAnhDung Thanks for the correction. yes Paul Halmos is the author.
Comment: Thanks Mohammad Riazi-Kermani, but I'm not looking to re-/learn these. I already know them or know how to prove/disprove them. I'm just looking for a list of formulas and stuff. Still, the Halmus textbook seems pretty close.


How tight should a Maid-o-Mist steam valve adjustment screw be?

Question: I have a single pipe steam heat system with radiators.  To use this system I use the Maid-o-Mist brand valves.  These valves come in different sizes.  The website provides a nice diagram about what should go where:

And it seems that the difference in the size is just about the little piece that screws into top of the valve.

Now here is the part I don't understand.  Because this part screws in, does it have to be tight?  It never says anywhere on the website and it feels like loosening it is an adjustment.  But maybe it just loosens because it was easier to make it that way.
Question >> How tight should the top piece be for normal operation?
Link of interest: Product web page
Comment: Tightening and loosening on a maid o mist does NOT adjust vent rate.
Answer: The particular model in the diagram should have the orifice hand tight. If the orifice is left loose it can vibrate loose and fall off. There are other models and other brands that are adjustable. By turning the cap you expose more or less of the orifice. The larger the orifice the faster the air is expelled. This allows the steam to enter the radiator at a somewhat controlled rate. This allows you to slow or increase the rate that the radiator warms to balance the heat from room to room.


How do I patch a sys attribute using a decorator?

Question: I have a function which depends on the Python version. I would like to test this in a unittest by mocking sys.version info. The following code works:
def test_python_version(self):
    with patch("sys.version_info", [3]):
        my_func()
    with patch("sys.version_info", [2]):
        my_func()

I would like to use a decorator, but the following code does not work. Why is this? How do I set the value of the MagicMock object that gets passed into my test? Thanks
@patch("sys.version_info")
def test_python_version(self, mock_version_info):
        mock_version_info.return_value = [3]
        my_func()
        mock_version_info.return_value = [2]
        my_func()

Fails with TypeError: '<' not supported between instances of 'MagicMock' and 'int' when my_func tries to do if sys.version_info[0] < 3.
Comment: Fixed my answer, sorry for the inconvenience.
Answer: Edit:
Yes it works. The original function returns a named tuple with major, minor and micro fields. You can mimic it by building your own named tuple. I just use a simple tuple as you access with int index instead. Problem with your code is in the way you indexed with [0] which was not right.
Edit2:
As Zaur Nasibov pointed out sys.version_info is not a function, and so my code was wrong despite looking fine with the mocks (as GenError also found). I have done a little change to fix it (see GenError answer for an alternative using PropertyMock)
import sys
from unittest.mock import patch

def my_func():
    version = sys.version_info # removed the ()
    print('Detected version:', version)
    if version[0] < 3:
        print('Error: Python 3 required.')

@patch('__main__.sys')
def test_python_version(mock_sys):
        mock_sys.version_info = (3,6,2)
        my_func()
        print()
        mock_sys.version_info = (2,7,0)
        my_func()

test_python_version()

Outputs
Detected version: (3, 6, 2)

Detected version: (2, 7, 0)
Error: Python 3 required.

Comment: Thanks for your comment @ZaurNasibov. I have just fixed the answer. Mocks are good at making code appear to work :)
Comment: my_func() has the line: `if sys.version_info[0] < 3` which causes `TypeError: '<' not supported between instances of 'MagicMock' and 'int'`
Comment: @pkiller162 You missed `()`  before `[0]`. See my edit.
Comment: `sys.version_info` is not callable. `sys` module should be patched instead (see @GenError's answer).
Answer: I found the answer by progmatico but it has a serious issue for me, as it requires to call sys.version_info() instead of sys.version_info which would break the code if ran normally.
Example:
#filename: a.py
import sys
def do_something():
    if sys.version_info > (3,5):
        print('Python 3.5 or newer')
    else:
        print('Python pre 3.5')

Now if I want to test both cases in a unit test @patch("sys.version_info") will lead to an error as given by OP. Changing do_something() to use sys.version_info() would break it if the mock is not used.
Test file:
#filename: test_a.py
from unittest.mock import patch, PropertyMock
import a

@patch('a.sys')
def test_a(mock_sys):
    type(mock_sys).version_info = PropertyMock(return_value=(3,4))
    a.do_something() # will show mocked python version

So you have to mock the sys module imported in the module a and set a PropertyMock on it.
Comment: Thanks for pointing the issue with my answer. Take a look at it after the fix. You don't have to use a PropertyMock, if you don't want to.


Volume of a solid of revolution around y axes

Question: The problem is to find the minimum volume for the solid of revolution around y axes given by the curve
$f(x)=-8ax^2+a+\frac{3}{4}$
My first idea was to find what is the parameter a that minimizes the area in the first quadrant given by integral
$\int_0^{\sqrt{\frac{a+3/4}{8a}}}f(x) dx$
So then the volume of the solid of revolution given by this curve would be minimum. The problem is that my answer doesnt match with the reference =(
Comment: What is your answer, how did you get it, and what is the given answer?
Comment: By the way, the answer that I got was $a=\frac34$.
Comment: Are you assuming only for $y \geq 0$? You need to minimise $\int_{0}^{a+3/4} \pi (f^{-1}(y))^{2}\, dy$, which is the volume of revolution about the $y$-axis. This is a different problem than minimising area.
Answer: $$V=\int_{x_1}^{x_2}2\pi x\,f(x)dx$$
where $f(x)=\frac{4a+3}{4}-8ax^2$ where $a\geq 0$, $x_1=0$ and $x_2=\sqrt{\frac{4a+3}{32a}}$ which is the positive $x$-intercept. Then,
$$V=\int_0^{\sqrt{\frac{4a+3}{32a}}}2\pi x(\frac{4a+3}{4}-8ax^2)dx=\frac{(4a+3)^2}{256a}\pi.$$
Minumum volume occurs when $\frac{dV}{da}=0$. The positive solution is $a=\frac34$.


How does android.provider.CallLog.Calls store its numbers?

Question: So my problem is that I'm trying to delete all call logs associated with a given number. In the Android API, android.provider.CallLog.Calls stores all the calllogs, and a context resolver (ctx.getContentResolver()) has a delete function that lets you delete whatever calllogs satisfy your conditions.
However, since I'm not sure how android.provider.CallLog.Calls stores its numbers (eg, with or without whitespace, hyphens etc) I don't know how to run a comparison on the number. Here's my current code:
<code>ctx.getContentResolver().delete(android.provider.CallLog.Calls.CONTENT_URI,
                        "number='"+numbers.getLong(i)+"'", null);
</code>
The API here (http://developer.android.com/reference/android/provider/CallLog.Calls.html#NUMBER) describes the number as "The phone number as the user entered it" which doesn't really help me.
Any thoughts on how I should tackle this issue?
Thanks,
Khalid
Answer: Why not just try out some code and see what you get back? My guess is that since the number is stored "as the user entered it", there will not be any dashes, as they simply just dialed the numbers.
Comment: Alas, I don't have an actual phone to work on. The emulator produces the number as just a number (no dashes etc). It doesn't work on my client's phone though, and I'm /guessing/ this might be why.


What is asbestos cement sheet?

Question: How do I tell if I have asbestos cement sheet?
How should I remove an asbestos cement sheet?
Comment: See: http://diy.stackexchange.com/questions/166/asbestos-removal - not a duplicate at all, but related. I also suggest ignoring the suggestion to DIY because I don't believe it's safe and the person who answered is putting people at risk.
Answer: Call a professional.
I'm not sure there are really any diy ways to handle asbestos.  In most places you need a license, and lots of expensive equipment to remove asbestos.  You might be able to find somebody in your area willing to come out and take a look for free, if you are really lucky and they are really nice (or really hard up for work) they might even test it for free.  The removal will most likely be a bit costly though.
Comment: @Ian: but if you break it or crack it during removal, there could be dust.
Comment: asbestos cement is not as bad as normal asbestos as you don't get any dust if you don't cut it etc
Comment: @Ian: Tester101 is right. You really don't want to take any chances with that stuff.

What is asbestos cement sheet?


Can WCF contract methods return null?

Question: I have a fixed-sized multidimensional collection exposed via a WCF contract, and I want to be able to return null for any coordinates in the collection that have not been populated. When I try this, I get an exception indicating that this is not supported: "FaultException`1: Object reference not set to an instance of an object."
I wondered whether some flag of OperationContract could be used, but none stand out.
Is what I want possible, or is there some intrinsic restriction within WCF?
Thanks
Answer: In WCF nothing prevents you from returning null from any operation contract method.
The exception you get is a FaultException<NullReferenceException> which means somewhere in your server-side code you are referencing an object which is set to null. Check your server-side code.
Comment: Thanks for the prompt reply. I'll check my workings again, and post further. My apologies for wasting your time, if it turns out I have.
Answer: Yes they can, mine do all the time. Could you post the relevant bits of your service contract and/or data contracts so we can see where the problem might be?
Comment: Thanks for the prompt reply. I'll check my workings again, and post further. My apologies for wasting your time, if it turns out I have.
Answer: As both Gart and Christian stated, you can indeed return null from WCF contract methods. I was in fact caught by my own (attempt at) cleverness, where the external (contract) type was converted from the internal type via an implicit conversion operator, within the implementation of which properties of the internal type were accessed as arguments to the constructor of the external type. Hence the NullReferenceException.
Doh! to me. Cred to G & C. Gart gets the "accept" by a hair, since reading his gave me the lightbulb moment.

Can WCF contract methods return null?


Fill in missing values with mode in SAS

Question: I think the logic to replace missingness is quite clear but when I dump it to SAS I find it too complicated to start with.
Comment: Two suggestions.  First, look into PROC EXPAND and PROC STDIZE, if you have those licensed.  They both have options related to what you're doing.  Second, give it a try.  You want to replace with modes, well, first step is _calculate those modes_.  Do that, see whether it becomes obvious to you how to incorporate them - if not, post what you have here and you can get more meaningful help.  Post enough data to make your problem clear and the code to at least calculate the modes and solve some of the simpler cases.
Comment: Still struggling with this?
Answer: Given no code was provided, I'll give you some rough directions to get you started, but put it on you to determine any specifics.
First, lets create a month column for the data and then calculate the modes for each key for each month. Additionally, lets put this new data in its own dataset.
data temp;
   set original_data;
   month = month(date);
run;

proc univariate data=temp modes;
   var values;
   id key month;
   out=mode_data;
run;

However, this procedure calculates the mode in a very specific way that you may not want (defaults to the lowest in the case of a tie and produces no mode if nothing occurs at least twice) Documentation: http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/viewer.htm#procstat_univariate_sect027.htm
If that doesn't work for you, I recommend using proc sql to get a count of each key, month, value combination and calculating your own mode from there.
proc sql;
   create table mode_data as select distinct
   key, month, value, count(*) as distinct_count
   from temp
   group by key, month, value;
quit;

From there you might want to create a table containing all months in the data.
proc sql;
   create table all_months as select distinct month
   from temp;
quit;

Don't forget to merge back in any missing months from to the mode data and use the lag or retain functions to search previous months for "old modes".
Then simply merge your fully populated mode data back to the the temp dataset we created above and impute the missing values to the mode when value is missing (i.e. value = .)
Hope that helps get you started.

Fill in missing values with mode in SAS


extraHeaders not being attached to petition

Question: I'm trying to integrate socket.io with my angular that. For that, I've followed the steps outlined in this article. Since my server (which uses Express) is using jwt based authentication, I'm setting the authentication headers as per the socket.io docs. Here's the Angular service code:
@Injectable()
export class PushNotificationsService {

  socket: SocketIoModel;
  observer: Observer<any>;
  environment;

  constructor (private authService: AuthService) {
    this.environment = environment; // This contains the server endpoints
  }

  async getQuotes (): Promise<Observable<number>> {
    this.socket = socketIo(this.environment.url, {
      transportOptions: {
        transports: ['polling'],
        polling: {
          extraHeaders: {
            'Authorization': `Bearer ${await this.authService.getToken()}`
          }
        }
      }
    });

    this.socket.on('data', (res) => {
      this.observer.next(res.data);
    });

    return this.createObservable();
  }

  createObservable (): Observable<number> {
    return new Observable(observer => {
      this.observer = observer;
    });
  }

  private handleError (error) {
    console.error('server error:', error);
    if (error.error instanceof Error) {
      const errMessage = error.error.message;
      return Observable.throw(errMessage);
    }
    return Observable.throw(error || 'Socket.io server error');
  }
}

If I inspect the socket attribute, I can see that the option is being set. But, when I inspect my app's petitions with the browser, I can see that the Authentication header is not present:

Any ideas on what I'm doing wrong?
Answer: Transports option goes at the same level as TransportOptions.
You could try if that makes a difference but I don't think that is your problem though as "polling" is the default anyway.


Db::Instance prestashop

Question: I added config.inc.php inside my php script in order to access to Db class provided.
The problem is that when I launch the script from the server, it redicted to the website prestashop and then I can't see what I want to echo in the html page.
More, I have made a error in order to see the behaviour: nothing is shown, he redirect to the prestashop website.
Please help me.
Answer: SOLVED
After lots of tests, the soloution is very easy.
In order to use class from Prestashop service in my_own_file.php, we have to include

config.inc.php located inside config directory
init.php located at the root of the store

But, to reach this two includes,  my_own_file.php has to be at the root of the prestashop store directory or inside it.
The reason is that, to access to prestashop store files, the file has to be part of the store also. Otherwise, you don't have the permission and your sever loads index.php .
Comment: Be sure to switch constant inside defines.inc.php _PS_MODE_DEV_ to true from false to see debug trace.

Db::Instance prestashop


Grab data outside a specific tag in Python BeautifulSoup4

Question: I am using Python 3.8 with BeautifulSoup4.
I am on Windows 10 and I use PyCharm.
I am kinda new with this lib but I was able to manage simple extractions. However, I have this HTML code (which I didn't make and which I cannot edit) :

               Achenheim (Région de Mundolsheim, Bas-Rhin)

                           >
                                                St-Georges : Max ROETHINGER, 1962.

               Adamswiller (Région de Drulingen, Bas-Rhin)

                           >
                                                Eglise protestante : George WEGMANN, 1846.

So far, I was able to grab the values "Achenheim" (in the span tag), and "St-Georges : Max ROETHINGER, 1962." (in the a tag).
I would like to know if it's possible to grab the following values:
(Région de Mundolsheim, Bas-Rhin)

I struggle because it's not really inside any specific tag, beside a li tag. But when I try to grab the text value of the li tag, I get this :

Achenheim (Région de Mundolsheim, Bas-Rhin)

>
                                                St-Georges : Max ROETHINGER, 1962.

My code is this:
from bs4 import BeautifulSoup
import requests as requests

r = requests.get('url_link')
soup = BeautifulSoup(r.content, 'html.parser')

regions = soup.select('ul li')
for r in regions:
    print(str(r))

It's not what I was expecting :(
Anyone knows how to grab a data that it outside a specific tag please? Again, I am trying to get :
(Région de Mundolsheim, Bas-Rhin)

Triming and slicing cannot be a solution in my case :/
Answer: You can use .find_next_sibling with text=True parameter:
for d in soup.select(".def"):
    print(d.find_next_sibling(text=True).strip())

Prints:
(Région de Mundolsheim, Bas-Rhin)
(Région de Drulingen, Bas-Rhin)

Answer: You could change your strategy selecting the elements and use the  instead:
for e in soup.select('ul span'):
    print(e.text)
    print(e.next_sibling.strip())
    print(' '.join(e.find_next('a').text.split()))

Example
from bs4 import BeautifulSoup

html = '''

               Achenheim (Région de Mundolsheim, Bas-Rhin)

                           >
                                                St-Georges : Max ROETHINGER, 1962.

               Adamswiller (Région de Drulingen, Bas-Rhin)

                           >
                                                Eglise protestante : George WEGMANN, 1846.

'''
soup = BeautifulSoup(html)

for e in soup.select('ul span'):
    print(e.text)
    print(e.next_sibling.strip())
    print(' '.join(e.find_next('a').text.split()))

Output
Achenheim
(Région de Mundolsheim, Bas-Rhin)
> St-Georges : Max ROETHINGER, 1962.

Adamswiller
(Région de Drulingen, Bas-Rhin)
> Eglise protestante : George WEGMANN, 1846.

Comment: Thank you for the very completed answer :)


How to check the type of installed insulated glazing

Question: In the Netherlands, insulated glass is rated by a standardized rating system, classifying it into 3 categories by the u-value:

HR : U value between 2.0 and 1.7
HR+ : U value between 1.6 and 1.3
HR++ : U value less than 1.2

The price difference between these types of insulated glass is quite large. After the glass has been installed, is there any simple way to measure the U value or otherwise check the type? I guess it would be quite easy for a swindling contractor to sell HR++ and install HR without it ever being noticed?
Answer: Louis it is a really good question.  First if you have the space to put the cheaper insulation then you can simply buy more of that to get the same results.  If the insulation type is the same but different U value then it only matters what total you are getting.
How to verify this?  This has been answered on the site many times - a couple by me.  There isn't an exact way but you can get a rough estimate.  Remember you are also measuring the installation not just the insulation.  If not packed correctly and there are gaps then you will have the same poor performance.
How do you know what a contractor installs?  You watch them do it.  If the insulation is covered in walls or whatever then there isn't an exact way to tell that they did or if it is the right stuff.  You need to be there and take pictures and ask questions.  A good contractor won't care if you are doing this.
Comment: Seems like you misunderstood insulated glazing with fiberglass insulation? Insulated glazing is used for windows, and is not hidden behind walls. It is the transparent part of the window and is made out of two layers of glass with a gap between them, sealed and filled with some invisible transparent gas. The glass should be coated with an (invisible) thin metal coating. The window and all glass parts and layers are openly viewable, however the features are all invisible to the naked eye. The only thing I can verify is two layers of glass with a gap between. How can I verify coatings and gas?
Answer: This is hard to do and I agree that there is a big range of cost between basic insulated sealed units and some of the high performance glass units which can be triple the cost.  Here in Canada when we install a commercial glass project we are required to provide warranty documentation from the glass supplier which shows the makeup of the sealed units ( glass thickness, low-e coatings and any gas filling details ).  This information even provides the invoice numbers for glass provided for the job and can be a great help in matching up replacement glass when breakage or insulated glass failure becomes an issue down the road.  I would try to get this documentation from window / glazing contractor.  If this is not available there is a measuring tool from CR Laurence that can tell you the glass thicknesses, airspace thickness and what surface the low-e coating is on.  It won't tell you the type of low-e glass nor whether there is any argon gas but will provide you with basic information.  A professional glazier can often take a look at the colour of the glass from inside and outside to point you in the right glass type direction as well.  Good luck!
Comment: Do you have a link to the tool from CR Laurence? I couldn't find it. Probably it wouldn't be worth the it for just me, but offering measuring as a service it could turn out profitable. Especially if it uncovers some wide scale swindling. I'm really wondering if there's any coating at all on my windows, I don't see any difference between the inside or outside, and no marking. The glass layer on the outside is a fraction thicker than the one on the inside. Here we only get warranty for the window frame, glass is usually covered by a separate insurance.
Answer: I finally (9 years later) found an easy way at the end of this video on YouTube (it's in Dutch).
Hold a lighter, match or candle in front of the glass and look at the reflections, with double glass you should see 4 reflections (each surface will reflect a little). If it is HR++ glass then the 2nd or 3rd reflection should have a slightly different color.
Here's an example where it can be clearly seen: https://youtube.com/shorts/a5ULReRtAbA


How to fill cracks when building wood furniture?

Question: This is my first thing here, and I'm still an amateur at DIY.
I'm building a raised bed for my daughter.
I'm using wood.
Right now I'm trying to find out what is the best material to fill in imperfections on the wood, and the places of the joins, and even the grain of the wood itself.
My final goal is to use a enamel paint to make "feel" smooth.
Answer: Good for you for tackling this project.  If you're an amateur and this is your first project, then don't try to be perfect because you will be beating yourself up for no reason.
If you are going to paint the finished project, then the looks don't matter so much.  You can buy wood filler that will fill any gaps and grain.  Force it into any gaps or cracks with a putty knife, and then sand smooth afterwards.   If needed, start with a coarse grain sandpaper (otherwise start with medium) and then progress to fine.   Wood filler can create fine dust, so use a dust mask while sanding.   For panels, I would recommend using MDF as it has a very smooth surface for painting.  Cutting MDF creates a LOT of dust, so always use a mask and remember that it's better to do this outside or with a dust collection system.
Comment: Thanks @Mark for all you suggestions, and yes, I know that this is not going to be perfect :-), but if I use the appropriate techniques / tools it's more likely to be better. Is there any particular brands of wood fillers that you use? I want to get as much info as possible because i'm in Portugal and the terminology will definately be different, but a product/brand name will stay the same, so it will be easier to find here.
Comment: I used the Lepages wood filler.  It's a pretty good product.
Answer: If the cracks are large, a catalyzed filler (like car body bondo) often works well.  I think "wood epoxy" is essentially the same product, except that it's tinted grey instead of pink, which may make it easier to stain to the desired hue.


How to run drywall backer parallel to I-joist?

Question: I'm trying to install a non-load bearing basement wall parallel to an I-joist.  The tricky part is, how do I run a drywall backer parallel to the I-joist? The top plate is wider than the flange of the i-joist, so I figured I put the edge of the top plate flush with the edge of the interior side of the flange.  I saw a diagram for how to do a wall with a regular flange, either putting a 2x4 on the flat and attaching to the top plate, or on its side and attaching to the joist.

If I made it flush like described above, would I be able to nail the 2x4 to the joist flange (would only be able to nail the bottom, not the top).  Could I get away with just using a 2x2 running parallel to the flange to act as the nailer?
Answer: Yes, 2x2s attached to a joist will work as a nailer, use screws to secure the drywall there, although the drywall mounted to the wall will support it if it is tight to it. Another way to get nailers in place is to use short scraps of 2X material and nail them perpendicular to the joists, flush to the bottom of the joists at 16 or 24" on center and set your wall to them. That way you do not need to limit yourself to position your wall under a joist.
Comment: Yah, I'm doing the blocking on two other walls in the basement, but I there are two walls where they just happen to run exactly under a joist and it' be easier to not have to install of the blocking (plus it seems like it'd be much more stable to use just the joist and not the blocking)
Comment: Technically, blocking would be more stable, as it would provide far more lateral support, than parallel.
Answer: I prefer the on-flat for the best fire sealing & another couple of inches for wall positioning. This can be done, without 6" screws or using easily split 2x2's. By, drilling a small hole, the size of the screw's Threads, through the 2x4. Then, drill a bigger hole, the size of the screw's Head, halfway into the smaller hole or halfway through the stud to sink 3" screws.
The vertical 2x4 install is fine by just being screwed to the bottom of the I-joist. You can also install an I-joist webbing filler or backer to then screw-in both the top & bottom of the 2x4. This, is a bit overkill, which is absolutely not a bad thing, but it would only be holding up drywall that is also supported by the drywall upon the wall below...ceilings must always be the first to get drywall.
You might also see short bridging 2x4's perpendicular to the joists that span to the next joist. This is completely acceptable since the drywall of the wall below will still seal the ceiling seams on both sides. This, allows you to put the wall exactly where you want it within the joist bay's otherwise open & empty span, rather than being stuck to just where the joists are.


Element UI Pagination in Chinese instead of English

Question: I started using the very nice Element UI components, and when I try to add the pagination component in my project using
<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage4" :page-sizes="[100, 200, 300, 400]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="400">
</el-pagination>

the text appears in chineese like this:

It also happens on their JSFiddle sample, but it's not happening on their website.
Do you know how can I use it in english?
Answer:
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en'
import App from './App.vue'

Vue.use(ElementUI, { locale })

new Vue({
  el: '#app',
  render: h => h(App)
})

http://element.eleme.io/#/en-US/component/i18n
Comment: Simple and Straight forward! ✨
Answer: Just add

and

The source:
https://element.eleme.io/#/en-US/component/i18n#import-via-cdn
It is also recommend that for production, you use a specific version of the unpkg. You can find the latest version by loading the url's (without the leading //) in your browser and then copying the redirected url.
Answer: 'Internationalization': https://element.eleme.io/#/en-US/component/i18n
By default the language of Element is Chinese. If you wish to use another language, you'll need to do some i18n configuration.
If you are importing Element entirely: (In your entry file, usually found in src > main.js configure it as shown below)
import Vue from 'vue'
import ElementUI from 'element-ui'
import locale from 'element-ui/lib/locale/lang/en'

Vue.use(ElementUI, { locale })

But if you are importing Element on-demand and not in your entire application:
// Here we are importing only the Button and Select component from Element
import Vue from 'vue'
import { Button, Select } from 'element-ui'
import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'

// configure language
locale.use(lang)

// import components
Vue.component(Button.name, Button)
Vue.component(Select.name, Select)

Important: The Chinese language pack is imported by default, even if you're using another language. But with NormalModuleReplacementPlugin provided by webpack you can replace default locale:
In your webpack.config.js file
{
  plugins: [
   new webpack.NormalModuleReplacementPlugin(/element-ui[\/\\]lib[\/\\]locale[\/\\]lang[\/\\]zh-CN/, 'element-ui/lib/locale/lang/en')
  ]
}

Answer: In case you're already setting the locale as suggested, this might also be caused by inconsistent bundling:

Your bundler might inline the element-ui/locale import
Your bundler might treat the element-ui import as external
Therefore, you set the locale on a second copy of the file instead of within element UI itself
Element-ui then reads from its own copy and ignores yours

(See https://github.com/3YOURMIND/kotti/pull/264 for a real PR that fixed a bundling issue like this)


Mongodb connections not closing in nodejs tests

Question: So I have a suite of cucumber tests and in the BeforeFeatures section I create connections to 2 databases on the same server, I have set the pooling to 2 so I can see when I connect 4 connections occur (2 databases with 2 pools).
Then at the end I close the databases like so:
var closeDatabase = function(callback) {
    db1.close(function(){
        db2.close(function(){
            console.log("DONE");
            callback();
        });
    });
};

Now this is invoked and I see the console output and the process closes so both database connections should be closed. However if I look at the mongodb logs:
2016-01-14T11:45:05.813+0000 [initandlisten] MongoDB starting : pid=888 port=27017 dbpath=C:\Tools\mongodb\data 64-bit host=SomePC
2016-01-14T11:45:05.818+0000 [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2016-01-14T11:45:05.821+0000 [initandlisten] db version v2.6.7
2016-01-14T11:45:05.822+0000 [initandlisten] git version: a7d57ad27c382de82e9cb93bf983a80fd9ac9899
2016-01-14T11:45:05.826+0000 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2016-01-14T11:45:05.829+0000 [initandlisten] allocator: system
2016-01-14T11:45:05.830+0000 [initandlisten] options: { storage: { dbPath: "C:\Tools\mongodb\data" } }
2016-01-14T11:45:05.846+0000 [initandlisten] journal dir=C:\Tools\mongodb\data\journal
2016-01-14T11:45:05.848+0000 [initandlisten] recover : no journal files present, no recovery needed
2016-01-14T11:45:05.871+0000 [initandlisten] waiting for connections on port 27017
2016-01-14T11:45:11.639+0000 [initandlisten] connection accepted from 127.0.0.1:51841 #1 (1 connection now open)
2016-01-14T11:45:11.646+0000 [conn1] end connection 127.0.0.1:51841 (0 connections now open)
2016-01-14T11:45:11.650+0000 [initandlisten] connection accepted from 127.0.0.1:51842 #2 (1 connection now open)
2016-01-14T11:45:11.653+0000 [initandlisten] connection accepted from 127.0.0.1:51843 #3 (2 connections now open)
2016-01-14T11:45:11.659+0000 [initandlisten] connection accepted from 127.0.0.1:51844 #4 (3 connections now open)
2016-01-14T11:45:11.662+0000 [conn4] end connection 127.0.0.1:51844 (2 connections now open)
2016-01-14T11:45:11.665+0000 [initandlisten] connection accepted from 127.0.0.1:51845 #5 (3 connections now open)
2016-01-14T11:45:11.669+0000 [initandlisten] connection accepted from 127.0.0.1:51846 #6 (4 connections now open)
2016-01-14T11:45:11.689+0000 [conn5] end connection 127.0.0.1:51845 (3 connections now open)
2016-01-14T11:45:11.689+0000 [conn6] end connection 127.0.0.1:51846 (3 connections now open)
2016-01-14T11:45:11.690+0000 [conn2] end connection 127.0.0.1:51842 (3 connections now open)
2016-01-14T11:45:11.690+0000 [conn3] end connection 127.0.0.1:51843 (3 connections now open)

So at the end although the 2 connections have ended it seems to leave 3 of the 4 connections active. This being said if we look at ports it seems to activate 6 ports even though it only has 4 connections.
So is this common? should I be worried or am I doing anything wrong? The whole reason this is an issue is because when I try to use the connections I get the error:
MongoError: server localhost:27017 sockets closed
So I am a bit baffled as to why its seemingly over-allocating and bombing out when I attempt to use the connections.
Answer: So the error is correct, it was closing the connections then using them, due to they way console outputs happen on windows they are not always 100% in the right order. It turned out cucumber was bombing out silently in an area and was having a knock on effect here.


forms authentication and deny access to all files

Question: I have created a "restricted" page with the forms authentication and it's working well.
<authentication mode="Forms">
    <forms loginUrl="login.aspx" defaultUrl="documents.aspx" />
</authentication>

<location path="documents.aspx">
    <system.web>
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</location>

I would like to deny access to a folder and all the files that it contains depending on this authentication. Basically, documents.apsx has a document list that you can download. If I try to access to www.mywebsite.com/documents I'm automatically redirect to the login.aspx. I added the following Web.config in my Documents folder:
<?xml version="1.0"?>
<configuration>

  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>

</configuration>

However, if I know the path of a document, for example www.mywebsite.com/documents/test.pdf I can access to this file.
My question is: How can I deny access to all the files in the Document folder if you are not authenticated?
Answer: Put all your doucments PDF in a folder and set restriction on that folder like this:
<location path="FolderName">
<system.web>
    <authorization>
        <deny users="?"/>
    </authorization>
</system.web>


How To Minimal ThisPHP Script

Question: Hi I have designed a page in which PHP checks for websites status if it gets 200 header status then it shows website is up else it shows website is down.
I have around 5 websites, and for this, I have to make the separate script, check the code below.
<!DOCTYPE html>

<title>Status Page
</title>

<?php
$URL  = 'https://www.example1.com';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_exec($curlHandle);
$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle); // Don't forget to close the connection
if ($response == "200") {
echo  "1. Example1 Is Running Fine";
}
else {
echo "1. Example1 Seems Down!";
}
?>
<?php
$URL  = 'https://www.example2.com';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_exec($curlHandle);
$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle); // Don't forget to close the connection
if ($response == "200") {
echo  "2. Example2 Is Running Fine";
}
else {
echo "2. Example2 Seems Down!";
}
?>
<?php
$URL  = 'http://www.example3.com/';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_exec($curlHandle);
$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle); // Don't forget to close the connection
if ($response == "200") {
echo  "3. Example3 Is Running Fine","";
}
else {
echo "3. Example3 Seems Down!";
}
?>
<?php
$URL  = 'https://www.example4.com';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_exec($curlHandle);
$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle); // Don't forget to close the connection
if ($response == "200") {
echo  "4. Example4 Is Running Fine","";
}
else {
echo "4. Example4 Seems Down!";
}
?>
<?php
$URL  = 'https://www.example5.com/';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_exec($curlHandle);
$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle); // Don't forget to close the connection
if ($response == "200") {
echo  "5. Example5 Is Running Fine","";
}
else {
echo "5. Example5 Seems Down!";

}

?>

Is there a simple method to do this instead of passing separate curl rule for each website?
I have gone with array and now it seems better, check new code below
<?php
$array = array( 'https://www.example1.com', 'https://www.example2.com', 'http://www.example3.com/', 'https://www.example4.com/', 'https://www.troublefixing.com/', 'https://easyfoodhealthtips.com/', 'https://cryptotipstricks.com/', );
foreach( $array as $value ) {
$URL  = $value;

$curlHandle = curl_init();

curl_setopt($curlHandle, CURLOPT_URL, $URL);

curl_setopt($curlHandle, CURLOPT_HEADER, true);

curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body

curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);

curl_exec($curlHandle);

$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);

curl_close($curlHandle); // Don't forget to close the connection
if ($response == "200") {
echo "$value Is Running Fine
","";

}

else {
echo "$value Seems Down!
","";

}
}
?>

On result page it shows the full URL as $value contains full URL, I want to show name of website like Example1, Example2 and so on.
Comment: Or an array of urls and loop through them.
Comment: try a switch case or a ternary
Comment: How to print the result of theme separately
Answer: Check out this link http://php.net/curl_multi_init

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>
Comment: That's too much copy-and-pasting, even if it were properly attributed.
Comment: for this problem -> "On result page it shows the full URL as $value contains full URL, I want to show name of website like Example1, Example2 and so on." use function -> str_replace("http://","", $value)

How To Minimal ThisPHP Script


Get Document from current user firebase swift

Question: I'm trying to get the firstname from this:

The user is logged in and I can access his uid, but I can't get the Document that belongs to that user, this is how I'm trying to do it:
<code>    private func getDocument() {

        var userID = Auth.auth().currentUser?.uid
            userID = String(userID!)

        var currentUser = Auth.auth().currentUser

//         Get sspecific document from current user
        let docRef = db.collection("users").document("bnf2s3RURUSV2Oecng9t")

        // Get data
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
            } else {
                print("Document does not exist")
            }
        }
    }
</code>
If you noticed, if I put manually "bnf2s3RURUSV2Oecng9t" it will access the data, but the point is to be able to know what ""bnf2s3RURUSV2Oecng9t" is so I can put it on that hard coded variable on top. My end goal is be able to get the first name of the current user :)
Answer: The problem is that your current authenticated user uid is not the same as the document uid. So normally if those ids where the same you would do something like this:
<code>    private func getDocument() {
        //Get specific document from current user
        let docRef = Firestore.firestore()
            .collection("users")
            .document(Auth.auth().currentUser?.uid ?? "")

        // Get data
        docRef.getDocument { (document, error) in
            guard let document = document, document.exists else {
                print("Document does not exist")
                return
            }
            let dataDescription = document.data()
            print(dataDescription?["firstname"] ?? "")
        }
    }
</code>
But in your case you would need to do it like this, since those values are not the same.
<code>    private func getDocument() {
         //Get specific document from current user
         let docRef = Firestore.firestore()
            .collection("users")
            .whereField("uid", isEqualTo: Auth.auth().currentUser?.uid ?? "")

         // Get data
         docRef.getDocuments { (querySnapshot, err) in
             if let err = err {
                 print(err.localizedDescription)
             } else if querySnapshot!.documents.count != 1 {
                 print("More than one document or none")
             } else {
                 let document = querySnapshot!.documents.first
                 let dataDescription = document?.data()
                 guard let firstname = dataDescription?["firstname"] else { return }
                 print(firstname)
             }
         }
     }
</code>
Comment: Excellent! Thank you very much for all your help :)
Comment: When I type `print(docRef)` it says: `` instead of `bnf2s3RURUSV2Oecng9t` also the result says: `Document does not exist`
Comment: well db was already `let db = Firestore.firestore()` . I tried your new code and I get the same
Comment: `print(Auth.auth().currentUser?.uid ?? "nil")` is going to print this: `XIbRKL7cK9N6Y4N7lRaoBsw2R5A3`
Comment: isn't the uid the one from the user? Which is printing it correct: `XIbRKL7cK9N6Y4N7lRaoBsw2R5A3`
Comment: is there a way to do instead of `Auth.auth().currentUser?.uid` do: `Auth.auth().currentUser?.firstname`?
Comment: Now it works! But it gives me: `Optional(Arturo)` is there a way we can leave it as `Arturo` only?
Comment: Hi Nicolas, I was testing my code now, because it's due tomorrow and I see that it's saying `"More than one documents or none"` do you know why? It seems that it's not getting anything from the user


Is a polynomial of degree 3 with irrational roots possible?

Question: It is easy to give an example of a polynomial of degree 3 with integer coefficients having:
(a) three distinct rational roots,
(b) one rational root and two irrational roots.
But for a while I am trying to construct one that all its roots are irrational but I can't. It seems that it is not possible at all?
Also, can a polynomial with integer coefficients of degree 3 have two rational roots and one irrational root?
Comment: If the polynomial has integer coefficients, then the sum of the roots is rational.  Therefore, it cannot have one irrational and two rational roots.
Comment: There isn't a clear, universally accepted, convention on "irrational $\implies$ real".  Some people say all non-real complex numbers are irrational. See, e.g., [this question](https://math.stackexchange.com/questions/823970/is-i-irrational)
 Always worth specifying your intent.
Comment: Note:  I assume you are requiring that all roots are real.  Otherwise $x^3-2$ does the job.
Comment: @ChinnapparajR, two rationals one irrational, is my question
Comment: @Edi with rational coefficients?
Comment: @taritgoswami, integer coefficients; and root must be real if they are irrational
Answer: By Vieta the sum of the roots must be rational, hence this excludes a single irrational.
All other cases are possible.
$$\begin{align}0&:x(x^2-1)=0,
\\2&:x(x^2-2)=0,
\\3&:8x^3-6x-1=0.\end{align}$$

The last one was built from
$$\cos3\theta=4\cos^3\theta-3\cos\theta=\cos\frac\pi3$$
so that the roots are
$$\cos\frac\pi9, \cos\frac{7\pi}9, \cos\frac{13\pi}9.$$
Comment: Sure it is, the roots of that are 0, sqrt(2), and -sqrt(2). The two irrational roots are sqrt(2) and -sqrt(2).
Answer: Yes, it is possible. Take $p(x)=x^3-3x+1$, for instance. By the rational root theorem, it has no rational root.
Comment: When there are two questions, and you say "it" is possible, we do not know which one you mean.  A reason to limit questions to one only.
Comment: @GEdgar: that's quite right. Of course, you can infer which case is targeted here.
Comment: @GEdgar When I posted my answer, there was only one question.
Comment: Adding my 2nd question was almost simultaneous with your answer! :)
Answer: To the first one of your queries the answer is - No, it's not possible to construct if you want all coefficients to be rational. As, from Vieta's formula we have sum of roots of a polynomial $f(x)=ax^3+bx^2+cx+d$ equals to $-b/a$, which is rational as you want all $a,b,c,d$ to be integers.
Now,if you want one root to be irrational, you can't get the sum a rational one. As, you will always need the conjugate surd(conjugate of $a+\sqrt{b}$ is $a-\sqrt{b}$, which is irrational) to make the sum a rational one. For any other non-algebraic irrational number like $e$, no matter what you take, you will get the product a irrational number, but from Vieta again product of roots is $-d/a$, a rational number.
For the case with all 3 irrational roots, see here.
Comment: See José's answer for three irrational roots with sum $0$ and product $-1$.
Answer: Take any second order polynomial with two irrational roots (shouldn't be hard) $q$, and take $$p(x) = (x-1)\cdot q(x)$$
then, clearly, $p$ has one rational root (it's $1$) and two irrational roots (the same as $q$)

However, it is not possible for the polynomial $p$ to have two rational roots $r_1, r_2$ and one irrational one $z$. That would imply that $p=(x-r_1)(x-r_2)(x-z)$, and clearly, the expanding this polynomial shows that the coefficient at $x^2$ is $-z-r_1-r_2$. This number is rational only if $z$ is also rational.
Comment: two rationals one irrational, is my question
Comment: This case is already known by the OP.
Comment: Note $0$ is rational.  So it is better to use the $x^2$ coefficient.
Comment: @GEdgar You are correct, I fixed it.


Connecting Android Application to Python Server

Question: I'm writing a program to send a String object (and eventually image, but starting small) from an Android Application to a python server.
My python server is pretty small right now it just listens and then prints what it receives.
import socket
import sys
print("---------------------------------------------")
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addy = ("localhost", 5589)
print("starting up on %s with port %s" % server_addy)
socket.bind(server_addy)
socket.listen(1)
while True:
    print("Waiting on connection...")
    print("---------------------------------------------")
    connection, client_addy = socket.accept()
    print("Connection Accepted")
try:
    print("Connection received from...", client_addy)
    while True:
        data = connection.recv(1024)
        print("Received \" %s \" from connection" % data)
        connection.close()
        break
finally:
    print("Closing Connection to ", client_addy)
    connection.close()

I've tested this with another python client that is able to connect to and send/receive data from this server.
So on my Android App side I have
public class score_verify extends AppCompatActivity {

private String input_score;
private Pattern pattern = Pattern.compile("[0-9]+");
private Socket socket;
private String url = "localhost";
private String metadata;
private int port = 5589;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_score_verify);
    Button submit = (Button) findViewById(R.id.submit);
    final EditText score = (EditText) findViewById(R.id.input);
    final CheckBox box = (CheckBox) findViewById(R.id.verify);
    metadata = getIntent().getStringExtra("metadata");
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            input_score = score.getText().toString();
            if(!pattern.matcher(input_score).matches()) {
                Toast.makeText(score_verify.this, "Please Enter A Valid Score", Toast.LENGTH_LONG).show();
            }
            else if(!box.isChecked()) {
                Toast.makeText(score_verify.this, "Please Verify that the Information is Correct", Toast.LENGTH_LONG).show();
            }
            else {
                try {
                    metadata += ("," + input_score);
                    metadataTask task = new metadataTask();
                    task.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

With the actual connection code being
private class metadataTask extends AsyncTask<Void, Void, Void> {
    PrintWriter printWriter;
    @Override
    protected Void doInBackground(Void...params) {
        try {
            socket = new Socket(url, 5589);
            printWriter = new PrintWriter(socket.getOutputStream());
            printWriter.write("Connecting!...");
            printWriter.flush();
            printWriter.close();
            socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

}
For the first section where I have URL I've tried it with "127.0.0.1", "localhost", and "10.0.2.2" and I get either a connection timeout or a (with localhost) a connection refused error.
I have
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

both in my manifest as well
Any help at all would be appreciated, I'm at about the end of my ability to diagnose this problem
Ping Results:
Pinging 192.168.1.89 with 32 bytes of data:
Reply from 192.168.1.232: Destination host unreachable.
Reply from 192.168.1.89: bytes=32 time=49ms TTL=64
Reply from 192.168.1.89: bytes=32 time=130ms TTL=64
Reply from 192.168.1.89: bytes=32 time=37ms TTL=64

Ping statistics for 192.168.1.89:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 37ms, Maximum = 130ms, Average = 72ms

Answer: Your python code seems to be accepting connection continuously forever in while loop, which prevent it from enter the try block. Also changed the address parameter in server_addy to    server_addy = ('', "port")
Providing you with the code below
import socket
import sys
print("---------------------------------------------")
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addy = ('', 5600)
print("starting up on %s with port %s" % server_addy)
socket.bind(server_addy)
socket.listen(1)
while True:
    print("Waiting on connection...")
    print("---------------------------------------------")
    connection, client_addy = socket.accept()
    print("Connection Accepted")
    try:
       print("Connection received from...", client_addy)
       while True:
                 data = connection.recv(1024)
                 print("Received \" %s \" from connection" % data)
                 connection.close()
                 break
    finally:
           print("Closing Connection to ", client_addy)
           connection.close()

This will serve single client connection at a time and upon closing of connection   it will accept next connection.
And in the android part use either of the two address to connect:

your private IP address (192.168.0.0)
Or, 10.0.2.2
Comment: Hi and thanks so much for the help! I changed the python server to your suggestion and added tried the Android program with both the 192 and the 10 locations. Doing the 192.168.0.0 I got a connection refused error and doing the 10.0.2.2 I got a connection timeout.
Comment: No, I'm using a physical phone
Comment: can you try to ping the private ip 192.168.  through your PC
Comment: The ip address of the phone?
Comment: Editing original post with ping results
Comment: Alright then, it getting challenging more and more. Can you try to use telnet command to make sure whether the port is listening (command:    telnet
Comment: I was able to successfully telnet into the python port
Comment: In your android code, use the private IP (192.168._._) to connect
Comment: Oh man it worked! I connected it to my PC's IP and it worked just fine! Thanks so much for all your help!!!!
Comment: Nither 10.0.2.2 or localhost will work in actual physical device, I would have ask for your test device earlier
Comment: It's all good, I should've specified I was using a physical phone from the getgo. Thanks for sticking with me!


Array.push() makes all elements the same when pushing an object

Question: I'm new to node and javascript and have been banging my head on the following. I've created an object as follows:
var Subscriber = {
'userID': String,
'email': String,
'name': String,
'stage': String,
'poster': Boolean,
'canEmail': Boolean,
'stage': String, }

I have  a function where I query mongodb, and loop through the results, attempting to load an array of subscribers, which I've declared as:
var s = Subscriber;
var subscribers = [];

The loop looks like this:
//load array of users that are subscribed to the group
        async.forEach(g.subscribers, function(item, callback) {
            //load user document for this user
            User.findOne({ _id: item}, function(err, u) {
                if(!err && u) {
                    //var s = new Subscriber();
                    console.log('Sub load, found user %s, building array item', u.email);
                    console.log('Subs @ loop start');
                    console.log(util.inspect(subscribers));

                    console.log('Heres foo: ' + util.inspect(foo));

                    s.userID = u._id;
                    s.email = u.email;
                    s.name = u.firstName + ' ' + u.lastName;
                    s.stage = u.stage;
                    s.poster = false; //we're just loading subscribers at this point'
                    if(s.stage != 'new') s.canEmail = true;

                    //push new subscriber onto the array
                    console.log('Pushing ' + util.inspect(s));
                    subscribers.push(s);

                    console.log('At end ' + util.inspect(subscribers));

                    foo.push(s.email);
                    console.log('Heres foo now: ' + util.inspect(foo));

                    callback(null, item);
                }

After each call to subscribers.push(s), the array has the correct number of elements, but all elements match the last values for s, like this (with two different users being pulled from the DB):
[ { userID: 4fc53a71163006ed0f000002,
email: 'email@example.com',
name: 'undefined undefined',
stage: 'new',
poster: false,
canEmail: true },
  { userID: 4fc53a71163006ed0f000002,
email: 'email@example.com',
name: 'undefined undefined',
stage: 'new',
poster: false,
canEmail: true } ]

Pushing a single element of s rather than the whole object seems to be fine. I added the "foo" array as a test, and it works fine:
Heres foo now: [ 'email@example.com', 'email@example.com' ]

What is going on here?!?!??!
Comment: Objects and arrays (which are objects) are passed by reference in JavaScript.  If `s` is an object, and you are re-using it by only changing the properties and then pushing the same object onto the array in a loop, then the objects in the array are all references to the same object.
Comment: Thanks! This was very helpful. I was thinking it might be something with references but just couldn't wrap my head around it. I guess this is what happens when you're last dev work was two decades ago in cutting edge languages like Pascal and C!
Comment: What does `g.subscribers` look like?
Comment: Related: [Array.prototype.fill() with object passes reference and not new instance](/q/35578478/4642212).
Answer: The problem is not with the push method of the Array.prototype but with your bindings.
You are modifying the same s object in every iteration in your async.foreach block which is actually the same Object as the previously defined Subscriber.
First you should move the declaration of the s variable to the foreach block.
And also if you want to create an object with default values, it should be a function, which returns a new object:
function Subscriber() {
  return {
    'userID':   '',
    'email':    '',
    'name':     '',
    'stage':    '',
    'poster':   false,
    'canEmail': false,
    'stage':    ''
  };
};

And then you can instantiate a Subscriber object like this:
var s = Subscriber();

See this answer or Closures on MDN for more explanation.
Comment: What a novice mistake I made. This is exactly what I was not seeing.
Comment: Thank you! I've been stumped for days until I found this solution. Not only did it resolve my issue but I now better understand closures and lexical scope.
Comment: Oh my god, i have the same problem in diferent scenario. Thanks for the solution.
Answer: Cloning the object before pushing into the array, also solves the problem.
temp = clone(s);
subscribers.push(temp);

Get https://www.npmjs.com/package/clone


My Shield has two separate stats of block chance. Do they stack?

Question: So I'm currently equipped with a shield called "Roundhaven". And in the stats it states two block chances(no "+%block chance" just "%block chance"). There is a "14% block chance" and several lines down another "15% block chance", see the below picture. Does this mean the shield gives me 29% block chance? Or is it a bug?
Comment: I seem to remember you could look at your character's stats and see the total values for everything. Does that help or am I misremembering?
Comment: yeah i forgot to look at the arcane statistics menu. Indeed it stacks
Answer: I found at least three different locations where they talk about 29% block change, so I think it stacks, and it is not a bug or anything. I have no idea why it is separated into two lines.
Sources:

Reddit:

I found one this week, and also Roundhaven, a 29% block lvl19 shield...

Runicgames forum

Manticore and Grell (and probably others) have a chance to drop roundhaven. It's 29% block

UrGameTips

The Lvl 23 "Roundhaven" Shield has 29% chance to Block
Comment: It is separated because one is the base block chance of the shield and the other is the property that was randomly selected which happens to further increase block chance.  With legendaries, they follow this pattern but are typically fixed properties.
Answer: You can use the Arcane Statistics screen (default key: J) to bring up a view that accurately shows the total values of each of your stats, including buffs, equipment, skills, etc.
Lots of info available online, including right here on Arqade:

Torchlight 2 - How powerful is a weapon, exactly?
How to find your character's total DPS in torchlight 2?


Faint sewer smell in highrise bathroom during high winds in one direction?

Question: I rent an apartment in a highrise, and often smell a faint sewage smell when there are high north-westerly winds with gusts.  Following suggestions on a past Stack Exchange posting, I did the simple test for a dry P-trap under the bathtub, i.e., putting my ear to the bathtub drain and listened for the flush of the adjacent toilet.  The P-trap doesn't seem to have dried out.
What are some other possible explanations of a faint sewage-like smell in a highrise bathroom, occurring only when there are high winds coming from a particular direction?
Comment: it could be coming in from outside if you are near the top of the building
Comment: I'm on floor 9 of a 20 story building, so I suspect not.
Comment: Are there any _other_ P-traps that might have dried out?  Sinks, floor-drains, laundries, dishwashers...
Comment: No, it's a small apartment with only the kitchen sink, bathroom sink, toilet, and bathtub.
Answer: Strong wind gusts here in Toronto will cause the water level in my toilet bowl to move up and down, almost as if it were being plunged. I'm on the second floor of a century factory loft. The wild variation in air pressure during strong winds must put pressure on the vent stack. Sometimes the water level in the toilet drops low enough to allow air from the stack to gurgle into the apartment. This is the kind of scenario that could be alowing sewer gases into your apartment, either through the toilet, tub, lavatory sink or kitchen sink.
Comment: It could be, at least for the drains (not the toilet, I never see any signs there).  But I never hear anything that would suggest this.  I wish there was a way to be sure.
Answer: If the high-rise was built before the 1980's then the plumbing stacks/vents may be composed of cast iron and galvanized steel. It's not uncommon for the cast iron to develop a crack where it is located in an area of concealment behind a wall. It's also not uncommon for the galvanized steel piping that connects to the cast iron to develop rust-through at the threaded connections. Either of these conditions can create a breach in the sewer odor confinement system i.e. the vent stack. When combined with variable air currents both inside and outside the building you can easily get a sewer odor in your unit. Have you told the building mgmnt. about the problem?
Do you have a floor drain perhaps located inside your laundry or mechanical closet? The integral drain trap could dry out and allow sewer gas into the home. It's best to pour a half gallon or so of water down the floor drains every couple of months in order to maintain the 'trap seal'.
Comment: Getting management to do anything is a lost cause unless there is something visibly in-one's-face.  It took a year of exhortation before they would do a bit of vacuuming of the exhaust ventilation for the bathroom and kitchen range hood.  That was when there *was* visible condensation on the windows causing mold. Unfortunately, I don't have a floor drain or even a mechanical room.  It is a mere 1-bedroom apartment. Fortunately, the wind shifted when I got back, so the smell is gone. When it recurs, I again ruminate over what can possibly be done.
Comment: But thanks for weighing in. The building is 80's era, but in Canada. I posted this question in hopes that the responses would provide enough  information to further characterize the problem to the extent that I would feel confident that I could get management to do something.


Sanity check: wire count and wire nuts

Question: I've got a box where
NMC comes in and hits a GFCI
GFCI feeds both one NMC going out (shop outlets) and a smart switch.
Smart switch feeds NMC going out (exterior outlet). Everything is correctly sized for 20A.
Since both the GFCI and the smart switch need neutral, this means five neutrals have to be connected to each other. I believe the switch neutral is currently daisy-chained past the GFCI neutral (I know hot is) bit that's still the three cables plus the pigtail having to come together in the box. That was successfully squozen into a single larger wire nut, and it all works, but I'm just a bit skeptical about whether that was really the right answer and will stay out that way.
What's the right way to handle this slightly complicated box, and what's the minimum box size for it? And are there any tricks to dressing down the wiring that would make it a bit less of a rat's nest? (Maybe subgrouping the neutrals?)
Comment: 1 Pigtail from GFCI Load neutral terminal, 2 Shop Outlets, 3 Smart Switch, 4 Switched Stuff -- that's four neutrals.  I don't count five neutrals. The neutral coming in to the GFCI goes directly to the Line neutral terminal.   I would use a Wago 221-415 for the neutrals.  It's easier to fold the neutral bundle into the box, and because you have a GFCI and smart switch that both *will* need maintenance, it's easier to remove and replace them without damaging the wires.
Comment: @jay613 not to be all isherwood, but the answer box is below. Keshlam, boxes that are anywhere close to maximum fill, particularly with bulky items like GFCIs in them (counted no differently than a normal-sized receptacle) are just plain tight to work in. Feel free to oversize the box for your own sanity.
Comment: Mud rings not only count, they are marked to tell you how much they count for.
Comment: Yes, those do sound like answers (and I'm often guilty of answer-in-comment myself). There's a deep mud ring which does gain a bit of space; never been sure if that counts or not. Sanity is good... I think I can see it from here...
Comment: Ohhhhhh guys.  I wanted confirmation of the 4 vs 5 neutrals, and I can't craft box fill answers (though I should probably start trying) so I kept it in comments for now.
Comment: I need to check that; it is a good question and might call for rewiring.
Answer: Codewise, unless you do a bad job and fail the "in a workmanlike manner" criteria, using one big wirenut or 2-3 smaller ones and a bunch of pigtails is the same. Pigtails within a box (as required if you want to spread out a connection to 2 or 3 wirenuts rather than one) are "free" for wire count / box fill purposes, though you can definitely make yourself miserable with how tight a box is that's just over minimum size by adding too many, or by mismanaging the wire paths into one big one.
If the GFCI has screw-and-clamp terminals that take two wires each, take advantage of that. That will cut the "wires per nut" by one.
First off, if I read your description correctly, the incoming hot and neutral just go straight to the Line terminals of the GFCI, no nuts or other junctions involved.
All the junctioning should be happening off the Load terminals, as you say the GFCI feeds it all. So the incoming cable does not see any junctions.
So, the GFCI Load terminals either have a pigtail that feeds outlets and switch, or a pigtail and one of the outlet neutrals if they are two-wire screw-and-clamp style. For the Load hots, all those have to feed is unswitched outlet and switch, so two-wire screw-and-clamp eliminates a wirenut completely on that side.
You have 6 wires, 2 devices (that count as 2 each), and 3 grounds (that count as 1) for wire count purposes. So, 11 is the magic number, and 24.75 cubic inches is your minimum box size. Not that I recommend skating anywhere near minimum box size if you don't absolutely have to. But in this case you have a box in place, so dealing with it being tight-but-legal is probably easier than upsizing it to comfortable-but-also-quite-generously-legal.
As noted in comments, a raised mud ring does add to the box's cubic inch count. Steel boxes are "standard" and not marked, (you just look up the number for the size of box) but raised covers and mud rings are marked with the cubic inches they add to the box they are attached to.
Answer: First, as the GFCI is about to explain by tripping... the GFCI "Load" terminals are special.  They are so special that I regularly argue that novices should not use them.  If the hot wire is coming off GFCI "Load", then its partner neutral wire must also come off GFCI "Load".  So if you are using "Load", that will preclude one giant group of neutrals.
Also note that the GFCI is designed to take 2 wires under each screw - read the instructions for how - and this can help.
Now, as far as wire nuts, the manufacturer provides a list of all wire combinations for which UL has certified their wire nut, e.g. this one for Ideal.  Though they also put a simpler chart in the sales brochure.   I'm really good at wire nuts (most people aren't) and trust me - try to stay in the "center of range" because making wire nuts work at their limits is hard.  Always do an earnest pull-test and learn from it.  And crank it like you mean it.   Or just use Wago lever-nuts.
Comment: I _think_ it is actually correctly, since the tester popped the GFCI as expected. From both the switched and unstitched outlets. But sounds like I Really Should recheck this.
Comment: No experience with the wagos. Sounds like I should learn. But then what do I do with the bin of nuts? ... Don't answer that.

Sanity check: wire count and wire nuts


Which followers will have their level changed when we use the setlevel command?

Question: How do I change follower level cap with console commands? says we can use setlevel to change attribuutes on the NPC.
But which NPC? The one we click? The one that follow us (can be several with mods) The one we are currently talking to? Or do we set the id somewhere via console?
Comment: The one you click.
Answer: You will change the entity (NPC or static object) that you have selected by clicking them whilst the console is open.
Also note that clicking an entity may be a hard task, you may sometimes get another object. If you aren't seeing a change occur after you do a getav etc, then it's likely that you have clicked the wrong entity. Try clicking them at a different angle.


Documentation report for a .Net Assembly

Question: I'm in the process of generating documentaion for my API using sandcastle,
however there are many undocumented sources in the assembly that that i'm generating the chm for, is there a way to get a list of the undocumented types (or those that have missing documetation for their members)?
Answer: I think that there is an FxCop (aka code analysis) warning that can be enabled when xml comments are missing or incorrect. This is done from the compilation settings for the project.
The doxygen tool can generate warnings and it reads the standard C# xml comments. It is  documented in the doxygen comment file how to enable warnings on missing docs.
Comment: It is possible to extract (using excel etc..) some sort of a report from the available warnings, even within VisualStudio itself, however i still feel that there ought to be a more professional tool for this, perhaps as an add in to other code quality enhancers/plugins such resharper or ndepend.


Linear combination of a family of independent random variables

Question: (From Achim Klenke - "Probability Theory") The following theorem holds:
Let $K$ be an arbitrary set and $I_k, k \in K$, arbitrarily mutually disjoint index sets. Define $I=\bigcup_{k\in K} I_k$. If the family $(X_i)_{i\in I}$ is independent, then the family of $\sigma$-algebras $(\sigma(X_j, j \in I_k))_{k\in K})$ is independent.
Now consider the following example (also from the mentioned book):
If $(X_n)_{n\in\mathbb{N}}$ is an indepenedent family of real random variables, then also $(Y_n)_{n\in\mathbb{N}}=(X_{2n}-X_{2n-1})_{n\in\mathbb{N}}$ is independent. Indeed, for any $n\in \mathbb{N}$ the random variable $Y_n$ is $\sigma(X_{2n}, X_{2n-1})$-measurable. (This is concluded from the fact that a linear combination of measurable maps is again measurable). It follows from the stated theorem that $(\sigma(X_{2n}, X_{2n-1}))_{n\in\mathbb{N}}$ is independent.
Now there are two issues: The book does not really define what $\sigma(X_j, j \in I)$ actually is. I assume it is the smallest $\sigma$-algebra, for which $(X_j)_{j\in I}$ are measurable, is this correct?
Second issue: If we know that $(Y_n)_{n\in\mathbb{N}}$ are measurable, how can we conclude that they are $(\sigma(X_{2n}, X_{2n-1}))_{n\in\mathbb{N}}$-measurable? It seems intuitive at first, but the more I think about it, the less it becomes.
And at last: Are there random variables $Z_j$ which are a function of independent random variables $X_i$ with $Z=f(X_1,X_2...)$ where $Z$ is measurable, but not $\sigma(X_1,X_2,...)$ measurable?
Answer: First of all: I guess, Klenke defines random variables to be objects mapping from some probability space $(\Omega, \mathcal{A}, P)$ into $(\mathbb{R},\mathcal{B}\mathbb{R})$.

Exactly, $\sigma(X_j : j \in I)$ is the $\sigma$-algebra generated by the vector valued map $$\Omega \ni \omega \mapsto (X_j : j \in I) \in \mathbb{R}^{I},$$ where $\mathbb{R}^{I}$ is equipped with the Borel-$\sigma$-algebra $\mathcal{B}\mathbb{R}^{I}$.
$X_{2n}$ and $X_{2n-1}$ are both $\sigma(X_{2n},X_{2n-1})$-$\mathcal{B}\mathbb{R}$ measurable. Since $\mathcal{B}\mathbb{R}$ is a Borel-$\sigma$-algebra, $Y_n := X_{2n} - X_{2n-1}$ is measurable on the exact same space; as you said before, as a linear combination of measurable functions.
The last question is a bit confusing. I guess, it should read

And at last: Are there random variables $Z$ which are a function of independent random variables $X_i$ with $Z=f(X_1,X_2...)$ where $Z$ is $\mathcal{B}\mathbb{R}$-$\mathcal{B}\mathbb{R}$-measurable, but not $\sigma(X_1,X_2,...)$-$\mathcal{B}\mathbb{R}$-measurable?

That is a somewhat harder question. It is definitely not possible, if $f$ is  $\mathcal{B}\mathbb{R}^I$-$\mathcal{B}\mathbb{R}$-measurable. The Doob Dynkin Lemma may help you.


Remove / purge repository spotify and opensuse

Question: When I go to Software & Updates and then to Other Software I get this boxes unchecked: http://repository.spotify.com stable non-free and http://download.opensuse.org/repositories/home:/Horst3180/xUbuntu_15.10//.

If I check them I am unable to download the updates, it will fail because of them, I guess.
I tried to install Spotify so I guess that is the reason they are there.
I have Ubuntu GNOME 15.10 on my machine. How to remove them from there? Thank you!
Comment: What exactly is your question? What do you want to achieve? And some terminal outputs of `sudo apt-get update` or `sudo apt-get install INSERT_PACKAGE_NAME_HERE` are better readable and more helpful than a screenshot usually. Copy it using the context menu or Ctrl+Shift+C (!) and paste it to your question ([edit] it, don't add output in comments) and format it as code (**`{}`** button in the editor or using Ctrl+K).
Comment: Is it possible to remove them from there?
Comment: If you simply uncheck them, they have no effect any more. It makes no difference whether a software source is unchecked or removed in that window. But if you really want to remove the source, there's a `Remove` button below the list. It will become clickable when you have selected a source in the list.
Comment: I kept clicking the right mouse button and nothing happen.
Answer: Remove the files from the /etc/apt/sources.list.d directory. Try this command:
sudo rm /etc/apt/sources.list.d/spotify.list

Then run sudo apt-get update and there should no longer be any references to http://repository.spotify.com
Comment: Are you sure that's the name of the file?
Comment: Worked great under Debian bullseye. Thank you.
Comment: That's where it was under Peppermint OS 7
Comment: well I'll assume (possibly unwisely) it's the same


How to add user specified values from a hash

Question: I'm trying to create a program that would take a string from user input and return the 'value' of the word where a=1, b=2, c=3 etc. i.e. "cab" = 6.
Unfortunately I can't figure out how to break down the user input variable and have it added together:
print "Give us a word to calculate: "
word = gets.chomp
alphabet = Hash[
  "a" => 1, "b" => 2, "c" => 3,
  "d" => 4, "e" => 5, "f" => 6,
  "g" => 7, "h" => 8, "i" => 9,
  "j" => 10, "k" => 11, "l" => 12,
  "m" => 13, "n" => 14, "o" => 15,
  "p" => 16, "q" => 17, "r" => 18,
  "s" => 19, "t" => 20, "u" => 21,
  "v" => 22, "w" => 23, "x" => 24,
  "y" => 25, "z" => 26
]

value = word.split("")
puts "Your word, \'#{word}\' has a value of: #{value}"

Comment: Here are some things. First, you can simply define a hash as `{ 'a' => 1, ...}`. Using `[]` to define a hash lets you input an array. You are basically mixing two conventions. Next, given a string, you do not need to use `split` if you want all the characters. Just use `string.chars`, which produces the array you need. Finally, you don't need to escape `'` (single quotes) inside a double-quote string.
Comment: You can do this in your head, right? Write down on a piece of paper the steps you take to do this yourself. Then figure out how to do each step in Ruby.
Comment: There is no need to construct a hash with 26 elements when you can write a small method to return the value for each letter: `def alphabet(c); c.ord - 96; end; alphabet('z') #=> 26`.
Comment: I've been trying, but I'm simply not that good at Ruby yet. After a few hours of tooling around with it, I decided to come here and ask for help.
Answer: You can use reduce method to add up the values of each char.
value = word.split("")
sum = value.reduce(0) {|sum, char| alphabet[char] + sum }
puts "Your word, \'#{word}\' has a value of: #{sum}"
#=> Your word, 'cab' has a value of: 6

Here we use reduce (which has an alias method inject) to reduce the array into a single value.  We start with initial value of 0, and iterate through each element of the array - in the block, we add the numeric equivalent of given char to the sum so far - and eventually end up with sum of all numeric values.

Answer to question in comments:

My only relevant follow-up question to this, is it possible to define
  the hash using ranges? I know that I can define them with ("a".."z")
  and (1..26) but I didn't know if there is a way to set those two
  ranges equal to one another based on their index values or somesuch

You can make use of Array#zip method that allows to merge two arrays by pairing elements at same index as sub-arrays.  Subsequently, we can take advantage of method Array#to_h which converts any array of 2-element arrays into hash.
alphabet = ('a'..'z').zip(1..26).to_h

Comment: Appreciate the actual thoughts and suggestions. Not sure why I'm being downvoted...I'm legitimately very new to programming in general and I thought this was the place to go for help.
Comment: @luminaire if this answer helped you, select it as the accepted answer. You will gain rep from that alone.
Comment: @luminaire Upvote and downvotes are not consistent on this forum - sometimes depends on maturity and mood of users I guess
Comment: Truly thanks for the help! This is a good solution and as I was requesting more information about the why, you were posting that very information. Have a great one and thanks again!
Comment: @luminaire Yes.  If you don't pass anything to `inject` the first element of the array will be used as initial value - which in this case would have been character `'c'` - but that would not make sense it in this case as we were meant to add value of `alphabet['c']`.  Hence, we must pass explicit initial value - `0` makes sense as we are summing values.
Comment: You can also use `#inject`.
Comment: @HunterStevens  `#reduce` is an alias of `#inject` - both are same
Comment: @WandMaker I know. Was just making a suggestion in case OP sees `inject` suggested elsewhere.
Comment: My only relevant follow-up question to this, is it possible to define the hash using ranges?

I know that I can define them with ("a".."z") and (1..26) but I didn't know if there is a way to set those two ranges equal to one another based on their index values or somesuch. Also sorry I'm not sure how to signify code within a comment >< Much noob
Comment: Perhaps `sum = word.each_char.reduce(0)...`.
Answer: I'd suggest the following as a good Ruby-way:
base = 'a'.ord-1
"catsup".each_char.map { |c| c.ord - base }.reduce(:+)
  #=> 80

Breaking it down:
d = 'a'.ord
  #=> 97
base = d-1
  #=> 96
e = "catsup".each_char.map { |c| c.ord - base }
  #=> [3, 1, 20, 19, 21, 16]
e.reduce(:+)
  #=> 80

Let's look more carefully at the calculation of e:
enum0 = "catsup".each_char
  #=> #<Enumerator: "catsup":each_char>

Note:
enum0.map { |c| c.ord - base }
  #=> [3, 1, 20, 19, 21, 16]

To see the elements of the enumerator enum0, which will be passed to map, convert it to an array:
enum0.to_a
  #=> ["c", "a", "t", "s", "u", "p"]

Now lets write:
enum1 = enum0.map
  #=> #<Enumerator: #<Enumerator: "catsup":each_char>:map>

Study the return value. You can think of enum1 as a "compound" enumerator.
enum1.to_a
  #=> ["c", "a", "t", "s", "u", "p"]
enum1.each { |c| c.ord - base }
  #=> [3, 1, 20, 19, 21, 16]

We can now use Enumerator#next to extract each element of enum, set the block variable c to that value and perform the block calculation:
c = enum1.next #=> "c"
c.ord - base  #=> 99-96 = 3

c = enum1.next #=> "a"
c.ord - base  #=> 1

c = enum1.next #=> "t"
c.ord - base  #=> 20

c = enum1.next #=> "s"
c.ord - base  #=> 19

c = enum1.next #=> "u"
c.ord - base  #=> 21

c = enum1.next #=> "p"
c.ord - base  #=> 16

c = enum1.next #=> StopIteration: iteration reached an end