Drive API for Android: App folder not getting sync

Question: I'm trying using the Google API for Android to create a file, search, download and delete in the app folder.
But i'm getting some problems...
If i use the 'getRootFolder()' to save my file everything works. But, if i use 'getAppFolder()' nothing works.
Example:

The user download my app, my app search if exist any created file.
If nothing return the app create a new file in AppFolder.
If the user uninstall the app and download again, the app can't reach the file.

I try 'requestSync' but nothing happens. I trying using the Listening for Changes and Receiving completion Events, they return 'Success' but still not sync the AppFolder.
I saw some similar problems, but none works for me.
If i use the 'getRootFolder()' everything works great...
Can you guys help?
Here some Code Examples:
OnConnected:
@Override
public void onConnected(Bundle connectionHint) {
    super.onConnected(connectionHint);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (sharedPreferences.getBoolean("automaticBackup", true)) {
        String FILE_PATH = this.getDatabasePath(DataHelper.DATABASE_NAME).getPath();
        String extension = MimeTypeMap.getFileExtensionFromUrl(FILE_PATH);
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        file = new File(FILE_PATH);

        if (hasInternetAccess()) {
            if (sharedPreferences.getBoolean("firstUse", true)) {
                Drive.DriveApi.query(getGoogleApiClient(), query).setResultCallback(restoreCallBack);
                final SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("firstUse", false);
                editor.apply();
            } else {
                // delete existing backup
                Drive.DriveApi.query(getGoogleApiClient(), query).setResultCallback(checkIfFileExists);
            }
        }
    }
}

Here i check if file exist, true delete, false create a new one:
final private ResultCallback<DriveApi.MetadataBufferResult> checkIfFileExists = new ResultCallback<DriveApi.MetadataBufferResult>() {

    private DriveId fileId;

    @Override
    public void onResult(@NonNull DriveApi.MetadataBufferResult result) {
        if (!result.getStatus().isSuccess()) {
            showMessage("Problem while checking if file exists...");
            return;
        }

        MetadataBuffer metadata = result.getMetadataBuffer();
        if (metadata.getCount() > 0) {
            fileId = metadata.get(0).getDriveId();
            if (fileId != null) {
                Drive.DriveApi.fetchDriveId(getGoogleApiClient(), fileId.getResourceId()).setResultCallback(deleteFile);
            }
        } else {
            Log.d(TAG, "No backup file found");
            // create new contents resource
            Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(createBackupCallBack);
        }
    }
};

Here the code to delete:
final private ResultCallback<DriveApi.DriveIdResult> deleteFile = new ResultCallback<DriveApi.DriveIdResult>() {

    @Override
    public void onResult(@NonNull DriveApi.DriveIdResult driveIdResult) {
        final DriveId driveId = driveIdResult.getDriveId();

        try {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    DriveId fileId = DriveId.decodeFromString(driveId.encodeToString());
                    DriveFile driveFile = fileId.asDriveFile();
                    com.google.android.gms.common.api.Status deleteStatus = driveFile.delete(getGoogleApiClient()).await();
                    if (!deleteStatus.isSuccess()) {
                        Log.e(TAG, "Unable to delete the old backup");
                        return null;
                    }
                    sharedPreferences.edit().remove(driveId.toString()).apply();
                    Log.d(TAG, "Removed old backup.");
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    // create new contents resource
                    Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(createBackupCallBack);
                }
            }.execute().get();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
};

Upload the file to Drive:
final private ResultCallback<DriveApi.DriveContentsResult> createBackupCallBack = new
        ResultCallback<DriveApi.DriveContentsResult>() {

            @Override
            public void onResult(@NonNull DriveApi.DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Error while trying to create new file contents");
                    return;
                }
                final DriveContents driveContents = result.getDriveContents();

                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(Void... params) {

                        OutputStream outputStream = driveContents.getOutputStream();

                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        try {
                            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                            outputStream.flush();
                            outputStream.close();
                            inputStream.close();
                        } catch (IOException e) {
                            Log.e(TAG, e.getMessage());
                        }

                        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                .setTitle(DataHelper.DATABASE_NAME)
                                .setMimeType(type)
                                .setStarred(true).build();

                        Drive.DriveApi.getAppFolder(getGoogleApiClient())
                                .createFile(getGoogleApiClient(), changeSet, driveContents)
                                .setResultCallback(fileCallback);
                        return null;
                    }
                }.execute();
            }
        };

Result Call Back from upload:
final private ResultCallback<DriveApi.MetadataBufferResult> restoreCallBack = new ResultCallback<DriveApi.MetadataBufferResult>() {

    DriveId driveId;

    @Override
    public void onResult(@NonNull DriveApi.MetadataBufferResult result) {
        if (!result.getStatus().isSuccess()) {
            showMessage("Problem while restoring...");
        }

        MetadataBuffer metadata = result.getMetadataBuffer();
        if (metadata.getCount() > 0) {
            File fileBD = getDatabasePath(DataHelper.DATABASE_NAME);
            boolean deleted = fileBD.delete();
            Log.d("DELETED", deleted + "");
            driveId = metadata.get(0).getDriveId();
            Drive.DriveApi.fetchDriveId(getGoogleApiClient(), driveId.getResourceId()).setResultCallback(idCallback);
        } else {
            Log.d(TAG, "No backup file found!");
        }
    }
};

Comment: Is it possible that the user uninstalls the app before the files are successfully uploaded to the server?
When the user uninstalls the app the files get deleted from the device.

You can use completion events to verify that the files are uploaded to the server.
Comment: Already use the ComplemetionEvent and he return 'Success' when finish, then i uninstall the app and install again the app can't find the file if they are in AppFolder. If they are in RootFolder is almost instant.
Comment: Maybe check that the app is still authorized after you uninstall (https://support.google.com/drive/answer/2523073?hl=en).
Comment: Yes still authorized, cause when he can't find the file i create a new one.
Comment: Maybe you can add some code samples so it's clear what you're doing?
Answer: It may be permission issue. Adding drive.appfolder authorization scopes to GoogleApiClient may solve your problem. For example:
mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_APPFOLDER) // required to access app folder
            .addOnConnectionFailedListener(this)
            .addConnectionCallbacks(this)
            .build();
    mGoogleApiClient.connect();

Comment: I Already got what i wanted to do, using the AppFolder, but thanks anyway
Answer: Found a solution, you need to sync with the drive before querying the AppFolder.
Use this after connecting to the drive:
Drive.DriveApi.requestSync(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
    @Override
    public void onResult(@NonNull Status status) {

    }
});


Is KeyError the appropriate Exception?

Question: I'm creating an open source project on Github and I want to make sure I do everything I can to make it robust, stable and that its Pythonic.  To this end, I have a question about what kind of exception I should use when I expect a key to exist in a dictionary and it is not included.
That is, the calling function would be something like:
def calling_func():
    my_dict = {
        'value_1': 1,
        'value_2': None,
        'value_3': '3',
    }

    foo(my_dict)

My function foo expects the dictionary to contain the key (and corresponding value), value_4.  Would it be appropriate to raise KeyError in the following case?
def foo(my_dict):
    expected_keys = ['value_1', 'value_2', 'value_3', 'value_4']

    for key in expected_keys:
        if key not in my_dict:
            raise KeyError

It seems the traditional use for KeyError is the inverse of this usage.
Should I create my own exception type for this?
class MissingKeyError(Exception):
    pass

Or something to this effect?
Comment: What gave you the impression `KeyError` is the inverse?
Comment: @Martijn Pieters Actually, now that I think about it what I'm doing is logically equivalent to a `KeyError`.
Answer: KeyError is the appropriate exception.
When possible, use Python exceptions, especially for APIs suitable for 3rd parties. This saves on imports and learning curves.
You can simplify your code:
if not my_dict.viewkeys() >= set(expected_keys):
    raise KeyError

or simply access all the keys:
for key in expected_keys:
    my_dict[key]  # test for presence early

or just not test and let the code that does use the key raise the exception.
Comment: +1 to "just [don't] test and let the code that does use the key raise the exception"
Comment: Thank you for simplification.  This implementation is building a URL POST to a 3rd party API and will not handle the missing key - it just pukes.  :(

Is KeyError the appropriate Exception?


Fair quiz without registration, is it possible in webapp?

Question: I'm going to make simple quiz form on site.
Are there ways to make it fair, that nobody vote up multiple times.
There are some ways to identify uniqueness of vote with their lacks:

Cookies - the simplest and easy to eliminate
IP - not stable,because of DHCP and local networks
Captcha or mail registration - not user friendly and complicate the process.

What is your experience for fair and user-friendly quiz?
Answer: If you're worried about cookies being too easy to eliminate/game, you can use evercookie. It's a JavaScript API that's billed as ""virtually irrevocable persistent cookies".
Comment: may these cookie affect on SEO and Firewall or antivirus.I mean,that looks like these cookies are hidden behind other file types. May it be suspicious for client's antivirus?
Comment: They are cookies. They can't affect firewall. Not sure if some malware checker would dislike them. No idea about SEO.


Name of a special right limit

Question: Let $f : [0, \infty) \to \mathbb{R}$ be differentiable on $(0,\infty)$ and $f(0+) \in \mathbb{R}$ exists (not necessarily equal to $f(0)$). Typically, the right derivative of $f$ at $0$ is defined as $\lim_{h \to 0+} \frac{f(h) - f(0)}{h}$ if it exists. However, I am concerned with $\lim_{h \to 0+} \frac{f(h) - f(0+)}{h}$. Is this limit common and has some special name?
For me, it seems to be some kind of "derivative to the boundary" of the function $f$ with restricted open domain $(0,\infty)$.
Comment: http://math.stackexchange.com/questions/265552/a-notation-question-what-does-it-mean-gx-fx  Folland uses the notation $G(x) = F(x+) = \lim\limits_{y\to x^+} F(y)$ which finds some use when proving monotone functions are Lebesgue differentiable $m$-almost everywhere.  $G'(x)$ would be precisely the limit you are interested in if I'm not mistaken.  I don't know that it has a special name however, someone else might be able to elaborate.  It can be shown as well that $G'(x) = F'(x)~~m$-almost everywhere.
Comment: I know the notation ... I edit the question above.
Answer: If $f$ is continuous at $0$ then $f(0)=f(0+)$ and both definitions are the same. If $f(0)\ne f(0+)$, then $f$ is discntinuous at $0$ and $\lim_{h\to0^+}(f(h)-f(0))/h$ does not exist. In this case the right concept of derivative would be $\lim_{h\to0^+}(f(h)-f(0+))/h$. Another way to think of this is the following: redefine $f$ at $x=0$ so that it becomes continuous, that is, redefine $f(0)=f(0+)$.
Comment: Yes, so I think the right name would be something like "right derivative" ... it generalizes the definition of a right-derivative for continuous functions like $f(x) = |x|$ where $\lim_{h \to 0+} (f(h) - f(0))/h$ exists and is equal to $\lim_{h \to 0+} (f(h) - f(0+))/h$ since $f(0+) = f(0)$.

Name of a special right limit


A screenshot is automatically taken upon wakeup

Question: Each time I wake up my computer, gnome screenshot opens up and takes a screenshot.
I have no idea why that is and what I might have done to start this. But I would like to stop it and don't know how.
Comment: Have you checked the startup applications app to see if there is anything unusual in there?
Comment: it'S solved. i was in the keyboard shortcut section, accidentely clicked on take screenshot, and, as I thought the ocmputer was frozen, I closed and opened the computer, which then was aken as the new shortcut for the screenshot.
Comment: Okay, thanks for for the clarification. Please mark this question as solved.
Comment: how do I mark it as solved?
Comment: Click the checkmark next to your answer:
Answer: i was in the keyboard shortcut section, accidentely clicked on take screenshot, and, as I thought the computer was frozen, I closed and opened the computer, which then was taken as the new shortcut for the screenshot
Comment: Hah you just discovered a new cool trick based in lid events!


Let $A$ be an $n\times n$ matrix, and assume the eigenvalue of $A$ is $0$, what does that tell us about the kernel?

Question: If we assume that $A$ has an eigenvalue of $\lambda = 0$, then what does that tell us about the kernel of $A$? Or more specifically, what does it tell us about the dimensions of the kernel of $A$.
I need someone to explain in detail please.
Comment: It shows that the dimension is at least one.
Comment: Downvote purely on the title of the question.  @LordSharktheUnknown has answered your question
Comment: @LordSharktheUnknown can you explain in more detail?
Comment: If $\lambda =0$ is an eigenvalue, then there is a nonzero eigenvector $x$ such that $Ax=\lambda x = 0\cdot x = 0$. Hence $x$ belongs to the kernel of $A$. Since $x\neq 0$, the kernel has a nonzero element, so its dimension is at least one.
Comment: Would the same logic apply for $\lambda$ = 1? or any other eigenvalue? as long as a matrix has at least one eigenvalue, then the dimension of the kernel is at least one?
Comment: No. The identity matrix has $1$ as its only eigenvalue, but the kernel has dimension $0$.
Comment: Is the identity matrix the only exception for having dimension 0 and eigenvalue 1 ?
Comment: @Soon_to_be_code_master For $\lambda  = 1$ you have $\dim\operatorname{Ker}(A - I) \ge 1$. In general, if $\lambda$ is an eigenvalue then $\dim\operatorname{Ker}(A - \lambda I) \ge 1$.
Answer: Recall that a matrix is just a linear transformation. Now a linear transformation is invertible if and only if it is full rank. This is equivalent to $\text{ker}(T) = \{0\}$, as well as $\text{det}(T) \neq 0$. Now $\text{det}(T) = \prod_{i=1}^{n} \lambda_{i}$, where $\lambda_{i}$ are the eigenvalues of $T$. So if an eigenvalue of $T$ is $0$, then $T$ is not invertible. Thus, $\text{ker}(T)$ is non-trivial, and so has dimension at least $1$.


Manipulating a summation expression for Future Value (Annuities)

Question: I've been given the following expressions for regular payments with regular annual compounding (Annuities):
(1) $$ F - (1 + r)F $$
(2) $$ F = d \sum^T _{t=1} (1+r)^{T-t}$$
where: ($F$) is a Future Value, ($r$) is the Rate of Interest, ($d$) is the payment amount, ($T$) is the total count of payments and ($t$) is the payment number.
I understand how to get to this point,
(3) $$ d\left[\sum^T_{t=1}(1+r)^{T-t} - \sum^T_{t=1}(1+r)^{T-t+1}\right] $$
but somehow my tutor has managed to manipulate the expression to,
(4) $$ -d[(1+r)^T - 1] $$
Does anyone know what my tutor did to go from (3) to (4)?
Comment: Using \Sigma instead of \sum is the reason why you saw $\displaystyle\Sigma_{t=1}^T$ instead of $\displaystyle\sum_{t=1}^T$.  (I fixed that and also attended to sizes of brackets and other things. ${}\qquad{}$
Comment: Thanks Micheal, though the way I had it before was how my tutor had expressed it.
Comment: It looks much better how you have displayed it
Answer: It's just a telescoping property.  The easiest way to understand it is to pick a value for $T$, say $T = 3$, and write out the sums explicitly:
$$\sum_{t=1}^T (1+r)^{T-t} = (1+r)^2 + (1+r)^1 + (1+r)^0,$$ and $$\sum_{t=1}^T (1+r)^{T-t+1} = (1+r)^3 + (1+r)^2 + (1+r)^1.$$  So their difference is simply $$-(1+r)^3 + (1+r)^0 = -((1+r)^3 - 1),$$ because all the intermediate terms cancel.  Now generalize this for any positive integer $T$, and you can see where the result comes from.


Stack around variable corrupted? C

Question: I have 2 issues, but this is the more pressing one...
printf("Enter the term: "); scanf("%d", &input);
fprintf(inputf, "%d,", input);

printf("Enter the id: "); scanf("%d", &input);
fprintf(inputf, "%d,", input);

printf("Enter last name: "); scanf("%s", name);
fprintf(inputf, "%s,", name);

printf("Enter first name: "); fgets(name, 15, stdin);
fprintf(inputf, "%s,", name);

printf("Enter the subject: "); scanf("%s", subsec);
fprintf(inputf, "%s,", subsec);

printf("Enter the catalog number: "); scanf("%d", &input);
fprintf(inputf, "%d,", input);
//ISSUE HERE!
printf("Enter the section: "); scanf("%s", subsec);
fprintf(inputf, "%s\n", subsec);

Whenever I input all of this information and press enter on the last variable entry I get a window that says this "Run-Time Check Failure #2 - Stack around the variable 'subsec' was corrupted." I can continue and the program pretty much does what I want it to and works, but why is this happening?
My second part is when I get to entering the last name, and then want to enter the first name, it takes in the "\n" character when I press enter for the firstname string variable, obviously dont want that happening, but the both first and last name need to be capable of holding strings with whitespaces. How do I kill both birds with a single stone? I used fget to allow me to hold whitespace, but it cases my "\n" capture issue, but if I change it back to scanf, I cant hold whitespaces!
EDIT: This is subsec
char subsec[MAX_SUBSEC];

MAX_SUBSEC is set to three, I use it previously as you can see, but I figured the second scanf (the one for section, not subject) would write over the original use of inputting subsec, Im going to say I am wrong? And I am not allowed to do this, thus the issue...
Input for subject will be "CSE" and the input for section will be "R01" And yes this is all going to be put into a file.
Comment: What's the definition of `subsec`?  Is it big enough to hold the whole string you're trying to read?
Comment: Regarding the white space in the names, a) `fgets` and manual removal of `'\n'`, b) `scanf("%[^\n]%*c",name);` pick one and don't mix.
Comment: What's the definition of input? I'm assuming inputf is a FILE *, correct?
Comment: @octopusgrabbus The `FILE*` is `inputf`; `input` seems to be an `int`.
Comment: Also, does it work if your input string for 'subject' is empty?
Comment: Please show your input, too.  If you're trying to input more than two characters for either the subject or section, you're going to have a problem with that short an array.
Comment: @DanielFischer I'm not quite sure what you mean? When I attempt your supposed fix in scanf, it gives me more "\n" 's and pushing my input even farther?
Comment: The `%[^\n]` conversion consumes characters until it finds a newline (caution: danger of buffer overflow, better add a field width, `%99[^\n]` if e.g. `name` is a `char[100]`). Then the `%*c` consumes the next character (the newline) without storing it anywhere. What do you mean "it gives me more "\n"'s and pushing my input even farther"?
Comment: When I add that to my scanf statement, it just skips the input for that line, and goes to the next. So I put it on the line for entering the first name, it skips it entirely and seeks input for the subject instead.
Comment: How does your `scanf` now look? You shouldn't add that, but replace the `%s` format with (something like) that.
Answer: If MAX_SUBSEC is 3 and you enter more than 2 characters for the subject or subsection, you'll overrun the subsec array on the stack and corrupt the stack frame (which may or may not cause problems.  You should use
scanf("%2s", subsec);         /* read up to two non-whitespace characters for subsec */

to ensure it doesn't try to read and store more than 2 characters (plus the trailing NUL) into subsec
You might also want to add a
scanf("%*[^\n]");             /* discard the rest of the input line */

after each scanf you have currently to discard the rest of the input line (in case some enters more than the single data item you want.  You can combine the two with
scanf("%2s%*[^\n]", subsec);  /* read 2 chars and discard the rest of the line */

if you want.
To enter strings of at most 15 chars (including NUL) with whitespace for first/last name, use:
scanf(" %14[^\n]", name);     /* read up to 14 chars from the line */

That will discard any leading whitespace (including the newline from the previous line) and then read into name, but won't discard trailing spaces from the name if someone enters them (you might want to clean them up).
Answer: Check if inputf, that I presume that is a pointer to an opened file, do a correctly reading of the variable. In other words, check if the file is open correctly and this file contain all data that you want to read.

Stack around variable corrupted? C


Obtain a count of XML elements per group in SQL

Question: I have an XML column that looks something like the following;
DECLARE @str AS VARCHAR(8000)

SET @str = '<Root xmlns="http://myurl.com/services/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
           <Notifications>
               <Notification>
                  <NotificationDate>2012-08-16</NotificationDate>
                  <Scopes>
                    <NotificationScope>
                        a
                    </NotificationScope>
                    <NotificationScope>
                        b
                    </NotificationScope>
                  </Scopes>
                </Notification>
                <Notification>
                  <NotificationDate>2012-08-20</NotificationDate>
                  <Scopes>
                    <NotificationScope>
                        a
                    </NotificationScope>
                  </Scopes>
                </Notification>
            </Notifications></Root>'

I want to be able to get a count of the number of NotificationScope Elements per notification. So for example, I am looking for something like;
Notification Date                   Count
 2012-08-16                          2
 2012-08-20                          1

In fact, as in reality as this data is obtained from a database column, I am really only interested in returning those records that have ANY Notification Date with a Count that is greater than 1.
So far, all I've managed to come up with is the following, but that just gives me a count of ;
declare @xmlvar XML;
set @xmlvar = (SELECT cast(@str AS XML))
;WITH XMLNAMESPACES('http://myurl.com/services/' AS p)
SELECT * FROM (
select @xmlvar.value('count(/p:Root/p:Notifications/p:Notification/p:Scopes/p:NotificationScope)', 'INT') AS 'NotificationScopeCount',
       @xmlvar.value('count(/p:Root/p:Notifications/p:Notification/p:NotificationDate)', 'INT') AS 'NotificationDateCount'
 ) a WHERE NotificationScopeCount > NotificationDateCount

but ideally, I'd like to be able to get the associated date also. Please forgive me if this is a horrible way of going about this, I haven't used XML datatypes much before in SQL.
Answer: You can try to use something like this:
;WITH XMLNAMESPACES('http://myurl.com/services/' AS p)
SELECT
    NotificationDate = Notif.value('(p:NotificationDate)[1]', 'DATE'),
    CodeCount = Notif.value('count(p:Scopes/p:NotificationScope/p:Code)', 'int')
FROM
    @xmlvar.nodes('/p:Root/p:Notifications/p:Notification') AS Tbl(Notif)

Gives me an output of:
Comment: Excellent. Thanks for that. I've checked out [your question](http://stackoverflow.com/questions/3685155/combine-cte-with-and-a-with-xmlnamespaces-in-sql-server) about how to combine a cte with xmlnamespaces to see how to acheive this :)
Comment: Thanks for this. Does the [1] in the NotificationDate column act as an aggregate type of value?
Comment: @MrMoose: no, the `[1]` just selects the first (of potentially multiple) entries in the list of XML nodes defined by that XPath. Since your `` node only ever contains a single `` (I assumed this), that's what you want - you get *the* notification date from the notification node. My code here doesn't do any aggregation (yet) - if you needed that, you'd have to aggregate yourself (e.g. by wrapping this into a CTE and then doing a `GROUP BY` on the date column)


Yahoo Sending PM Algorithm

Question: I want to write a PHP code (or other code like perl ...) that send a yahoo PM to my friend .
may you help me in algorithm , about how to connect to yahoo server , how to send the pm ...
Thanks .
Answer: Yahoo's developer site should be a good start. For example, a PHP library for Yahoo Mail is linked there.

With the Mail API, you can build applications that display message
  summary information, parse message contents, manage folders, and even
  compose and send messages.
Client libraries in Python, PHP and VB.NET are available to make using
  the Mail developer service easier.

This could be a good start to do something similar with the Yahoo Messenger API.
More searching reveals the Yahoo Messenger PHP SDK and libpurple, a library for IM access.
Comment: perl before bovines.... (pun intended). +1 for an answer that the Q didn't deserve.

Yahoo Sending PM Algorithm


What's the minimum height for the spawning area of a mob farm?

Question: Considering a standard mob farm design, what's the minimum height I should build the spawning floor so that I'm sure I get 100% efficiency (no other mobs are counted toward the mob count cap)?
I don't feel like lighting up every cave yet, and I desperately need a working mob farm.
Comment: Are you asking how high the drop needs to be?
Comment: @fraener Nope. The way I kill the mobs is irrelevant in this question. Just at what level the spawning pads needs to be in order to avoid mobs in the underlying caves being counted towards the mob cap.
Answer: If your concern is solely limited to other hostile mobs lowering your grinder's efficiency, then quoted from minecraft wiki,

Hostile mobs (and some others) that move farther than 128 blocks from the nearest player will soon despawn (see Despawning), so even with a larger chunk loading radius, the mob spawning area is more-or-less limited to spheres with a radius of 128 blocks, centered at each player.

What this means is that to get 100% efficiency, you should build 128 blocks above the tallest terrain you are at. ie 128 blocks about ground level.
Comment: I don't understand. Let's say the ground level is `X`; You are saying I should build the spawning pads at `X + 128`? Wouldn't that count mobs also down to `X - 128` below and therefore lower the mob cap?
Comment: @Jefffrey Any mobs that is 128 blocks away from you despawns thus, if you build it X + 128 high, and your player is at X + 128, the only valid location for mobs to spawn is your spawn platform
Answer: This depends on many factors, including your position as a player and the type of terrain around you.
Mobs will despawn when they are out of a 128 block radius of the player.
This means that for the spawner to be active if the player is anywhere within 128 blocks at the spawner's level, it has to be at least 128 blocks above the ground. This works for pretty much any generic mob farm, and it works in a populated server. Having blocks in an area above level y128 can decrease efficiency of mob spawning, since it has to account for more chunks, though, so here are some other options:
If you want to make a less tall, but still efficient design you can locate the player above the farm so that the despawn radius includes the spawner but excludes the rest of the world. Note that this design is better suited for AFKing, since you will have to make many trips up and down for this to work. This can be used for witch farms, as well as hostile mob farms.
You can also "sanitize" a 128 radius area, by lighting up every cave and surface you can find. This is obviously quite tedious, but it can allow for a ground-level farm that is active no matter where the player is. This works for witch farms as well, and is probably your best efficiency if you are playing on a server.
Comment: Interesting. So I'd go `Ground + 128` up and then AFK on top of the farm?
Comment: You'd build a big tower that is greater than 128 blocks above the ground, then you'd stand on it. You would have the mob farm inside a 128 block radius of you, but the ground would be outside that radius. Any mobs that are on the ground will immediately despawn, but the mobs in the farm will not. Note that this might not work so well for an XP farm, I think you'd have to build an elevator that moves the mobs up to where you are (so they don't despawn after 30 seconds.) Here's a video that shows someone using this technique for a witch farm. https://www.youtube.com/watch?v=hj0YPPjticE


Computation of solution of minimization problem

Question: I have $u(x) = e^x \in H^1 (\Omega)$ and $\Omega = (0,1)$ and should compute the solution $p \in \mathbb P^2$ of the minimization problem: $$|| u-p||_{H^1(\Omega)}^2 = inf ||u-q||_{H^1(\Omega)}^2$$ where $q \in \mathbb P^2$. In addition to that, I should determine the $H^1(\Omega)$- and the $L^2(\Omega)$-norm of the difference u-p.
My questions:
a) How does the linear system looks explicitly and how does the error representation look like?
b) The information of (a) should be enough to let the system solved by Maple / Mathematica / ... ?
Thanks for your help!
Comment: Oh no sorry, I told some fake news -- $\mathbb P^2$ is the space of polynomials of degree <= 2. Actually, I'm not sure if one writes $\mathbb P^2 $ or $\mathbb P_2$. But anyway, it's the space of polynomials. :)
Comment: What do you mean by $\mathbb{P}^2$ ?
Comment: $ \mathbb P^2$ is the extended Euclidean plane. Can you help me? :)
Comment: In that case what is the meaning of $u-p$ ? (sorry for the questions I don't quite understand the problem but I am willing to help :-))
Answer: First method
Let $p=ax^2+bx+c$. Then as $p'(x)=2ax+b$ you have.
An explicit computation leads to (using wolfram alpha:
$$\|u-p\|_{H^1}^2=\int_0^1 (e^x-ax^2-bx-c)^2+(e^x-2ax-b)^2 dx=\frac{23 a^2}{15}+a \left(\frac{5 b}{2}+\frac{2 c}{3}-2
e\right)+\frac{4 b^2}{3}+b (c-2 e)+c^2+2 c-2 e c+e^2-1$$
this is a quadratic function of tree variables so taking the gradient in $(a,b,c)$ leads to a system of 3 equations with 3 unknowns, more precisely:
\begin{align}\frac{46}{15} a+\frac{5 b}{2}+\frac{2 c}{3}-2e=0\\
\frac{5}{2}a+\frac{8}{3} b+c-2e=0\\
\frac{2}{3}a +b+2c+(2-2e)=0
\end{align}
Second method (the best one in my opinion)
Note that $H^1$ is an Hilbert space with the inner product:
$$\langle u, v\rangle = \int_0^1 (u' v' +uv)(x) dx$$
So the question can be rewritten as:

Find the orthogonal projection of $u$ on the linear subspace $\mathbb{P}^2$.

You can then use usual tools of hilbertian spaces: with $q_0,q_1,q_2$ an orthonormal basis of $\mathbb{P}^2$ (you can find one from $(1,x,x^2)$ using Gram Schmidt ) you obtain:
$$p=\langle q_0,u \rangle q_0+\langle q_1,u \rangle q_1+\langle q_2,u \rangle q_2$$
which directly leads to the expression of $p$ and of the distance.
Comment: Thanks a lot four your answer! This helped a lot! :)


Bootstrap Placing Elements one under another

Question: I'm using bootstrap to position some cards one near another but i'm not really able to do it because it always places the cards one under another.

 Car

                     Price

                    City

 Car

                     Price

                    City

Basically i need those 2 cards to be on the same row and one after another but i don't understand what's wrong.Are those cards too big?
Answer: The problem is your inline style definition for your cards: width: 20rem. Essentially, you're giving the card 2/12 of the grid to work with (col-sm-2) and then giving a hard definition of the card to have a width of 20rem, which forces the next card to take up the next line.
Also, you need to specify another row after your col-8 declaration. Here's my code:

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

 Car

                       Price

                      City

 Car

                       Price

                      City


Need help identifying electrical wiring

Question: My house was built in 1985. It has the 3 aluminum wires for the range outlet. The previous range was a 2001 model and was directly connected in a box. I wish to install an outlet. I have been told that the bare wire is a neutral. Is this true? If so, can I just use the 3 prong outlet and bond the ground on the range's power cord to the range? Is this okay to do?
Comment: Is there a path you can use to get a 10AWG copper wire from the range location back to a suitable grounding point? (either the panel the circuit came from, a 30A+ grounded circuit, or a point on the grounding electrode conductor system?)
Answer: Yes, the bare wire is neutral.
I would think twice about installing a receptacle. Most ranges can be installed hard-wired, and I consider that preferable. However, with aluminum wiring you need to check the installation instructions for the range. The instructions may say only copper wiring, in which case you need to use a receptacle. If they allow copper or aluminum then hard-wiring may be a better idea, though you need to make sure that you use appropriate connectors. Note that not all receptacles are rated for aluminum wiring, so you need to check that as well.
But first you need to check if the wires are big enough! The existing breaker is one clue, as it should match the wiring. In addition, see if there is any printing on the cable, as that should tell you the size of the wires. If the wires are big enough then you can use them. If the wires are too small (e.g., 10 AWG for 30A but your new range needs 40A) then you will need to replace the cable with a new, larger cable.
3-wire (hot/hot/neutral) connections are allowed if they already exist but are not allowed for new installations (a straight range replacement is allowed). 4-wire (hot/hot/neutral/ground) connections are much safer. If you replace the cable due to size requirements then you must put in a 4-wire cable (and 4-wire plug/receptacle if you don't hard-wire).
Even if you don't need to replace the cable, you can still make it safer and use a 4-wire connection by running a separate ground wire. It is a little tricky because of the bare neutral, but it can be done. The ground wire does not have to follow the path of the existing cable, it just has to somehow get from point A (your range) to point B (your panel).
Answer: That is aluminum SEU cable.   "Service Entrance, Unarmored". Since the service entrance (weatherhead through meter pan to main breaker) doesn't have ground, neither does this cable.
This was banned in 1966 (pre-moonshot) for all appliances except ranges and dryers.  Dryer/range manufacturers convinced NFPA that it would be OK to "ground" (hah) the chassis of the appliance to the neutral wire, and not have a ground.  This causes catastrophe if the neutral wire has a connection problem - electrifying the chassis of the appliance - but manufacturers argued this should be a rare event since dryer and range connections were rarely disturbed.  It was banned in 1996 (post-Kurt Cobain) for ranges and dryers because the data proved accidents were not so rare after all.
The insidious thing about it, with ranges, is the range typically still works. Almost every load on a range is 240V only, and will work fine without neutral.  It's mainly there for the oven light.* So there will be nothing to warn you that the appliance is faulty/energized.
Installations whose permit was pulled prior to NEC 1996 being adopted were allowed to use this type of cable.  However it is banned in new work and improvements.

I wish to install an outlet.

I don't think so. That would be "new work" and would kick you into the new rules.
As manassehkatz says, if it's feasible to retrofit a #10 copper ground from there to a) another junction box with #10 copper ground going back to the panel, b) the panel, or c) the Gronding Electrode (bare copper wires going over to water pipe), then you can install a 4-prong outlet all good and proper.  This is due to the retrofit ground rules 250.130(C).
I don't think this would be legal but it would be much safer -- you could install a GFCI breaker and wire a 4-prong receptacle with the ground conected to nothing at all. Label the receptacle  "GFCI Protected / No Equipment Ground".  Use a 4-prong cable on the range and wire normally for a 4-wire cable (neutral and ground separated). Yes, oven neutral floats, connected to nothing.  That helps the GFCI work.
Also, you need to think about ampacity. #10 aluminum wire is only allowed 25 amps. #8 aluminum is 35A.  #6 aluminum is 50A.  (NEC 240.4(D) and 310.15(B)(16).)   If this compels you into a whole cable replacement, you can replace with 4-wire cable as follows:

40A: #8 any type of copper, or #6 aluminum
50A: #6 NM or UF, #8 other types of copper such as SER, or #6 aluminum

* Even dumber is the reason for 120V oven lights. Oven lights must be incandescent (for the heat).  So back in the day, any common 20 cent light bulb would suffice, why make people buy special 240V oven bulbs? (clearly HP and Epson wasn't selling ovens back then). Today, the benefit is lost, as CFL/LEDs will burn up in an oven, so you have to buy a special oven bulb after all.
Comment: Note that SEU is still legal for 240V circuits that do *not* use a neutral (such as hot water heaters, air conditioner outdoor units, and some spas/hot tubs)
Comment: @ThreePhaseEel yes, because of the rule that lets you use SEU neutral as ground instead.  Now all you need is a no-neutral range/oven!  (Why isn't that a thing yet?  Cooktops handle it fine, the oven is the only holdout.  That would really moot the entire safety issue around NEMA 10 sockets.  So easy, and save many lives.)
Comment: Yeah, some low-end imported ranges come oh-so-close to being no-neutral, for that matter (one could even make a no-neutral range that used a standard 120V light bulb using a small control transformer to step down the 240V to 120V, or some other arrangement for that matter)
Answer: You got an excellent answer from Harper, but I'd like to add an important note: you can't connect aluminum wiring to copper wiring by simply twisting them together or using a wire nut! If you don't use specially-rated connectors, the differing expansion rates of copper and aluminum can work the connection apart and cause arcs. Worse yet, the two metals interact chemically, causing corrosion and oxidation. Either of these situations could cause a fire.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Need help identifying electrical wiring


Concatenate dataframes and remove duplicates based on multiple columns value

Question: I want to concatenate two dataframes that have the same columns and remove duplicates.
I then want to remove duplicates of the new dataframe based on multiple key columns.
For example I have these two dataframes
import pandas as pd

    data1 = {'first_column':  ['1', '2', '2', '2'],
            'second_column': ['1', '2', '2', '2'],
           'key_column1':['1', '2', '2', '6'],
          'key_column2':['1', '2', '2', '1'],
           'fourth_column':['1', '2', '2', '2'],
            }
    df1 = pd.DataFrame(data1)

    data2 = {'first_column':  ['1', '2', '2', '2'],
            'second_column': ['1', '2', '2', '2'],
           'key_column1':['1', '3', '2', '6'],
          'key_column2':['1', '5', '2', '2'],
           'fourth_column':['1', '2', '2', '2'],
            }

    df2 = pd.DataFrame(data2)

Expected output:
Answer: Use pandas.concat to concatenate a list of dataframes. Then, use pandas.DataFrame.drop_duplicates() to drop the duplicate records. The pandas.DataFrame.drop_duplicates() function has a parameter called subset that you can use to determine which columns to include in the duplicates search. Here's how to do it, using the example you gave:

import pandas as pd

data1 = {
    "first_column": ["1", "2", "2", "2"],
    "second_column": ["1", "2", "2", "2"],
    "key_column1": ["1", "2", "2", "6"],
    "key_column2": ["1", "2", "2", "1"],
    "fourth_column": ["1", "2", "2", "2"],
}
df1 = pd.DataFrame(data1)

data2 = {
    "first_column": ["1", "2", "2", "2"],
    "second_column": ["1", "2", "2", "2"],
    "key_column1": ["1", "3", "2", "6"],
    "key_column2": ["1", "5", "2", "2"],
    "fourth_column": ["1", "2", "2", "2"],
}

df2 = pd.DataFrame(data2)

df_combined = (
    pd.concat([df1, df2])
    .drop_duplicates(subset=["key_column1", "key_column2"], keep="first")
    .reset_index(drop=True)
)
df_combined

The above code outputs the following:

If you want to wrapt it all inside of a function here's how you might consider doing it:
from __future__ import annotations
from typing import List
import pandas as pd

def concat_no_dups(*dfs: pd.DataFrame, key_columns: List[str] | str | None = None) -> pd.DataFrame:
    """
    Concatenate dataframes together and drop duplicates based on equality of
    selected columns.

    Parameters
    ----------
    dfs : pd.DataFrame
        A sequence of dataframes.
    key_columns : List[str] | str | None, optional
        The columns to use as keys to drop duplicates.
        If no list, or column provided, it uses all the columns
        from the concatenated dataframe, to search for duplicates

    Returns
    -------
    df_combined : DataFrame
        The concatenated dataframe with duplicate rows removed.

    Raises
    ------
    KeyError
        If one or more keys from `key_columns` do not exist in the dataframe,
        obtained after combining all `dfs` together.

    Examples
    --------
    >>> import pandas as pd
    >>> data1 = pd.DataFrame(
        [['a', 12], ['a', 15], ['b', 19], ['c', 18]],
        columns=['key', 'value']
    )
    >>> data2 = pd.DataFrame(
        [['a', 16], ['a', 10], ['b', 13], ['e', 19]],
        columns=['key', 'value']
    )
    >>> concat_no_dups(data1, data2, key_columns='key')
      key  value
    0   a     12
    1   b     19
    2   c     18
    3   e     19
    >>> concat_no_dups(data1, data2, key_columns=['key', 'value'])
      key  value
    0   a     12
    1   a     15
    2   b     19
    3   c     18
    4   a     16
    5   a     10
    6   b     13
    7   e     19
    >>> concat_no_dups(data1, data2)
      key  value
    0   a     12
    1   a     15
    2   b     19
    3   c     18
    4   a     16
    5   a     10
    6   b     13
    7   e     19
    >>> concat_no_dups(data1, data2, data1)
      key  value
    0   a     12
    1   a     15
    2   b     19
    3   c     18
    4   a     16
    5   a     10
    6   b     13
    7   e     19
    """
    df_combined = pd.concat([df for df in dfs])
    if key_columns is None:
        key_columns = list(df_combined.columns)
    elif not hasattr(key_columns, '__iter__') or isinstance(key_columns, str):
        key_columns = [key_columns]
    missing_keys = pd.Index(key_columns).difference(df_combined.columns)
    if not missing_keys.empty:
        raise KeyError(
            f"The following key columns weren't found: {list(missing_keys)}. "
            f"Available columns: {list(df_combined.columns.astype(str))}."
        )
    return df_combined.drop_duplicates(subset=key_columns).reset_index(drop=True)

Comment: Please note that you need keep=False to get the right result
Answer: You need first to concat"
df = pd.concat([df1, df2])

And then to remove duplicates by not leaving any of them (keep=False):
df.drop_duplicates(keep=False, inplace=True)
df

  first_column second_column key_column1 key_column2 fourth_column
3            2             2           6           1             2
1            2             2           3           5             2
3            2             2           6           2             2

if you need to reset the index, do:
df.reset_index(drop=True, inplace=True)
df

  first_column second_column key_column1 key_column2 fourth_column
0            2             2           6           1             2
1            2             2           3           5             2
2            2             2           6           2             2


Skyrim: Wasted all J'zargo's scrolls

Question: I have wasted all of the J'zargo Experiment scrolls on enemies not the undead. And I am too far in the game to reload. What to do now?
Comment: console commands.
Comment: Are you on pc ? If so, @ColinD is correct.  Just use console commands
Answer: These scrolls are part of the quest J'zargo's Experiment.  Sadly, there's no (in-game) way to get more if you've used them all up on the wrong enemies:

If you use up all ten scrolls without killing three undead enemies, the quest will be failed.

The only reward for this is J'zargo will be willing to be a follower for you - there's no questline this locks you out of, etc - so you might just give up and move on.
Another alternative is to use the console, if you're on the PC.  Try:

resetquest MGRAppJzargo01

which should reset this quest and allow you to retry it.
If you haven't talked to J'zargo and failed the quest, you might also be able to just give yourself more scrolls:

additem 000967e3 10

should give you 10 more of the relevant scroll.

Skyrim: Wasted all J'zargo's scrolls


multiple audio html : auto stop other when current is playing with javascript

Question: I have 10 audio players with simple html audio tags on a html5 page.
No jquery, no special audio js plugins, etc...
Does anyone has a simple script in js to pause all other players when the current player is playing ?
I don't want to use js plugins because i want to keep a simple audio html code.
Answer: you can use event delegation. Simply listen to the play event in the capturing phase and then pause all video file, but not the target one:
document.addEventListener('play', function(e){
    var audios = document.getElementsByTagName('audio');
    for(var i = 0, len = audios.length; i < len;i++){
        if(audios[i] != e.target){
            audios[i].pause();
        }
    }
}, true);

Comment: Can I upovte +100 ? I love how ready-to-use-just-copy-paste-it it is :)
Comment: Thanks i'm doing a small music project... Works easy! :)
Comment: perfect answer!
Comment: Incredibly helpful.
Comment: `len = audios.length` seems like an unnecessary step. You can just do `i < audios.length`.
Answer: Instead of looping over all audio tags on a page and pausing them, you can store a reference to the currently playing element, and have only that one pause when playing another.
document.addEventListener("play", function(evt) {
    if(this.$AudioPlaying && this.$AudioPlaying !== evt.target) {
        this.$AudioPlaying.pause();
    }
    this.$AudioPlaying = evt.target;
}, true);

Comment: I've fixed just one thing to prevent the same audio element to get caught into a bad working loop because you must skip the current one with `if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)`. Thank you, i've created that based on this and other questions related on [this gist.](http://erm3nda.github.io/blog/2016/06/02/javascript-html5-audio-swapper-and-remember-me-function)
Comment: Changed to a better version that doesn't use global variable, and fixes the bug @m3nda mentions (Thanks).
Comment: Works perfectly in the latest browsers (2024) for both audio and video content. Perhaps `$MediaPlaying` would be a better fitting name, since your code works with both.
Answer: Mixing both previous answers that didn't work, i've used that. I just added && window.$_currentlyPlaying != evt.target and all is working.
Also i've created a gist with this and other goodies for audio tags. javascript-audio-tags
window.addEventListener("play", function(evt)
{
    if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
    {
        window.$_currentlyPlaying.pause();
    }
    window.$_currentlyPlaying = evt.target;
}, true);

Comment: This one worked for me without any hitch. I just popped it at the bottom of the page where I have a similar audio script running.
Answer: $("audio").on("play", function() {
    var id = $(this).attr('id');

    $("audio").not(this).each(function(index, audio) {
        audio.pause();
    });
});

$("video").on("play", function() {
    var id = $(this).attr('id');

    $("video").not(this).each(function(index, video) {
        video.pause();
    });
});

Comment: you can upvote if it work for you.
você pode aumentar se funcionar para você.
Answer: I don't know if it is because of Chrome updates, but the previous answers did not work for me. I modified a bit of the code here and came up with this:
document.addEventListener("play", function(evt)
{
    if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
    {
        window.$_currentlyPlaying.pause();
    }
    window.$_currentlyPlaying = evt.target;
}, true);

I don't know why, but the widow.addEventListener was not working for me, but I liked the idea of having the currentPlaying variable stored in the window element instead of having to create it outside of the listener prior to using it.
Answer: Best solution rewritten regarding ECMA 2022:
  document.addEventListener('play', (event) => {
    const audios = [...document.getElementsByTagName('audio')];

    audios.forEach((audio) => audio !== event.target && audio.pause());
  }, true);

Comment: Exactly! A collection has very similar structure to an array: it's indexed just the same and can be iterated with a for loop. But to use array methods like forEach it needs to be converted into an array first.
Comment: `...document`, is this a thing? What are `...` for?
Comment: `document.getElementsByTagName('audio')` is a thing :) A collection of DOM nodes to be exact. And we use `...` aka spread operator to make an array of it.
Comment: It's the first time I come across the three-dot notation. I see; it seems like the call returns a `NodeList` or `HTMLCollection` (I don't care), and then it is turned into an Array.
Answer: You can even try this solution, if you don't want to loop through
var previousAudio;
document.addEventListener('play', function(e){
    if(previousAudio && previousAudio != e.target){
        previousAudio.pause();
    }
    previousAudio = e.target;
}, true);

Comment: tried to edit the first misspelled 'previous' but edits need to be at least 6 characters so I couldn't.
Comment: The only difference between my code and this is the `document.xxx` instead of `window.xxxxx`, so, using Ajax or iframes would break the usage, i guess.
Comment: @dijon add "Hope it works" to the end of the answer :-)
Answer: I made a player at the bottom and changed the src every time the user clicks on play
this is just one way of doing it
HTML
<audio src="tracks/track1.mp3" type="audio/mp3" class='audios'></audio>

<audio src="tracks/track2.mp3" type="audio/mp3" class='audios'></audio>

<audio src="tracks/track3.mp3" type="audio/mp3" class='audios'></audio>

  <audio class='main-audio' controls>
     <source src="#" type="audio/mp3">
  </audio>

JavaScript
const audios_with_src = document.querySelectorAll('.audios')
const play = document.querySelectorAll('.fa-play')
const pause = document.querySelectorAll('.fa-pause-circle')
const stop = document.querySelectorAll('.fa-stop')
const main_player = document.querySelector('.main-audio')

for(let i =0; i < audios_with_src.length; i++) {
 play[i].addEventListener('click', (e) => {
    main_player.src = audios_with_src[i].src;
    main_player.play()
    })

pause[i].addEventListener('click', () => {
    main_player.pause()
})

stop[i].addEventListener('click', () => {
    main_player.pause()
    main_player.currentTime = 0;  // there is no stop() function so had to do this
})

}


Apache Spark: How do I convert an RDD[(String, String)] into a Array[String] in scala-spark?

Question: The code i am running looks like this
<code>val termCounts: Array[(String, Long)] = tokenized.flatMap(_.map(_ -> 1L)).reduceByKey(_ + _).collect().sortBy(-_._2)
//   vocabArray: Chosen vocab (removing common terms)
val numStopwords = 20
val stopWord = sc.wholeTextFiles(".../stopword.txt")
val vocabArray1: Array[String] =
termCounts.takeRight(termCounts.size - numStopwords).map(_._1)
val vocabArray = vocabArray1 diff stopWord
</code>
see, i wanted to use the diff function and it only works with same types.
Answer: When you use sc.wholeTextFiles("/root/folder/to/textfiles/")  it will read each part file in that folder into a String.
So if your set up is
<code>  /root/folder/to/textfiles/
   .../part1.txt
   .../part2.txt
   .../part3.txt
</code>
part1.txt, part2.txt, part3.txt are all read as single records. So your RDD[(String, String)] would be a pair of path to file name and the whole file as a string.
like so.
<code>    ("/root/folder/to/text/files/part1.txt", "actual contents of part1.txt as a String"),
    ("/root/folder/to/text/files/part2.txt", "actual contents of part2.txt as a String")
    ...
</code>
You probably want to tokenize the actual contents of each file before mapping them.
<code>  stopWord.flatMap(tokenize(_._2)).collect()
</code>


how to check if a row is null in xlsx using java

Question: I am using Apache POI to read xlsx file, it works well. I have question to you when row is found null, how I'm able to handle it? My file only contain 50 row, but it show 1000 row, rest of row found null.
<code>try {
    FileInputStream file = new FileInputStream(new File("D://productData.xlsx"));
    Workbook workbook = WorkbookFactory.create(file);
    Sheet sheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    CountryCode countryCode = userDao.getCode(sheet.getRow(1).getCell(4).toString());
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        if (row.getRowNum() == 0) {
            continue;
        } else if (row.getRowNum() == 1) {
            //some operation
        } else if (row.getRowNum() == 2) {
            continue;
        } else {
            ExcelData excelData = new ExcelData();
            try {
                for (int i = 0; i <= 6; i++) {
                    row.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
                }
                //some operation
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    file.close();
    response.setResponse(data);
} catch (Exception e) {
    e.printStackTrace();
}
</code>

how can i read null row from excel and how can terminate from
  iterator when row is null in the excel sheet.
  Thanks
Answer: If you fetch a row, and get back null, then that means there is no data stored in the file for that row - it's completely blank.
POI by default gives you what's in the file. With Cells, you can set a MissingCellPolicy to control how missing and blank cells are handled. There's some examples of using this in the Apache POI docs. With rows, they're either there or not, so you need to check for nulls when fetching a row.


What is the set of values of $a$ ($a \in \mathbb{R}$) for which $\log_a(x^2 + 4) \ge 2$, $\forall x \in \mathbb{R}$?

Question: How can I find the set of values of $a$, with $a \in \mathbb{R}$ such that:
$$\log_a(x^2+4) \ge 2, \forall x \in \mathbb{R}$$
How should I approach this?
Answer: Note that
$$\log_a(x^2+4)=\frac{\log(x^2+4)}{\log a} $$
Thus we need
$$\log(x^2+4)\geq 2\log a$$
(assuming $a>1$). This must in particular hold for $x=0$. Thus we need
$$\log 4=2\log 2\geq 2\log a$$
I'm sure you can figure it out from here.
If $a<1$ we need $$\log(x^2+4)\leq 2\log a$$
But this is impossible since $2\log a<0$ and $\log(x^2+4)>0$.
Comment: Shouldn't we consider $2$ cases when we multiply by $log$ $a$? One case when $a \in (0, 1)$ so $log$ $a< 0$, therefore the sign of the inequality would change and the other case when $a \in (1, +\infty)$ so $log$ $a > 0$, therefore the sign of the inequality would remain the same. I went throught the math and I get the same result but I just want to make sure. Shouldn't we also take that into consideration?
Comment: @user You're right. Let me edit.
Comment: @user See my update.
Answer: Note if $0 < a < 1$ then $\log_a M$ is decreasing; If $M > 1$ then $\log_a M < 0$, $\log_a 1 = 0$ and if $0< M < 1$ then $\log_a M > 0$.  And $M < N\iff M> N$.
So $\log_a (x^2 +4) \ge 2 \iff a^{\log_a x^2 +4 } = x^2 + 4 \le a^2 \iff x^2 \le a^2 -4$.  But because $a^2 < 1$  then $a^2 -4 < -3$ and $x^3 < -3$ is impossible.  So $\log_a(x^2 + 4) < 2$ for all $0< a < 1$.
And if $a > 1$ then $\log_a M$ is increasing; If $M > 1$ then $\log_a M > 0$, $\log_a 1 = 0$ and if $0< M < 1$ then $\log_a M < 0$.  And $M < N\iff M< N$.
So $\log_a (x^2 +4) \ge 2 \iff a^{\log_a x^2 +4 } = x^2 + 4 \ge a^2 \iff x^2 \ge a^2 -4$.
For this be be true for all $x$ then $x^2 \ge 0$ and $x^2 =0$ is possible.  So this is only possible and is always possible if $x^2 \ge 0 \ge a^2 -4$.
Or in other words if $a^2 \le 4$ or $|a| \le 2$. But as $a >1$ we have:
$1 < a \le 2$.
=== badly worded earlier answer below ===
If $a > 1$ then $\log_a(x^2 + 4) \ge 2\iff a^{\log_a (x^2 + 4)}=x^2 +4 \ge a^2\iff \sqrt{x^2 + 4} \ge a$.  Now $\sqrt{x^2 + 4}$ can be as small, but no smaller than $2$ and can take on all values higher than $2$ so this can only be true for all $x$ (assuming $a > 1$) and will be true for all $x$ if $a \le 2$.
Or to put it another way.  If $a > 2$ then if $0 \le x < \sqrt{a^2 -4}$ we have $x^2 + 4 < a^2$ and $\log_a (x^2 + 4) < 2$.  But if $1 < a \le 2$ then $a^2 \le 4 \le x^2 + 4$ for all $x$ and $\log_2 (x^2 + 4) \ge 2$.
And if $0< a < 1$ then $x^2 + 4 \ge 4 > 1$ so $\log_a x^2 + 4 < 0$ for all $x$.
And $\log_a$ is undefined for $a\le 0$ or $a = 0$.
so $\log_a (x^2 + 4) \ge 2 \iff 1 < a^2 < x^2 + 4$ and that is only true for all $x$ if $1< a \le 2$.


Heatilator fireplace fail

Question: We have an old heatilator fireplace in our 1960's house.  I called a well recommended Fireplace guy to replace the rotted out damper, and he inspected the fireplace and told me (and showed me) that there is no liner in my chimney.  He said that the heatilator box is shot and the fix is an insert and stainless steel liner.  We bought our house about a year ago and used the fireplace all winter, so I do want a working fireplace. He quoted me about $4300.
My questions are this:  What is your feedback for this scenario?  Is this the proper fix for the problem?  Is there an alternate workable fix that you can think of?
Thank you for your help.
Comment: Fix for which problem? The bad damper or the lack of a modern safety feature (the liner)?
Comment: Call your homeowners insurance agent as well. About 10 years ago my parents homeowners insurance paid like 80% of the chimney re-lining.  Completely shocked my parents at the time, the chimney company was who suggested asking.
Comment: Both, plus the firebox failure.  He told me that the 1950's-1960's heatilator fireplaces are failing and that mine has.    Thanks for the suggestion about insurance company.
Answer: I would call a chimney person to inspect the chimney and make recommendations to fix the chimney. He will be able to give you pricing on your repair options for the chimney. The cost of the chimney repairs will vary depending on the type of fuel you will be using and what the codes are for your area. Where I live the cost for a chimney repair for natural gas is much less than the cost to burn a solid fuel (wood) etc. Depending upon the condition of the present insert, you could see if it can be repaired.
Comment: Thank you.  The guy who came in is a chimney person and well recommended.  I was hoping for confirmation of what he told me and any alternate ideas.
Comment: We don't have natural gas, so that is not an option.  (Don't have it in our neighborhood; we are very rural.)  This is a wood-burning fireplace.

Heatilator fireplace fail


Unable to connect other monitors, Lenovo L470

Question: No matter what kind of connection(VGA,HDMI via DisplayPort,DVI via DisplayPort) I tried, the monitor recieves no Signal from the Laptop. I have dual-boot with Ubuntu 20.04 and Windows 10, so i tried it on Windows and worked without problems. My guess is there is something going wrong with ubuntu. So i tried adding modes to xrandr, tried reinstalling the graphic driver, i tried older kernel versions and nothing worked.
Output of xrandr:
xrandr: Failed to get size of gamma for output default
Screen 0: minimum 1920 x 1080, current 1920 x 1080, maximum 1920 x 1080
default connected primary 1920x1080+0+0 0mm x 0mm
   1920x1080     77.00*

Output of lshw -C -display:
*-display UNCLAIMED
       description: VGA compatible controller
       product: HD Graphics 620
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 02
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm vga_controller bus_master cap_list
       configuration: latency=0
       resources: memory:f0000000-f0ffffff memory:e0000000-efffffff ioport:e000(size=64) memory:c0000-dffff

Output of dpkg --get-selections | grep mesa
libegl-mesa0:amd64              install
libgl1-mesa-dri:amd64               install
libgl1-mesa-dri:i386                deinstall
libgl1-mesa-glx:amd64               install
libglapi-mesa:amd64             install
libglu1-mesa:amd64              install
libglx-mesa0:amd64              install
mesa-utils                  install
mesa-va-drivers:amd64               install
mesa-vdpau-drivers:amd64            install
mesa-vulkan-drivers:amd64           install

I'm happy if you could help me.
Any ideas?
Comment: Check dmesg and grep for intel.. unclaimed means the driver is not loaded
Answer: I took a more detailed look at dmesg and saw this:
[    0.050136] You have booted with nomodeset. This means your GPU drivers are DISABLED
[    0.050138] Any video related functionality will be severely degraded, and you may not even be able to suspend the system properly
[    0.050141] Unless you actually understand what nomodeset does, you should reboot without enabling it

In the past, I had enabled nomodeset in grub, because Ubuntu didn't boot for whatever reason.
After i removed it and updated grub, everything work fine, as always.
Big thanks to @Alex for helping me with this issue.


Why is FSX crashing on single player?

Question: I got FSX for my birthday and I couldn't wait to start it up; when I did it worked fine but 2 days later -- after 2 mins of gameplay below 16x speed -- it crashed. I also have service packs one and two; I had no mods installed at the time, which is annoying because [...]. I got an epic AI mod but now it still crashes; I can only play multiplayer now :)
Why is it crashing? How can I fix it?
Comment: Are you getting any error message in the event log or anything?
Comment: Does it run OK when you run it at normal speed? What are you using for multiplayer, VATSIM?
Comment: Also: are you on windows 8 or 8.1? If just 8, I suggest running the upgrade.
Comment: No errors in the event log, it seems to be when you put it below 16x speed, it crashes, higher speed it doesen't
Answer: Here are a couple of possible solutions:
Make sure that the latest windows updates are installed if you are on windows 8 upgrade to 8.1, also make sure you have the latest drivers, especially for you graphics card.
Seeing as there is no error in the event log something in the FSX game folder might have got corrupted, try deleting the logbook file in the Flight Simulator X Files folder, which should be located in your Documents folder. it normally solves start-up problems with FSX and seeing as you only get 2 minutes into the game before it crashes, it might be a fault occurs at start-up.
Alternatively something may have gone wrong when you installed the service packs SP1 and SP2, I would suggest reinstalling those. Although I have heard of cases were having the services packs installed causes FSX to crash when running on windows 8 and 8.1 so you might want to just uninstall them.
My final solution being a reinstall of FSX, if you have to do this and have problems with a 1628 error see this page:
installshield error 1628 when installing FSX on Windows 8.1
If none of these or any fixes you've tried fail I would suggest asking the question on a flight sim forum, as there will be more people that are knowledgeable about FSX.

Why is FSX crashing on single player?


Van Dyke's matching rule

Question: I am looking at Perturbation Theory by E.J. Hinch. The author introduces Van Dyke's matching rule:
(m term inner)(n term outer) = (n term outer)(m term inner)
To be used to match the terms in an inner solution to the the terms in the outer solution for some perturbed differential equation.
Hinch when comparing with introducing intermediate variables says: 'Van Dyke's matching rule usually works and is more convenient.'
Does anyone know an example where this matching rule doesn't work?
Edit
In section $5.2.6$ of the book above, the author gives an example of where the matching rule is meant to fail. Is this an example where the matching rule actually fails or just shows some care in comparing terms is required? In particular, would the intermediate variables approach have any problems?
Comment: Section 5.2.6 of that book is called "Failure of Van Dyke's matching rule", which sounds like it might help.  http://books.google.com/books?id=mqY4ZM0BWwIC&lpg=PP1&pg=PA72#v=onepage&q&f=false
Comment: Yes, I read this. But I don't see how the example given actually makes the method fail. Just have to apply with a little more care but no more than we would with the intermediate variable approach.
Answer: Okay I have found an example:
$f_{xx} + \frac{1}{x}f_x+f_x^2 +\epsilon ff_x=0$ for $x>1$
$f=0$ on $x=1$ and $f\rightarrow 1$
The solution is something close to $\log(1+\log(x)/\log(1/\epsilon))$
Van Dyke's rule fails because when expanding an infinite number terms are of the same order (in size).
However, with the intermediate variable approach since we are scaling by $\epsilon^{-\alpha}$ with $\alpha \in[0,1]$ we are able to choose $\alpha$ so that there are only a finite number of terms the same order.
The example is completely contrived though, I would feel much better with a more natural example.
Thank you for your effort J.Meyer and J.M.
Answer: A detailed discussion of the validity of Van Dyke's matching rule was given by L. E. Fraenkel in the first of the series of three papers: L. E. Fraenkel (1969) "On the method of matched asymptotic expansions, Pts. 1-3", Mathematical Proceedings of the Cambridge Philosophical Society, 65(1), pp. 209-231 (part 1), pp. 233-261 (part 2) and pp. 263-284.
This is the link to the first part: http://dx.doi.org/10.1017/S0305004100044212
On the page 217 Fraenkel gives a simple example, which looks about as artificial as yours, but, to quote his words: "This example is artificial only in its simplicity; functions resembling that above occur in curtain problems involving a circular cylinder whose radius is small compared with some other reference length".

Van Dyke's matching rule


Does static provide additional guaranties in JMM context?

Question: I am reading about java singleton and I've met strange things.
I will refer to following artice as example(you can easy find more)
Author provides the following singleton:
public class ASingleton {

    private static ASingleton instance = new ASingleton();

    private ASingleton() {
    }

    public static ASingleton getInstance() {
        return instance;
    }

}

and comments:

Pros:
   -Thread safety without synchronization
   - Easy to implement
Cons:
   - Early creation of resource that might not be used in the application.
   -The client application can't pass any argument, so we can't reuse it.
       For example, having a generic singleton class for database connection
     where client application supplies database server properties.

I want to get clarification about Thread safety without synchronization point.
I've read concurrency in practice book and don't remember anything related with this.
I missed something or this clarification is not relevant?
Additionally I want to tell you that you can encounter the same singleton but field marked as static final instead of just static
P.S.
I understand that I can read JMM  and this one contains the answer but I am usual guy and I can't undertand this source.
Comment: You don't have the guarantees of visibility (which would confer the thread safety) because the field isn't `final`.
Comment: @Andy, yes, I've corrected it a bit because text unrelated with code. I think author descibed the variant I provided
Comment: it would have to be `static final` in order to get the properties described.
Comment: Note!  When the author says "thread safety", that does _not_ mean that it makes the entire singleton thread safe.  It only means that the `getInstance()` method is thread safe.  A thread that calls `getInstance()` will never see the singleton object in a partially initialized or uninitialized state.
Comment: @ james large Why? getInstance is not synchronized
Answer: According to securecoding.cert.org this is a valid pattern:

Variables that are declared static and initialized at declaration or from a static initializer are guaranteed to be fully constructed before being made visible to other threads. However, this solution forgoes the benefits of lazy initialization.

The point is: loading classes is a well defined operation. And executing static initializing code falls into the same category.
It is important to understand: JMM knowledge is only "required" when you go for the static field + lazy init variant:

Initialization of the static helper field is deferred until the getInstance() method is called. The necessary happens-before relationships are created by the combination of the class loader's actions loading and initializing the Holder instance and the guarantees provided by the Java memory model (JMM). This idiom is a better choice than the double-checked locking idiom for lazily initializing static fields [Bloch 2008]. However, this idiom cannot be used to lazily initialize instance fields [Bloch 2001].

Finally: the final keyword should not affect this at all. Using final is much more about expressing your intent to declare a well, final thing - instead of one that gets potentially updated later on.
Comment: class loading != class initialization  from my point of view. All statuc fields and satic blocks initialize when access happens. P.S. maybe it depends on classloader flags but by default it works so
Comment: this text related with example where field declared as **static final**
Comment: *"All statuc fields and static blocks initialize when access happens."* - Basically, yes ... but it is more complicated than just "access".
Answer: That idiom is sound  with respect to the JMM.
There is a happens before relationship between the static initialization of a class and the use of any static variables.  This is a consequence of the locking that occurs during the initailization procedure described in JLS 12.4.2.

According to my reading, instance does not need to be declared as final here to get the required happens-before.  It is advisable for other reasons though.
Comment: "For each class or interface C, there is a unique initialization lock LC".  Step 1: "Synchronize on the inititialization lock".  Etcetera.  Look at the fine print that talks about how the procedure can be optimized **provided** that happens-before is preserved.  Finally go to the JMM section and note that 1) acquiring a lock is a synchronization action, and 2) synchronizes-with implies happens-before.
Comment: Like I said, this is a *consequence* of the procedure.  The JLS authors assume that 12.4.2 will be read / interpreted in the context of other relevant parts of the spec.  (They often don't spell things out ... if they can be logically inferred from other parts of the spec.  Redundancy leads to errors.)
Comment: can you discover other reasons?
Comment: I don't see quote in JLS which prove your answer


How can the element that an event is attached to be determined in React?

Question: Assuming I have a button element with a child element inside of it. If I add an onClick event to the button and then click the child, the event.target will be the child. How is it possible to find the element that has the click handler (in this case the button)?
The code below is a simplified example of the problem, in my app I have a few levels of nesting so using parentElement wont suffice.

const Button = (
  <button
      class="outer"
      onClick={() => console.log(event.target)}>

  </button>
);

ReactDOM.render(Button, document.getElementById('root'));
.outer {
  width: 200px;
  height: 200px;
  background: green;
}

.inner {
  display: block;
  width: 100px;
  height: 100px;
  background: red;
}

Comment: Hmm, where does `event` variable come from, because it it not passed from the listener? How is it optional, because it still magically works...
Answer: You need to use the property currentTarget: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
What MDN says:

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.
Answer: You need currentTarget instead of target. See https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget


How do I reformat v$session.osuser?

Question: I am trying to set up an Oracle WebLogic Datasource for my job. But every time I try to connect to the database, I get this error:
Connection test failed.
Message icon - Error Connection property: format error: Property is 'v$session.osuser' and value is 'Yann (Intern)'
I tried changing my username to "YannIntern" to remove the special characters, but the error is still the same and it also happens when I try to use Oracle SQL Developer. How can I stop the format error?
Comment: I don't know the answer. Though, if possible, try to use uppercase (e.g. YANNINTERN). In Oracle, username is stored in uppercase by default so ... maybe that's what prevents you from establishing connection.
Answer: Java reads this from the user.name property which defaults from the os username. However, this can be overriden by  setting -Duser.name=Yann
Here's an example in sqlcl
<code>
SQL> select  sys_context('userenv', 'os_user') from dual;

SYS_CONTEXT('USERENV','OS_USER')
------------------------------------
klrice

 <<< a short command to set java properties >>>
 <<< which is the same as a -D property     >>>

SQL> set property user.name kris
Setting user.name to kris (klrice)

SQL> @connect-klrice
Connected.
SQL> select  sys_context('userenv', 'os_user') from dual;

SYS_CONTEXT('USERENV','OS_USER')
----------------------------------
kris

SQL>

</code>
Answer: Same happened to me, I have parenthesis in my computer's name. I spent a lot of time researching but finally, I have the solution (I created an account just to answer this haha). To solve this you have to:
-Go to the folder location where you installed SQL Developer.
-Then go to: \ide\bin\ide.conf
-At the end add the following line:
<code># Custom VM Option
AddVMOption  -Duser.name=<YourUsername>
</code>
-Save the file, and restart SQL Developer, you will be able to connect and avoid that error message.

How do I reformat v$session.osuser?


how to keep the value of a variable in a closure

Question: i need to create multiple javascript functions which have a static id inside, so the function itself knows what data to process.
Here is some code:
(function(){
  function log(s){
    if(console && console.log) console.log(s);
    else alert(s);
  }
  var i = 10; while (i--){
    window.setTimeout(function(){
      // i need i to be 10, 9, 8... here not -1
      log(i);
    },500);
  }
})();

The problem ist that i allways gets updated by the loop, and i need to prevent this.
Thanks in advance for any help, comments or tips!
Answer: Just create a function and call it.
while (i--) {
    (function(i) {
        // use i here
    })(i);
}

Comment: Thanks, but that wont work i my case. the function will be called delayed.
Comment: @Florian How? setTimeout is executed _inside_, `function(i)` is executed immediately.
Answer: (function(){
  function log(s){
    if(console && console.log) console.log(s);
    else alert(s);
  }
  var i = 10; while (i--){

    (function() { // start anon func

      var copy = i; // copy loop variable

      window.setTimeout(function(){
        log(copy); // refer to copy
      },500);

    })(); // end anon func and call it immediately
  }
})();

Comment: Normally you pass the value to copy to the anonymous function as an argument
Comment: Thanks Daniel for providing an additional example, i think i do understand the concept now!
Answer: A little better approach to using an immediately invoked function in each iteration, is to have your log() function return a function.
(function(){
  function log(s){
    return function() {
        if(console && console.log) console.log(s);
        else alert(s);
    };
  }
  var i = 10; while (i--){
    window.setTimeout( log( i ),500 );
  }
})();

The overall result is that you end up constructing fewer function objects.
If you wanted the calls to be at an interval, either use setInterval(), or change this:
window.setTimeout( log( i ), 500 );

to this:
window.setTimeout( log( i ), i * 500 );


How to change custom view font?

Question: I have prepared one custom view, in custom view I have displayed alphabets. It is working fine, but in case of "g" it is displaying like this,

I want to change like this "g". How to change it? Please help me. I used the following code for painting,
<code>Paint mPaint=new Paint();
mPaint.setDither(true);
mPaint.setColor(0xFFFFFFFF);
mPaint.setTextSize(350);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);

Typeface typeArial;
typeArial = Typeface.create("arial", Typeface.BOLD);
mPaint.setTypeface(typeArial);
</code>
In onDraw(),
<code> bmpCanvas.drawText("g",50, 230,mPaint);
</code>
Please help me...
Answer: You can achieve it by setting programatically by down loading the text style and place in assets folder,for example to set custom font typeface as follows,try the same in you case for paint object.
<code> TextView txt = (TextView) findViewById(R.id.custom_font);
  Typeface font = Typeface.createFromAsset(getAssets(), "Helv Neue 67 Med Cond.ttf");
  txt.setTypeface(font);
</code>
Comment: thanks senthil for reply, is there any chance change "g" with out using ttf file
Comment: suppose i created typeface using above code, next time i want clear typeface for that just use txt.setTypeface(null); right

How to change custom view font?


Can I decorate this skirting board install?

Question: I've just had a carptener install skirting board and I'm struggling to see how I'll decorate them so they look half-decent.
After he installed them he complained that the walls were difficult and therefore there were some large gaps between the skirting and wall (up to 11mm at its worst). He's filled these with caulk but already I'm seeing it come away in some places.
He's also put in a couple of joins on the longer lengths without asking me. These aren't especially long lengths so it's just him saving wood. They're only 2, 3 and 3.5m lengths. The joins are really obvious.
One of the external mitres is 2mm off.
Some of the nails aren't flush with the skirting.
Lastly, the gap between the skirting and the floor varies from no gap to 6mm.
Is it possible for me to caulk/fill around these issues? Or should I get him back in? I'm not sure if I'm being unreasonable or not.
Pictures here.
Comment: It's certainly possible for the carpenter to reduce that gap - either by doing a better job of filling it, or by using a different method to attach the skirting to the wall. But it's not 'normal' for him to have to go to those lengths and not something he would have expected to have to do when he took the job. Tbh what I think he should have done was to call you over to look at the problem & discuss possible solutions at the time he first noticed that the walls are so uneven, rather than doing a half-assed job of filing the gaps.
Comment: Are you certain he's finished? I would have at least expected those joints to be tidied up & nail holes caulked.
Comment: The large gaps between the walls and skirting are almost certainly the plaster's fault and your carpenter probably couldn't have done much about those. If I had to guess then I'd probably say that he didn't put any foam backer rod into those large gaps before trying to fill them - which would lead to the large blob of caulk shrinking a lot as it dried, You can always caulk some more to fill the new gaps...
Comment: He's done but you're not. Set the nails. Use sanding sponge in places if necessary. Caulk, Paint : Both hide all sins. That gap at the floor is the only real problem. You're trying to get away w/o using quarter round? He needed to know that up front, or you needed to be more adamant about it. That being said... not setting your own nails is some BS, but I'd assume his work was otherwise to spec (as per contract). All in all, that's what every BS-painted-trim job looks like before (quarter round) paint.
Comment: Yep he's done. Invoice sent over. He said that it's the decorator's job to fill the nail holes. He said that caulking the gap between the wall and skirting would normally be the decorator too. I suspect he may have gone ahead and done that mainly because of the huge gaps.
Comment: I'm not sure if this is the plasterer's fault or the carpenter's. My previous skirting (before replastering) fit perfectly with hardly any gap.
Comment: Ah okay that's good to know.
Comment: Yeah all of the caulk in the wider gaps is coming away now after a few hours :(
Comment: I think opportunity has gone to get the plasterer to sort this out. So is it acceptable for the carpenter to not have been able to minimise that gap between the skirting and wall? 11mm seems ridiculous.
Comment: Please move the images to Stack Exchange's imgur domain by uploading them using the dialog available by clicking the image icon while [edit]ing your question. This post would be better for having them in it. The post will loose a significant amount of it's utility once the images are gone from the URL you've provided.
Answer: As for the gaps between the bottom of the base board (skirting) and the floor ... that is normally covered over with a base shoe molding. Base shoe is a small dimension molding that can be pressed down to fit the variations in the floor surface. Base shoe molding is normally only skipped when carpeting is going to be installed on the floor.
A nice trick regarding base shoe molding is to fully paint it (primer plus top coats) before it is installed. This way, after install, all that needs to be done is to fill the nail holes and do very small touch-up painting. It makes for a really clean look along the floor. If a pneumatic nailer is used to install the base show the nail hole size is minimized.
In days gone by it was common to just use flat boards for skirting instead of the types in common use today that have the top shaping features formed into the skirting. This allowed for the use of an additional small shaped molding called the top cap to finish off the top edge. Similar to the base shoe, the top cap was flexible and would cover the gap between the skirting board and the wall. In those days the idea to squirt calking compound along the top edge of base boards was unheard of.


What's the ideal width and number of products in line (ecommerce website - responsive)

Question: We have an ecommerce site - daily deal website.
I would like to get your opinion on what website width should be. I was thinking about 1000px OR 1200px. But in the case of 1000px we would display 3 products in a line, and on 1200px - 4 products in a line; we display products in a grid.
I am afraid that 4 products in line would be a little too much information. What do you think?
Answer: The honest answer is it depends on the focus of the site and the general design and the demographics of the user base.
Here is the list of steps I would suggest to figure out this problem

Establish the maximum resolution which you plan to support by looking at the user demographics and analytics if available. This would help you establish your maximum resolution from a grid or media query perspective.
Depending on the focus of your website, define what are the sizes of the images you need to show. In an ecommerce site it is highly recommended to  have crisp and visble images as they help define the decision making of the users and you might find out based upon your product, you might need to with larger or smaller images. To quote this article

In usability testing, users glean product details from images,
  including details that aren't covered in the product description.
  Large images can show more detail, and multiple views offer even more
  information. Pictures of products in use or in context go a long way
  to answering customer questions. We've seen a user realize that a
  toaster had big enough slots for bagels and another know that coasters
  had feet that would protect her wooden furniture, simply by looking at
  product images.
The increase in image size is not only seen on product pages. Category
  pages, which often cram as many tiny images of products on one page as
  possible, are also using larger images. This lets user see detail
  early on in the shopping and comparison process, helping users spend
  their time exploring the right products.

For example if you are showing deals on products and want to highlight the products very clearly, you might go with large displays like this which allow you to show only two images side by side

however if you are going to show objects which dont need to be so detailed a smaller image set might work with this like the example given below

Hence based upon your product and the importance of product photography, you will need to decide how many products to show in a line while ensuring the corresponding gutter space is present between the products to enable the site to responsively scale as needed across mobile devices.

Here are examples of sites showing three,four and five products in one line ensuring there is sufficient breathing space between the products to allow the user to quickly scan the content.
Answer: It really depends on how much information you're showing with the product to me.
If you're just showing the product image, price and name I wouldn't set a limit on how many across you can go at all. As long as the information can breathe, it looks nice and it's easy to follow.
Comment: I don't know. There is definitely a point where the line is too long, and the eye is drawn to the right rather than down the page. Which can have the effect of de-emphasising usability features like filtering that traditionally live in a left-hand nav.
Answer: I'm not aware of any research supporting a specific number of columns on a product listing page, and I've been looking. So in the absence of research, I'd suggest falling back on convention.
There are definitely usability problems with going with too many columns. At the point where the long line of product images starts drawing the eye to the right of the screen, rather than than down the page, you start to visually de-emphasise usability controls sat on the left of the page.
In general, most responsive designs currently used seem to cap out at 5 columns total. Assuming you've got a left-hand nav, then following that convention you can comfortably stretch to 4 columns of products, but shouldn't go to 5.


Transfer of photos from UbuntuOne to my computer

Question: How do I get photos from UbuntuOne storage to my computer?
Answer: If you enable/sign into Ubuntu One and let it sync then your files should be available locally.
Then you can move them to where ever you wish.


Doctrine MongoDB Hash type as enhancing key/value form in Symfony 2.1

Question: I have a mapping in MongoDB as type hash, named "meta_info" which simply holds a key/value list of something, I'd like to make it to a form in Symfony2 which can be enhanced dynamically (with js), to have it look (basically) like this:
<input type="text" name="meta_info[key][]" /><input type="text" name="meta_info[field][]">   [- remove row]
<input type="text" name="meta_info[key][]" /><input type="text" name="meta_info[field][]">   [+ add row]

My first ideas were to make two textfields (key/value) which can be duplicated using js (thats not the problem) and which get converted to a json string onSubmit and converted back to an array inside my setter method of my Document class.. But this seems kinda dirty..
I was also thinking about embedding forms (which works very well with embedded documents now in sf2.1!) - but I don't know how to achieve this for a simple key/value hash (which should also be stored like that in mongodb)
Thanks for any ideas and approaches!
Answer: Thinking about this in terms of Symfony forms, you likely want to have a dynamic collection of inner forms, each of which has key and value input fields. I can't think of another implementation to handle this case, as you're essentially foregoing any notion of a schema by using a hash field. That's mainly what distinguishes this case from embedded documents in ODM (which would have mappings), even though MongoDB is going to store in the same manner (nested objects).
One alternative implementation is to have an EmbedMany relationship of documents that contain key and value properties. OpenSky uses this internally to represent product attributes. It consumes a bit more storage in the MongoDB document, since you have an array of objects with key and value fields instead of a single object of key/value pairs, but there are some clear benefits:

The structure can be mapped, which plays nicely with your existing ODM schema.
Since you have a model for each key/value pair, it's more natural to represent this with Symfony forms.
Perhaps most importantly if you're going to query by this data, you can take advantage of multi-key indexing to index dynamic keys and values and then use $elemMatch queries for key/value lookups. If you were just using a hash field with dynamic keys, there would be no straightforward way to index multiple keys (each distinct field path would require an explicit index, or explicit mention in a compound index).
Comment: I was also thinking to embedyMany documents with key/value properties.. I'll try it, many thanks


change or disable modifier key (alt) which activates the application menubar?

Question: Is there any way to either globally change the modifier key which activates the application menu bar from alt- to something else, or if not, at least to globally disable it?
I use a mac for work and I pretty much only run Firefox and Sublime Text3 on my Ubuntu 14.04 laptop (unity). Both apps allow for changing keyboard shortcuts, either natively or via extensions, and I can get the shortcuts close to my mac, but you can't setup shortcuts such as alt-t to open a new tab in Firefox, as that pulls up the 'Tools' menu.
Any help would be appreciated - it's obviously not a huge priority, but this itch has been bugging me long enough that I'm finally scratching it - it sort of feels like my .emacs are out of sync or I have different versions of emacs running on the different machines :(
Answer: Install CompizConfig Settings Manager via Ubuntu Software Center or terminal: sudo apt-get install compizconfig-settings-manager.
Then open CompizConfig and go to Ubuntu Unity Plugin > General > Key to show the menu bar while pressed, and change it. Hope this will help you.
Answer: Install Compiz With Extras
sudo apt-get install compizconfig-settings-manager compiz-plugins-extra -y

Then open CompizConfig and go to Ubuntu Unity Plugin > General > Key to show the menu bar while pressed, and change it.
Comment: hmm it seems both you and @PaulB answered the question the way I phrased it, but I guess I phrased it wrong. the fix changes which key displays the application menubar, but alt-F still opens up the File menu.  not sure if these are application-level bindings of if they'll work with -F where there is some sort of system-level binding for the application menu sub-menus. I'm gonna have to do some more research and either edit my question or give up. thanks for your help though
Comment: So to clarify, your looking for an application level binding as opposed to a system level binding?
Comment: I'm not sure. Do you know if alt- is provided by the system, or if applications have to set those key bindings up.


postgrest retreive ranked results

Question: I made a game, with level and scores saved into an sql table like this :
create table if not exists api.scores (
id serial primary key,
pseudo varchar(50),
level int,
score int,
created_at timestamptz default CURRENT_TIMESTAMP
);

I want to display the scores in the ui with the rank of each score, based on the score column, ordered by desc.
Here is a sample data :
 id |  pseudo  | level | score |          created_at
----+----------+-------+-------+-------------------------------
  1 | test     |     1 |     1 | 2020-05-01 11:25:20.446402+02
  2 | test     |     1 |     1 | 2020-05-01 11:28:11.04001+02
  3 | szef     |     1 |   115 | 2020-05-01 15:45:06.201135+02
  4 | erg      |     1 |   115 | 2020-05-01 15:55:19.621372+02
  5 | zef      |     1 |   115 | 2020-05-01 16:14:09.718861+02
  6 | aa       |     1 |   115 | 2020-05-01 16:16:49.369718+02
  7 | zesf     |     1 |   115 | 2020-05-01 16:17:42.504354+02
  8 | zesf     |     2 |   236 | 2020-05-01 16:18:07.070728+02
  9 | zef      |     1 |   115 | 2020-05-01 16:22:23.406013+02
 10 | zefzef   |     1 |   115 | 2020-05-01 16:23:49.720094+02

Here is what I want :
 id |  pseudo  | level | score |          created_at           | rank
----+----------+-------+-------+-------------------------------+------
 31 | zef      |     7 |   730 | 2020-05-01 18:40:42.586224+02 |    1
 50 | Cyprien  |     5 |   588 | 2020-05-02 14:08:39.034112+02 |    2
 49 | cyprien  |     4 |   438 | 2020-05-01 23:35:13.440595+02 |    3
 51 | Cyprien  |     3 |   374 | 2020-05-02 14:13:41.071752+02 |    4
 47 | cyprien  |     3 |   337 | 2020-05-01 23:27:53.025475+02 |    5
 45 | balek    |     3 |   337 | 2020-05-01 19:57:39.888233+02 |    5
 46 | cyprien  |     3 |   337 | 2020-05-01 23:25:56.047495+02 |    5
 48 | cyprien  |     3 |   337 | 2020-05-01 23:28:54.190989+02 |    5
 54 | Cyzekfj  |     2 |   245 | 2020-05-02 14:14:34.830314+02 |    9
  8 | zesf     |     2 |   236 | 2020-05-01 16:18:07.070728+02 |   10
 13 | zef      |     1 |   197 | 2020-05-01 16:28:59.95383+02  |   11
 14 | azd      |     1 |   155 | 2020-05-01 17:53:30.372793+02 |   12
 38 | balek    |     1 |   155 | 2020-05-01 19:08:57.622195+02 |   12

I want to retreive the rank based on the full table whatever the result set.
I'm using the postgrest webserver.
How do I do that ?
Answer: You are describing window function rank():
select t.*, rank() over(order by score desc) rnk
from mytable t
order by score desc

Comment: Yeah sql end I know, but I"m using postgrest webserver : http://postgrest.org/en/v7.0.0/index.html which does not permits SQL requests I believe
Comment: Can you create a view with the above query and call it from PostgREST?

postgrest retreive ranked results