"Either or" validation of multiple inputs with same error message

Question: My form has four fields. I need:
  - validation to succeed if at least one field is populated
  - to use the same error for all the fields "Please enter a phone or email"
The code below does not work on a contigent basis- all fields are validated separately even though I use the function to check them all at once. What am I doing wrong?
var rule = function (el) {
//return                                        <-- old
  return (                                    //<-- new
    ($("#CustomerEmail").val() === "") &&
    ($("#CustomerMobile").val() === "") &&
    ($("#CustomerWork").val() === "") &&
    ($("#CustomerHome").val() === "")
  //;                                         <-- old
    );                                      //<-- new
  };

$("#CustomerEmail").rules("add", { required: rule });
$("#CustomerMobile").rules("add", { required: rule });
$("#CustomerWork").rules("add", { required: rule });
$("#CustomerHome").rules("add", { required: rule });

UPDATE:
Turns out my code was ok after all, but that return was on a line of its own, and that makes JS explode.
Would still like to know how to attach a single error message to the group, rather than have four errors show whe validation fails.
Answer:
validation to succeed if at least one field is populated

Your rule only succeeds if ALL fields have a value (since you are using the AND operator). If one is enough use the OR operator
var rule = function (el) {
  return
    $("#CustomerEmail").val() ||
    $("#CustomerMobile").val() ||
    $("#CustomerWork").val() ||
    $("#CustomerHome").val();
  };

Comment: A field is required if all the other fields are empty, i.e. logical and. But even if I change it to logical or, it doesn't work. Must be using the plugin incorrectly somehow?
Answer: Here's a solution that first involves adding a new validation method for Must_Have_One. The method name is matching class added to each element in group, or you can use rules object to define the method.
HTML
<input name="name" class="must_have_one" />

JS
var $form_group=$('.must_have_one')

$.validator.addMethod("must_have_one", function() {
    var must_have_els=$form_group.filter(function(){
        return this.value !='';
    });

    if (must_have_els.length) {
        return true;
    } else {
        return false;
    }
}, 'Must have one of .....');

var myFormValidator = $("form").validate({
    groups: {
         must_have_one : "name email"
    },
    errorPlacement: function(error, element) {
        if (myFormValidator.groups[element.attr("name")]) {
            /* determine placement for message for group*/
            error.insertAfter($form_group.last());
        }
        else error.insertAfter(element);
    }
})

DEMO: http://jsfiddle.net/UzjZM/1/
Comment: Doesn't seem to work? Maybe because "must_have_els" is undefined?
Comment: i deleted something i shouldn't doing some refctoring for last update...try this http://jsfiddle.net/UzjZM/2/
Comment: This works excellently, but the real problem was in my syntax. See update.
Comment: @charlieftl how would I add the messages to my existing code above?
Comment: method I gave you includes message. You would have to write the message object and include all 4 fields doing it your way. See `messages` in docs
Answer: Although @charlietfl's code works, here is a modified version of my original code, which works:
var eitherors = $("#CustomerEmail, #CustomerMobile, #CustomerWork, #CustomerHome");
var message  = "Please enter either a phone number or email address";

// define the required validation rule
// will return true when all inputs are blank
var requiredRule = function (el) {
  return eitherors
    .filter(function () { return $(this).val() !== "" })
    .length === 0;
};

// define the required validation error message
// returns the error message when 1) all inputs are
// blank, and 2) only for one of the fields (I chose the first one)
var requiredMessage = function (arg, el) {
  return (requiredRule() && eitherors.first().is(el))
    ? message
    : "";
};

// use same rule and message on all the "either-or" inputs
eitherors.each(function () {
  $(this).rules("add", {
    required: requiredRule,
    messages: { required: requiredMessage }
    });
  });

This is generic, so will work on any group of elements by only changing the jQuery array and the error message.


how to set direction for list of values 'LOV' in oracle forms

Question: how can I change direction of LOV using set_item_property ?
I want to change the direction based on a parameter value , if set_item_property is not available do you have any suggestions ?
Comment: What does "direction" mean in this context? I've never heard of that.
Answer: use an 'ORDER BY' clause at the end of the query. using either ASC for ascending data 'ABCD' or DESC for descending order 'ZYX' e.g.
SELECT *
  FROM table
ORDER BY parameter ASC

OR
SELECT *
  FROM table
ORDER BY parameter DESC

Answer: If you mean ordering of the listed values in ascending or descending manner by the word direction, you can manage it through use of Set_Lov_Property.
You should be calling the existing LOV from a text field(call tf1).
Add a check box item (call cb1) next to tf1.
Forms creates a Record Group as LOV being created with the same name as default(call 'mylov01'). Assume this Record Group has a select statement having order by col0 asc clause.
Manually create an extra Record Group with name mylov01_desc having order by col0 desc clause.
Add a KEY-CLRBLK trigger to that field with the code
declare
    v_lov varchar2(50) := 'mylov01';
    v_grn varchar2(50);
begin
    if    Checkbox_Checked('cb1') then
        v_grn := v_lov||'_desc';
    else
        v_grn := v_lov;
    end if;

    Set_Lov_Property( v_lov, group_name, v_grn );
    list_values;
end;

Invoke the LOV by pressing F7 whenever the cursor is in tf1.
The list would return rows in descending order for col0 column provided that  cb1 is checked, otherwise would be in ascending order.
P.S. KEY-LISTVAL is the default trigger to invoke a LOV, and fired through Ctrl+L key combination. I prefer disabling this default behaviour by adding KEY-LISTVAL trigger for tf1 with a code null; in it in order to invoke the LOV from pressing the single key F7 only.
Comment: Why KEY-CLRBLK?  Seems to me like KEY-LISTVAL on the text field ("tf1" in your example) would be the better option.
Comment: yes, might be, but I would prefer pressing on a single key(`F7`) rather than combination (`Ctrl+L`) @AndyDan .
Comment: Maybe your key mapping needs to be updated.  For us, key-listval is F9.  And using a key for purpose other than it's intended requires the user to know that, in this particular case, they need to use a different key to get the LOV than they usually do.


ImportXML with flexible conditions

Question: I have to fetch the price of Lego items
http://mightyutan.com.my/batman-movie/?id_category=1413&n=100
But the challenges here are the price are split into two conditions

No discount, reflect regular price
With discount, show discounted price

How could I use ImportXML for my column to display discounted price, else regular price? I only know to capture a fixed xpath pattern
//div[@class='content_price']/span[@class='price'][1]

Also, I have display the title of the Lego set, for due to the items with no discount, total rows return from my title and price are not tally
Thanks for the help
Answer: try this if you want to use include class:
//*[contains(@class,'product-block-inner')]//span[contains(@class,'price')][last()]

or better this when you are sure class won't be changed:
//*[@class = 'product-block']//span[@class='price'][last()]

as discount is located after initial price - just get last price element for product, so it will be discount or if it's not available - initial price =)
Comment: Thanks Vitaliy! i been struggle for days and you solved in few lines!
Comment: Some additional request, how can i make the return result "RM999.90" become "999.90"?
Comment: Please check this: https://stackoverflow.com/questions/6539531/how-to-use-the-translate-xpath-function-on-a-node-set . In Xpath 1.0 you can do it only for single element. (both substring and translate functions won't help in xpath 1.0 with node-set). The most simple way is to remove unneeded symbols programmatically when you've got your elements)
or in google spreadsheets use "replace all" function for set of cells)

ImportXML with flexible conditions


Reconciling apt and snap installations of dotnet

Question: Having two installations of .NET:
$ lsb_release -d
Description:    Ubuntu 22.04.1 LTS
$ which dotnet
/usr/bin/dotnet
$ which dotnet-sdk.dotnet
/snap/bin/dotnet-sdk.dotnet

The two installations seem independent:
$ dotnet --list-sdks
6.0.109 [/usr/lib/dotnet/dotnet6-6.0.109/sdk]
$ dotnet-sdk.dotnet --list-sdks
7.0.100-rc.1.22431.12 [/snap/dotnet-sdk/181/sdk]

I have tried to apt remove all dotnet:
sudo apt remove --purge dotnet-sdk-6.0
sudo apt remove --purge dotnet-runtime-6.0
sudo apt remove --purge aspnetcore*

but after that dotnet still points to something not installed via snap:
$ which dotnet
/usr/bin/dotnet

Following the symlinks:
/usr/bin/dotnet -> /etc/alternatives/dotnet
/etc/alternatives/dotnet -> /usr/lib/dotnet/dotnet6-6.0.109/dotnet

Since PATH has /usr/bin/ before /snap/bin the non-snap version kicks in when dotnet is exectuted and the brute force solution would be move /snap/bin to the front of PATH but I'm not sure if this could have unexpected consequences.
What is best way to reconcile these? My preferred options, I think, would be to only have the snap managed installations.
Answer: After another attempt to sudo apt remove --purge dotnet6xxxx I finally paid attention to The following packages were automatically installed and are no longer required section.
After sudo apt autoremove only the snap versions are left:
$ which dotnet
/snap/bin/dotnet
$ dotnet --list-sdks
7.0.100-rc.1.22431.12 [/snap/dotnet-sdk/181/sdk]


using images as buttons in html5

Question: I am making a web app that plays sounds. The interface I would like to use is that of a piano/keyboard. User will press a key and sound is played.
I have used <button> to call the functions and embedded images of keys inside them but it does not look good and has a border around each key.
<button onclick="freqA4()">

</button>

Is there a GUI designer for HTML5 that will allow me to use attratcive high res images and assign events to them?
Or should I use canvas to animate a keyboard and assign function calls to certain areas like image mapping?
A large emphasis of this app will be on the appearance.
Any help would be great as I have very little experience in html/html5.
Comment: You need to use CSS to remove the border from the button.
Answer: You can use normal links links ( tags), or you can use input elements of type image <input type="image" src="keyboardpics/key1.jpg" onclick=freqA4()" />.
You can of course use CSS to style any of them (even the button you use)
Answer: First include this in your HTML: http://meyerweb.com/eric/tools/css/reset/
Define each button as CSS style
.button {
  width: <button width>
  height: <button height>
}
#key1 {
   background: url('/keyboardpics/key1.jpg') no-repeat
}
#key2 {
   background: url('/keyboardpics/key2.jpg') no-repeat
}

In your HTML

...

Comment: Is there a way to set the alt text for an image with this method?  I guess not because there isn't actually an img element any more?

using images as buttons in html5


Only return a value of a name, no duplicated name (MYSQL)

Question: I'll try to redo everything with better examples.
This query was the first, and it shows everybody:
SELECT t2.name as name, t1.key as keyy, t1.value as valuee
FROM player_storage t1 INNER JOIN players t2 on t2.id = t1.player_id
WHERE t1.value > 0 AND t1.key IN (99781,99780,99777)
ORDER BY keyy+0 DESC, valuee+0 DESC LIMIT 5

Real output:

name
level
keyy
valuee

AAAAA
558
99781
1

BBBBB
559
99780
1

AAAAA
558
99777
490

BBBBB
559
99777
470

CCCCC
361
99777
456

The thing wrong is that I don't want to see 99777 of the names who have 99781 or 99780, if they have one of the first, I just want to see that one, not their 99777.
@Craig helped me to get to this:
SELECT t2.name as name, t2.level as level, t1.key as keyy, t1.value as valuee
FROM player_storage t1 INNER JOIN players t2 on t2.id = t1.player_id
WHERE t1.value > 0 AND

(
    t1.key IN (99781, 99780)
    OR
    (
        t1.key IN (99777)
        AND NOT EXISTS
        (
            SELECT 1 FROM player_storage tx
            WHERE tx.player_id = t1.player_id
            AND tx.key > t1.key
        )
    )
)

ORDER BY keyy+0 DESC, valuee+0 DESC LIMIT 5

And I think it's what I need, but this is somehow skipping some results, see output:

name
level
keyy
valuee

AAAAA
558
99781
1

BBBBB
559
99780
1

EEEEEE
87
99777
189

DDDDDD
21
99777
145

ZZZZZZ
570
99777
2

This is hiding A and B results from 99777 as I wanted, but it should show C result as third, since on last output (from query above) he was the third with most 97777.
I think this query above is achieving my result, but somehow it's with this problem.
edit.
player_storage structure: https://i.stack.imgur.com/yUcY4.png
Comment: I'm sorry, but I cannot follow your description of your data! Can you pls provide sample data, expected output, and actual output in **tabular format**?
Comment: I've tried to add tables with results, but on preview edit tables are fine, when i place the edit, it breaks, some help?
Answer: SELECT t2.name as name, t2.level as level, t1.key as keyy, t1.value as valuee
FROM player_storage t1 INNER JOIN players t2 on t2.id = t1.player_id
WHERE t1.value > 0
AND
(
    t1.key = 99781
    OR
    (
        t1.key IN (99780, 99777)
        AND NOT EXISTS
        (
            SELECT 1 FROM player_storage tx
            WHERE tx.player_id = t1.player_id
            AND tx.key > t1.key
        )
    )
)
ORDER BY keyy+0 DESC, valuee+0 DESC LIMIT 5

Comment: Edited to this:

`SELECT t2.name as name, t2.level as level, t1.key as keyy, t1.value as valuee
FROM player_storage t1 INNER JOIN players t2 on t2.id = t1.player_id
WHERE t1.value > 0
AND
(
 t1.key IN (99781, 99780)
    OR
    (
        t1.key IN (99777)
        AND NOT EXISTS
        (
            SELECT 1 FROM player_storage tx
            WHERE tx.player_id = t1.player_id
            AND tx.key > t1.key
        )
    )
)
ORDER BY keyy+0 DESC, valuee+0 DESC LIMIT 5`

Exactly what I wanted, thank you so much.
Comment: I see - so if a player has both 99781 AND 99780 keys, you want both of those to display?  If that's the case, then your edit make sense
Comment: I tought that it worked as I wanted. But it's showing only 1 user with key 99777 and not returning all the 5 I ask on the end. I'll try to be more clear, but commenting is a bit hard. Only max 1 user will have the 99781 key, then there are max 2 with 99780 key, then I want to show who have most 99777 value until limit 5 total (on the 3 keys).
Comment: could you help whenever possible? sorry for tagging.
Comment: Hi @YuriAniceto - sorry, I've been unavailable for a few days.  To be honest, you should have enough guidance in those queries to be able to implement what you need.  You'll just need different combinations of the t1.key IN (...something) and the NOT EXISTS clause.  Have you had further attempts at a query to achieve the results you're after?  You could update your question with your progress so far
Comment: remade everything on the question, hope it helps.
Comment: @YuriAniceto, if I mock up your dataset on my MySQL server and then run the second query (in your question), I get the results that you are expecting - so, off the top of my head, I'm unsure why you are not.  Can you advise what the actual data-types are in your table structures?  Also, what are the primary keys on each table, and what existing indexes are there?  I'm thinking that potentially the data-type of the "value" column may be the cause of confusion
Comment: added picture with the table structure, the values come from a system, so I don't know if I can change some of that stuff. Hope it helps.
Comment: Hmmm.... because the "key" and "value" columns are varchar/text, then your mathematical calculations, and inferred ordering, may not necessarily be working exactly as you expect.  Assuming that these columns really do only hold numeric values, then you could amend your query so that each reference to "key" or "value" is wrapped in a CAST() - eg. CAST(t1.key AS UNSIGNED) - including in the ORDER BY clause.  See if that makes a difference


How can I track achievement progress?

Question: I'm preparing to clear Instant Karma tonight, but I want to know how much progress I have made in the achievement.
Is there a way I could track my achievements (like the quests are track-able at the right side)? Or I need to keep waiting until I get it?
Answer: Unfortunately, and unlike the achievement system in World of Warcraft, there does not seem to be a way to track achievements on the main GUI. You can, of course, continue to track it via the achievement UI, but that's not generally something you want to have open in the middle of a boss fight.
The thing about this particular achievement, though, is that it'll pop up as soon as you achieve it. So until it shows up and you get the toast, know that you've still got skeletal minions to let get killed.
Comment: Another thing that I've noticed, is that the achievement screen doesn't appear to keep itself up to date when you're watching for an achievement that involves multiple kills or whatever, if you check half way through I'm finding it's still sat at 0, even though the achievement is applied at the correct point.
Answer: If you click on the achievement from the menu, it will show you your progress.

You can tell which achievements can be expanded by the <code>+</code> icon.

How can I track achievement progress?


When I change display to "none" and "block", my title repositions rather than disappearing and reappearing where it originally was

Question: I have it set so that when you click start, it will hide the main page and then make it reappear, although it will be in a different location. I'm not sure if the issue is within the html, css, or javscript as I'm pretty new to all of this. Supposedly, I need more words for this post to post, so I'm going to just fill the rest of this section with a bunch of meaningless words.
Here is a preview: https://htmlpreview.github.io/?https://github.com/holychickencow/A-Fair-Game/blob/main/index.html
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Play&display=swap" rel="stylesheet">
    <title>A Fair Game</title>

A Fair Game

        <button onclick="startGame()" id="start">Start</button>

            <button onclick="openHow()">How to Play</button>
            <button onclick="openSettings()">Settings</button>

        <button onclick="openMain()">Back</button>

        <button onclick="openMain()">Back</button>

CSS
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    background-color: black;
    font-family: 'Play', sans-serif;
}

.main{
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    flex-direction: column;
    height: 100vh;
    width: 100vw;
}

#title{
    font-size: 300%;
    font-weight: bold;
    color: white;
    letter-spacing: 4px;
}

.bottom{
    display: flex;
    justify-content: space-around;
}

button{
    padding: 20px 100px;
    border-radius: 5%;
    margin: 40px;
    border-color: #03e9f4;
    color: #03e9f4;
    transition: 0.5s;
    letter-spacing: 4px;
}

#start{
    padding: 40px 200px;
}

button:hover{
    background: #03e9f4;
    color: #050801;
    cursor: pointer;
    box-shadow: 0 0 5px #03e9f4,
                0 0 5px #03e9f4,
                0 0 25px #03e9f4,
                0 0 100px #03e9f4;
     -webkit-box-reflect:below 1px linear-gradient(transparent, #0005);
}

Javscript:

function openSettings(){
    document.getElementById("mainPage").style.display = "none";
    document.getElementById("settingsPage").style.display = "block";
}

function openHow(){
    document.getElementById("mainPage").style.display = "none";
    document.getElementById("howPage").style.display = "block";
}

function openMain(){
    if(document.getElementById("settingsPage").style.display == "block"){
        document.getElementById("settingsPage").style.display = "none";
    }
    else{
        document.getElementById("howPage").style.display = "none";
    }
    document.getElementById("mainPage").style.display = "block";
}

function startGame(){
    document.getElementById("mainPage").style.display = "none";
    document.getElementById("mainPage").style.display = "block";
}

Answer: the problem is that you set display for main in CSS as flex and then in js you set it to block.
the other problem is that in startGame() function, you need to set a condition for each execution. because in the way you write it, it will go none then flex.
I used this condition to hide mainPage.
function startGame(){
    var mainPage = document.getElementById("mainPage");
    if (mainPage.display = "flex") {
        document.getElementById("mainPage").style.display = "none";
    } else {
        document.getElementById("mainPage").style.display = "flex";
}
    }

I hope this will help you understand how to set things better. good luck.


MS-Access SQL statement to update table based on query result

Question: I am trying my hand at MS-Access and am self-taught up to this point so please be patient with me. I have researched this to the best of my ability but still can't get it to work.
I have a table and I am populating fields based on query results.  My first SQL statement works but my second one does not, it gives me a

"Type mismatch in expression"

error. The first query has the same number of records as the table while the second query will have a different number of records depending on which table is referenced.
I want the table updated from the second query where ever the table ID and the query arcfilenumber match, any non-matches would be skipped.
'Runs the query for sorting the weld parameter data
DoCmd.OpenQuery "Temp_Query"

'Code to copy data to proper table
Dim mySQL5 As String

mySQL5 = "UPDATE [" & tblDESTINATION & "] INNER JOIN [temp_query] ON([" & tblDESTINATION & _
         "].ID = [temp_query].expr4) SET [" & tblDESTINATION & "].[S_" & FIELD & "] = [temp_query].expr1"
DoCmd.SetWarnings False
CurrentProject.Connection.Execute mySQL5
DoCmd.SetWarnings True

DoCmd.Close acQuery, "Temp_Query"

'This sets and calls a query that will get the Weld Numbers associated with the selected jig.
'and moves the weld information to the proper table
Dim mySQL9 As String
Dim qdf As DAO.QueryDef
Dim qdfOLD As String
Set qdf = CurrentDb.QueryDefs("qWELD_NO")
With qdf
qdfOLD = .SQL
.SQL = Replace(.SQL, "TEMP", Me.JIG)
DoCmd.OpenQuery "qWELD_NO"

' Code to do stuff with SQL-string/query

mySQL9 = "UPDATE [" & tblDESTINATION & "] INNER JOIN [qweld_no] ON([" & tblDESTINATION & _
     "].ID = [qweld_no].arcfilenumber) SET [" & tblDESTINATION & "].[W_" & FIELD & "] = [qweld_no].weld_no"

MsgBox mySQL9
DoCmd.SetWarnings False
CurrentProject.Connection.Execute mySQL9
DoCmd.SetWarnings True

.SQL = qdfOLD ' Reset SQL to old setting
End With
Set qdf = Nothing

DoCmd.Close acQuery, "qWELD_NO"

Any suggestions or help would be greatly appreciated.
EDIT:
The resulting SQL statement looks like this:
UPDATE [DUWYP-48670] INNER JOIN [qweld_no] ON([DUWYP-48670].ID = [qweld_no].arcfilenumber) SET [DUWYP-48670].[W_5_26_2017] = [qweld_no].weld_no

EDIT2:
I have changed the table field type to number and created an expresion in the query to put in 1s and 0s, still no go.  I moved the SQL instruction out of the WITH code and it still doesn't work.  I can't figure out why it works just a few code lines before but not after.  Is it because of the different number of records?  Should I open a recordset and loop through instead of SQL?
Comment: Is this Access or SQL Server??? They are not the same thing.
Comment: Sorry, ms-access, I'm trying to make an SQL statement to do the job.
Comment: The error indicates linking fields are not same data type.
Comment: Destination field is set to short text and the generated query result is a mix of letters and numbers.  For the part that is working it is putting query generated numbers into a numbers field.
Comment: do the query manually, then look at it in SQL view and start from that.
Comment: If everything is the correct data type the only thing I can see obviously wrong is that there isn't a space after `ON`
Comment: I have already posted the SQL statement and you can see from the code that it is in the same format as the working SQL statement.  The difference is the referenced query.  I have figured out that the Type Mismatch is in the  [arcfilenumber] field.  It is generating a number by a mathmatical calculation but it is creating the field as short text.  I can get it to work by changing the query to a make table query and then changing the [autonumber] field type to number.  Now I would like to have the query field set to number but don't know how.
Comment: You could cast them both as long numbers - `ON (CLNG([" & tblDESTINATION & _
     "].ID) = CLNG([qweld_no].arcfilenumber))`
Comment: There we go!  Thank you Darren, that worked perfectly.  I was stumped trying to get a data type to a query expression, I never thought to set it individually in the SQL.  Do you want to post that as an answer so I can accept it?
Answer: This may not be the ideal solution.  I'd advise getting the fields in the database table in the correct format to start with.
Saying that though, it's often beyond our control how the data arrives so we have to coerce the data into something that can be used.
In this case the text can be converted to the long data type by using CLNG.
UPDATE  [DUWYP-48670] INNER JOIN [qweld_no] ON
            (CLNG([DUWYP-48670].ID) = CLNG([qweld_no].arcfilenumber))
SET     [DUWYP-48670].[W_5_26_2017] = [qweld_no].weld_no

This link lists some of the other data types that can be used:  https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/functions/type-conversion-functions.
Note - not all the types in the link can be used by Access (it's just the first link I found and deals with VB rather than VBA).


Attachment's name charset/encoding in IBM Notes Document

Question: I have a web-service provider(Java), which imports a .doc file  to the  NotesDocument. The problem occurs with  files with Russian characters in their names - they aren't correctly transferred.
For example, if the filename will be equal to Безымянный.doc, it will be transferred as Áåçûìÿííûé.doc.
File directory = new File("C:\\Attachments 1C");
String filename = "Безымянный.doc"
String path = directory + "\\" + filename;
Stream outStream = sess.createStream();
sess.setConvertMIME(true);
MIMEEntity body = newDoc.createMIMEEntity("rtBody");

Stream inStream = sess.createStream();
if (inStream.open(path, "binary")) {
    if (inStream.getBytes() > 0) {
        do {
            byte[] buffer = inStream.read(32767);
            outStream.write(buffer);
        } while (!inStream.isEOS());
        inStream.close();

        MIMEEntity child = body.createChildEntity();

        String fileSuffix = path.substring(path.lastIndexOf(".")+1);

        child.setContentFromBytes(outStream, fileSuffix, MIMEEntity.ENC_IDENTITY_BINARY);

        MIMEHeader header = child.createHeader("Content-Disposition");
        header.setHeaderVal("attachment; filename=\"" + filename + "\"");
        header = child.createHeader("Content-ID");
        header.setHeaderVal(path);
        outStream.truncate();
    }else
        return "empty file";
}else
    return "couldn't open the file";

How to fix this?
Answer: The standards for this are not quite final and the behavior will depend on what browser is being used. See the question and answers to this previous question on StackOverflow for a detailed explanation and for information about what works with various browsers.
Comment: I tried this: String dispositionFileName = URLEncoder.encode(filename, "UTF-8") - doesn't work.
Comment: I don't work with browsers in this case. The file attaches to the  NotesDocument in the IBM Notes environment.
Answer: The problem is solved by encoding the filename using MimeUtility(others don't work):
String filenameEndoded = MimeUtility.encodeText(filename,"Cp1251","B");


Qt/OpenGL - rendered primitives are distorted

Question: I was following a tutorial on youtube on how to use OpenGL within Qt. I have two classes:
glWidget -> Inherits from QGLWidget;
GLWindow -> Inherits from QMainWindow and has a form.
Within GLWindow's form I place a Widget and promote it to glWidget so that whatever is rendered on glWidget is displayed through Widget on GLWindow.
I implement the following inherited functions in glWidget:
<code>void glWidget::initializeGL()
{
    glClearColor(0.1, 0.1, 0.1, 1.0);
}

void glWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_TRIANGLES);
            glColor3f(0.2, 0.8, 0.1);
        glVertex3f(-0.5, -0.5, 0.0);
            glColor3f(0.8, 0.3, 0.9);
        glVertex3f(0.5, -0.5, 0.0);
            glColor3f(0.1, 0.1, 0.5);
        glVertex3f(0.0, 0.5, 0.0);
    glEnd();
}
</code>
I plan on using shaders and buffers later, but I'm puzzled as to why my rendered primitive appears like this:

It appears the triangle has been transformed in world space, rather than local space. If it were in local space then the triangle would appear at the centre of the screen. The tutorial I'm referring to can be found here: https://www.youtube.com/watch?v=1nzHSkY4K18
I don't know what I'm doing wrong here. At first I thought it had something to do with my vertices, and I know this is immediate mode and should probably try with buffers/shaders instead; but I'd still like some insight as to what I'm doing wrong here. Why isn't the triangle being rendered as it appears in the tutorial? Should I be passing something in the constructor of glWidget or something?
Comment: Did you implement resizeGL and left it empty ?
Comment: Thanks, it renders fine now!
Comment: Ok, I'll make it an answer for future readers .
Answer: When extending QGLWidget keep in mind that resizeGL() will get called automatically :

resizeGL() - Sets up the OpenGL viewport, projection, etc. Gets called whenever the widget has been resized (and also when it is shown for the first time because all newly created widgets get a resize event automatically).

It seems that in your case the Widget gets resized automatically, so a solution would be to just override it and let it empty.
When extending QGLWidget is usually a good practice to also override the resizeGL function.


Public Classes only with public shared functions in a .NET website

Question: I've run into a legacy project set up as a .NET Web Site Project (yes, I know...) and I see lots of classes like these:
Public Class ControlStuff

    Public Shared Sub DoStuff(ByVal key as String)
       ...
    End Sub

    Public Shared Function IsAvailableStuff(ByVal key as String) as Boolean
        ...
        Return stuff
    End Function
End Class

Since it's being used in a web application, does this pose a problem when two or more visitors force the execution of any of these Sub or Function and values from one of them are returned to the other(s)? or does IIS isolate them?
Comment: Depends on what the function do. If they have their own variables and don't try to read/write shared resource then it should be ok.
Comment: What the_lotus said.  For instance, a sub that writes to a file could run into file locking issues if run at the same time by multiple users (or by the same user).  It depends on the situation and the code as to whether it's an issue.  Just having shared methods isn't really an issue, depends on what they do.
Comment: They only retrieve a single record from the database, usually appending sqlparameters based on Session variables. Others do simple Redirects to other webforms, things like that
Comment: If that's all it's doing I don't see any issues with it in regards to it being in a static class.  In terms of the DB, whether the call is made here or elsewhere in the project shouldn't matter (whether you call it in a static class, or a code behind or a controller, etc.).  If you have locking issues with the DB because of pending transactions then that's something you'd have to handle in all of these places (again the static class not really being the issue).
Comment: Thanks. But what about a class that has no properties, no data? it's just a bag for holding a bunch of methods. Can this be seen as an allowed or good practise OOP?
Answer: I often com e across it. It's often used to make functions/subs that work all over the current project but you do not want to be in your standardtoolbox. I do not see a problem doing this (OOP wise).Objects do not have to have properties or methods and can have shared methods. Overall this practice makes life a bit easier by separating your project-only routines from your standardtoolbox.
Comment: what do you mean by standard toolbox? I'm not speaking about IDE's toolboxes :(


Observer behavior in Minecraft version 1.11

Question: I'm playing Minecraft: Java Edition, 1.11 on PC. The reason I'm playing this version is because of the lack of OptiFine releases for the current version.
My question is concerning the behavior of Observers in this version.
I built a pumpkin farm as shown in the screenshot below. The farm works, but the Observer facing the pumpkin is only sending redstone pulses two times:
First is when the pumpkin grows and the second is when the piston retracts.
My question is, why the Observer is not sending a pulse when the piston extends? Doesn't that count as a block update?
If that's right, then the observer should send  a total of three redstone pulses, which would obviously break this farm. But that's not the case.
Comment: I think it would help to see the farm from a few more angles.  From this angle, I can't clearly see how the farm even works to begin with.
Comment: On another note im pretty sure there is optifine for the current version. It's listed on their download page https://optifine.net/downloads
Comment: @MBraedley, thanks for the comment. But I can't post screenshots as I'm in work. However I can detail its working. Whenever a pumpkin grows, the Observer below activates the sticky piston above which in turn pulls the Observer in front of it. This Observer activates the piston below and it breaks the pumpkin. When the piston retracts the Observer causes the sticky piston to push the Observer above, back to its original position.
Answer: I did some testing and it seems like observers have a 1-tick cooldown time.
The observer detects when the piston extends and breaks the melon block, one tick later the piston retracts, which is not detected by the observer, because it is still within it's cooldown time.
Another tick later there is an air block in that spot, which doesn't have a block update.
I rebuilt your farm like this in 1.11.2 and it should be accurate:

Note: This is from personal testing and not from any official source, it appears to be correct, but it may be wrong.
Comment: The lower piston seems to be powered by the upper observer by utilising quasi-connectivity. The piston is supposed to be powered by the observer, BUT it should require a block update to notice that it's beeing powered. Can anyone eplain how the piston knows that it's being powered by quasi-connectivity in this case? I tested this in 1.14.3 and it works there, too.
Comment: @SlayerDiAngelo In an extreme case (because I'm currently not sure how quickly everything moves), the observer detects the melon and turns on. As long as it is on, the upper piston would be extended and it wouldn't retract until the observer turns off again. When the observer turns off, the piston retracts, this alone should take at least one more tick. Also: the lower piston does not extend at the same time as the upper piston retracts (Or at least I think so, it's not much time in between so there is a possibility that my judgement, or my memory from when I tested it is off)
Comment: I saw one design somewhere that uses a flying machine to break and collect the melons, it would be fairly expensive, but extending it would basically cost nothing except for dirt, hoes, and water. You can also make a time based solution, which would require one piston and a little redstone dust per block where melons grow. You can then use one clock for many melon spots.
Comment: so does this imply that Observers had a 1 redstone tick cooldown?
Comment: @SlayerDiAngelo That's a much better way to word it. I didn't test 2 or more tick pulses, so it may be a longer cooldown.
Comment: It is a 1 tick cooldown.
Comment: Now that I think of it, you can have a 1-tick clock by having 2 observers face each other, so I kind of already knew that, but I didn't think about it earlier
Comment: @bearb001, I'm kind of puzzled, if Observer had a cooldown, then how is it detecting the extension of the piston below, if it just detected the pumpkin below it one tick before?
Comment: @SlayerDiAngelo I would have to do a bit more research to get an exact value, but there are at least 2 ticks between the melon growing and the piston that breaks it extending. a cooldown time of 1 tick does not interfere with this.
Comment: @bearb001, are you taking into account that Observers didn't have the one tick delay as it has in the current version?
Comment: I did some testing now, I'm not completely sure how accurate it is, but it seems like there are 9 ticks between the melon growing and the melon being broken by the second piston in both versions. I'm not sure how accurate the method was, but the error should be less than 2 ticks.
Comment: I realized that I was measuring game ticks, this would mean that it's 2, or 3 redstone ticks between the melon growing and the melon being broken.
Comment: @bearb001, thanks for your effort. Is there any way to make this farm less resource intensive? Right now it uses a ton of Observers and pistons to automate just three pumpkin patches!
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96314/discussion-between-slayerdiangelo-and-bearb001).


Expat Xbox gaming

Question: I've just recently moved to then Netherlands from the U.S.. The only device that's really given me trouble so far is our Xbox 360 slim. The power supply is 110-only and the converter I bought for it can't really handle it (goes for about 40 minutes then overheats). I'm considering buying a new 360 here, but I'd rather not because I can't be sure that my games I brought from the states will work.
I can't find any 220-volt power supplies for 360 slims that get decent reviews and don't really know how much power the thing draws to help me pick a higher-capacity converter.
Does anyone have any advice for a gamer in a strange land? Where to get a European PS? How much power to spec in a converter?
Comment: Whoops! Sorry, guys! I tried to find that answer, but was obviously searching for the wrong terms. Let me edit this to focus on the power portion of the question...
Comment: The Xbox 360 consoles are region-locked.
Answer: If you consult Microsoft's support page (under "AC power cords") about this.
You'll notice that you need a PSU that is compatible with a 230v @ 50Hz outlet for the Netherlands, which should be compatible with your NTSC Slim console (whose PSU is made for a 120v @ 60Hz outlet) because the DC output is the same (look at your PSU).
NTSC: AC input: 100-127v-3.7A, 47.63 MHz, DC output: 135 watts
PAL: AC input: 200-240v-2A, 47.63 MHz, DC output: 135 watts
It's recommend contacting Xbox 360 support and asking for a "replacement," checking your local game/electronics store, or even Ebay.

Expat Xbox gaming


Publishing Scala project to local repository?

Question: I'm trying to publish a project into my local repository with sbt.
This is my build.sbt file
name := "myProject"

organization := "co.myorganization"

version := "2.0"

scalaVersion := "2.11.0"

sbtPlugin := true

This is my publishLocal command output:
[info] :: delivering :: co.myorganization#myProject;2.0 :: 2.0 :: release :: Thu May 15 14:57:24 COT 2014

All seems to work fine but in my other project I'm getting this error when I try to use it as a dependency like so:
"co.myorganization" % "my-project"  % "2.0"

Error output:
::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: co.myorganization#my-project;2.0: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: co.s4n#s4n-autenticacion;2.0: not found
[error] Missing task key: scalaInstance
java.lang.IllegalArgumentException
    at org.sbtidea.Settings.logErrorAndFail(Settings.scala:11)
    at org.sbtidea.Settings$$anonfun$task$1.apply(Settings.scala:24)
    at org.sbtidea.Settings$$anonfun$task$1.apply(Settings.scala:24)
    at scala.Option.getOrElse(Option.scala:120)
    at org.sbtidea.Settings.task(Settings.scala:24)
    at org.sbtidea.SbtIdeaPlugin$.projectData(SbtIdeaPlugin.scala:163)
    at org.sbtidea.SbtIdeaPlugin$$anonfun$2.applyOrElse(SbtIdeaPlugin.scala:88)
    at org.sbtidea.SbtIdeaPlugin$$anonfun$2.applyOrElse(SbtIdeaPlugin.scala:87)
    at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:33)
    at scala.collection.TraversableLike$$anonfun$collect$1.apply(TraversableLike.scala:278)
    at scala.collection.immutable.RedBlackTree$.foreach(RedBlackTree.scala:79)
    at scala.collection.immutable.TreeMap.foreach(TreeMap.scala:202)
    at scala.collection.TraversableLike$class.collect(TraversableLike.scala:278)
    at scala.collection.immutable.TreeMap.collect(TreeMap.scala:48)
    at org.sbtidea.SbtIdeaPlugin$.doCommand(SbtIdeaPlugin.scala:87)
    at org.sbtidea.SbtIdeaPlugin$$anonfun$org$sbtidea$SbtIdeaPlugin$$ideaCommand$2.apply(SbtIdeaPlugin.scala:45)
    at org.sbtidea.SbtIdeaPlugin$$anonfun$org$sbtidea$SbtIdeaPlugin$$ideaCommand$2.apply(SbtIdeaPlugin.scala:45)
    at sbt.Command$$anonfun$applyEffect$1$$anonfun$apply$2.apply(Command.scala:60)
    at sbt.Command$$anonfun$applyEffect$1$$anonfun$apply$2.apply(Command.scala:60)
    at sbt.Command$$anonfun$applyEffect$2$$anonfun$apply$3.apply(Command.scala:62)
    at sbt.Command$$anonfun$applyEffect$2$$anonfun$apply$3.apply(Command.scala:62)
    at sbt.Command$.process(Command.scala:95)
    at sbt.MainLoop$$anonfun$1$$anonfun$apply$1.apply(MainLoop.scala:100)
    at sbt.MainLoop$$anonfun$1$$anonfun$apply$1.apply(MainLoop.scala:100)
    at sbt.State$$anon$1.process(State.scala:179)
    at sbt.MainLoop$$anonfun$1.apply(MainLoop.scala:100)
    at sbt.MainLoop$$anonfun$1.apply(MainLoop.scala:100)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:18)
    at sbt.MainLoop$.next(MainLoop.scala:100)
    at sbt.MainLoop$.run(MainLoop.scala:93)
    at sbt.MainLoop$$anonfun$runWithNewLog$1.apply(MainLoop.scala:71)
    at sbt.MainLoop$$anonfun$runWithNewLog$1.apply(MainLoop.scala:66)
    at sbt.Using.apply(Using.scala:25)
    at sbt.MainLoop$.runWithNewLog(MainLoop.scala:66)
    at sbt.MainLoop$.runAndClearLast(MainLoop.scala:49)
    at sbt.MainLoop$.runLoggedLoop(MainLoop.scala:33)
    at sbt.MainLoop$.runLogged(MainLoop.scala:25)
    at sbt.StandardMain$.runManaged(Main.scala:57)
    at sbt.xMain.run(Main.scala:29)
    at xsbt.boot.Launch$$anonfun$run$1.apply(Launch.scala:57)
    at xsbt.boot.Launch$.withContextLoader(Launch.scala:77)
    at xsbt.boot.Launch$.run(Launch.scala:57)
    at xsbt.boot.Launch$$anonfun$explicit$1.apply(Launch.scala:45)
    at xsbt.boot.Launch$.launch(Launch.scala:65)
    at xsbt.boot.Launch$.apply(Launch.scala:16)
    at xsbt.boot.Boot$.runImpl(Boot.scala:32)
    at xsbt.boot.Boot$.main(Boot.scala:21)
    at xsbt.boot.Boot.main(Boot.scala)
[error] java.lang.IllegalArgumentException

Please advise.
Comment: I was adding it as a normal dependency. It was my fault. So I remove sbtPlugin := true and voila! It works now. Thank you!
Comment: Are you adding your project with `addSbtPlugin` or as a normal dependency?
Answer: If you build the project as plugin sbtPlugin := true it will add an extra information about the sbt version.
You have to add these kind of artefacts with addSbtPlugin, additionally because you've overridden default Scala version for the plugin you'd have to add it to the addSbtPlugin method:
addSbtPlugin("co.myorganization" % "myproject" % "2.0", "0.13", "2.11")

assuming that you want to add your plugin to Sbt version 0.13 and Scala 2.11.
When doing plugins better stick with default version of Scala.
If your intention is not to have a plugin remove sbtPlugin := true from your build.sbt.
Answer: Perhaps you need to add your local repository to the resolvers list?
resolvers += "Local Maven Repository" at file(
    Path.userHome.absolutePath+"/.m2/repository").toURL.toString


how to prove series convergence

Question: Can someone help me to prove convergence of the series $$\sum\limits_{k\ge 0}\frac{\left(\frac{2-\nu}2\right)_k}{k!},$$ where $\nu$ is the positive number and $\left(\frac{2-\nu}2\right)_k$ is falling factorial ?
Answer: Let $u_{n}$ be the general term of the series.
Then $\frac{u_{n+1}}{u_{n}} = \frac{\frac{2-v}{2}-k}{(k+1)(\frac{2-v}{2}-k+1)} \rightarrow 0$ as $n \rightarrow +\infty$ (and is positive for $k$ large enough).
You can now conclude using the ratio test (https://en.wikipedia.org/wiki/Ratio_test).
Comment: I am grateful to you for assistance.
Answer: $\frac{(x)_k }{k! } = \binom{x}{k}$ (Identity in Wikipedia page for falling factorials),
So your sum is just $\sum \limits_{k \geq 0} \binom{\frac{2-v}{2} }{k} = 2^{1-\frac{v}{2}}$,
Which is a finite value, hence the sum converges.
Comment: Thanks a lot for help!

how to prove series convergence


How can I reach Whimsyshire, the secret level in Diablo III?

Question: There's information that there's a secret level in Diablo III, similar to Diablo II's "Secret Cow Level".
How can I reach that secret area in Diablo III?
Comment: [There is no cow level](http://i.stack.imgur.com/HwilC.jpg)
Comment: Here is the "cow-level" from Diablo 3 [In the Land of Killer Unicorns](http://d3db.com/achievement/i/in-the-land-of-killer-unicorns). but I have no clue how to get there...
Comment: I wonder if maybe you can tack on how many times this level can be accessed? Or should that be a new question?
Comment: The money's on [killer pink unicorns](http://www.diablofans.com/topic/41499-diablo-3-new-cow-level-models-quests-and-so-much-more-massive-spoiler/).
Comment: @stay this has been addressed in [this question](http://gaming.stackexchange.com/questions/67141/can-you-access-the-secret-level-in-diablo-3-more-than-once-per-difficulty)
Comment: Note that Blizzard is doing like Findus ... They are putting horses in their game instead of cows :-/ .. Coincidence ? I don't think so  ;-)
Answer: According to sources on the Blizzard forum, the secret level is called Whimsyshire:

Whimsyshire is essentially a single-level dungeon, much like the dungeons you find randomly while exploring the wilderness.  Just like these random dungeons, it has chests and other lootable objects, plus a plethora of monsters, including some champion and unique monsters.
Level-wise, it contains monsters and loot that are roughly on par with the first act of Nightmare (if you're visiting the Normal variant - I assume that it is roughly on par with the first act of the difficulty one harder than the difficulty you enter the portal in) - nothing super difficult or super awesome.  It may be worth visiting/farming if you've cleared the difficulty you're on, but are having trouble with the first act of the next difficulty.  Otherwise, it's probably likely to be underwhelming.
In order to visit Whimsyshire, you must craft a Staff of Herding, and take it to a specific area in Act 1.

The Staff of Herding
Unlocking Whimsyshire requires a Staff of Herding, which can be crafted at the blacksmith for 50,000 gold and requires the following items:
Black Mushroom -  Cathedral Level 1
The mushroom in a patch of mushrooms that occasionally spawn on level 1 of the Cathedral (screenshot).  When you enter the room, your hero will remark about the unusual mushrooms.  The room it spawns in always looks the same so you can look for it in the minimap.  (minimap screenshot).
If you're past this point in the story, go to Act 1, Mission 4: Reign of the Black King.  Travel from the New Tristram waypoint to the Cathedral Garden, and then walk out the gate and back around to the front of the Cathedral.  Open the door and descend to Cathedral Level 1.
Leoric's Shinbone - Leoric's Manor
The shinbone is found occasionally in the fireplace of Leoric's Manor.  From the entrance to the manor, walk forward to the staircase, and hang a right.  The room with the fireplace is on the first floor on the right side.  A large painting of an old man hangs over the fireplace. If the shinbone is present, there will be logs in the fireplace.  Click the logs to get the bone.  (screenshot).
If you're past this point in the story, return to Act 1, Mission 9: The Imprisoned Angel. Take the waypoint to Leoric's Manor.  Backtrack through the manor into the room with the large statue overlooking a double staircase, and then head into the room to the northeast on your minimap.
Wirt's Bell - Caldeum Bazaar
Squirt the Peddler sells this item at the Hidden Camp in Act 2.  This vendor was moved in patch 1.0.4 to stand just up and to the right of the waypoint in the Hidden Camp.  The item is on the "Miscellaneous" tab.  The cost for the bell is 100,000 gold.
Liquid Rainbow - Mysterious Cave in Dahlgur Oasis
From the Act 2 waypoint "Path to the Oasis," travel southeast.   Zaven the Alchemist may be here, and if so you can save him to access the cave. (screenshot)  The item is in a the "Mysterious Chest" which also may not spawn, even if you're in the right dungeon.
If you're past this point, load Act 2, Mission 7: Blood and Sand.  Take the "Path to Oasis" waypoint, as noted above.
Gibbering Gemstone - Caverns of Frost in Fields of Slaughter
This item drops from a "purple" class monster named Chiltara that has a chance of spawning in the second level of Caverns of Frost, a random dungeon that may or may not appear in the Fields of Slaughter.  Other dungeons may appear here, but you can only find this item in the Caverns of Frost.
From the waypoint "The Bridge of Korsikk" travel almost due east.  You should see a small cluster of debris that has a small, U-shaped indentation in it.  (screenshot)  The dungeon may spawn northwest, or southeast of this debris.  (There are other potential locations, but these are the fastest 2 to check)  Ensure this is the Caverns of Frost before clearing it!
If you've passed this point, load Act 3, Mission 6: Siegebreaker.  Take the waypoint to "The Bridge of Korsikk" as noted above.
Plans for the Staff of Herding - Great Span
This item is a random drop from Izual, who is a midboss on the Great Spire.  Unfortunately, there's not a "fast" quest checkpoint for this one - you're going to have to start Act 4, Mission 4: Prime Evil, and then fight through the Silver Spire Level 1 in order to get to the Great Span.
Izual tends to favor attacks that freeze you in place, so bring any skills you know which can break his freezing spell.  Many of the "movement" skills (ie, Spirit Walk) can do this.  If you kill Izual and he does not drop the plans, you'll have to exit out, reset the quest to "Quest Start" and start over again, fighting through Silver Spire Level 1.
For this reason, I'd suggest being overleveled before you attempt this - fighting this area repeatedly is likely to be time consuming and frustrating if you can't just obliterate everything quickly.

A few additional notes:

Given that most of these are random drops, in some cases from random monsters in random dungeons you can expect to invest a decent amount of work in getting each of these components.  You may try to get the Shinbone a dozen or more times, for instance.
If you search the indicated area and don't find the item/dungeon/boss, you'll have to exit back out to the character selection screen and resume the game again to get another chance.
These items may spawn in other locations; I've listed the locations where I or others have had good luck finding them.
The items are marked as "account bound" - so you won't be able to buy these at the auction house, for example.

The Staff of Herding you create from this recipe only unlocks the Normal difficulty variant of Whimsyshire.  To unlock Whimsyshire on higher difficulties, you'll need to upgrade the staff.  You can find more information about how to find the plans for these upgrades in this question:
How do I get higher difficulty Plan: Staff of Herding?

Opening Whimsyshire
Once you have the staff, travel to New Tristram by choosing any of the quests in Act 1 past the point where the road to Old Tristram is open.  From the New Tristram waypoint, follow the road towards Old Tristram.  When the path turns to the right past the abandoned houses, you will find a fissure in the ground along the southern edge of the path.  Nearby will be the Ghost of the Cow King. (screenshot)  With the Staff of Herding in your inventory, clicking on the Ghost will trigger a few lines of dialog, and then the fissure will open.

Other related questions:
Can I enter Whimsyshire if I follow someone in my party with the Staff of Herding?
Is there any achievement related to Whimsyshire?
Sharing Whimsyshire crafting materials between difficulties
Do the Staff of Herding crafting items drop in all difficulties?
Will a higher level Staff of Herding open the lower difficulty Whimsyshire?
Can you access the secret level in Diablo 3 more than once per difficulty?
Comment: OMG! Please tell me that's real!
Comment: I've seen a guy opening up this level on hardcore and waiting for n00b players to follow his waypoint just to find themselves in the middle of a mob on this level which is relatively hard. Even when you are level ~20 by the end of Act I getting there by mistake can get you killed in a hit or 2. This guy in the span of an hour or two killed over 30 people doing so. He says this is the only way he can have fun until blizzard comes up with pvp. So take care when following waypoints on hardcore Act I. Make sure it doesn't go to "Whimsyshire". He almost got me killed, at least I got the achievement
Comment: During hours of excruciating ***not-gaming***, I came across a list of what appears to be every room in the game.  Every time I have come across a room and looked it up on this list, it has been there - (for example, the Fowl Lair).  You can check for yourself, but Whimsyshire is listed - http://webcache.googleusercontent.com/search?q=cache:SOtpZDxrtAAJ:wowbox.tw/us/d3/zone.php%3Fstl%3DLevelArea+&cd=1&hl=en&ct=clnk≷=us&client=firefox-a .
Comment: This is real. I've been there. Loot and XP isn't great, and monsters are tough so after a visit or two I went to nightmare - more rares. It took me 2-3 hours of farming.
Comment: This is real - my brother apparently got all the items needed to unlock this by his second playthrough.  I have seen this level personally.
Comment: Man, i've been through Cathedral Level 1 like 15 times now and no BM
Comment: congrats on another gold answer badge :)
Comment: I found the gibbering gem to be hardest largely because of the conflicting information about Chiltara's spawning ... I just spawned here in the cave level 2, she was buried near the resplendant chest and there was another blue pack on level 2 and a gold pack on level 1.
Comment: Video not working anymore. Could you fix it?!


What is std::string(itr, itr) supposed to do?

Question: The web site cplusplus documentation for std::string constructor taking two input iterators states in part:

Copies the sequence of characters in the range [first,last), in the same order.
first, last:
Input iterators to the initial and final positions in a range. The range used is [first,last), which includes all the characters between first and last, including the character pointed by first but not the character pointed by last.

What does this mean in the degenerate case where first == last?  On the one hand first is included and on the other last is excluded?  What does the official C++ standard say should happen in this case?  Should an exception be thrown?
Comment: *The* documentation does not say that.
Comment: The construction of an empty string is not such a degenerate case.
Comment: @WilliamKF: cplusplus.com is not "The" documentation.  That's someone's summary of the documentation.  Some people also have problems with that website's accuracy, though IMO they seem to have fixed most of the errors.
Answer: I don't know what documentation it is you're reading, but the standard says (§21.4.2/15):

[..] constructs a string from the values in the range [begin, end), as indicated in the Sequence Requirements table

And the Sequence requirements table (Table 100) defines X a(i, j) for a valid range [i, j) as:

Constructs a sequence container equal to the range [i, j)

A range is valid when the second iterator is reachable from the first (through incrementing). For two iterators that are equal, the range is empty. See §24.2.1/7:

A range is a pair of iterators that designate the beginning and end of the computation. A range [i,i) is an empty range; in general, a range [i,j) refers to the elements in the data structure starting with the element pointed to by i and up to but not including the element pointed to by j. Range [i,j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined.

So if first == last, as you say, you will get an empty string. If last is not reachable from first, you have undefined behaviour.
Answer: The range is empty, so there's nothing to copy. The result is an empty string.
Answer:
What does this mean in the degenerate case where first == last?

It means that the input range is empty, so the string will be empty.

What does the standard say should happen in this case?

C++11 24.2.1/7 says:

A range [i,i) is an empty range
Answer: One thing I've used it for several times is constructing a std::string from a substring in a large C-style string (const char*). You can pass it two const char* pointers and it will construct a string from the characters starting at the first pointer and ending one before the second pointer.
If first == last, the result is an empty string. If first > last, behavior is undefined (thanks Mooing Duck)
Comment: That's undefined behavior, no exception is required to be thrown


Setting up Dagger 2 and project organization in Android

Question: I have a project organized in a way similar to below in Android studio:

:lib_commons
:module_auth
:app_demo

lib_commons and module_auth are basically Android library projects.
module_auth is meant to be an independent, pluggable module to be attached to a couple of apps in the project. It contains an activity and a couple of fragments with injectable fields. Since Android would be in charge of managing these activities&fragments, I would have to inject the fields manually, something like daggerComponent.inject(this) in the activity
The application component, as well as other relevant modules currently reside in the various apps in the project (e.g app_demo), all to be instantiated by an Application subclass in the corresponding app.
This means I won't have access to the application component from module_auth, as a result, making injection impossible.
I have tried moving the dagger component to commons, but that would require it having a knowledge of all possible injection points, which would  be impossible since commons generally has no idea of the existence of any of these apps.
The question
What is a possible clean approach to organise the project such that I can access the application component from this module? Keeping in mind that the component would actually be instantiated in the app_demo's Application object
In dagger 1, I could easily place the object graph in commons, and call graph.inject(this) from any registered class in the project. I would only have to load corresponding dagger modules separately for each app.
I could create an abstract Application in commons containing an abstract getModules method which would then be implemented in the apps. However the object graph is still the same one, and injection is pretty straight forward.
How do I acheive this in dagger 2?
Kindly advise. Thanks.
Answer: Okay, so I found a way to deal with this, with a little insight from this blogpost https://www.future-processing.pl/blog/dependency-injection-with-dagger-2/
This is my approach:
I have a component interface, say AppComponent in :lib_commons that is practically empty. This will serve as the super component for the concrete apps :app_*
I have an abstract BaseApplication in :lib_commons, something like
public abstract class BaseApplication<T extends AppComponent> extends Application {
    private T mComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        mComponent = createComponent();
    }

    protected abstract T createComponent();

    public T getComponent() {
        return this.mComponent;
    }
}

The base activities, fragments etc look similar to this:
public class BaseActivity extends Activity {
    /**
     * Get the Main Application component for dependency injection.
     */
    protected <C> C getAppComponent(Class<C> componentType) {
        return componentType.cast(((BaseApplication) getApplication()).getComponent());
    }
}

So, in the ':module_* where the actual components doesn't exist yet, I will create regular interfaces declaring the injection methods, so that injection is as simple as
getAppComponent(InjectionInterface.class).inject(this);

Finally, the :app_* modules would contain the actual component interface which will extend the super AppComponent  and every other corresponding InjectionInterface declared in the modules it depends on. I will then create a concrete Application class that extends BaseApplication and simply implements the abstract createComponent method, completing the injection circle.
Hope this helps someone.


MySQL Cross Join with concat field

Question: I have 2 tables in a MySQL database: Products and ProductsType.
Each element of the Products table has a type which is contained in ProductsType table.
Each table has a field named "code".
I'd like to have a VIEW with the cartesian product of these 2 tables and I know that I can do it with a CROSS JOIN.
But I'd like that in this VIEW I can see the CONCAT of the 2 fields named "code" of my 2 tables. Is that possible?
I've also thought that I can make 3 tables, Products, ProductsType and ProductsWithType and in the first 2 I put some triggers "after insert" that keep updated the third table ProductsWithType, but I'd like to know if it is possibile to do with a view.
Thanks in advance
Answer: Are you looking for this?
CREATE VIEW vw_products_types AS
SELECT CONCAT(p.code, t.code) combined_code, p.product_name, t.type_name
  FROM Products p CROSS JOIN ProductsType t

Here is SQLFiddle demo

MySQL Cross Join with concat field


Multiple Depots in Fortess

Question: In my fortress I have two depots, one right next to my stockpile hub and one in an airlock arrangement by the entrance.
I wish to use the one further into my depot by default but then use the airlock one during a siege, is there any way this can be done?
Answer: It is generally advised to only have one depot. Having a second is known to cause bugs in the merchant AI.
If you are dead set on having two there is a small possibility that blocking all access to a depot (for example with a raising drawbridge) would make the merchants path to the depot that was accessible, but I have not tested it. Such a gateway would need to be creature tight, because otherwise some of the traders could still path to it.
Such a construction would look like this:
<code>0000000
0DDDDD0
0DDDDD#
0DDDDD#
0DDDDD#
0DDDDD0
0000000
</code>
Where 0 is wall, D is your depot, and # is a bridge built to raise westward. The bridge would need to be attached to a lever in order to be opened an closed. You would need to arrange both depots like this and leave just one of them open, and it still might not work, or might not work reliably.

Multiple Depots in Fortess


How to prove two of following central extensions are isomorphic?

Question: Given group $D_3= \langle r,s | r^3 =s^2=(rs)^2= 1\rangle$
The following are $3$ central extensions of $D_3$ by $\mathbb{Z}_2\cong \langle b|b^2=1\rangle$.  I want to know which one of $G_2$ and $G_3$ is isomorphic to $G_1$? Or $G_2$ is isomorphic to $G_3$?
$$G_1=\langle r,s, b | r^3 =s^2=(rs)^2= 1,b^2=1, [r,b]=[s,b]=1 \rangle \cong D_3\times \mathbb{Z}_2 $$
$$G_2=\langle r,s, b | r^3 =s^2= 1, (rs)^2=b ,b^2=1, [r,b]=[s,b]=1 \rangle$$
$$G_3=\langle r,s, b | r^3 =1, s^2=(rs)^2=b , b^2=1, [r,b]=[s,b]=1 \rangle$$
with commutator $[,]$ is defined by $[a,b]=a^{-1}b^{-1}ab$.
It relates the group cohomology $H^2(D_3,\mathbb{Z}_2)=\mathbb{Z}_2$. It says that they are totally two kinds of central extension. $G_1$ belongs to the trivial central extension. One of $G_2$ and $G_3$ should belong to the trivial case or $G_2\cong G_3$. I don't know how to show explicitly.
Comment: I think the key takeaway is that you can always get any central extension of any finite group $G$ by $C_2$ following this recipe: add the generator "$b$", make it commute with all of $G$'s generators, and then set every relator of $G$ either to $b$ or to $1$.  The problem is (and why this is not a trivial theory) that not every such presentation gives you an actual central extension (and sometimes two different ones give you the same group).
Comment: Are you sure these are isomorphic? The second looks like the double cover of $D_3$ corresponding to the nontrivial element of $H^2$.
Comment: $G_2$ is of order $6$ not $12$. The relations force $b=1$. If you put $s^2=b$ in $G_2$ instead of $s^2=1$ then you get a group of order $12$ but it is not isomorphic to $G_1$.
Comment: @DavidHill Sorry, I edit the question.
Comment: @DerekHolt Sorry, I correct the question.
Comment: As I said before $G_2$ has order $6$ so it cannot be isomorphic to $G_1$ or $G_3$. $G_1$ and $G_3$ are not isomorphic because $G_3$ has cyclic Sylow $2$-subgroup of order $4$, whereas $G_1$ has Sylow $2$-subgroup $C_2 \times C_2$.
Comment: @DerekHolt It's impossible. $G_1, G_2, G_3$ are all central extension of $D_3$ by $\mathbb{Z}_2$. There are only two kinds of such central extension. At least two of $G_1, G_2, G_3$ are isomorphic.
Comment: It's not impossible.  $G_2$ is just $D_3$, while $G_3$ is the group $C_3\rtimes C_4$.
Comment: @SteveD That's my point. I originally thought that seting every relator of $G$ to $b$ will generate a central extension. But from Derek Holt's answer it seems that $G_2$ is not a central extension because $G_2\cong D_3$. Am I right?
Comment: Everything you said in your comment to Derek Holt's answer is correct.
Answer: Here is a proof that $b=1$ in $G_2$, so $|G_2|=6$.
$$rsrs=b \Rightarrow r^{-2}srs=b \Rightarrow r^{-1}srsr^{-1}=rbr^{-1}=b \Rightarrow r^{-1}sr=brs = (rs)^3.$$
So then $s^2=1 \Rightarrow (rs)^6=1$, but $(rs)^4=b^2=1$, so $(rs)^2=b=1$.
Comment: So that means $G_2$ is not a central extension? $G_1$ and $G_3$ are in different extension classes?


Instead of virtual keyboard black box appears and shifts the app

Question: I'm a beginner with Xcode/Swift. I'm using Xcode 7.2.
I built an app that has functionality to bring up the keyboard when a textbox is clicked and remove the keyboard when somewhere else is clicked.
When I run my project in the simulator though, instead of the virtual keyboard appearing a black box appears at the top of the screen and shifts the app down. Clicking on any other text boxes causes the black box at the top of the screen to grow.

I tried running iPhone5 through iPhone6Plus in the simulator and this happened with all of them. With iPhone4s the virtual keyboard popped up as intended, but all of the views became distorted.
Any idea why this is happening?
Here is the code from the view controller if it helps:
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var runningTimeTextField: UITextField!
    @IBOutlet weak var strengthTimeTextField: UITextField!
    @IBOutlet weak var runningCalTextField: UITextField!
    @IBOutlet weak var strengthCalTextField: UITextField!
    @IBOutlet weak var foodIntakeTextField: UITextField!
    @IBOutlet weak var weightTextField: UITextField!
    @IBOutlet weak var bloodPressureTextField: UITextField!
    @IBOutlet weak var submitButton: UIButton!
    @IBOutlet weak var intakeLabel: UILabel!
    @IBOutlet weak var caloriesBurnedLabel: UILabel!
    @IBOutlet weak var pressureLabel: UILabel!
    @IBOutlet weak var weightChangeLabel: UILabel!
    @IBOutlet weak var weightChangeLabel2: UILabel!

    var count : Int = 0

    var calc : calcModel = calcModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //Initialize text boxes to 0
        runningTimeTextField.text = "0"
        strengthTimeTextField.text = "0"
        runningCalTextField.text = "0"
        strengthCalTextField.text = "0"
        foodIntakeTextField.text = "0"
        weightTextField.text = "0"
        bloodPressureTextField.text = "0"

        //Set report lablels to hidden
        self.intakeLabel.hidden=true
        self.caloriesBurnedLabel.hidden=true
        self.pressureLabel.hidden=true
        self.weightChangeLabel.hidden=true
        self.weightChangeLabel2.hidden=true

        //Added for keyboard stuff:
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);

        runningTimeTextField.delegate=self
        strengthTimeTextField.delegate=self
        runningCalTextField.delegate=self
        strengthCalTextField.delegate=self
        foodIntakeTextField.delegate=self
        weightTextField.delegate=self
        bloodPressureTextField.delegate=self

    }

    //Added for keyboard stuff:
    func keyboardWillShow(sender: NSNotification) {
        self.view.frame.origin.y -= 100
    }
    func keyboardWillHide(sender: NSNotification) {
        self.view.frame.origin.y += 100
    }

/*
    //Displays error that function is not overwritten.
    //Make the keyboard disapear as user touches outside the  text boxes
    override func touchesBegan(touches: Set<NSObject>,withEvent event: UIEvent) {
        view.endEditing(true)
        self.runningTimeTextField.resignFirstResponder()
        self.strengthTimeTextField.resignFirstResponder()
        self.runningCalTextField.resignFirstResponder()
        self.strengthCalTextField.resignFirstResponder()
        self.foodIntakeTextField.resignFirstResponder()
        self.weightTextField.resignFirstResponder()
        self.bloodPressureTextField.resignFirstResponder()
    }
*/
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
        self.view.endEditing(true)
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.runningTimeTextField.resignFirstResponder()
        self.strengthTimeTextField.resignFirstResponder()
        self.runningCalTextField.resignFirstResponder()
        self.strengthCalTextField.resignFirstResponder()
        self.foodIntakeTextField.resignFirstResponder()
        self.weightTextField.resignFirstResponder()
        self.bloodPressureTextField.resignFirstResponder()
        return true;
    }

    @IBAction func submitPressed(sender: UIButton) {
        //Reveal output labels
        self.intakeLabel.hidden=false
        self.caloriesBurnedLabel.hidden=false
        self.pressureLabel.hidden=false
        self.weightChangeLabel.hidden=false
        self.weightChangeLabel2.hidden=false

        //Get input values
        let calBurnedRunning = Int(runningCalTextField.text!)
        let calBurnedStrength = Int(strengthCalTextField.text!)
        let intakeNum = Int(foodIntakeTextField.text!)
        let weight = Double(weightTextField.text!)
        let pressure = Double(bloodPressureTextField.text!)

        count++

        //Use calc model to calculate health report
        intakeLabel.text = String(calc.calculateCalories(intakeNum!, count: count))

        caloriesBurnedLabel.text = String(calc.calculateCaloriesBurned(calBurnedRunning!, calBurnedStrength: calBurnedStrength!, count: count))

        pressureLabel.text = String(format: "%.2f", calc.calculateBloodPressure(pressure!, count: count))

        weightChangeLabel.text = String(format: "%.2f", calc.weightChange(weight!, count: count))

         weightChangeLabel2.text = String(format: "%.2f", calc.weightChangeWeek(count))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Answer: There are two problems.  One is this code:
func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 100
}
func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 100
}

You should not be messing with the frame of a view controllers view.
The other is this line:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
    self.view.endEditing(true)
}

This is causing the keyboard to be dismissed before it has a chance to appear.


Web based Voice over IP application with Rails

Question: I was planning to develop a project including VoIP functionality between mobile app client and web browser with Rails as back-end. After I did some research, I had several questions.
First I Google it around and found most of VoIP applications have a client installed. Is that possible to just use web browser to make a audio call? I did a project of simple computer-to-computer VoIP with Sockets and some Audio library. I think what I can do is to use sockets to connect web browser (JavaScript?) with mobile client. (I'm not very experienced with Client-side JavaScript so not sure what can be done in browser.)
Second I searched about real time application with Rails, and many other developers are talking about rails + node.js + socket.io + redis. For what I'm understanding (not know node.js very well), node.js is a server javascript engine. So does that means there are two back-end running for one application?
Last I searched about VoIP in rails and found Adhearsion for Ruby which is built on to asterisk. Adhearsion did have some way to integrate with rails which is good. But does this make for communicate with actual phone (i.e. regular phone call with phone number)? If I installed Adhearsion, do I answer the phone call through terminal or some client application or web browser?
I'll continue research more about Adhearsion and other stuff.
Any clarification or guidance would be very helpful. Thanks.
UPDATE:
As for first question, I found WebRTC probably the solution.
Some Sources:
Are there any web standards for voice over IP?
SIP, asterisk, adhearson and VoIP
node.js + socket.io + redis + rails — RealTime application
http://www.slideshare.net/DieterPisarewski/ruby-voip
Answer: We use Twilio for SMS stuff.  I haven't used their voice features, but I think they may do what you want.  No affiliation and no idea if they really do, but might check them out.
https://www.twilio.com/voice
https://www.twilio.com/webrtc
https://www.twilio.com/client/mobile
Comment: I've been using Twilio for years -- absolutely love it.


How to resolve "/bin/sh: 1: sshfs: not found" when trying to mount remote drive?

Question: I'm trying to mount a remote drive on a server that I have SSH access to using fuse/sshfs
I created a mount point at /mnt/review/server and created the following entry in my fstab, as per ArchWiki:
me@server:/    /mnt/review/dori    fuse.sshfs    defaults,user,noauto,idmap=user,allow_other 0 0

I've also tried a slightly different entry, based on the Ubuntu documentation:
sshfs#me@server:/    /mnt/review/dori    fuse    defaults,user,noauto,idmap=user,allow_other 0 0

Each time, I just get /bin/sh: 1: sshfs: not found - nothing in the system logs.
This did work back when I was running Kubuntu 14.04 - I've since changed to Mint running on Ubuntu 14.04, and now I get this.
It seems like SSHFS is not installed - but I can't find anything helpful on Google for this message. I've also made sure the the fuse package is installed. I'm stuck for how to resolve this.
Comment: Are you using OpenSSH or an alternative like Dropbear?
Comment: openssh - never used anything else
Answer: You need to install sshfs before you go further.
sudo apt-get install sshfs

Now, you should test that everything is working correctly. You should try mounting your server with.
sshfs -o idmap=user $me@server:/ /mnt/review/dori

If that works, unmount the directory with
fusermount -u /mnt/review/dori

The use the second line you posted about from /etc/fstab.
sshfs#me@server:/    /mnt/review/dori    fuse    defaults,user,noauto,idmap=user,allow_other 0 0

Comment: d'oh - could have sworn I'd checked that package was installed - thanks
Answer: Since you said sshfs wasn't installed yet, have you tried installing it?

sudo apt-get update
sudo apt-get install sshfs


How do I change the edge style between an mxCell and mxPoint in mxgraph?

Question: I am trying to draw an edge with specific edge style, other than the default one. The problem is that I am drawing an edge between a cell and a point so that the edge appears as if coming from a cell to space in the graph.
edge = graph.insertEdge(parentCell, null, label, myCell,null);

I get exception:
"java.lang.ClassCastException: com.mxgraph.util.mxPoint cannot be cast to com.mxgraph.model.mxICell"

when I use this code:
mxGeometry geoCell = myCell.getGeometry();
mxPoint termPoint = new mxPoint(geoCell.getX() - (120 - (offset)), geoCell.getY() + 100);
graph.insertEdge(parentCell, null, "", myCell, termPoint, "edgeStyle=elbowEdgeStyle;elbow=horizontal;orthogonal=0;");

I am using JGraphX 1.10. Is there something I can replace the point with that wouldn't error and give the appearance of the edge connecting to space?
Answer: Try setting the terminal point on the geometry of the edge, you can't use the point as a source terminal as it's expected to be a cell (see exception):
edge.geometry.setTerminalPoint(termPoint, true);

If you are trying to implement a space between the terminal and the edge you can also use the STYLE_PERIMETER_SPACING for the vertex or one of STYLE_SOURCE/TARGET_PERIMETER_SPACING for the edge.
Comment: Yes, that's exactly what I was trying to do. Thank you.


How can I obtain Blade Shards?

Question: I am interested in obtaining an Ascended Tempered Spinal Blades back piece. In order to create one, I need a total of 925 Blade Shards. However, I appear to be gaining Blade Shards very slowly and I would like to complete this back piece very soon.
Is there a good method of farming Blade Shards?
Answer: I'm guessing by "very slowly" you mean from gathering sprockets in your home instance?
These items were dropped in abundance during the Escape from Lion's Arch part of the Living Story; since you can't go back in time to that, you can currently only get them in limited quantities from Aetherblades, e.g. in the Edge of the Mists, in the Aetherblade path of Twilight Arbor, or wherever else you can find them - I think some are still around the Not so secret jumping puzzle and you can get them from the chest at the end of that JP as well.
But yes, the going will be slow compared to farming them while the Living Story was going on.
Edit: As Gwen said in the comment, you can also use the Blade Shard recipe to multiply blade shards using sprockets and some dust. Assuming you have enough sprockets, that should speed things up a bit.
Comment: @Andreas: Yes, hence my first sentence: "... from gathering sprockets in your home instance". :-)
Comment: You can turn [Sprockets into Blade Shards](http://wiki.guildwars2.com/wiki/Blade_Shard) with the mystic forge
Comment: @Gwen: Indeed - updated the answer, thanks for pointing that out :-)
Comment: @AmosM.Carpenter The sprocket node in your home instance occasionally drops these as well
Comment: @AmosM.Carpenter Can't believe I somehow skipped that first sentence XS

How can I obtain Blade Shards?


How to work out Percent in PostgreSQL using Count

Question: I want to work out the percentage of reads (records) that have a quality score above a certain threshold. I got both values needed using the below queries.
select count(read_header) from k12_read where quality_score  > 25;
select count(read_header) from k12_read;
I tried this below however it just returns 0.0
select (select count(*) from k12_read where quality_score >= 25) / (select count(*) from k12_read) * 100.0 as percentage;
I also found this online but it also just returned 0.0 when tried.
Any ideas on how I can achieve this?
Comment: try casting the result of the each of the select statements used in the calculation to decimal or something, because the result of count will be integer and the result of the calculation will be < 0 which as an integer will = 0.
Answer: Postgres does integer division.  An easy way to fix this is by multiplying by 1.0 or casting the value to a float:
select ((select 1.0 * count(*) from k12_read where quality_score >= 25) /
        (select count(*) from k12_read) * 100.0
       ) as percentage;

By the way, I think your query is simpler if you use conditional aggregation with avg():
select avg(case when quality_score >= 25 then 100.0 else 0 end)
from k12_read;

Comment: Brilliant! Multiplying by 1.0 worked perfectly and thanks for giving a much cleaner solution as well.


Can anyone identify the manufacturer of this spigot

Question:
Who is the manufacturer of this outdoor spigot? Can probably pack stem as that is where it is leaking but would like to just replace both seals.
Comment: Try doing a "gravestone rubbing" with a soft pencil on some paper - there appear to be letters just above the symbol/logo but I can't quite make them out. Also, where in the world is this spigot located (which tends to affect likely manufacturers.)
Answer: Usually all seals used are standard, and not manufacturer specific.
Take them out and go shopping.
You have regular garden hose seal (probably 3/4 inch)
Then you have a o-ring type seal at valve on top.
You also have a seal inside the valve, usually with hole in the middle to screw it to the valve. Then you have teflon tape around the body of the valve.
Comment: Thank you for all the info. I also tried the "gravestone rub" but no luck on it.  Early 80s in Dallas, Tx area.


First Get and then Post google sheet data to firebase database using angular

Question: I am trying to get the data from google sheet in the JSON form and then post those data to firebase database using angular.
So Far I am able to get the google sheet data in the form of JSON:
the response I am getting is array of columns and rows. My question is How can I make post request to firebase to post these response ?
To make the get request I did following method.
landing-page.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../shared/auth.service';
import { Field } from '../model/field';

@Component({
  selector: 'app-landing-page',
  templateUrl: './landing-page.page.html',
  styleUrls: ['./landing-page.page.scss'],
})

export class LandingPagePage implements OnInit {
  private collection: AngularFirestoreCollection;
  myCollection: Observable<Field[]>;
   constructor(private auth: AuthService, private router:Router, private http :HttpClient,private afs: AngularFirestore) {
    this.collection = this.afs.collection("Exceldata");
    this.myCollection = this.collection.valueChanges();
   }

  ngOnInit() {
    this.excelData();

  }
logout()
{
  this.auth.signOut();
}
excelData(){

   var sf = "https://docs.google.com/spreadsheets/d/1qeCEUlVt_hnuyhnoT1wxMMSv7kZW1s4cUIRLynJ0TxQ/gviz/tq";
 this.http.get(sf,{responseType: 'text'}).subscribe(res=>{
   const data =res.toString().match(/google\.visualization\.Query\.setResponse\(([\s\S\w]+)\)/);
   if(data && data.length==2){
     const obj=JSON.parse(data[1]);
     const table=obj.table;
     const header =  table.cols.map(({label}) => label);
     const rows = table.rows.map(({c}) => c.map(({v}) => v));
     console.log(header);
     console.log(rows);
     console.log(this.collection.doc().set(Object.assign({}, rows)));
    }

 });
}
}

Field.ts
export interface Field{
    Id:string;
    Name:string;
    Major:string;
}

Answer:
Install AngularFirestore
Declarations:

private collection: AngularFirestoreCollection;
myCollection: Observable<Model[]>;
3.
constructor(private afs: AngularFirestore) {
            this.collection = this.afs.collection<Model>("collectionName");
            this.myCollection = this.collection.valueChanges();
          }

In your function:
this.collection.doc().set(Object.assign({}, newItemToSave));
Comment: what will be the `Model[]` ?Do I need to make interface class for it ?
Comment: I am getting following error
 `Type 'Observable' is not assignable to type 'Observable'.
  Type 'DocumentData[]' is not assignable to type 'Model[]'.
  Type 'DocumentData' is missing the following properties from type 'Model': Id, Name, Major`
Comment: Yes the model should be your database schema eg { id, name, major }
Comment: I tried by adding Model but I am getting above error:
`export interface Model{
    Id:string;
    Name:string;
    Major:string;
}`
I have update my code after the change.
Comment: private collection: AngularFirestoreCollection;
Comment: One more question: It post every time whenever I refresh page how do I stop posting repetitively ? I just want to post new  data only not the old one.?
Comment: Move step 4 into its own function that you can call maybe on button click/any other condition. Shouldn't be in the constructor if that's where you put it.


Access logs captured with os_log from within the iOS app

Question: As of 2021, is it possible to access the logs captured with the os_log within the iOS app programmatically, for example, to send the log archive over the network?
On the page I've linked, there is a line:

You can also access log messages programmatically using the OSLog
framework.

Which leads to the OSLog framework page, available only on macOS 10.15+.
Is there any way to get the logs out on the iOS, without connecting the device to the computer and using the Console app, or asking a user to collect analytics and mail it to us?
Answer: Yes, it's possible, available with iOS 15


Can I lay sod overtop of a seeded yard where some of the seed has started growing?

Question: Quick back story: we had a house built and the front and side yards had sod included. We opted not to pay for sod in the back and just had it seeded. However, the builder didn't add any top soil to bring it up to the same level as ours or our neighbors sod so our back yard grade is about an inch lower.
It is a muddy mess in some places because the neighbor's sprinkler runs off into our yard and the the seed has been washed out so it is growing only in random patches in the yard. Other parts are barren because the soil is sandy and hard. The grass that has sprouted is still pretty tender and small.
My question is, can I lay sod down over top of the existing seed/straw and in some cases new grass to bring the the yard up to level with the side yard and neighbors yard or should I try to remove the existing straw/seed/grass first before laying the new sod? I'd assume at a minimum I'd need to rake up the straw first.
Comment: Question is better suited here https://gardening.stackexchange.com/
Comment: I would think that existing sprouts will die if you cover them with sod. The dead sprouts and the straw will break down and provide some nutrients for the new lawn. Just like compost, but an inch down. I'm no expert, but I can't really see anything wrong with the idea. Make sure the straw is spread evenly - clumps will leave bumps in the sod and when it decomposes it will leave holes that the soil above will sink into.
Comment: New sod will probably kill the new grass, so you will be wasting the cost of seed and labour, but besides that should be able to just lay the sod down as is.
Comment: @PlatinumGoose thanks, I didn't know about that one. I'll use that in the future.
Comment: Aside - if you do this, consider weedkilling the old grass first, which will kill any lurking weeds.  Wait a week before laying your fresh ready-lawn on top.
Answer: Sure. The sod doesn't much care what organic material it's installed over. The new grass and straw will decompose with time.
Be aware that sod isn't a magic bullet. It won't grow over poor quality soil much better than the seed would have. You really want at least 4-6" of topsoil under any lawn.
Answer: Clover lawn.
There is not that much dirt in sod.  It wont provide a lasting increase in elevation.  Plus the dirt underneath stays poor.  I learned this by trying to lay sod on concrete.  It works for a few months.
How about this idea.
1:  Get a bunch of yard waste, leaves, mulch etc.  Ideally collect from neighborhood, or get a truckload delivered.
2:  Till it into your sandy hard soil with a roto tiller or with a spade if you are feeling strong.
3:  Seed lawn with clover.  All the new organic matter will make soil nitrogen poor but clover likes that.  You can buy clover seed for clover lawns on line.  I had great luck with crimson clover but it is an annual.  Or an annual might be good if you don't want a forever clover lawn.

If you keep a clover lawn, great.  If not, let the crimson clover finish up then turn it in and seed with grass.  Your soil will be conditioned with a season of organic matter and clover roots.  It will be higher because of all the stuff you added.  Your grass will be happy.  Your neighbor can keep watering it for you.


Find the dimension of a vector subspace

Question: I'm doing a problem on finding the dimension of a linear subspace, more specifically

if $\:$ {$f \in \mathcal P_n(\mathbf F): f(1)=0, f'(2)=0$} is a subspace of $P_n$, what is this dimension of this subspace? Here $\mathcal P_n(\mathbf F)$ denotes a vector space of Polynomials of degree $n$ over the real number field.

At first glance, I thought the dimension is infinity, but I think perhaps since the degree is restricted, the dimension should be finite. Yet I find it hard to specify the number of dimensions. Being a beginner of linear algebra, I would like to hear some detailed explanation on how to solve this type of problems.
Thanks in advance!
Comment: two things: you need to add some extra info about what you've tried, any thoughts you have, etc. Second, what is $P_n(F)$?
Comment: I don't know what $\mathcal P_n(\mathbf F)$ is, but your set seems like a kernel of dimension $2$.
Comment: Hint. If you know why the dimension of the space of polynomials of degree at most $n$ is $n+1$ then you can look at what those conditions imply about the coefficients of $f$ in your subspace. (I suspect someone will post this as an answer.)
Comment: @xhimi I don't think $2$ has to be a root. Just the derivative is zero there.
Comment: @xhimi Note that the set definition says nothing about $f(2)=0$.
Comment: Okay I have edited the question on request, and hopefully it is clearer than before, and thanks for pointing out things to me.
Comment: Thanks Ethan Bolker and @ajotatxe :)
Answer: Intuitively, dimension is the number of degrees of freedom.  The elements of $\mathcal{P}_n(\mathbb R)$ are polynomials of degree $n$ (more precisely, at most $n$), so they look like
$$ a_0 + a_1 x + a_2 x^2 + \dotsb + a_{n-1} x^{n-1} + a_n x^n $$
To specify such a polynomial, you have to specify $n+1$ numbers, the coefficients $a_0,a_1,\dotsc,a_n$.  So there are $n+1$ degrees of freedom in this "space" of polynomials.
To prove that formally, you'd want to think of polynomials $a_0+\dotsb+a_nx^n$ as being linear combinations of the polynomials $1,x,x^2,\dotsc,x^n$, and show that these latter polynomials form a basis.  This is done in chapter 2 of Axler.
Again intuitively, a constraint that specifies a single number reduces the number of degrees of freedom by 1.  Thus imposing the constraint that we will only work with polynomials $f(x)$ satisfying $f(1)=0$ should, we expect, reduce the dimension from $n+1$ to $n$.
The formal version of this is the rank-nullity theorem (Axler's theorem 3.4), which is why everybody's giving answers involving it.  I see Axler doesn't do that until chapter 3, though.
So I think the only thing you can do at this point is to produce an explicit basis for the subspace in question.  Exercise 8 in chapter 2 is similar; have you tried that?  (And for playing with polynomials, exercises 9 and 12 in the same chapter are good.)
(I have the 2nd edition of Axler's text; hopefully it matches yours.)
Comment: +1 for pointing the OP to the relevant places in his text.
Answer: Hint
For any linear function $T:V\to W$ we have that $\dim\ker T+\dim\text{Im} T=\dim V$.
Now consider $T(f)=(f(1),f'(2))$.
Comment: Another sorry I do not understand ker and Im. I appreciate your help though.
Answer: If you want to do this from scratch, it's a slog but you can actually display a basis for the given subspace:
According to your conditions:
$p(x)=(-a_{1}-a_{2}-\cdots -a_{n})+(-4a_{2}-12a_{3}-\cdots -n2^{n-1}a_{n})x+a_{2}x^{2}+\cdots +a_{n}x^{n}$.
Substituting again for $a_{1}$, we have
$(-(-4a_{2}-12a_{3}-\cdots -n2^{n-1})-a_{2}-\cdots -a_{n})+(-4a_{2}-12a_{3}-\cdots -n2^{n-1})a_{n}x+a_{2}x^{2}+\cdots +a_{n}x^{n}$.
This is, finally,
$(4a_{2}+12a_{3}+\cdots +n2^{n-1}a_{n}-a_{2}-\cdots -a_{n})+(-4a_{2}-12a_{3}-\cdots -n2^{n-1}a_{n})x+a_{2}x^{2}+\cdots +a_{n}x^{n}$
$=(3a_{2}+11a_{3}+\cdots +(n2^{n-1}-1)a_{n})+(-4a_{2}-12a_{3}-\cdots -n2^{n-1}a_{n})x+a_{2}x^{2}+\cdots +a_{n}x^{n}$
Factoring out the $a_{i}$, we have
$p(x)=(x^{2}-4x+3)a_{2}+(x^{3}-12x+11)a_{3}+\cdots +(x^{n}-n2^{n-1}x+(n2^{n-1}-1))a_{n}$
To finish, just observe that the set of $n-1$ vectors
$\left \{ x^{2}-4x+3,x^{3}-12x+11,\cdots ,x^{n}-n2^{n-1}x+(n2^{n-1}-1) \right \}$ spans the subspace and is linearly independent since all the vectors have distinct degrees. Therefore the dimension of the subspace is $n-1$.
Answer: Hint
Denote $\varphi$ the linear form $P \to P(1)$ and $\psi$ the one $P \to P^\prime(2)$. You can prove that $(\varphi, \psi)$ is an independent family using carrefuly selected polynomials.
Then the subspace $H=\{f \in \mathcal P_n(\mathbf F): f(1)=0, f'(2)=0\}$ is the orthogonal of the subspace of linear forms generated by $\{\varphi, \psi\}$.
Comment: I'm sorry I'm a beginner of linear algebra, and do not understand what is orthogonal. But thanks for your answer.
Answer: I suppose $\mathscr P_n$ denotes the vector space of polynomials with degree at most $n$. If that is the case, in the canonical basis $ \{1, x,\dots,x^n\}$, the matrix  of the linear map:
$$\begin{aligned}
\varphi\colon\mathscr P_n&\longrightarrow \mathbf R^2\\
f&\longmapsto (f(1),f'(2))
\end{aligned}\quad\text{is}\quad\begin{bmatrix}
1&1&1&1&\dots&1\\
0&1&4&12&\dots&n 2^{n-1}
\end{bmatrix} $$
and it has clearly has rank $2$. Hence by the rank-nullity theorem, the subspace, which is $\ker\varphi$, has dimension $n-1$.
Comment: I have not learned the rank-nullity theorem. I'm currently at Chapter 2 of Axler's Linear Algebra Done Right. Is there some other methods of reaching the correct answer(I think n-1 is the answer)?
Comment: If you know row-reduction, it is as clear: you have a suystem of linear equations of rank $2$ in a vector space of dimension $n+1$.
The solutions are a subspace of dimension $n+1-2$.

Find the dimension of a vector subspace