How can I get my GRUB menu to be hidden, AND have the shift or esc keys show the hidden GRUB menu at boot time

Question: I'm running Ubuntu 16.10, and I'm trying to hide my GRUB menu at power on/boot time, and wish the menu to appear only when I hit the Shift or Esc keys.
I change the appropriate options in /etc/default/grub and it still won't hide the menu.
In researching this, I found this post from 2013 GRUB hidden menu not working that indicates that the problem has been around for a while, and suggests a change to /etc/grub.d/30_os-prober which I'd rather not do. That code suggests that since its found multiple OS's, it's going to set the GRUB_TIMEOUT=10 anyway.
Here's a snippet of what I have now in /etc/default/grub... a menu with a 10 second countdown...

GRUB_DEFAULT=saved
GRUB_SAVEDEFAULT=true
GRUB_HIDDEN_TIMEOUT_QUIET=true
#GRUB_HIDDEN_TIMEOUT=0
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

If I uncomment #GRUB_HIDDEN_TIMEOUT=0, then sudo update-grub insists that I also set GRUB_TIMEOUT=10 to GRUB_TIMEOUT=0. I do that, and I still see the GRUB menu.
In terminal, typing info -f grub -n 'Simple configuration' describes the various options, and at the very end of the info, it shows that some of the current commands have been depreciated, and suggests that the newer replacements are better.
Does anybody know how I can get my GRUB menu to hide in 16.10 AND have it recognize Shift or Esc keys at boot time?
Comment: @OrganicMarble The problem does have to do with multiple OS's. To test, I did modify that portion of code in /etc/grub.d/30_os-prober, and although I got no menu, I wasn't able to force a menu with shift or esc at boot time. Still working on it.
Comment: I'm glad you asked this.  I couldn't get mine to work either, and this confirms that it is because of the box being a dual booter.
Comment: I added some more info on bugs related to yours in my answer, they may help you understand the nature of the problem more thoroughly.  I am also looking at Grub2 code - trying to help :)
Comment: Try using Grub Customizer if you haven't,  General Setting Tab in this order - 1 Uncheck the box "look for other operating systems" and 2 Uncheck "show menu" then save. Test that and see if "Shift" will bring up the menu and then also what happens if nothing is pressed.
Comment: I can understand that you'd rather not modify `/etc/grub.d/30_os-prober` but I really don't see the harm. You can keep a copy backed up or #Comment your changes so that you can reverse them if need be. The [workaround](http://askubuntu.com/a/281719/225694) you found seems the most reasonable solution at the moment.
Comment: @ElderGeek my edit of `/etc/grub.d/30_os-prober` was a little different than what the link shows, and although the menu was hidden, I couldn't get shift or esc to bring up the GRUB menu at boot time. So it was **really** hidden. There definitely is a systemic problem with GRUB.  A bigger problem is that any more intense mods to GRUB scripts could render me with an unbootable system, and no easy way to undo the mods.
Comment: Ok. Since your modification to /etc/grub.d/30_os-prober was "different" I'm not surprised your result was different.  I don't consider re-installing grub from live media or replacing a backed up file an onerous task, but I respect your right to feel that way. Since "intense" and "easy" are relative terms I guess I have nothing more to add. I do wish you the best of luck however.
Comment: @heynnema Thank you for the clarification. I've edited the title to add a bit of clarity.
Comment: Have you tried editing a new file /etc/grub.d/99_reset_timeout to include resetting the timeout to 0 or 1?  It would get evaluated last, so the timeout would be redeclared (should be overwritten) and just work without editing os_prober.
Comment: @RobotHumans thanks for your input. Unfortunately 16.10 doesn't seem to have the file that you refer to.
Comment: Read *new file*.  It shouldn't have that file to begin with.  You're not modifying something. You're creating something new, so you can delete it to revert changes.
Comment: @OrganicMarble see my answer
Comment: @ElderGeek see my answer
Comment: I'm glad you found a solution!
Answer: OK folks, here's the answer... to obtain a hidden GRUB menu in dual-boot configurations... two edits... and a sudo update-grub...
Edit #1
To obtain a hidden GRUB menu in a multi-boot configuration, we first need to edit /etc/default/grub. Open this file using the below command:
sudo -H gedit /etc/default/grub

Once the file is open, replace these lines
GRUB_HIDDEN_TIMEOUT_QUIET=true
#GRUB_HIDDEN_TIMEOUT=0
GRUB_TIMEOUT=10

with these:
GRUB_HIDDEN_TIMEOUT_QUIET=false
GRUB_TIMEOUT_STYLE=countdown
#GRUB_HIDDEN_TIMEOUT=0
GRUB_TIMEOUT=3

This will cause GRUB to display a 3 second countdown timer on the screen.  By doing this, a user can hit the Esc key to bring up the default menu. Otherwise, the default OS will boot.
If you wish that the default OS should be set to the last-booted OS, add the below two lines under the "GRUB_TIMEOUT=3" shown above:
GRUB_DEFAULT=saved    # change an existing line to this
GRUB_SAVEDEFAULT=true # add this line

Edit #2
Next, the OS prober needs to be updated to disable the quick_boot feature. To do this, open /etc/grub.d/30_os-prober in your favorite editor and change the below line (line 23 in 17.04) by replacing the 1 with a 0:
quick_boot="1"

When you're done, the line should read like:
quick_boot="0"

Save the files and then run the below command to reconfigure the bootloader and to apply your changes:
sudo update-grub

Comment: That did it! +1.
Comment: Looks like a good solution :) Now I have a simple question about it. If you change the GRUB_TIMEOUT from "3" to "1" Will you boot faster. And can you provide links, if any, where one can read how this code works.  I want to understand what this code is doing and its sequence of function calls etc.  Much appreciated.  It is nice when you can solve your own questions - good job on that.
Comment: @xtrchessreal yes, changing the 3 to a 1 makes it 2 seconds shorter. I figured that 3 seconds was enough time for me to get my hand over to the Esc key, if I wanted to. You can look at `info -f grub -n 'Simple configuration'` for more info.
Comment: +1 for Q and +1 for A. Last two nights I've been googling this with all kinds of hair brained modifications to 30_os-proper, creating 31_blah_blah and creating 40_custom all to no avail. This is in AU, ArchLinux, Fedora and many other places.If you want more votes I'd suggest tracking down all the wrong answers here in AU (there are lots) and Voting to close them as duplicates of this one then ping me (@ me) in AU general chatroom with a link to the duplicate and I'll vote it too. Thanks for this great research and working solution! :)
Comment: @WinEunuuchs2Unix thanks for the nice comment, and the votes! I myself did lots of research before I found that nobody had an elegant solution, or any solution at all... but I was determined :-)
Comment: Well done solving what 10's of thousands around the world are struggling with. There is a lot to be said for "RTFM" and I'm rather embarrassed even though I used `info yad` extensively I never clued into trying `info -f grub -n 'Simple configuration'` like you did. There's a new Ubuntu newsletter starting up and I'll ask a mod if this is a good candidate.
Answer:
I guess you want to try 'everything' available via /etc/default/grub. Did you read this link,
help.ubuntu.com/community/Grub2/Setup#Configuring_GRUB_2
I suggest that you try removing the following lines from /boot/grub/grub.cfg,
...
set timeout_style=menu
if [ "${timeout}" = 0 ]; then
  set timeout=10
fi
### END /etc/grub.d/30_os-prober ###

Yes, I know, you would have to do it every time update-grub has run, but you can make a script for it.
Comment: @OrganicMarble see the update to my question. Maybe you can try some/all of my mods and see what you come up with.
Comment: Thanks for your response. I'll take a look at that link. I also had found a way to modify /etc/grub.d/30_os-prober so that I wouldn't have to edit grub.cfg each time.
Comment: This makes sense to me, as in a multiboot system it looks like this code changes the timeout back to 10 from 0 Which seems to defeat HIDDEN_TIMEOUT....
Comment: @heynnema could you post your changes to os-prober?  When I looked at the link in your question and compared it to the code in my os-prober, the line numbers did not make sense, so I assume os-prober has changed since then, and I was afraid to mess with it.
Comment: @sudodus please see my answer
Comment: I'm glad you found a solution, and that you are happy with it :-)
Answer: I believe this issue may be due to multiple OS according to this excerpt from
Grub2 wiki:
If no other operating system is detected GRUB 2 will boot straight into the default operating system and no menu will be displayed.
If another operating system is detected the GRUB 2 menu will display.
AND
Saving an OS can be achieved by running sudo grub-set-default if GRUB_DEFAULT=saved is set in /etc/default/grub. It may also be saved if GRUB_SAVEDEFAULT=true is also set in /etc/default/grub. In this case, the default OS remains until a new OS is manually selected from the GRUB 2 menu or the grub-set-default command is executed.
The Grub2 Wiki also states: Note: There is a longstanding confirmed bug on the hidden menu feature in GRUB 1.97 to GRUB 1.99. The menu may not hide as specified in the description on this page. While editing the 30_os-prober script can fix this issue, it is beyond the scope of this page.
As a work around you can set the GRUB_TIMEOUT="1"and you will only see the menu for 1 second.  If I need to switch to another OS I simply hit the arrow down key within that second and the menu will appear until I make a choice.
There may be a potential syntax problem associated with the bug.  I am not a Grub2 expert but in my grub file every command line ends with ="some quoted setting" I remember from my coding days that "quotes" were to pass a string where as non quotes were passing simple numeric values to the variables. I am not UP in new code techniques. e.g. Here  is some of my grub output:
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT="Ubuntu"
#GRUB_HIDDEN_TIMEOUT="0"
GRUB_HIDDEN_TIMEOUT_QUIET="true"
GRUB_TIMEOUT="1"
GRUB_DISTRIBUTOR="`lsb_release -i -s 2> /dev/null || echo Debian`"
GRUB_CMDLINE_LINUX_DEFAULT=""
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

I'm looking into this Grubbug  :) for more info as well as This Bug Both of these are Grub2 related 2yrs old. Some of this could be related to the MBR code before the handoff to Grub2
Comment: @ElderGeek with regard to bug #1401318  the person the bug is assigned to TJ explains the behavior from the MBR to Grub as he states "sleep --interruptable $timeout" etc.  If you read all of his statements in the bug comments I think you will see what at least part of the problem is. He is also assigned to bug #425979 which is similar in issues. Both bugs dealing with holding shift key to bring Grub menu NOT working when set to be hidden. This is what the OP is trying to figure out as well.  I hope this clarifies why the links are in my posted answer.
Comment: Thanks for your response. I already am using the SAVEDEFAULT method. TIMEOUT=1 certainly shortens the menu appearance time. The problem does have to do with multiple OS's. To test, I did modify that portion of code in `/etc/grub.d/30_os-prober`, and although I got no menu, I wasn't able to force a menu with shift or esc at boot time.
Comment: Those bugs you linked don't seem relevant or am I missing something?
Comment: Pardon my confusion. I read the question as saying "how I can get my GRUB menu to hide" Thank you for clarifying. I must have missed that comment.
Comment: @ElderGeek actually, the question is, "how can I get my GRUB menu to be hidden, **AND** have the shift or esc keys show the hidden GRUB menu at boot time". I've gotten it to hide. I haven't gotten the shift or esc keys to work. Apparently this problem goes way back to 2013 or before, and only effects multi-boot configurations.
Comment: @xtrchessreal please see my answer
Comment: So the reason that grub.cfg sets the timeout from 0 back to 10 IS BECAUSE there is a bug preventing shift from waking up GRUB?


Grep next word after pattern match

Question: I'm trying to get grep/sed out the following output: "name":"test_backup_1" from the below response
{"backups":[{"name":"test_backup_1","status":"CORRUPTED","creationTime":"2019-11-08T15:03:49.460","id":"test_backup_1"}]}

I have been trying variations of the following grep -Eo 'name:"\w+\"' but no joy.
I'm not sure if it would be easier to achieve this using grep or sed?
The way I am running this is curling a response from the server and saving it to a local variable, then echo out the variable and pipe grep/sed
example of what I am running
echo ${view_backup} | grep -Eo '"name":"\w+\"'
Comment: If `jq` is available, please try: `jq -r .backups[].name input.json` which yields `test_backup_1`.
Comment: Have you considered parsing the JSON instead?
Comment: then try debugging it further.. for example, does this work? `a='{"backups":[{"name":"test_backup_1","stat'` followed by `echo "${a}" | grep -Eo '"name":"[^"]+"'` ... and so on..
Comment: What would parsing the JSON do for me?

The above response is from a curl from a server and all I need to retrieve is the name
Comment: The server this will be running on won't have `jq` installed on it
Comment: Then how about: `grep -Eo '"name":"[^"]+"' input.json`?
Comment: Hi @Sundeep expect output would be "name":"test_backup_1"
Comment: @tshiono, that returned
Comment: grep is a line-oriented tool, don't use it for parsing JSON. if jq isn't available, you still have python, perl, etc.
Comment: @user3292394 `echo '{"backups":[{"name":"test_backup_1","stat' | grep -Eo '"name":"[^"]+"'` does return `"name":"test_backup_1"` ... so probably you have some other issue unrelated to `grep` or may your `grep` version doesn't support some part of this command?
Comment: Hi @Sundeep, running the above command did return the expected output, but when I tried to echo out the local variable and run it, it returned a blank.
Comment: Hi @Sundeep, I found, my error. Thanks for your help
Answer: Referencing @sundeep answer
grep -Eo '"name":"[^"]+"'
resulted in the expected output
Answer: Make sure to transform the file to one line before grep
and pipe from your curl
echo `curl --silent https://someurl | tr -d '\n' | grep  -oP "(?<=name\":\")[^\"]+"`

will return
test_backup_1
If you want more variables you can chain the -oP grep like in this example where I get some data on a danish license plate (bt419329)
curl --silent https://www.tjekbil.dk/api/v2/nummerplade/bt41932 | grep -oP -m 1 "(?<=\"RegNr\":\")[^\"]+|(?<=\"MaerkeTypeNavn\":\")[^\"]+|(?<=\"MaksimumHastighed\":)[^,]+"| tr '\n' ' '

returns
BT41932 SKODA 218

Grep next word after pattern match


How can I improve Yorick's damage without making him too squishy?

Question: I'm testing Yorick as AD carry (sometimes is needed a top or mid that are not AP and does not need more tank), so I tested some builds but I didn't like so much about the damage received.
Here what I did in one test:

Manamune
Mercury's Treads
Trinity Force
infinite Edge
Atma's Impaler
and the last item i didn't finish, i was thinking in Warmogs or Spirit Visage.

The output was good (solo baron with an easy time, good damage, good resistence), but he was not resistant enough (This is why warmog or sv).
He attack speed is pretty low for Blood thrist instead of Infinite edge.
I have build him as Tank the whole time, he damage is great, but can't say that he can be a carry with a tank's build.

Which equip should I get for last item?
Should I change IE For BT?

NOTE: I think this question may help others champions like Nasus or Urgot.
I am really in a loss here, really appreciate some help
Comment: Honestly, you can't do much more damage than that build and expect to stay alive. Yorick is a bruiser more than an AD carry for a reason - he's a melee that can stay in the fight and keep others in the fight too with his ultimate. Melee characters tend to fail when not built tanky. Because they have to get in people's faces, they tend to take lots of damage. However, for your experiment, I think the synergy with IE and Atma's is better than bloodthirster, and Warmog's will boost your damage as well as make up for the lack of lifesteal (which has been nerfed recently anyways).
Answer: To answer your questions:

In your build I would take Warmog's Armor or Guardian Angel as the last item.
I think Infinity Edge is better since it works well with Atma's Impaler

However, you cannot think like that. There is no build which is generally good. Sometimes it is better to get this item othertimes that item.
If you want a general build for Yorick I would go for this one:

Boots of Speed + 3 or 4 health pots (4 pots - when solo top, wait near the fountain and buy 4th pot ASAP)
Tear of the Goddess => Manamune
probably Mercury Treads unless they have a heavy ad team, then I would go for Ninja Tabi
straight for Atma's Impaler
Warmog's Armor (tankier build) or Frozzen Mallet (better chasing)
The other one of the previously mentioned items or the new item Maw of Malmortius
Trinity Force (damage) / Guardian Angel (tanky build) / Infinity Edge (in case I have Frozen Mallet)

In case of a need I would upgrade boots before finishing Manamune, but after Tear of the Goddess. If I woudlnt be doing very well I would also get Wriggle's Lantern after Manamune or even before that and Spirit Visage, but those are items you want to sell in late game.
Early boots upgrade and Atma will give you enough resists and in combination with Manamune you will have circa 250 AD.
Finally, I think that Yorick is better with a tankier build rather than AD.
Ad NOTE: I think Nasus benefits more from a far different build. Urgot is also good with Manamune and Atma, but before Atma he really needs Brutaliser and after Atma it is better to go different items. You can also build Frozen Heart before Atma which makes you even tankier and gives you some damage, too (since you have Manamune).
Comment: Sometimes eve Last Whisper can be handy when enemy team has plenty of Armor.
Comment: i tested warmog as the third item, works well, but not good damage. LW is a good call (I think) Thanks for your answer =) Good list of gear you made.
Comment: Thanks, I have tried my best although I am not completely a Yorick player :) I thnk Yorick is quite fat in the beginning so you can get Atma before Warmog, so Warmog would be 4th as I suggested. However, Warmog is more about sustain and therefore more damage in a longer fight. Obviously it is useless as a burst item (ad item).


How to find the sum of particular rows

Question: How to find the sum of particular rows, before that I should find the rows by column names
Like below in image, I will be having a table from which I need to

Find the columns by column names
after finding the column names, sum should be done at last+1 column
(Like total of "Sum of Arrears-Basic"+"Sum of Basic"+"Sum of Arrears-HouseRentAllowance")

*Dynamically means column names may varies every month so i should do loop through the column names and find which columns are available and that columns i should find the sum at last column
Comment: Welcome to Stack Overflow. Please note that because this is no free code writing service it is necessary to show either what you have tried so far and where you got stuck or errors (by showing your code) or at least to show what you have researched and the effort you made. Otherwise it is just asking us to do all the work for you. Reading [ask] might help you to improve your question.
Comment: ActiveCell.FormulaR1C1 = "=SUM(RC[-19]:RC[-13])"  instead of this i need to do this dynamically
Comment: Please explain everything within your question ([edit]). What do you mean by "dynamically"? Also I see no column names that you are talking about. Please be much more specific. Maybe include a screenshot if it helps you to explain it better. Try to give us a full example and show what you have tried so far. Reading [mcve] could help to improve your question.
Comment: Sorry, i am a beginner and hence forth i will try to ask my questions clearly....
Comment: This should give you a start: [5 Different Ways to Find The Last Row or Last Column Using VBA](https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba). Try something on your own and then come back with your code and a question to it.
Answer: I've added your data to range A1:D5 and I'm outputting the totals to range E2:E5 using the following macro.
Sub addTotals()
    With ActiveSheet
        .Range("E2:E5").Formula = "=SUM(A2:D2)"
    End With
End Sub

Comment: Thank you for your effort, i need that in vba code were it will search for the column name , and find basic,hra,pf are their and then it should add all those values in last column

How to find the sum of particular rows


using awk and printf in for loop bash

Question: How can I use awk and printf in for loop?
Here is my code
for fileName in /home/BamFiles/sample*
do
       sampleIds=${fileName##*/}

    for Bam in /home/BamFiles/sample*/*.bam
    do
        samtools idxstats $Bam | awk '{i+=$3+$4} END {printf("%s\t%d",$sampleIds Bam)}'
    done

 done

I get the the following error
 awk: fatal: not enough arguments to satisfy format string
 `%d    %s'
     ^ ran out for this one

Expected output is
  sample1  52432
  sample2  32909
  sample3  54000
  sample5  45890

Thanks
Answer: Awk can never be able to expand a shell variable. You are also trying to pass only a single argument to printf (nothing is passed for %d.
Perhaps you want it this way:
samtools idxstats "$Bam" | awk -v "file=$fileName" '{i+=$3+$4} END {printf("%s\t%d\n", file, i)}'

Note that embedding a variable's value directly to awk's code may be possible by using double-quotes but is not recommended:
samtools idxstats "$Bam" | awk "{i+=\$3+\$4} END {printf(\"%s\\t%d\", $file, i)}"

Suggestion:
shopt -s nullglob
for sample in /home/BamFiles/sample*; do
    for bam in "$sample"/*.bam; do
        samtools idxstats "$bam"
    done | awk -v sample="${sample##*/}" '{ i += $3 + $4 } END { printf("%s\t%d\n", sample, i) }'
done

Or
shopt -s nullglob
for sample in /home/BamFiles/sample*; do
    for bam in "$sample"/*.bam; do
        samtools idxstats "$bam" | \
            awk -v sample="${sample##*/}" -v bam="${bam##*/}" \
                '{ i += $3 + $4 } END { printf("%s\t%s\t%d\n", sample, bam, i) }'
    done
done

Comment: thanks for your answer. I was suppose to pass sampleIds to %d so I have edited it.
Comment: @hash Can you try my suggestions?
Comment: When you tried my first suggestion you probably omitted \ or added a space after it. I modified it to just run it as a line.

using awk and printf in for loop bash


how to trigger re-render of rating component

Question: I am trying out React for first time. I have taken a problem to try building a 5-star rating component. It prints all logs properly. Just that the component is not re-rendering when state is changed. Appreciate your time reading this. Here is JSFiddle version of the problem.
HTML:

CSS:
span {
  margin: 10px;
  font-size:25px;
}

span.active {
  color:red;
}

JS:
class RatingApp extends React.Component {

    constructor(props) {
    super(props)

    this.state = {
        rating : 0,
        items: [
            {id:1, active: false },
            {id:2, active: false },
            {id:3, active: false },
            {id:4, active: false },
            {id:5, active: false }
        ]
    }
}

toggleClass(itemId) {

    console.log("itemId ----" + itemId);

    var changedItems = this.state.items;
    console.log("id ----" + changedItems[itemId-1].id);
    console.log("active ----" + changedItems[itemId-1].active);
    console.log("pre changedItems ---- " + changedItems);
    for(var i=1; i<=5; i++) {
        if(i<=itemId) {
            changedItems[i-1].active = true;
            console.log("active class added");
        }
        else {
            changedItems[i-1].active = false;
        }
    }
    console.log("post changedItems ---- " + changedItems);
    this.setState=({
        rating: itemId,
        items: changedItems
    });
};

render() {
    return (

        {this.state.items.map(item => (
         this.toggleClass(item.id)}
        >
           *

        ))}

    )
  }
}

ReactDOM.render(<RatingApp />, document.querySelector("#app"))

Comment: `this.setState=(` should be `this.setState(`. `this.setState` is a function you should call, not a property to assign to.
Comment: Thank you @FelixKling sir ! That is working. I shall accept your solution if you kindly put this as answer.
Answer: remove the = after this.setState
The first issue is this part
this.setState=({
        rating: itemId,
        items: changedItems
    });

it should be
this.setState({
        rating: itemId,
        items: changedItems
    });

Answer: The error is in
this.setState=({
rating: itemId,
items: changedItems
})
change it to this.setState({
rating: itemId,
items: changedItems
})
Refer below

class RatingApp extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
        rating : 0,
        items: [
        {id:1, active: false },
        {id:2, active: false },
        {id:3, active: false },
        {id:4, active: false },
        {id:5, active: false }
      ]
    }
  }

  toggleClass(itemId) {

    console.log("itemId ----" + itemId);

    var changedItems = this.state.items;
    console.log("id ----" + changedItems[itemId-1].id);
    console.log("active ----" + changedItems[itemId-1].active);
    console.log("pre changedItems ---- " + changedItems);
    for(var i=1; i<=5; i++) {
        if(i<=itemId) {
            changedItems[i-1].active = true;
        console.log("active class added");
      }
      else {
        changedItems[i-1].active = false;
      }
    }
    console.log("post changedItems ---- " + changedItems);

  /*
  this.setState=({
        rating: itemId,
        items: changedItems
    }); */
    this.setState({
        rating: itemId,
        items: changedItems
    });
  };

  render() {
    return (

        {this.state.items.map(item => (
           this.toggleClass(item.id)}
          >
           *

        ))}

    )
  }
}

ReactDOM.render(<RatingApp />, document.querySelector("#app"))
span {
  margin: 10px;
  font-size:25px;
}

span.active {
  color:red;
}
<!doctype html>

  <meta charset="utf-8">


Getting error Operator '!=' cannot be applied to 'Boolean' and 'Int' in a very simple if statement

Question: Here is a part of my code in Kotlin:
if (result[0] != 0 and result[2] != 0){
            textView_result.text = result[2].toString() + " " + result[0].toString() + "/" + result[1].toString()
        }

To clarify, result is a List with length 3. This is a very simple code that if the number at index 0 and 2, both are not equal to zero, then the following has to be run.
However, in the condition specified for if, I'm getting this error:

Operator '!=' cannot be applied to 'Boolean' and 'Int'

Am I doing something wrong?
Edit: I tried making new Integer values for result[0], [1] and [2] and replacing them with the integer, but to no avail.
Comment: check out this doc https://kotlinlang.org/docs/reference/equality.html
Comment: you can cast the value that is getting interpreted as a bool to an int.
Comment: `and` is bitwise operator similar to `&` in java or many other languages.
Answer: Make Another int called
List1 = result[1];
Like that, then try to replace it in the condition instead of result[x]
Answer: Use && instead of and
if (result[0] != 0 && result[2] != 0){
        textView_result.text = result[2].toString() + " " + result[0].toString() + "/" + result[1].toString()
    }

Because and operator required both side Integer(someInt and someInt)  But in your case result[0] != 0 and result[2] != 0 both evaluates to boolean values then and operator is applied which is not permitted
Other way you can cast values and use and operator


Could a regular expression be used to find text between pairs of delimiters

Question: I need to parse an email template for custom variables that occur between pairs of dollar signs, e.g:
$foo$bar$baz$foo$bar$baz$wtf

So I would want to start by extracting 'foo' above, since it comes between the first pair (1st and 2nd) of dollar signs.  And then skip 'bar' but extract 'baz' as it comes between the next pair (3rd and 4th) of dollar signs.
I was able to accomplish this with split and filter as below, but am wondering, if there's a way to accomplish the same with a regular expression instead?  I presume some sort of formal parser, recursive or otherwise, could be used, but that would seem like overkill in my opinion
const body = "$foo$bar$baz$foo$bar$baz$wtf";
let delimitedSegments = body.split('$');

if (delimitedSegments.length % 2 === 0) {
  // discard last segment when length is even since it won't be followed by the delimiter
  delimitedSegments.pop();
}

const alternatingDelimitedValues = delimitedSegments.filter((segment, index) => {
  return index % 2;
});
console.log(alternatingDelimitedValues);

OUTPUT: [ 'foo', 'baz', 'bar' ]
Code also at: https://repl.it/@dexygen/findTextBetweenDollarSignDelimiterPairs
Answer: Just match the delimiter twice in the regexp

const body = "$foo$bar$baz$foo$bar$baz$wtf";
const result = body.match(/\$[^$]*\$/g).map(s => s.replace(/\$/g, ''));
console.log(result);
Comment: Nice, I was thinking it would have to do with match $ followed by non-$ just as you have except I was forgetting the global flag, it's on by default in regex101.  I think this makes a nice canonical Q/A because I wasn't finding anything quite on point when googling.
Answer: You could use this regex /\$\w+\$/g to get the expected output'

let regex = /\$\w+\$/g;

let str = '$foo$bar$baz$foo$bar$baz$wtf';
let result = str.match(regex).map( item => item.replace(/\$/g, ''));
console.log(result);
Answer: You can use capturing group in the regex.

const str1 = '$foo$bar$baz$foo$bar$baz$wtf';
const regex1 = /\$(\w+)\$/g;

const str2 = '*foo*bar*baz*foo*bar*baz*wtf';
const regex2 = /\*(\w+)\*/g;

const find = (str, regex) =>
  new Array(str.match(regex).length)
  .fill(null)
  .map(m => regex.exec(str)[1]);

console.log('delimiters($)', JSON.stringify(find(str1, regex1)));
console.log('delimiters(*)', JSON.stringify(find(str2, regex2)));


Javascript; Using createElement to load data from localStorage

Question: The problem im having is finding out a way when data is loaded that it will create its own Elements the way i have it set for when clicking on "Rasie New Pokemon".
function newPokemon() {
var newDiv = document.createElement("div");
// Creates a new div
var xpPar = document.createElement("p");
var lvlPar = document.createElement("p");
var nxtLvlPar = document.createElement("p");
var namePar = document.createElement("p");
// Creates a new paragraph element

var newImg = document.createElement("img");
// Creates a new image element

var pokemon = ["Mudkip", "Treecko", "Torchic"];
// Array containing pokemon that can be raised

var randNum = Math.floor(Math.random() * 3);
// Chooses a randome number between 1 and 2

if (numOfPoke < 1) {

    newDiv.id = "content";

    newImg.style.cursor = "pointer";
    newImg.id= "pokemon";

    switch (randNum) {
        case 0:
            newImg.src = "http://www.pokestadium.com/pokemon/sprites/img/main-series/5/black-white/animated/front/258.gif";
        break;
        case 1:
            newImg.src = "http://www.pokestadium.com/pokemon/sprites/img/main-series/5/black-white/animated/front/252.gif";
        break;
        case 2:
            newImg.src = "http://www.pokestadium.com/pokemon/sprites/img/main-series/5/black-white/animated/front/255.gif";
        break;
        default:
            alert("Something went wrong! Alert the creator of the game!");
        break;
    }

    newImg.onclick = function() {
        addXP()
    };

    xpPar.id = "xp";
    xpPar.innerHTML = "XP: " + xp.toFixed();

    lvlPar.id = "lvl";
    lvlPar.innerHTML = "Level: " + lvl;

    nxtLvlPar.id = "nxt_lvl";
    nxtLvlPar.innerHTML = "XP To Next Level: " + xpToNxtLvl.toFixed(2);

    namePar.id = "name";
    namePar.innerHTML = pokemon[randNum];

    document.body.appendChild(newDiv);
    document.getElementById("content").appendChild(newImg);
    document.getElementById("content").appendChild(xpPar);
    document.getElementById("content").appendChild(lvlPar);
    document.getElementById("content").appendChild(namePar);
    document.getElementById("content").appendChild(nxtLvlPar);

    numOfPoke++;
    // Adds one to the pokemon counter
} else {
    alert("Only one Pokemon can be raised at a time!");
}
// Allows only one new pokemon to be raised
}

This is the function i am using to create the elements. What i want is for when the data is loaded it will create the data in a smiler way.
here is a link to my files.[1] I couldn't get it to work on jsfiddle for some reason.
Comment: Oooooooo no jQuery! You are brave.
Comment: @Derek朕會功夫 or, like me, he's just too scared to use jQuery. Also @Zer0Pr0x you can't store an element in `localStorage` (as you've probably discovered), but you can store the information and then populate an element with it
Comment: @Markasoftware - Why would one be scared to use jQuery?
Comment: @Derek朕會功夫 i don't know, I'm just kind've kidding. I don't like it because (like all JavaScript libraries) isn't essential for anything; everything it does can be emulated with pure JS and since it doesn't do any reallly hard to do stuff, I don't want it. I use libraries for things like unzipping `.zip` files (something I don't know how to do and is pretty difficult, i think), but jQuery...I don't see the point
Comment: @Markasoftware - I was trying to not use jQuery too at one point. I tried, and the code was starting to get extremely messy. I couldn't chain methods, and had to use `for` every single time to loop through an array... ahh those time had passes and jQuery... is so *amazing* that simply no one can assist! (okay that's a bit exaggerated but whatever :P) Just think of how you can add CSS styles without jQuery! >_<
Comment: @Derek朕會功夫 this is getting REALLY off-topic, so I'm going to post this as the last thing here. First off, jQuery is stupid. Second off, you can use `Array.prototype.forEach` instead of `for` loops (such as `someArray.forEach(function(curValue){alert(curValue);});` or `[].forEach.call(someArray,function(curValue){alert(curValue);});` and also, your website is down because of too much CPU usage. And I know somebody's going to mark this as too chatty
Comment: @Markasoftware - *What the* too much CPU usage Thanks for telling me that.
Comment: Im just playing around with what i learned in my intro to JavaScript class that i just finished up last semester. Unfortunately we didn't learn jQuery but i definitely plan on learning it.
Answer: Instead of saving it into local storage and getting people mad when they clear their cache how about storing it on a server ? And Create a php array on that server containing the data of your pokemon ?
var currentPokemon;

var Pokemon = {

    0: {
        Name: "Mudkip",
        Exp: 0,
        NextExp: 50,
        Lvl: 1,
        Img: "http://www.pokestadium.com/pokemon/sprites/img/main-series/5/black-white/animated/front/258.gif"
    },

    1: {
        Name: "Treecko",
        Exp: 0,
        NextExp: 50,
        Lvl: 1,
        Img: "http://www.pokestadium.com/pokemon/sprites/img/main-series/5/black-white/animated/front/252.gif"
    },

    2: {
        Name: "Torchic",
        Exp: 0,
        NextExp: 50,
        Lvl: 1,
        Img: "http://www.pokestadium.com/pokemon/sprites/img/main-series/5/black-white/animated/front/255.gif"
    }

};

currentPokemon = Pokemon[Math.floor(Math.random() * 3)];

/*
    Now you can get all data you want from currentPokemon :)
*/

Comment: So basically this is an Array.
Comment: Er anything wrong with that ? Oh damn diden't see local storage my bad
Comment: Because `[a, b]` is the same as `{0: a, 1: b}`.
Comment: I like being explicit :p
Comment: I plan on using PHP in the future. This semester i will be taking a php/mysql course so i'm really excited for that! My goal here is just to play around with what i know about JavaScript from my class that i just finished up. The reason i went with localStorage was because that's the only way that i could think of to save the data with JavaScript unless there is another way?
Comment: My goal with my code is to find a way to have the load data display the same way that i used with the newPokemon() function. Im have troubles with the load and saving with localStorage. This game is just something that i am putting together to test my JavaScript Skills that i have learned so far.


How do I diagnose a defective switch in a 4-way setup?

Question: The split-level entryway in my house has a light that is controlled by three switches. Let's call them A, B, and C. A is a 3-way, B is a 4-way, and C is a 3-way turn-knob dimmer.
As long as switch A is in the "up" position, the other two function as expected. But when switch A is down, the light will not turn on at all from either of the other points. I have looked at the connections on all three switches and they all seem to be okay.
Am I right to assume that if one of the switches itself is malfunctioning, switch A is the culprit? I think it could be C as well, since they appear to be connected (there is a red wire in the boxes and A and C, but not at B) and one of the traveler wires on those could be bad.
EDIT: I am not sure the dimmer switch C is wired correctly at all, but there is no label or anything to go on. It has two black wires and one red. I tried switching what I think are the two travelers and it behaved exactly the same way, and I tried switching the two black wires, which resulted in even fewer combinations working correctly.
Comment: There's a decent chance it is just wired incorrectly. Can you show some pictures or a diagram of each box and from the light? Needs to show wire colors, cables and connections. The missing red wire on B does sound suspicious.
Comment: Did it spontaneously stop working, did something change (what?) or has it never worked?
Comment: I can't really get to the light box, but I decided to take a continuity tester to switch A and determined it was defective - open circuit when in the down position. Replaced the switch and all is well. What was confusing me was the connections at switch C - the dimmer (2 blacks and a red). It turns out the red wire is the common.
Comment: We just moved into the house and it has never worked right.
Comment: You do understand that screw color, not position, indicates which 3-way switch terminals are for the travelers?  Also that both travelers will always be in the same cable regardless of color...
Comment: Trial and error troubleshooting is almost never a good idea when it comes to electricity.  Get a multimeter, and safely probe the circuit. Don't just blindly swap wires around.
Comment: In this case, I think trial and error is safer than touching multimeter leads to live wires. I do have a non-contact tester but it's too sensitive to have been of any use here. With 3-way switches, all that happens if you wire it wrong is what was happening here (some combinations don't work).
Answer: I agree with gregmac that is probably a wiring problem. If it isn't a wiring problem it's probably the dimmer and the dimmer itself may even be the wrong type. You might think about getting another three way switch and replacing the dimmer for test purposes only. If it works with the 3 way switch you know it's the dimmer. If it doesn't work then I would bet the dimmer was miss-wired when it was installed and I would start to see if the carriers and the line/load conductors are on the right terminals of the switch. If that isn't the problem then you probably need on site help to troubleshoot the problem.
I am assuming that most of us don't want to answer this question is because it takes quite a bit of work to try and explain how to troubleshoot the circuitry. Not that it's hard but as my instructors told me "it's easy once you learn how to do it."
Hope this helps.
Comment: As odd as it sounds, the 3-way regular switch was bad. I guess it goes to show you should eliminate the simplest fixes first.


I can't fill the horizontal gap between two flex items in a row

Question: I am designing a web page and I tried to stack a clip-art image and description in a row in flex. There is a gap between those two which doesn't go away despite adding justify-content. I have used color to better visualize the situation.
The faulty part

        body {
          background-color: rgb(220, 220, 220);
        }
        nav {
          display: inline;
          text-align: right;
        }
        nav > * {
          margin: 0px 20px 0px 0px;
          font-family: serif;
          text-decoration: none;
          color: black;
        }
        img {
          width: 25%;
          height: auto;
          display: inline;
          text-align: left;
          margin: 0px 600px 0px 0px;
        }
        header {
          display: block;

          margin: 0px 0px 0px 0px;
          width: 100%;
        }
        div {
          display: block;
          width: 70%;
          margin: 0px 200px 0px 200px;
          text-align: center;
        }
        #email {
          background-color: white;
          border: black solid;
          width: 300px;
          height: 25px;
          margin: 0px 0px 10px 0px;
        }
        #submit {
          width: 200px;
          height: 25px;
          display: block;
          margin: auto;
          border: solid black;
          background-color: yellow;
        }
        #features {
          display: block;
        }
        #clip {
          width: 100px;
          height: 100px;
        }
        section {
          display: flex;
          flex-direction: row;
          margin: 50px 100px 50px 100px;
          background-color: yellow;
        }
        article {
          display: flex;
          flex-direction: column;
          background-color: pink;

        }
        article > * {
          margin: 0px 0px 0px 0px;
        }

          Features
          How it works
          Pricing

Hand-crafted, home-made masterpieces

        <form id="form">

        <input type="email" id="email" placeholder="Enter your email" required>
        <button type="submit" form="form" target="_blank"id="submit">Let's get started!</button></form>

      <div2 id="features">

Premium Materials

Our trombones use the shiniest brass which is sourced locally. This will increase the longevity of your purchase.

Fast Shipping

We make sure you recieve your trombone as soon as we have finished making it. We also provide free returns if you are not satisfied.

Quality Assurance

For every purchase you make, we will ensure there are no damages or faults and we will check and test the pitch of your instrument.

      </div2>

This is the full code. And I am trying to get the items of 'section' in '#features' element to be close together.
Comment: Please provide your full CSS, including the wrapper element
Comment: I added full code @GalAbra
Answer: try this
section
{
  display: flex;
  flex-direction: row;
  margin: auto;
  background-color: yellow;

}
article
{
  display: flex;
  flex-direction: column;
  background-color: pink;
}

Comment: Thank you @Waids  though it only removed the margins around section and didnt close the gap.
Comment: Welcome bro
And do up +
Answer: I rewrote your code, consider the following:
Snippet

You have complete control over your paddings and margins in .flex-container > img, article

html {background-color: rgb(220, 220, 220)}
#features{width:100%;text-align:center}
#clip{height:200px;width:200px}
.flex-container {
  margin:auto;
  max-width:700px;
  display: flex;
}
.flex-container > img, article {
  background-color: #f1f1f1;
  margin: 10px 5px 0 0;
  padding: 20px;
  font-size: 15px;
}

Premium Materials

Our trombones use the shiniest brass which is sourced locally. This will increase the longevity of your purchase.

Fast Shipping

We make sure you recieve your trombone as soon as we have finished making it. We also provide free returns if you are not satisfied.

Quality Assurance

For every purchase you make, we will ensure there are no damages or faults and we will check and test the pitch of your instrument.

Note: if you want to learn more about flexbox I suggest this page
Comment: Thank you for the edit, and beautifying it too! It helped!
Comment: I am a beginner and your edits gave some very useful insights!
Answer: What I could understand, that you want to display your content in one row after removing the gap.
Following is the solution to fulfill your requirement.I changed CSS only.Also updated HTML document structure by including head tag and title tag and included style within the head tag which is proper way to write HTML page.
Complete code is as follows;

<!DOCTYPE html>

    <title>Test</title>

            Features
            How it works
            Pricing

Hand-crafted, home-made masterpieces

        <form id="form">

            <input type="email" id="email" placeholder="Enter your email" required>
            <button type="submit" form="form" target="_blank" id="submit">Let's get started!</button>
        </form>

    <div2 id="features">

Premium Materials

Our trombones use the shiniest brass which is sourced locally. This will increase the longevity of your purchase.

Fast Shipping

We make sure you recieve your trombone as soon as we have finished making it. We also provide free returns if you are not satisfied.

Quality Assurance

For every purchase you make, we will ensure there are no damages or faults and we will check and test the pitch of your instrument.

    </div2>

Note: Also if you want to display your content in multiple lines i.e single in one row, then just make following changes in my modified/updated code;
#features {
    display: block;
}

Remove background color from section and article. i.e Yellow and pink.Hope this will solve your problem.
Comment: Thank you the edits! It totally helped. Apparently, the problem was with 'img' element and the display attribute of the '#feature' element. Also, thank you for the suggestions related to neatness!
Comment: You are welcome. If it solves your problem then accept my [answer](https://stackoverflow.com/help/someone-answers).


Wireless adaptor (TL-WN8200ND) shows the networks but wont connect

Question: Hello i just bought my new wireless adaptor and is the ( TL-WN8200ND ) and i have ubuntu 17.04 in my computer i have a dual boot pc with windows 7 and ubuntu the problem is in the ubuntu the adaptor shows me all the wifi networks i click to connect it gives me the password i write the password correct im sure for that because i check for caps lock and language, it takes 10-15 secons then is giving me the message you are disconected and i know its not router fault because i have tried with other wireless routers + i open my phone hotspot and again same problem.If anyone knows something how to fix this please tell me i really need ubuntu!
Comment: try this answer https://askubuntu.com/a/395826/694267
Comment: I dont have internet connection in the system is there any option to download things from windows where my adaptor is working and after install it in the ubunut
Comment: drivers need to be compiled to the kernel you are using. you might be able to find a precompiled one (may give the same performance as the generic one), but normally you download the source and compile it (this gives the best results).  it is possible that you could download the sourse from windows
Comment: Sorry but im not so good at ubuntu if u have the time to tell me how to do that ?
Comment: I don't know where to get it from windows
Comment: @ravery It is quite unlikely that the three-year-old driver you linked is better than that included in 17.04.
Comment: @chili555 -- I use it myself, works better than the ditsro driver which continually disconnects. the only difficulty here is it need to add the divice code for the USB
Comment: Please try this first: https://askubuntu.com/questions/902992/ubuntu-gnome-17-04-wi-fi-not-working-mac-address-keeps-changing
Answer: Please implement the fix outlined here: Ubuntu GNOME 17.04: wi-fi not working -- mac address keeps changing?
Next, please check to see if two possibly conflicting drivers are loaded:
lsmod | grep rtl

If you find that both rtl8192cu and rtl8xxxu are loaded, then blacklist one:
sudo -i
echo "blacklist rtl8192cu"  >>  /etc/modprobe.d/blacklist.conf
exit

After making these two changes, reboot and let us hear the result.


Mini DP compatibility with Ubuntu 18.04.3 and Nvidia GTX1050

Question: I have a laptop with an Nvidia GTX1050 running Ubuntu 18.04.3 (Kernel 4.15). The laptop has one hdmi port and one mini DP.
I have had a monitor plugged into the laptop via hdmi for a while. I've bought a second monitor to go dual screen. When I plug in a monitor into the mini DP, ubuntu enters low graphics mode and I cannot use the UI.
I have confirmed both monitors work fine individually via hdmi. The problem is specific to the mini DP.
I have tried mini DP to hdmi and mini DP to VGA so far. I'm not sure whether to try any other adapter options (mini DP to DP would be my next try).
I assume I'm missing a driver, but I am not actually sure which driver I am even missing, would it be a graphics card driver?
Any help much appreciated.
Answer:
I opened software updater
Went to Additional Drivers
Under Nvidia I had 'Using X.Org X Server' selected
I changed this to 'Using Nvidia driver.. (proprietary)' and it everything works


How to promptly get workitem history with tfs java sdk?( with out workitem.open())

Question: for reasons, i must use tfs java sdk, so i always need workitem.open() to load revisions for each workitem from workitemclient.Query(),like below code:
WorkItemCollection workItemCollection = workItemClient.query(wiql);
for(int i = 0; i < workItemCollection.size(); i++)
{
    WorkItem workItem = workItems.get(i);
    workItem.open();
    workItem.getRevisions()
        .forEach(r -> {
            //..."System.History").getValue());
            //..."System.History").getOriginalValue());
        });
}

if don't use open(), Revisions must be empty;
that open() method cost 55 millseconds for each workitem,that's unacceptable。
so any suggestion for better efficiency ? Thanks a lot。
/////////////////////////////////////////////////////////////////////make it/////////////////////////////////////////////////////////////////////
i make it that cut the time.
use SQL like blow :
String sql = "select [System.Id],[System.ChangedBy],[System.ChangedDate],[words]"
    + " from Tfs_DefaultCollection.dbo.WorkItemsEverable"
    + " left join Tfs_DefaultCollection.dbo.WorkItemLongTexts on [System.Id] = [ID] and [System.Rev] = [Rev]"
    + " where FldID=54" // behalf History field
    + " and"+conditionSql;

conditionSql : " id in ('12','1324','1')"
now use this method, average cost mills for retrieve history(changedby,changedDate,History) just 2~4 mills(test case is 30 ~ 1000 workitems)
/////////////////////////////////////////////////////////////////////still/////////////////////////////////////////////////////////////////////
any advise for better code/efficiency would be appreciate。
Answer: The revision history can only be retrieved for work item fields available in the collection WorkItem.Fields, so if you used the below code to get the workitem revision history you will NOT see the history but end up reloading the current workitem object again and again.
   foreach (Revision revision in wi.Revisions)
            {
                Debug.Write(revision.WorkItem);
            }

You may try to get value of fields in the work item revision:
// Returns a work item object
            var wi = GetWorkItemDetails(id);

            // Get All work item revisions
            foreach (Revision revision in wi.Revisions)
            {
                // Get value of fields in the work item revision
                foreach (Field field in wi.Fields)
                {
                    Debug.Write(revision.Fields[field.Name].Value);
                }
            }

Helpful blog: http://geekswithblogs.net/TarunArora/archive/2011/08/21/tfs-sdk-work-item-history-visualizer-using-tfs-api.aspx
Comment: Thanks  but you first part C# code can't help my java question. i test in C# case, revision always be auto load, so there won't appear same open() delay before getRevisions in C#.   i  make it today by Querying in TFS's Database.   done.


How to insulate water pipe in exterior garage wall?

Question: We have lived in our house for almost four years. Last winter we had about a week of sub freezing temperatures (not super common for Oklahoma City). Unbeknownst to us the pipe section of a hose spigot burst and we didn't find out until the next Spring (only leaked when the spigot was turned on). There was a small (2 inches) where the pipe was not wrapped in foam right before the spigot and inside that corner.
This is on a corner of our garage, both walls are exterior.
I just had a plumber replace the spigot and he said some fiberglass insulation between the pipe and the exterior wall and a spigot cover should prevent it from happening again. Will that work? I feel like any type of fiberglass insulation wouldn't help because both sides of the wall are not climate controlled. My original plan was to fill the corner with spray foam and make sure the rest of the pipe is properly wrapped with foam. But I'm not sure if that will be sufficient.
Comment: It usually depends on how sub freezing the temperatures get.  My location would recommend heat tape for pipes, your location might get by with some insulation.  Cold air drafts near the pipe is worst.
Answer: Insulation slows the movement of heat -- it doesn't prevent freezing. Surprisingly, in some cases, a spigot connected to highly-insulated indoor plumbing will still freeze because the insulation restricts indoor heat from warming the pipe.
Your plumber's advice is sound. The spigot cover will reduce the amount of heat that can conduct through the spigot to the outdoors. The fiberglass (or foam) between the pipe and the exterior wall will reduce the amount of heat that can escape toward the outdoors through that wall. Absence of insulation between the garage and the pipe will allow whatever minimal heat is available in the garage to easily reach the pipe.
The question, then, is "how much heat is available in your garage?" Does the garage remain always above freezing? Even though the garage is not climate controlled there's some heat in there. Heat from the engine of an often-used vehicle, heat from the attached house, even heat from the sun shining on a window or door helps.
If the garage does not reliably stay well above freezing then supplemental heat on that pipe will be recommended. Usually that takes the form of electric heat tape/cable.
Answer: Insulation is not a solution, but it helps. Since this is not the home and you didn't state it was critical to have year-round water, you have two options

heat the lines or area so that freezing can't happen.
drain the lines so that there is no water to freeze

Which is right for you is up to you.

Heating is more costly to set up and has ongoing costs and prone to failure during electric loss, but very convenient.
Draining is almost fail-proof and a not very expensive, one time cost, but is not very convenient.

I would advocate draining the line during the possible freezing months so you don't have to worry about freezes.
Comment: You actually don't need to drain it. Shut off the source and open the tap. Any frozen water will "push out" and not burst the pipe. The only way to burst pipe is if the pipe is completely shut.

The insulation also won't help much, because it only slows down heat loss, and since the water doesn't generate heat, you're only making the freezing take longer. 8 hours at sub-zero temperature will freeze it unless you actively heat it.
Comment: @Nelson I've heard that works, but I've always worried that the open end could freeze first can create an ice plug in the pipe that would act as a cap and allow water behind it to freeze and burst the pipe.
Comment: Even if the ends freeze, what happens is that when the ice is formed further down in the pipes, this creates pressure from the ice to the pipes, which actually melts it. The ONLY way for pipes to burst when freezing is if the valves are completely shut, because otherwise, the water will melt along the pipe and come out the end of the faucet, even if it is frozen first.  When you see this in action, you'll have this icicle form from the faucet, and it'll grow out of the faucet as the water inside the pipe freeze and push out from the open faucet.
Comment: Mechanical pressure creates heat. This is how skates work.


tensorflow/lite/core/subgraph.cc BytesRequired number of elements overflowed. Node number 1 (CONV_2D) failed to prepare. tflite

Question: I am trying to convert a CNN model into tflite model. I converted it successfully, but this error happens when I try to load and run the model.
I am building a flutter app.
It initializes the Tensorflow Lite runtime but then raises this error.
I/tflite  (27856): Initialized TensorFlow Lite runtime.
E/flutter (27856): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(Failed to load model, Internal error: Unexpected failure when preparing tensor allocations: tensorflow/lite/core/subgraph.cc BytesRequired number of elements overflowed.
E/flutter (27856):
E/flutter (27856): Node number 1 (CONV_2D) failed to prepare.

Answer: I think I have figured out the problem.
After spending days trying to solve this problem. I found out that the model I was using to convert was an ImagNet pretrained model which is InceptionV3. The problem is may be there are some layers could not converted.
I used the following and they worked perfectly fine.

MobileNet and MobileNetV2.
NasNet Mobile version.
OR if you are new to deep learning and don't want to train or skip the deep learning part you can use Teachable Machine then convert it easly.

I hope this could help you guys!! Thank you
Answer: I ran into the exact same issue the last few days. I tried to load and run a tflite model on Android. I finally figured out how to solve the problem.
I was creating my model using:
model = Xception(include_top=False)

The important part here is include_top=False, together with the default argument input_shape=None.
If you look at the source code of Xception, Inception, MobileNet, or whatever (that you can find here), you will see that at some point before creating the first layer they call
input_shape = imagenet_utils.obtain_input_shape(
    input_shape,
    default_size=<default_size>,
    min_size=<min_size>,
    data_format=backend.image_data_format(),
    require_flatten=include_top,
    weights=weights)

which is implemented here, with the most important part for us being:
if input_shape:
    ...
else:
    if require_flatten:
        input_shape = default_shape
    else:
        if data_format == 'channels_first':
            input_shape = (3, None, None)
        else:
            input_shape = (None, None, 3)

Thus, if I am not mistaken, when we set include_top to False, instead of getting the default shape we end up with undefined number of rows and columns. I am not sure how this is converted to tflite, although there is no error raised during conversion, but it really seems that Android cannot work with that (probably this is equivalent to setting an infinite image size). Hence this error when initializing the interpreter:

BytesRequired number of elements overflowed

When I set the proper input_shape argument in the constructor, i.e.
model = Xception(include_top=False, weights=None, input_shape=(rows, cols, channels))

then the converted model was working fine on Android.
As for why it is initializing correctly with MobileNetV2 in the same situation, i.e. by creating the model like so:
model = MobileNetV2(include_top=False)

I cannot explain...
Hope this brings an answer to your original question.
Answer: In fact, this is specified in the documentation, for instance in Xception:

 input_shape: optional shape tuple, only to be specified
   if `include_top` is False (otherwise the input shape
   has to be `(299, 299, 3)`.
   It should have exactly 3 inputs channels,
   and width and height should be no smaller than 71.
   E.g. `(150, 150, 3)` would be one valid value.

Whilst for MobileNetV2:

 input_shape: Optional shape tuple, to be specified if you would
   like to use a model with an input image resolution that is not
   (224, 224, 3).
   It should have exactly 3 inputs channels (224, 224, 3).
   You can also omit this option if you would like
   to infer input_shape from an input_tensor.
   If you choose to include both input_tensor and input_shape then
   input_shape will be used if they match, if the shapes
   do not match then we will throw an error.
   E.g. `(160, 160, 3)` would be one valid value.

Although it is not crystal clear.


Hot and Neutral on Same Circuit Breaker

Question: I just installed a new GFCI and it keeps shutting off even though I connected it properly.
I traced the wires and found that the neutral was connected to the same Circuit Breaker as the hot. WHY? And how can I fix this so my GFCI will work?
Comment: Are you sure you don't have HOT-HOT here?  Just because the wire is white doesn't mean someone didn't hook it up to the hot and that's what it looks like to me from the photo.
Comment: @SheenaMB -- what was plugged into this outlet?  Can you post photos of the face of the old outlet, even?
Comment: @SheenaMB also, can you post a photo of the label on the inside of the door to your breaker box please?
Comment: What loads does this breaker serve? Also, what amperage is said breaker?
Comment: This is leading to an outlet that I changed to a GFCI. 20amp. I thought it was a hot white wire and tried attaching both to a hot and it immediately shut off.
Comment: I threw the old outlet away and there is no sticker or labeling of any kind on the door of the breaker box. Had to turn on/off each circuit breaker to figure out which switch went to which outlet.
Comment: @SheenaMB -- can you post a photo of the breaker box as a whole then please? And fish the old outlet out of the trash? (Unless the trash has gone out the door already, of course)
Answer: You'll need a 20A GFCI breaker for this
What you are looking at there is a 240V circuit on a two-pole breaker; both the black and white wires are hots, but from opposite legs of your service (one pulls one way, the other pulls the other way), which is why connecting them both to the LINE HOT on the GFCI receptacle tripped the breaker (as it should have, to stop the game of electrical tug-of-war you inadvertently created).
As a result, you can't use a GFCI receptacle on this circuit at all, as 240V GFCI receptacles simply are not made; instead, you need to use the correct GFCI circuit breaker for your panel to provide protection to a regular (non-GFCI) 240V receptacle of the correct configuration (and a Sharpie, black electrical tape, or the likes to remark that white wire in your picture as a hot wire).
And by the way, the correct receptacle for your application is a NEMA 6-20T; if the receptacle there already wasn't a NEMA 6, it'll need to be replaced with one, lest you leave a 240V boobytrap for the next poor bloke who has to service this circuit!
Answer: That was a 240V circuit
The problem was, it was a different style of outlet, and you didn't notice that.
In the future, don't throw any parts away until the project is done.

It was one of the two on the right.  (Or at least, it was supposed to be. Sometimes lazy people running grow lights or Bitcoin miners just use the standard recep and put 240V on it).
You did not realize that the circuit was for 240V.
You actually want a 120V circuit, apparently.
Now, I gather that you don't give any care about running 240V anything, and what you actually want is the one on the left, but with GFCI.  Am I right?
So that won't be terribly hard.  You're going to need to go back into your service panel where you took the picture, grab a flashlight and shut off the main breaker.  Parts of the panel will still be hot; don't touch anything you don't absolutely need to.
Then you see that white wire on the breaker?  Move that to the neutral bar.   The bar with a whole bunch of other white wires.   It must have its own screw; it can't share a screw even if you see other wires sharing screws.  Neutrals can never share screws (3 grounds probably can, if your panel labeling says they can).
At that point you should be able to wire up the GFCI normally and have it work.  Be prepared for the possibility that you fried this GFCI and anything you had plugged into it at the time.
No no, I really need a 240V circuit
If took a close look at the pool pump, boat lift, tanning bed or European coffeemaker and thought "Wait. That does have a different plug than all my other stuff.  I do need one of the ones on the right."  Then you need to follow ThreePhaseEel's advice above.
A $80 GFCI circuit breaker is the only possible way to GFCI protect this 240V load. It is mandatory as of NEC 2020 (which only Massachusetts has adopted, so far, but 44 states will in the next 2 years).  It is a good idea in a kitchen or anyplace with water e.g. poolside or dockside.
Answer: The White Wire Is A Hot Wire.  It is not neutral.  Black electrical tape should have been rapped around the end of the white wire signifying it's a hot wire, not neutral.

Hot and Neutral on Same Circuit Breaker


Allow downspout discharge to cross a sidewalk in a freezing climate?

Question: I have two downspouts whose discharge I need to get past a sidewalk.  Currently for each gutter, corrugated tubing is run underground, under the sidewalk, for approximately 20 feet where it discharges out the side of the hill approximately 18 inches lower than where it began (it's not a steep hill).
One of the corrugated tubes has a dip in the middle of the run which isn't ideal, but otherwise during the summer this configuration works decently for the time being.  In the winter is a different story--the tubing quickly freezes up and remains frozen until the ground thaws, which creates big problems for roof melt-water and early-Spring rainfall.
In the winter I've tried disconnecting the tubing and installing downspout extensions that run to the near edge of the sidewalk (so the water runs across the top of the sidewalk and then down the hill).  This allows the gutters to drain properly but creates some icing problems on the sidewalk.  I don't leave it like this in the summer due to concerns that the quantity of water will erode the concrete in those areas.
What is the ideal configuration so it can drain properly?
I've attached a crude sketch and a photograph.
Sketch:

Photo:
Comment: does the one that doesn't have a dip in it drain properly in the winter?
Comment: Anything preventing digging the defective one up and giving it a proper gradient so it will drain? Or does it do a tremendous dip under the walkway?
Comment: Neither of them drain properly in the winter.  The discharge end covers with snow and then eventually it'll freeze back up the whole tube.
Comment: I have the same problem. I am considering simply switching the configuration twice yearly and running the downspouts into pipes that rest on top of the sidewalk during the winter season, then converting back to underground pipes the rest of the year. Have not figured out the best way to do that and I wanted to avoid that but I don't want stuff freezing and backing up either.
Answer: The preferred solution that I've seen is to discharge the gutter through a couple inch air gap into a catch basin that outputs into the underground drain. The air gap allows for water to drain into the yard when the catch basin freezes solid.
And while it's a bit late to change your underground drains, I prefer the solid pipe installed with a slight slope over the corrugated tubing. It's less likely to collapse over time and water doesn't have anywhere to be trapped in the tube.
Answer: One option to consider is adding a heating wire to each pipe, perhaps extending into the bottom of the downspout.  That way water can flow away and not over the sidewalk.  The heater does not need to operate 24x7.  A thermo control could engage it at a suitable range of pipe temperatures (or representative air temperatures).  Perhaps from 20–31 °F (-7 to -0.5 °C).  Warmer than that and water will flow freely.  Colder than the low end and probably no water would be coming from the roof.
Another idea is that it looks like the eave might be wide enough to put the gutter mostly past the sidewalk.  Instead of discharging into the downspout, what if it were disconnected and replaced with a rain chain?  It can slant outward somewhat to keep the sidewalk drier.
Answer: You could build arbors across your sidewalk and run the downspouts across and down.
Comment: This is an outside the box answer! Good lateral thinking.
Answer: I have a similar home in Michigan. I used pop-ups where they are installed as you show in your sketch. https://www.homedepot.com/p/NDS-Pop-Up-Drainage-Emitter-with-Elbow-for-4-in-Drain-Pipes-Green-Plastic-422G/100153624#overlay
Here is a link. Here is a link to a role out. https://www.homedepot.com/p/Frost-King-Automatic-Drain-Away-Downspout-Extender-System-DE46/202518593
The system will not allow me to post a picture so I put the link. When pasting it moves my answer and when trying to post it says nobody even if there is text and a picture.


Why does $1+2+\dots+2003=\dfrac{2004\cdot2003}2$?

Question:
Why does $1+2+\dots+2003=\dfrac{2004\cdot2003}2$?

Sorry if this is missing context; not really much to add...
Comment: Because half a square is a triangle.
Comment: have you heard arithmetic progression?

https://en.wikipedia.org/wiki/Arithmetic_progression
Comment: @Evariste what?
Comment: @Evariste isn't it a rectangle?
Comment: I realize I was a bit quick, but essentially the idea is a square. As you can see, $2003\times 2004$ is very close to a square. This pictures helps the understanding a bit :http://oi67.tinypic.com/e9vvi8.jpg
Answer: $$\begin{array}{ccc}
S&=&1&+&2&+&3&+&\ldots&+&2001&+&2002&+&2003\\
S&=&2003&+&2002&+&2001&+&\ldots&+&3&+&2&+&1\\ \hline
2S&=&2004&+&2004&+&2004&+&\ldots&+&2004&+&2004&+&2004
\end{array}$$
There are $2003$ columns, so $2S=2003\cdot2004$, and therefore $S=\dfrac{2003\cdot2004}2$.
Comment: This formatting is gorgeous; great use of array.
Comment: @suomynonA: You're welcome!
Answer: By symmetry, the numbers are all centered around $\frac{n+1}{2}$, and there are $n$ of them.
Comment: Yeah, the number $\frac{n+1}{2}$ is an axis of symmetry for the numbers, when you look at them on the number line.
Comment: This kind of answer is only useful to those who are used to phrases like "by symmetry"
Comment: well. I tried to answer the question "why" as much as possible.
Comment: Oh, I see, thanks
Answer: $$\sum_{i=1}^n i = \frac{n(n+1)}{2}$$
You can show by induction.


Python Websockets handles one time use only

Question: I want to make a python code that browsers can connect to get a video stream.
Problem is that my python code handles only one time use, meaning if you open the browser it will connect to that websocket correctly, but if you refresh the page, or another client want to access a stream from in parallel it doesn't work
My code:
import asyncio
import websockets
import cv2
import os
import signal

async def time1(websocket, path):

    while True:

            vid = cv2.VideoCapture('V_DRONE_097.mp4')
            vid.set(cv2.CAP_PROP_FPS,24)

        try:
            #v = VideoStreamWidget()
            #v.ops()

            while(vid.isOpened()):

                img, frame = vid.read()

                #frame = cv2.resize(frame, (640, 480))
                encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 65]
                man = cv2.imencode('.jpg', frame, encode_param)[1]
                #sender(man)
                #print(len(man.tobytes()))
                #cv2.imshow('img',man)
                await websocket.send(man.tobytes())

        except :
            pass

async def main():
    loop = asyncio.get_running_loop()
    stop = loop.create_future()
    #loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)

    port = int(os.environ.get("PORT", "8585"))
    global stop1
    async with websockets.serve(time1, "", port):
        await stop
    stop1 = False
'''
async def main():
    async with websockets.serve(time1, "localhost", 8585):
        await asyncio.Future()  # run forever

asyncio.run(main())
'''
if __name__ == "__main__":
    while True:
        asyncio.run(main())

I want the server to keep working even if the client (browser) refreshes the page or close it and comeback later.
This is the code of javascript running in the browser if that will help:
openSocket = () => {

socket = new WebSocket("ws://127.0.0.1:8585/");
let msg = document.getElementById("msg");
socket.addEventListener('open', (e) => {
    document.getElementById("status").innerHTML = "Opened";
});
socket.addEventListener('message', (e) => {
    let ctx = msg.getContext("2d");
    let image = new Image();
    image.src = URL.createObjectURL(e.data);
    image.addEventListener("load", (e) => {
        ctx.drawImage(image, 0, 0, msg.width, msg.height);
    });
});
}

and this is the HTML code:
<!DOCTYPE html>

        <title>Python_Websocket_Live_Streaming</title>
        <link rel="stylesheet" type="text/css" href="style.css">

            Connection failed. Somebody may be using the socket.

            <canvas id="msg" width="960" height="720" style="display:inline-block" />

I've searched and tried many solutions but non worked.
My final goal is to integrate this with flask API
Update 1:
yes it is stuck in the time1 function
I've known from wrapping the "send" function in a try catch:
try:
                            await websocket.send(man.tobytes())
except websockets.exceptions.ConnectionClosedError:
                            print("clean up")
                            break

when the browser closes/refresh the page, clean up is printed infinitely
Edit 2
It was stuck in the outer loop, that while true loop. Solved now Thanks
Comment: Exactly where do you see this error?  Which line of code?
Comment: Wait, is it from trying to start another server from the outermost while loop?
Comment: My bad that message was desplayed when I was integrating it in flask api, this message will not be shown in the above code . But it still doesn't work.. I've edited the question
Answer: There are a few culprits, but ultimately I think that while(vid.isOpened()) prevents the async from ever being free
edit
or stuck in the outer while loop
Comment: How would that cause this error?  The `websockets` module is capable of handling multiple requests.
Comment: @TimRoberts It looks like it's stuck looping in the `time1` function
Comment: yes it is stuck in time1 function, I've edited the answer
Comment: @SuhailHany If this fixed it, I would appreciate you accepting my answer
Comment: It did fix it, thank you very much . I don't know how in the world I didn't notice that but you save my time


Pandas: set a default datetime for None values

Question: I have a Pandas dataframe with columns that contain dates as strings (in SQL-like format). However, many cells contain None values. I'm trying to convert these columns to Pandas dates using to_datetime and set a "default" value for cells that contain the None value. Example code below:
import pandas as pd

>>> d = {'a': [1,2,3],
        'd1': ['2016-01-01','2015-10-02',None],
        'd2': [None,'2016-04-03',None]}
>>> df = pd.DataFrame(d)
>>> print df
   a          d1          d2
0  1  2016-01-01        None
1  2  2015-10-02  2016-04-03
2  3        None        None

>>> date_cols = ['d1','d2']
>>> df[date_cols] = df[date_cols].apply(pd.to_datetime)
>>> print df
   a         d1         d2
0  1 2016-01-01        NaT
1  2 2015-10-02 2016-04-03
2  3        NaT        NaT

It's simple enough to convert the valid strings to a date, I just want to replace the NaT with the default_date. This is what I'd like the final dataframe to look like:
>>> default_date = '2015-01-01'
>>> print df
   a         d1         d2
0  1 2016-01-01 2015-01-01
1  2 2015-10-02 2016-04-03
2  3 2015-01-01 2015-01-01

Comment: Calling `fillna` at the end does not work?
Answer: use fillna
df[date_cols] = df[date_cols].fillna(pd.to_datetime('2015-01-01'))
df


1" to 3/4" EMT bushing or adapter?

Question: What's the proper bushing or coupling for stepping 1" EMT down to 3/4"?  Does such a fitting (bushing?) even exist?
My searches for a 1" to 3/4" EMT adapter pretty much come up empty.
Goal: the top of the outdoor box I'm using to house some outlets has a female threaded fitting which works great for 1" EMT, but I'm running 3/4" so I need some kind of step-down.
Are the fittings in the tops of the outdoor boxes regular NPT pipe thread, so a 1" x 3/4" NPT galvanized bushing will work?  (Or whatever NPT size the 1" and 3/4" EMT uses).
Comment: Are you trying to interface a 3/4" EMT to a 1" threaded hub? What sort of box is this?
Comment: @ThreePhase yes.  The box is an old Midwest, I'm guessing 8" x 12".  I think it may have been a temporary construction thing with a main breaker, a 220 and a 110.  The main breaker was broken so I've removed that and I'm just using the 220 and 110.
Comment: Gary could you post some photos of "the top of the outdoor box I'm using to house some outlets has a female threaded fitting which works great for 1" EMT"? I'm worried that we are having terminology misunderstandings (e.g. hub vs. connector vs. coupling).
Answer: I think you should search for "reducing bushing". Here's one I found (example only) but it seems to be sold in box quantities only. Why not check with a local or online electrical supply house?

Technically, EMT conduit isn't threaded itself, just via end fittings, while rigid and IMC are/can be directly threaded.
Edit: According to @ThreePhaseEel I was wrong thinking the threading of EMT fittings matches that of rigid/IMC threading.  As TPE describes in their answer, there are apparently special fittings to convert EMT ends into female or male rigid pipe threading (which would connect to a threaded hub in a box).
Comment: It sounds like the quantity issue is due to trying to shop online. Nobody wants to sell electrical gear online, or to be more precise, nobody wants *to ship* electrical gear by mail because the cost of shipping is usually very high relative to value.  Also, since all electricians have local supply relationships and don't buy mail order, you're left with novices who don't know what they're doing, have exceedingly high returns and chargebacks, and are very hand-holdy.
Comment: @Harper-ReinstateMonica Yes. I have found some supply houses with online operations that have been good to work with. I suspect it helps to be ordering items other than standard DIY items, like 3-conductor rated split bolts :)  In my area, high commercial space rents have driven away the local open-to-the-public plumbing and electrical supply houses that used to be in the area. Perhaps one needs to develop a mapping app to identify local retail supply houses.
Comment: @Armand thanks, will try local supply house.  I used to deal with them when doing more construction (barn, arena, house, etc.) but they generally say "wholesale only" and despite more-or-less being the builder I don't have a commercial license and am not going to pretend to be one.  I would prefer to give them the business and don't mind paying some extra for it if it's not some outrageous pretend retail price.  I used to avoid ACE only because they were always 2x the big box but recently bought ground rods at about the same so maybe that has gotten better.
Comment: @GaryAitken That Ace ratio still generally holds in my area :(
Comment: @Gary that's what happens. People find out ACE is more than big-box on certain items the big-box puts out there as loss leaders. Then they get angry and swear they'll NEVER set foot in a hardware store again. Then they get trapped by big box's poor selection.
Comment: This isn't sufficient -- it gets the reducing done, but doesn't solve the much larger issue of getting the EMT into a threaded hub in a compliant way
Answer: You need the correct EMT-hub transition setup in addition to a reducing bushing
While it's true that you'll need a 1" to ¾" threaded reducing bushing (Bridgeport 1163 or equivalent) for this installation, that's not the only piece you need to make this work.  You see, the threads on standard EMT connectors are designed to mate to the threads on locknuts, not the somewhat different threads found on the inside of the hub fitting sitting atop your construction power outlet box (cabinet), or on the inside of a reducing bushing for that matter.  As a result, an inspector is within their rights to reject your installation if you simply slap a standard watertight (compression) EMT connector in your reducing bushing and call it a day.
Instead, you'll need to use a Bridgeport 291-RTNPT to make the EMT-hub transition work here.  If you can't obtain one of those through your local supply house, your local inspector should accept a rig consisting of a EMT-RMC female-female transition fitting (Bridgeport 291-RT or equivalent) and a ¾" RMC nipple threaded into the reducing bushing instead.
Comment: I've added an image of the box and the fittings (3/4") I was thinking of using on the 3/4" EMT going to and into the box.
Comment: Wow - that's knowledge!
Comment: Not sure I understand this.  EMT is not watertight, at least not standard couplings.  This EMT is running inside a shed, and the construction outlet box / cabinet is also inside the shed.  Can't the normal EMT threaded male adapter with tightening ring be used to snug it down?  Or are you saying I'm going to need water-tight couplings as well?
Comment: @GaryAitken -- by "threaded male adapter with tightening ring" are you referring to a *compression* EMT connector/fitting, or are you referring to a *setscrew* EMT fitting?
Comment: @ThreePhaseEel Gary might mean "lockring" when he writes "tightening ring".
Comment: @Gary Can you post photos of the "threaded female fitting" in the box you've got?
Comment: @GaryAitken yeah, you're in a bit of an edge case with the three-sided shed and sideways rain, I'd talk to your inspector to see if you need a watertight run there
Comment: @ThreePhase  The "tightening ring" I was referring to is apparently what is technically called a lockring.  Thanks Armand
Comment: @GaryAitken -- locknut, really

1" to 3/4" EMT bushing or adapter?


Error when calling method in ES6

Question: Im getting an error that this.filterEvents is not define when calling a method from an onChange event in my class ? Cant quite figure out why?
I've tried calling it with Datepicker.filterEvents or this.constructor.filterEvents and this.filterEvents() -  without any luck :( - So hoping someone can point me in the right direction on where the error is?
Code here:
const daterangeConfig = {
  mode: "range",
  minDate: "today",
  dateFormat: "j M",
  weekNumbers: true,
  locale: 'da',
  onChange: function(selectedDates, dateStr) { //instance also param
    //update filter label with selected dates
    let filterBtn = document.querySelectorAll('[data-filterTrigger]');
    let filterBtnIndex = 1;
    let filterLabelTargetSpan = filterBtn[filterBtnIndex].nextElementSibling.querySelector('.btn--filter__labelb');
    filterLabelTargetSpan.innerText = dateStr;
    Datepicker.filterEvents(selectedDates);
  }
};

class Datepicker {
  constructor(container) {
    // Run initializing code once the DOM is ready.
    onReady(() => this.init(container));
    // You can put other initializer-code here if it isn't dependent on the DOM in any way.
    this.picker = new Flatpickr(this.dom.container, daterangeConfig);
  }

  init(container) {
    this.dom = {
      container
    };
  }

  filterEvents(dates) {
    console.log("filter events now");
  }
}

Comment: `filterEvents` is a method of the *instance*, not of the `Datepicker` class. Please also show us how/where (and how often) you construct a `new Datepicker`.
Comment: If `filterEvents` does not need to use `this` (as in `this.dom` or `this.picker`), just make it a `static` method.
Comment: Setting up an onReady handler inside an object constructor sounds extremely wrong. The onReady handler should instantiate your object instead.
Comment: If you want to use it without instantiating  the class that need to have static in front of the method. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Static_methods
Comment: Please show us the code of `Flatpickr` and how it uses `daterangeConfig`
Answer: If filterEvents() is intended as a static method, meaning its logic is relevant to the DatePicker class but independent of any instance, then you can make it a static method as follows
class DatePicker {
  static filterEvents(dates) {
    ...
  }
}

and refer to it as DatePicker.filterEvents.
In your code, you define filterEvents() as an instance method rather than a static method, which makes it accessible to instances of DatePicker but not available as a method of the DatePicker class. If you do intend to perform logic in filterEvents() which depends on a specific instance, then filterEvents() should be declared as you have done without the use of the static keyword and be referenced as this.filterEvents. It's important to understand that the this must refer to the relevant DatePicker instance.
See also the bind() method which may be useful depending on the desired behavior and code structure.

Error when calling method in ES6


How to check if username and password is correct on login when using HTTP Basic?

Question: I have created a web service that uses HTTP Basic. I am developing an Android application that will present the user a login screen with a textfield for username and another for password. When correct username and password is provided the user will see a new screen.
How can I validate on login that the username and password is correct? Since the dashboard screen that the is taken to after successful login does not by itself needs data from the webservice I can't check if it fails.
Do I have to check against a URL in my application (sending a HEAD request) and see if it fails? Are there any conventions here?
Comment: Your question is unclear.
Comment: How can I check if the username and password entered by an user on login to be correct when I later need to use it when accessing the web service API
Answer: Check the response String and look here HTTP status codes
You can also use for example a mozilla add-on like Poster to check the server response.
Comment: This doesn't answer the question.
Answer: Ok i guess you need to apply validations on username and password.
Validation are decided by the server end i.e.  how username and password should be
for instance USERNAME.
1) Should not be less than 2 characters and max. length is decided.
2) If Email is to be used as Username then validation for email i.e. mus contains @,. etc.
for Password
1) Length of password should not be less than 6 or no to be greater than 20.
2) May or may not contain special characters.
Ask your server end that how they like to receive the username and password and check if user supplied inputs are valid or not , if valid only then make a HTTP call otherwise show user his respective error validation message.
Answer: you can send your username and passwords using http get/post method and can validate this at srver side


Script to convert unicode characters in  format to their ASCII equivalents

Question: Im doing some changes in Linux locale files /usr/share/i18n/locales (like pt_BR), to change the default format of dates, time, numbers, etc. But since unicode chars are presented as strings in the <U9999> format, text is very hard to read.
Here is a snippet of it:
LC_TIME
abday   "<U0044><U006F><U006D>";"<U0053><U0065><U0067>";/
    "<U0054><U0065><U0072>";"<U0051><U0075><U0061>";/
    "<U0051><U0075><U0069>";"<U0053><U0065><U0078>";/
    "<U0053><U00E1><U0062>"

So, how to make a simple script (may be bash, python, pearl, whatever) to convert this text replacing the <Uxxxx> codes to their ASCII equivalents? (yes, they are all ASCI chars below 255, most even below 127)
If several answers are received, Ill accept the most elegant and/or the more detailed explained one (like options and flags used in comands)
As an example, the above text would be converted to:
LC_TIME
abday   "Dom";"Seg";/
    "Ter";"Qua";/
    "Qui";"Sex";/
    "Sáb"

Bonus points for another script that could do the opposite: convert all chars of a given string to <Uxxx> format.
Thanks!
Comment: Characters U0080 to U00FF (i.e. decimal from 128 to 255) inclusive are **NOT** ASCII. They would have to be converted using an encoding of your choice, probably `latin1` in your case.
Comment: The Unicode notation is used because not all Unicode characters have an ASCII equivalent.  So, what do you want done with Unicode sequences that don't have an ASCII equivalent (which is the majority of Unicode sequences - by the number of possible sequences; not necessarily the majority by the number of used sequences).
Comment: I think there are tools in the XML pantheon of utilties that could handle this much  better. I recommend you tag this post with XML (maybe XSLT too?). Good luck!
Comment: @shelter: Ok, ive added the tag. Are there any tools in simple linux scripting (bash, python, etc) that handle XML?
Comment: @Jonathan/John: true, but in that file (pt_BR) 99% of the unicode used is actually asci chars between U0020 and U0079. Very few is between 80 and FF, and none is above FF. So they would be perfectly printable in my system. I dont mind if a few characters go wrong, as long as 99% of the text becomes human readable. Its **very** time-consuming to check an ASCI table, char by char, just to decode strings like "%d %Y %z %HH:%MM", or "%d-%m-%Y", or "Saturday". I would like to change date, currency formats, but it would take hours to decode, and then re-encode. Hence the need for a script  to help
Answer: Using Fields
#!/bin/bash

awk -F'<U0+|>' '{
    for(i=1;i<=NF;i++)
        if($i ~ "^[0-9A-F]+$")
            $i=sprintf("%c", strtonum("0x"$i))
}1' OFS="" /path/to/infile

Explanation

-F'<U0+|>': This is the magic that makes this script so short. We tell awk that the field separator is either <U0+ or a simple >.  The benefit of doing this is that awk will auto-strip these characters for us so we don't have to do it manually with gsub() when it comes time to do the strtonum() conversion.
for(i=1;i<=NF;i++): iterate over each field
if($i ~ "^[0-9A-F]+$"): check if the current field is only composed of hex digits. Remember that due to #1 above something like <U006F> will be seen as 6F at this point
$i=sprintf("%c", strtonum("0x"$i)): replace the hex digit with its corresponding ascii value.  We must prefix the field $i with "0x" so awk knows its a hex value
}1: shortcut for a mandatory print or always print each line
OFS="": set the Output Field Separator to the null string.  If we don't do this, we will get spaces in the output everywhere there was a <U0+ or >

Using match() [requires gawk]
#!/bin/bash

gawk '{
    while(match($0, //)){
        pat = substr($0,RSTART,RLENGTH)
        gsub(/U0+|[<>]/,"",pat)
        asc = sprintf("%c", strtonum("0x"pat))
        $0 = substr($0, 1, RSTART-1) asc substr($0, RSTART+RLENGTH)
    }
}1' /path/to/infile

Comment: @MestreLion: look at my new optimized version. I'll put notes on how it works
Comment: Looks great so far! Ill test it to see if it works. Care to explain the parameters used? Ive never played with awk command before. Also, i guess the reverse script would be even simpler (from "abcd" to ""), since it doesnt need any regex matching.
Comment: It worked! I changed /path/to/infile to "$1" and saved the script as "unicode-decode", tested with both "en_US" and "pt_BR", it worked perfectly for the 1st, and great for the other. Words like "Sábado" and "Março" became corrupted, but that was expected and its no big deal (I only wish gedit was not so picky about this, it refused to open the file), but i could cat the results and read on screen, so its fine.
Comment: +1 for the optimization. And now chars between 80 and FF do not corrupt the on-screen result (terminal shows them as a single "?" char in black-on-white), and gedit accepts the text and shows the right character perfectly!!! AWESOME!!!
Comment: @MestreLion: glad it worked out for you, not bad for < 100 chars of awk code eh? =).  I also added an explanation section in case that's helpful to you or whomever will read this.
Comment: Amazing answer and awesome explanation. Your detailed breakdown allowed me to understand each character of that sweet, smart little script. And helped me learn a ton about awk (sooooo much more friendly then sed!).
Comment: Stay tuned as I will now create a new question for the reverse script. And again, thank you very much!
Comment: @MestreLion: if you post another question about the reverse script and write another well-written question with sample input and desired output I'll attempt to answer that as well.
Comment: There ya go: http://stackoverflow.com/questions/5527981/script-to-convert-ascii-chars-to-uxxx-unicode-notation
Comment: @MestreLion: got it.  Answer [*HERE*](http://stackoverflow.com/questions/5527981/script-to-convert-ascii-chars-to-uxxx-unicode-notation/5528045#5528045).  It was bit more complicated due to the fact that you only want to do unicode transliteration between double-quotes.  If you wanted to do it to *every* character then it would have been a simple one-liner.
Comment: I got this error: awk: line 6: function strtonum never defined. Solved it by installing gawk and changing awk to gawk
Comment: @SiegeX I used the first example. Did not try the second one
Answer: Here's a script in Python that converts <U9999> strings to their ASCII (0-127) equivalent using unidecode module:
#!/usr/bin/env python
import fileinput, re, sys
from unidecode import unidecode # to install, run: $ pip install unidecode

for line in fileinput.input(inplace='--inplace' in sys.argv):
    print re.sub(r'',
                 lambda m: unidecode(unichr(int(m.group(1), 16))),
                 line),

It accepts input from stdin and/or files given at command-line.
$ u9999-to-ascii data.in
LC_TIME
abday   "Dom";"Seg";/
    "Ter";"Qua";/
    "Qui";"Sex";/
    "Sab"

Note, there is no á character due to ascii doesn't support it, so the script replaced it by its ascii analog a.
If you don't need ascii then:
#!/usr/bin/env python
from __future__ import print_function
import fileinput, re, sys

for line in fileinput.input(mode='rb', inplace='--inplace' in sys.argv):
    print(re.sub(br'', lambda m: br'\u'+m.group(1),
                 line).decode('raw-unicode-escape'), end='')

This script works in both Python2.6+ and Python3.x. Example:
$ u9999-to-unicode.py data.in
LC_TIME
abday   "Dom";"Seg";/
    "Ter";"Qua";/
    "Qui";"Sex";/
    "Sáb"

Note, there is á. This script might produce an error if your terminal encoding doesn't support all Unicode characters from data.in.  You could use .encode() method in this case.


Trigger left mouseup with jQuery

Question: I try to trigger the mouseup event with jQuery. But I want to bind to this event the fact that this is a left click. This fact is checked in another function :
$('body').mouseup(function(e) {
    if (e.which == 1)
        ...
}

So I cannot just do $('body').mouseup();.
I've looked at the documentation of mouseupbut I haven't found the solution. Do you know it please ?
Answer: You can create an Event object yourself, and then call .trigger on it.
// Create a new mouse up object with 'which' specified to be 1.
var e = $.Event( "mouseup", { which: 1 } );
// Triggers it on the body.
$("body").trigger(e);

Note, I'm triggering on the body element, you were triggering on a div with ID=body. If this was intentional you'd need to change it from "body" to "#body" like in your code.
Comment: `body` was just an example. Thank you very much !
Answer: I don't seem to be having the same problem with binding the mouseup event to either the left or the right button click. I have created a test in jsfiddle that you can reference.
$('body').mouseup(function(e){
if (e.which === 1){
//left click stuff here
}
});

http://jsfiddle.net/7J6ew/
Comment: Sorry, I'm not a great English speaker, but you haven't understood my question.
Comment: Apologies, looking back at the question, I understand what you're asking. In that case, Benjamin's answer is excellent!

Trigger left mouseup with jQuery