Custom Vue dropdown maintain focus

Question: I tried to find the solution here for this, but couldn't and decided to write a question.
So I am trying to build a simple drop-down menu component in Vue which has toggle button and the user is free to click around and tab around the items but as soon as the focus leaves the component, the menu should collapse.
Now, I maintained the focus with @blur and @focus events, but I have a problem with the Toggle button. If i attach the same listeners to it, then clicking on it shows and immediately hides the menu, so you have to click again to expand it.
Here is the fiddle demonstrating the problem.
If, however I remove the listeners, then clicking on button after the focus has been inside the component is problematic.
I guess my approach is wrong, so here's the expected behavior:

The Toggle button is just that - a toggle button. It should collapse/expand the list on clicks
The list can be expanded only by clicking on Toggle button when it is closed
The list is collapsed ether by clicking on Toggle button when it is expanded, or by focusing out of it. This includes the focus out on the button (i.e. clicking the toggle button to expand the list and then clicking somewhere outside without focusing any of the items).

EDIT: Thanks to @Sphinx I managed to get the dropdown to work as I expect it to. Here's the updated fiddle.
Comment: There is both a `@focus` and `@click` on your button, both get triggered if you click it (if you haven't just clicked it before). You probably just want to remove the `@focus` from the button.
Comment: @Tommos has the problem right, but note that it is browser dependent. On some browsers, when you click on a button, the browser fires a `focus` event before the `click` event. That's what's causing the behavior you're seeing. The `focus` event opens the menu, and then the `click` event toggles it, which closes it. When you click on the button the second time, there's no `focus` event because the button already has focus from the previous click.
Comment: @Tommos Thanks, I get why is this happening. But if you remove `@focus`  handler, then the list cannot be collapsed by clicking on `Toggle` button after clicking on any list item.
Answer: For your case, as the comments under the question already pointed out, you have to handle many situations, like @focus and @click will be triggered in a row, @blur of <button> and @blur of

 will be triggered when click at either of them.
It is not a good idea. But you can check This fiddle, it is one solution with setTimeout & clearTimeout. Then you may already seen it delays 100ms by setTimeout(()=>{}, 100) ( I added some logs, you can open the browser console to check the work flow). The reason is we have to wait enough time to make sure next event handler (like focus is triggered first, then click will be triggered later) can clear previous setTimeout in time, unless the menu may be open first, then is closed again. (PS: for some old machines, 100ms may not be enough, it depends on how fast current render is finished)
One solution:

remove @focus and @blur
when this.showMenu is true(opened), add one listener=click for Dom=document it will execute this.hide() when triggered.
Then inside this.hide(), remove that listener=click from Dom=document.
to prevent the menu is collpased when click at the button and the menu, add the modifier=stop, it will stop the click event's propagation to upper level Dom nodes.

If you wrap <button> and
 into one
, then only need to add the modifier=stop like <template>
<button></button
...

</template>.
Below is one demo:

Vue.config.productionTip = false

new Vue({
  el: "#app",
  data: {
    showMenu: false,
    items: ['Option 1', 'Option 2', 'Option 3', 'Option 4']
  },
  computed: {
    listClass: function() {
      if (this.showMenu) {
        return 'show';
      }
      return '';
    }
  },
  methods: {
    toggle: function() {
      this.showMenu = !this.showMenu
      this.showMenu && this.$nextTick(() => {
        document.addEventListener('click', this.hide)
      })
    },
    hide: function() {
      this.showMenu = false
      document.removeEventListener('click', this.hide)
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

ul {
  list-style: none;
  display: none;
}

li {
  padding: 5px;
  border: 1px solid #000;
}

li:hover {
  cursor: pointer;
  background: #aaa;
}

.show {
  display: block;
}

    This is one demo:

  <button @click.stop="toggle" tabindex="0">
    Toogle menu
  </button>

{{ item }}

Comment: Thanks much. I remember that approach with `document.click` back from jQuery days. Seems to work the way I want to, I just need to add `@focus` and `@blur` since I need keyboard navigation to work also, so the list would collapse when you TAB out of it.
Answer: Im not sure if this fixes what you're trying to accomplish, but you could try using
@mouseenter and @mouseout
<button
@click="toggle"
tabindex="0"
@mouseenter="itemFocus"
@mouseout="itemBlur"
>
Toogle menu

Here's the fiddle: https://jsfiddle.net/xhmsf9yw/5/
Answer: I'm about 40% certain I understood the problem...
based on your description, it seems like the button shouldn't be a toggle, but an open.
template:

  <button
    @click="showMenu"
    tabindex="0"
    @focus="itemFocus"
    @blur="itemBlur"
    >
    Toogle menu
  </button>

{{ item }}

method:
showMenu: function(){
    this.showMenu = true;
},

this will open the menu when it's closed, but will not close it
https://jsfiddle.net/wc1oehx9/
Comment: Almost. But I would like to be able to collapse the list by clicking on toggle button when it is open. Thanks for the help.
Answer: The trick with these types of UI with multiple ways of interaction is to set state of the UI element, and have the UI element reflect that state.
So what I did was this:

If mouse enters, the menu should be open
If mouse leaves, the menu should be close
If its focused, the menu should be open
If its blurred, the menu should be close

So here's my solution: https://jsfiddle.net/jaiko86/e0vtf2k1/1/
HTML:

  <button
    tabindex="0"
    @focus="isMenuOpen = true"
    @blur="isMenuOpen = false"
    @mouseenter="isMenuOpen = true"
    @mouseout="isMenuOpen = false"
    >
    Toogle menu
  </button>

{{ item }}

JS:
// simplified for clarity
new Vue({
  el: "#app",
  data: {
    showMenu: false,
    items: [ 'Option 1', 'Option 2', 'Option 3', 'Option 4' ],
    isMenuOpen: false,
  },
  computed: {
    listClass() { // you can omit the `: function` in new ES standard
      return this.isMenuOpen ? 'show' : ''; //ternary op saves lines
  },
  methods: {
    // not needed, as it's done in HTML
    // toggle: function(){
    //  this.showMenu = !this.showMenu
    //},
    /*
    we no longer need these methods:
    itemFocus: function() {
        var self = this;
      Vue.nextTick(function() {
        if(!self.showMenu) {
            self.showMenu = true;
        }
      });
    },
    itemBlur: function() {
        var self = this;
            Vue.nextTick(function() {
        if(self.showMenu) {
            self.showMenu = false;
        }
      });
    }
    */
  }
})

Answer: I had faced a similar issue, I referred to the code below to solve it. For an depth explanation on how this works here is the link to the website I referred.
This is the HTML:

  My Logo

    <button id="user-menu" aria-label="User menu" aria-haspopup="true">

    </button>

        My profile
        Logout

This is the CSS:
#user-menu ~ #user-menu-dropdown {
  transform: scaleX(0) scaleY(0);
  transition-timing-function: cubic-bezier(0.4, 0, 1, 1);
  transition-duration: 75ms;
  opacity: 0;
  top: 3.25rem;
}
#user-menu ~ #user-menu-dropdown:focus-within,
#user-menu:focus ~ #user-menu-dropdown {
  transform: scaleX(1) scaleY(1);
  transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
  transition-duration: 100ms;
  opacity: 1;
}

Custom Vue dropdown maintain focus


Create a 2d array that prints out a snowflake PYTHON

Question: I am trying to create a piece of code that will accept a odd number as a input and create a snowflake using this graph of n * n
Enter Integer: 5
* . * . *
. * * * .
* * * * *
. * * * .
* . * . *

Im pretty sure Im on the the right track
n = int(input("Enter odd input: "))
while n % 2 == 0:
  print("Invalid Input.  Input must be odd")
  n = int(input("Enter odd input: "))
snowflake = [["."] * n for i in range(n)]
middle = int((n-1) / 2)
for i in range(n):
  snowflake[i][2] = "*"
  snowflake[2][i] = "*"
  snowflake[i][i] = "*"
  diagnol = 5-i
  snowflake[i][diagnol] = "*"
for i in snowflake:
  for j in i:
    print(j, end=' ')
  print()
print()

But I keep getting this error
snowflake[i][diagnol] = "*"
IndexError: list assignment index out of range

Can someone help edit my code or give me a tip?(This is a homework assignment)
Comment: As you learn how to write code, you should also learn how to debug. [This article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) gives some great tips to get you started. I suggest printing out the values of `snowflake`, `i`, and `diagonal` to see what you are doing wrong.
Comment: Well the first iteration `i=0`, so `diagnol=5` which is indeed outside the bounds of the list.
Comment: Print the index so you will find where you are getting out of range
Comment: @Code-Apprentice thank you :)
Answer: After debugging it I found that 5 was too big and that some of the code would only work if the input was 5
n = int(input("Enter odd input: "))
while n % 2 == 0:
  print("Invalid Input.  Input must be odd")
  n = int(input("Enter odd input: "))
snowflake = [["."] * n for i in range(n)]
middle = int((n-1) / 2)
for i in range(n):
  snowflake[i][middle] = "*"
  snowflake[middle][i] = "*"
  snowflake[i][i] = "*"
  diagnol = n -1 -i
  snowflake[i][diagnol] = "*"
for i in snowflake:
  for j in i:
    print(j, end=' ')
  print()
print()

Answer: I decided not to fix your algorithm, but as a working example to provide my own algorithm:
Try it online!
n = 9
a = [['.'] * n for i in range(n)]
for i in range(n):
    a[n // 2][i], a[i][n // 2], a[i][i], a[i][n - 1 - i] = ['*'] * 4
print('\n'.join([''.join(a[i]) for i in range(n)]))

Output:
*...*...*
.*..*..*.
..*.*.*..
...***...
*********
...***...
..*.*.*..
.*..*..*.
*...*...*


Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/enterprise/universal/i18n/LocalStringsImpl

Question: When I undeployed the war file(glassfish) using asadmin and when I try restarting the glassfish it throws error, what can be the possible problem may be jar file or something is missing.
/opt/glassfishv3/glassfish/bin/asadmin undeploy war-name
/opt/glassfishv3/glassfish/bin/asadmin deploy war-name.war
./etc/init.d/glassfish restart

Starting Glassfish ...
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/enterprise/universal/i18n/LocalStringsImpl
        at com.sun.enterprise.admin.cli.AsadminMain.<clinit>(AsadminMain.java:94)
Caused by: java.lang.ClassNotFoundException: com.sun.enterprise.universal.i18n.LocalStringsImpl
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Answer: The problem arised from a missing jar file that is common-util.jar More about common util jar files
The missing file comes under the above mentioned jar file
jar -tvf common-util.jar
--o/p set of files inside the jar as below

com.sun.enterprise.universal.i18n.LocalStringsImpl.class


Dúvida ao contar elementos de uma tabela no formato chr

Question: Como consigo contar os aeroportos de chegada se estão descritos na tabela em formato ?
Já usei este código e não obtive o resultado esperado:
destino_frequente <- flights %>%
        select(origin, dest) %>%
        arrange(desc(origin))

Answer: Creio que você possa resolver utilizando o count do dplyr:
flights %>% count(dest))


root is logged in even though I disabled the root login

Question: I got a new unmanaged vps (centos7) a few days ago. I took care of all the initial stuff: disabled root login, set up a firewall, etc...
And now I was installing apache, php, mysql and at one point I just wanted to check the logged users, so I typed who -s and i got:
root     hvc0         2014-12-27 00:04
me       pts/0        2014-12-29 01:37 (xxxxxxxxxxxxxxxxxxxxxxx) <--- this is me
And i was surprised to see root is logged in for 2 days. Is this normal or is it someone that has broken into my vps?
Answer: hvc0 is the xen serial console, i.e. the fake serial-like console emulating an old-school directly-attached serial console you'd have on a physical server.  It depends on your VPS provider whether or not they expose that console to you, perhaps via a web interface.  If they do, have a look there and you'll find root logged in, and can logout.  If that wasn't you, and the history looks odd, then perhaps someone has managed to log in to the web interface, get to the console, and guess the root password (unlikely, but a bad thing; you may as well consider the server compromised and in need of a rebuild, if this is the case)
It's also possibly the VPS hosting provider, but as you say "unmanaged VPS", they shouldn't even have the root password.
Comment: Thanks, it's probably not an attacker by looking at the logs. Can you tell me how to log as root into hcv0 so i can log it out? I have no idea.
Comment: Your VPS provider may expose the console through a web interface somewhere.  Are you able to tell us which provider that is?
Comment: My VPS provider is site5.
Comment: http://kb.site5.com/types/unmanaged-vps/unmanaged-vps-how-to-access-the-console/


Windows Phone Offline routing

Question: I am trying to made windows phone application with offline routing. I have found that It is possible by using Bing API.
I have registered and got the key, but I can't find, how can I use the key.
I am using following code:
<code>    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        RouteQuery query = new RouteQuery();

        List<GeoCoordinate> wayPoints = new List<GeoCoordinate>();

        wayPoints.Add(new GeoCoordinate(47.23449, -121.172447));
        wayPoints.Add(new GeoCoordinate(47.062638, -120.691795));

        query.Waypoints = wayPoints;
        query.QueryCompleted += geoQ_QueryCompleted;
        query.QueryAsync();
    }

    private void geoQ_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
    {
        try
        {
            Route myRoute = e.Result;
            MessageBox.Show("Completed");
        }
        catch (TargetInvocationException)
        {
            /// Unauthorized access exception 0x8004231C
            Thread.Sleep(1000); // waiting for  completing the query
            geoQ_QueryCompleted(sender, e);
        }

    }
</code>
But I am getting Unauthorized access exception 0x8004231C.
I would like to ask you, how can I fix it?
Comment: possible duplicate of [Bing Maps GetRoute gives '0x8004231C' error](http://stackoverflow.com/questions/23218392/bing-maps-getroute-gives-0x8004231c-error)
Answer: You don't need the key to show offline map. If you have map downloaded on your device, then offline routing should work. You can see the sample to get more details.
Following is the quote from msdn sample,
<code>However, mapping services also work without Internet connectivity when maps are downloaded for offline use.
</code>

Windows Phone Offline routing


last_insert_id oracle

Question: Tenho uma dúvida sobre banco oracle.
Criei duas tabelas e setei uma delas com um campo com foreing key (ver abaixo o FK)
tbl_cidade
*id_city* (PK e auto incremento) - gerado com sequence, visto que não temos auto_increment no oracle
municipio
tbl_escolas
cod (PK)
escola
*id_city (FK)*
Como diabos monto um INSERT para popular as duas tabelas? Até hj só montei insert's pra UMA tabelas no oracle.
Answer: Use a cláusula RETURNING em seu comando INSERT:
INSERT INTO tbl_cidade (...) VALUES (...)
RETURNING id_city INTO var_id;
e depois utilize var_id no INSERT da tabela tbl_escolas.
Comment: Tipo isso?

http://pastebin.com/ZKU9cbut#
Comment: Deu certo, muito obrigado!

last_insert_id oracle


Unattended Kickstart Install

Question: I've looked around quite a bit and have seen similar setup and questions, but none seem to work for me. I'm using the following command to create a custom ISO:
/usr/bin/livecd-creator --config=/usr/share/livecd-tools/test.ks --fslabel=TestAppliance --cache=/var/cache/live

This works great and it creates the ISO with all of the packages and configs I want on it. My issue is that I want the install to be unattended. However, every time I start the CD, it asks for all of the info such as keyboard, time zone, root password, etc. These are my basic settings I have in my kickstart script prior to the packages section.
cdrom
install
autopart
autostep
xconfig --startxonboot
rootpw testpassword
lang en_US.UTF-8
keyboard us
timezone --utc America/New_York
auth --useshadow --enablemd5
selinux --disabled
services --enabled=iptables,rsyslog,sshd,ntpd,NetworkManager,network --disabled=sendmail,cups,firstboot,ip6tables
clearpart --all

So after looking around, I was told that I need to modify my isolinux.cfg file to either do "ks=http://X.X.X.X/location/to/test.ks" or "ks=cdrom:/test.ks". I've tried both methods and it still forces me to go through the install process. When I tail the apache logs on the server, I see that the ISO never even tries to get the file. Below are the exact syntax I'm trying on my isolinux.cfg file.
label http
  menu label HTTP
  kernel vmlinuz0
  append initrd=initrd0.img ks=http://192.168.56.101/files/test.ks ksdevice=eth0
label localks
  menu label LocalKS
  kernel vmlinuz0
  append initrd=initrd0.img ks=cdrom:/test.ks
label install0
  menu label Install
  kernel vmlinuz0
  append initrd=initrd0.img root=live:CDLABEL=PerimeterAppliance rootfstype=auto ro liveimg liveinst noswap   rd_NO_LUKS rd_NO_MD rd_NO_DM
menu default
EOF_boot_menu

The first 2 give me a "dracut: fatal: no or empty root=" error until I give it a root= option and then it just skips the kickstart completely. The last one is my default option that works fine, but just requires a lot of user input. Any help would be greatly appreciated.
Comment: Have you verified that the file is still called "test.ks" within the ISO? It's possible your command renamed the file...
Comment: @VishalKotcherlakota - Yes I have confirmed that the ks file is in the appropriate location. That is why I also tried to do it via the http kickstart as well just in case there were some permission issues and that didn't work either.
Comment: From what I can tell, it looks like `livecd-creator` uses the kickstart file to determine what to include in the Live CD. It sounds like you're going to want to use `mkisofs` to re-master the install disk with your kickstart file.
Comment: @VishalKotcherlakota - That is kind of what I was thinking. How I'm using the livecd-creator tool is doing additional stuff to the image and not respecting the kickstart script. I'll research the syntax of mkisofs and try that.
Comment: Cool, make sure to post your own answer if you come across it. :-)
Answer: As the comments to the question state, livecd-creator is really intended for a different purpose.
For bootable ISOs there are two paths to take:

Make a network book iso and provide all software from network install tree, most common.
Create a custom rolled ISO that includes the kickstart and install tree.

There are lots of write ups for number 1 as it is fairly common and has lots of benefits.  Here are a few:

https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/s1-kickstart2-putkickstarthere.html#s2-kickstart2-boot-media
http://mikent.wordpress.com/2012/04/12/how-to-create-a-kickstart-iso-boot-disk-for-redhat/

Number 2 is primarily for the times where you don't have a network available install tree.  Here is how you do number 2:

Make sure your kickstart sets in the install source to 'cdrom'
Install mkisofs (this will give you either mkisofs or genisoimage, mkisofs command below should work with both)
Download ISO
Mount ISO
mount -o loop /path/to/iso /mnt/point

Copy entire directory structure of ISO to a new folder.
mkdir -p /path/to/new/isosource
cp -pr /mnt/point/* /path/to/new/isosource/

Place your kickstart in the new folder
cp /path/to/my/ks.cfg /path/to/new/isosource/

move into folder that contains new folder
cd /path/to/new

Make sure isolinux directory is writeable
chmod u+w isosource/isolinux/*

Add ks entry in isosource/isolinux/isolinux.cfg for the 'Install' entry by changing
append initrd=initrd.img

to:
append initrd=initrd.img ks=cdrom:/ks.cfg

Make the ISO
mkisofs -o file.iso -b isolinux/isolinux.bin -c isolinux/boot.cat \
  -no-emul-boot -boot-load-size 4 -boot-info-table -R -J -v -T isosource/

Comment: So you can basically clear out RPMs you don't want and just re-create the repodata.
Comment: In regards to dmourati's concern below, yes, using a kickstart over the network is way easier.  However, if you have a network server available there are much better options :)  I've only seen one place where the manual process above was necessary, but I'm sure there are more.
Comment: Greg - Thank you very much for that information. It seems like it is exactly what I'm looking for. However, I did try the steps and I'm running into some errors. "dracut Warning: Boot has failed. To debug this issue add "rdshell" to the kernel command line. Kernel panic - not syncing: Attempted to kill init! Pid: 1, comm: init Not tainted 2.6.32-220.4.1.el6.i686 #1" This is when I use the following boot syntax "append initrd=initrd0.img ks=cdrom:/ks.cfg root=live:CDLABEL=SL-62-i386-LiveCD rootfstype=auto ro liveimg textinst noswap  rd_NO_LUKS rd_NO_MD rd_NO_DM".
Comment: I think I found my problem. In the errors above, I was using a LiveCD to do my testing. If I do this for a DVD install instead, I don't get the same errors. I just have to figure out how to make the new ISO image smaller and still respect the kickstart script.
Answer: You are making this much harder than you need to.  Just take the stock ISO and boot it with a ks option at the command line.  See below.
http://fedoraproject.org/wiki/Anaconda/Kickstart#How_Do_You_Perform_a_Kickstart_Installation.3F
Comment: Great, now automate that.
Comment: @MichaelHampton Why?  All he asked for was an unattended install.  Presumably he will be there to insert the CD and boot the machine.  Waiting for boot and typing a few characters still makes the whole install "unattended."  Are there more automated ways to go?  Of course, see PXE booting, cobbler, razor, etc.  That's not the question though.  OP got off track by thinking he needed to recook the CD.

Unattended Kickstart Install


Views and joining content types on specific field in Drupal 7

Question: How can I 'LEFT OUTER JOIN' or 'LEFT JOIN' using Views in Drupal 7.
Here is what I'm trying to do, using an example from Wikipedia:
I have 2 content types: Employee's and Department's (tables below)
The "DepartmentID" noted in the Employee Table below in my case would be the NodeID of the department from the "Department" custom content type.

How can I use Drupal 7's Views module to Display a list of employees with the department name pulled from another content type as noted in the graphic below?
(The SQL statement below is really what I'm hoping to be able to do with the Views module, the table is the output I'm hoping to achieve.)
Answer: In views 3 you have the relationships which manage JOINS between tables.
First you add your relation with the table and then in the next screen you can select Require this relationship.

If you check this checkbox, a LEFT JOIN will be made between the tables, if you uncheck it, it will generate a LEFT OUTER JOIN.
Comment: I needed to install References (http://drupal.org/project/reference as well for D7, but this is exactly what I was looking for.  Thank you @tostinni
Comment: what if now relationship is needed? for example in most visited content view there are all nodes including the ones which has not been visited till now. this does not need relationship


cd from zsh displays wrong name of cwd (~variable)

Question: I have a shell script that is run via an alias in zsh using alias wd=". /path/to/wd". The script executes a ruby program and cds to the output of it. It works, but after the cd command, the directory shows as "~result" instead of its actual name.
A simplified version of the shell script is as follows
#!/bin/sh

result=$(ruby engine.rb $*)
cd $result

It obviously has to do with the cd using a variable, "result", as that's the name it gets.
If if change to another directory and back the wrong name is still used.
Tried this is bash where it works correctly, so this is a zsh issue.
Comment: No, I'm asking *you* what *you* mean.
Comment: Where does the directory "show"?
Comment: Haha! The directory shows the wrong name in the terminal prompt. In my case it shows `simon ~result $`
Answer: This is caused by the AUTO_NAME_DIRS option (which is not enabled by default):
         AUTO_NAME_DIRS

         Any parameter that is set to the absolute name of a directory
         immediately becomes a name for that directory, that will be used
         by the `%~' and related prompt sequences, and will be available
         when completion is performed on a word starting with `~'.
         (Otherwise, the parameter must be used in the form `~param' first.)

In other words, with AUTO_NAME_DIRS enabled whenever you do something like
project=/path/to/my/project, ~project becomes an abbreviation for /path/to/my/project.
This lets you do things like cd ~project or ls -lh ~project as a shortcut for that directory.
If you just don't like the directory being displayed as ~project in your prompt, you can
replace %~ with %d in your prompt to always display the full path.
If you don't want this behavior at all, do unsetopt AUTO_NAME_DIRS in your config.
If you want to keep the option on, but disable it inside your script so it doesn't make result a named dir, do emulate -LR zsh at the top of your script. This temporarily resets all options to their defaults while the script runs. It's best practice to always use emulate -LR zsh in scripts to prevent weird things like this from happening. This is better than doing unhash -d result to fix it after the fact.
Comment: perfect, I used `%d` for the prompt. `unsetopt AUTO_NAME_DIRS` did not really work.
Answer: This appears to be a case of a static named directory being used. Because the value of result is a path (presumably) beginning with /, zsh is using that variable as the "name" of the path and abbreviating it when it displays the full path in your prompt. See man zshexpn under "Static named directories" for details.
Comment: Awesome! The solution was to remove with `unhash -d result`
Comment: That man page is huge! Do you know if the conclusion that I should accept it or is there a chance of a workaround?
Comment: You might be able to remove `result` from the named directory hash table with `hash -d result`.


Como transformar String de hora para um inteiro?

Question: Exemplo, recebo uma String com a hora do dia "16:20".
O dia tem 1440 minutos. Como saber em qual intervalo de zero a 1440 está esta hora? Num valor inteiro(integer).
Answer: Creio que não precise de uma classe como Calendar para resolver, basta um split e fazer uma operação matemática, assim:
String horacompleta = "12:39";
String[] horamin = horacompleta.split(":");

int hora = Integer.parseInt(horamin[0]);
int min = Integer.parseInt(horamin[1]);

int minutos = (hora * 60) + min; //Pega o total

Pode colocar em uma função assim:
public static int hour2minutes(String fullhour)
{
    String[] parts = fullhour.split(":");

    int hour = Integer.parseInt(parts[0]);
    int min = Integer.parseInt(parts[1]);

    return (hour * 60) + min;
}

E para usar, faça assim:
hour2minutes("12:39"); //759
hour2minutes("16:20"); //980
hour2minutes("23:59"); //1439

Veja um teste no IDEONE: https://ideone.com/amkZW8
Answer: Exitem várias formas de fazer isso. Outra além do Guilherme seria, por exemplo usando o SimpleDataFormat para converter a string em formato de data, e depois usar a classe TimeUnit convertendo milissegundos em minutos usando o método toMinutes(). Veja como ficaria:
public int hour2min(String hour) {
    try {
        Date date = new SimpleDateFormat("kk:mm").parse(hour);
        return (int) (TimeUnit.MILLISECONDS.toMinutes(date.getTime())-180);
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }
}

Para usar basta fazer assim:
Log.wtf("",""+hour2min("18:23"));

Saída:
1103

Comment: Muito bom este porque ele valida os dados de entrada +1
Comment: @GuilhermeNascimento peguei o nome da função lá da sua sugestão: "hour2min" -utes


Questions re: Gmail Sidebar Gadget Deprecation

Question: We stumbled across a deprecation notice for the Gmail sidebar gadgets at https://developers.google.com/gmail/sidebar_gadgets which states that

Warning: Gmail sidebar gadgets are now deprecated and will soon cease to be supported.

This statement and the website are unclear and we cannot find any deprecation notice with specific dates and impact.
Additionally, since the add gadget by URL lab was deprecated, most of this page can't be used anyway.
However, we deployed a gadget via the marketplace which is crucial to our operation of Google Apps because of the Google Apps 50K contacts limit.
I've submitted a ticket to the GWSC with the following questions but I figured I would mention it here as well since we are a bit shocked to have stumbled on this notice and that it hasn't been shared via any channels we have found.  Perhaps I missed it?

Does this sidebar_gadget deprecation apply to marketplace apps such as the one USAID wrote and is using?
Can you please point me to the official deprecation notice and especially the date of impact?
What will be replacing the sidebar gadget as this is an integral part of our day to day use of Google Apps?

Any input appreciated as I'm specifically worried that Google did not anticipate people doing things with sidebar in marketplace apps and when they took away the gadget by URL lab, they thought they killed the only avenue to using these gadgets.  Hopefully, I'm worried for naught and marketplace apps are fine but...
Regards,
KAM
Answer: Google usually perform spring-cleanings. Usually announces around march-april which features will be removed, and by july-august performs removal. However marking a feature as deprecated does not necesarilly mean immediate removal.
Also, maybe this is related to Google G-suite marketplace: https://gsuite.google.com/marketplace/
BTW: in any situation, combine something that "is crucial to our operation" and something that depends on a closed SaaS or cloud plattform it's usually not a good idea, except if your data/services/developments can be moved to other platformS.


PowerShell - Export to Excel - How to Add Column for File Name

Question: My code currently goes through a list of folders/subdirectories looking for '.csproj' files. The properties "Include" and "Version" are taken from the found .csproj file(s) and are exported to an excel sheet. While this works and I do get two columns for each property, I need to show the name of the file that each excel row entry belongs too. I haven't been able to find an approach to this. So in my final excel sheet, I need 3 rows: Include, Version, NameOfTheFile.
Through troubleshooting I added "$xml.name" after the line "Select-Object -Property Include, Version" and this added spaces in the excel sheet between each batch of properties. That's somewhat helpful, but the name of the files would be far more sufficient.
$Directory = Get-ChildItem C:\Repos\Common\Caching\src -Directory
$ErrorFiles = [System.Collections.Generic.List[string]]::new()

$result = foreach ($d in $Directory) {
    Write-Host "Working on directory $($d.FullName)..."
    $folders = Get-ChildItem -Path $d.FullName -File -Recurse -Filter *.csproj
    foreach($folder in $folders) {
        try {
            $xml = [xml](Get-Content $folder.FullName -Raw)
            $xml.SelectNodes("/Project/ItemGroup/PackageReference") |
            Select-Object -Property Include, Version
            $xml.Name

        }
        catch {
            Write-Warning $_.Exception.Message
            $ErrorFiles.Add($folder.FullName)
        }
    }
}

$result | Export-Excel -Path C:\Temp\ExampleExcel.xlsx -AutoSize -AutoFilter

Answer: You can use a calculated property with Select-Object, the only change you would need to do is this:
$xml.SelectNodes("/Project/ItemGroup/PackageReference") |
Select-Object -Property Include, Version
$xml.Name

For this:
$xml.SelectNodes("/Project/ItemGroup/PackageReference") |
Select-Object -Property Include, Version, @{
    Name = 'NameOfTheFile'
    Expression = { $folder.Name } # => this is a file though
}


How do I call the Pie function?

Question: I have the center point, radius, and angle to draw the pie, but the Pie function takes 4 points as input data. Does anyone have any conversion function or better explanation for this?
Answer: The four points in the pie function:

Upper left corner of the bounding rectangle.
Lower right corner of the bounding rectangle.
Point on the circle that marks the beginning of the pie.
Point on the circle that marks the end of the pie (counter clockwise).

Conversion:
Centerpoint: Cx, Cy
Radius: r
Angle: a
Assuming your pie starts at the top.

X1 = Cx-r, Y1 = Cx+r
X2 = Cx+r, Y2 = Cy-r
X3 = Cx,   Y3 = Y1
X4 = Cx + r sin(a), Y4 = Cy + r cos(a)

You might have to flip a sign somewhere, but this should do the trick.
With two different angels (a and b):

X3 = Cx + r sin(a), Y3 = Cy + r cos(a)
X4 = Cx + r sin(b), Y4 = Cy + r cos(b)
Comment: this draws a pie from zero to angle A, where does the angle B come so we have a pie from A to B?
Answer: This is written in (old) C++, but most of it should convert to Delphi (or almost anything else) pretty easily. It also assumes the inputs are in percentages (a full circle is 100%) instead of raw angles, but (again) that should be pretty easy to deal with. It has a conversion from percentage to angle in radians, so a conversion from other units should be a pretty trivial adjustment.
class section {
    double percent;
    int color;
public:

    section(double percent_, int color_) :
        percent(percent_), color(color_) {}

    void draw(HDC destination, POINT const &center, int diameter, double &start_angle);
};

void section::draw(HDC destination, POINT const &center, int radius, double &start_angle) {

    double start_x, start_y, end_x, end_y;
    double angle, end_angle;

    int top = center.y - radius;
    int bottom = center.y + radius;
    int left = center.x - radius;
    int right = center.x + radius;

    // now we have to convert a percentage to an angle in radians.
    // there are 100 percent in a circle, and 2*PI radians in a
    // circle, so we figure this percentage of 2*PI radians.
    angle = percent / 100.0 * 2.0 * 3.1416;

    end_angle = start_angle + angle;

    // Now we have to convert these angles into rectangular
    // coordinates in the window, which depend on where we're
    // putting the chart, and how big we're making it.
    start_x = center.x + radius * cos(start_angle);
    start_y = center.y + radius * sin(start_angle);

    end_x = center.x + radius * cos(end_angle);
    end_y = center.y + radius * sin(end_angle);

    // Now we need to actually draw the pie section by selecting
    // the correct color into the DC, drawing the section, then
    // selecting the original brush back, and deleing our brush.
    HBRUSH brush = CreateSolidBrush(color);

    HBRUSH old_brush = (HBRUSH)SelectObject(destination, brush);

    Pie(destination, left, top, right, bottom,
        (int)start_x, (int)start_y, (int)end_x, (int)end_y);

    SelectObject(destination, old_brush);
    DeleteObject(brush);

    // our sole awareness of other sections: the next section will
    // start wherever we finished.
    start_angle = end_angle;
}

How do I call the Pie function?


Show that normal distribution has 0 mean and unit variance

Question: For a normal distribution,
$$\phi(x)=\frac{1}{\sqrt{2\pi\sigma^2}}\times e^{\frac{-1(x-\mu)^2}{2\sigma^2}}$$
Question:Prove that the standard normal distribution has 0 mean and unit variance?
Answer: Lemmas we will use before we begin:
If $f(x) = -f(-x)$ then $\int_a^a f(x) dx = 0 $ for any $a \in \mathbb{R} $
Mean
$\mathbb{E}[X] = \int_{\mathbb{R}} xf_X(x) dx$
Using lemma above and noticing that $xf_X(x)$ satisfies the property above we are done for zero mean.
Variance
$\mathbb{V}[X] = \mathbb{E}[X^2] - \mathbb{E}[X]^2 = \mathbb{E}[X^2]$ as $\mathbb{E}[X] = 0 $
Hence $\mathbb{V}[X] = \int_{\mathbb{R}} x^2f_X(x) dx = 1$


Is the convergence in "the topology of pointwise convergence" for sequences or nets?

Question: The topology of pointwise convergence on $Y^X$, where $Y$ is a topological space and $X$ is a set, is defined to be the topology  that topologize the pointwise convergence of mappings from $X$ to $Y$.
In the definition, I was wondering if the pointwise convergence here is for all nets of mappings or all sequences of mappings? I am thinking it is the former, but in what I have seen sequences are mentioned all the time in a non-definition context that a sequence converges wrt the topology of pointwise convergence iff the sequence converges pointwise.
Or when specifying the topology of pointwise convergence, one has to also specify whether the convergence is for nets or sequences? If nets or sequences are not specified, which one is the default?
Thanks and regards!
Answer: The topology $\mathcal{T}$ of pointwise convergence on $Y^X$ is defined as the initial topology with respect to the projections $(\pi_x)_{x \in X}$ where $$Y^x \ni f \mapsto \pi_x(f) := f(x) \qquad (x \in X)$$
Let $(f_{\iota})_{\iota \in I}$ a net in $Y^X$ and $f \in Y^X$. Then $f_\iota \to f$ in $(Y^X,\mathcal{T})$, if and only if, $$\forall x \in X: \underbrace{\pi_x(f_\iota)}_{f_\iota(x)} \to \underbrace{\pi_x(f)}_{f(x)}$$ i.e. if the net is pointwise convergent. This fact can be easily concluded from the following theorem.

Let $X$ a non-empty set and $((X_\kappa,\mathcal{T}_\kappa))_{\kappa \in K}$ a family of topological spaces. Let $f_{\kappa}: X \to X_{\kappa}$ a mapping ($\kappa \in K$) and denote by $\mathcal{T}$ the initital topology with respect to $(f_\kappa)_{\kappa \in K}$. Then the following statements are equivalent for a given net $(x_\iota)_{\iota \in I}$ in $X$ and $x \in X$:

$x_\iota \to x$ in $(X,\mathcal{T})$
$\forall \kappa \in K: f_\kappa(x_\iota) \to f_\kappa(x)$ in $(X_\kappa,\mathcal{T}_\kappa)$
Comment: Thanks! I understand you define the topology of ptwise cvg to be the product topology. My definition (in my first and second paragraph) is different, and is in terms of topologizing a given family of nets or sequences together their respective "limits". My question was if the given family is of nets or of sequences. Although your reply doesn't address my question directly, I guess the answer to my question is nets instead of sequences?
Comment: @Tim I'm not sure whether I understand you correctly. What do you mean by "topologozing a given family of nets or seq. together their respective "limits""? You wrote nothing abot families of nets/seq. in your post above at all. Do you want to define a topology $\tau$ on $Y^X$ such that $f_n \to f$ in $(X,\tau)$ iff $f_n \to f$ pointwise ... and asking whether this equivalence then also holds for nets? (By the way, it's not only "my definition" of topology of ptw. cvg. - it's probably the most [popular](http://en.wikipedia.org/wiki/Pointwise_convergence#Topology) one.)
Comment: "Do you want to define a topology $τ$ on $Y^X$ such that $f_n→f$ in $(X,τ)$ iff $f_n→f$ pointwise" yes, that is what I meant, except that I am asking whether $f_n$'s are any net or sequence. "asking whether this equivalence then also holds for nets?" Not really, as I mentioned, my question of whether it is about nets or sequences comes before finding the topology on $Y^X$ not after finding one.
Comment: @Tim As Henno Brandsma already pointed out it doesn't suffice to ask for pointwise convergence of sequences to define a unique topology. That's why on defines the topology using projections (which leads to pointwise convergence of nets).
Answer: If you want to define a unique topology, then you cannot stop at sequences. You should define net convergence, and a net convergence can define a topology (if it satisfies the 4 Kelly conditions etc.).
If you just postulate that all sequences converge in $X^Y$ iff they do pointwise, then this does not define a unique topology.
To see this, let $Y$ be the co-countable topology on $\mathbb{R}$, let $X = \{0,1\}$ for concreteness. Then the pointwise convergence (from nets, or per convention, as the initial topology) is just the product topology of 2 co-countable spaces. A sequence converges in it, iff it is eventually constant (in both coordinates, and so overall). But the discrete topology on $Y \times Y$ (as sets) has the exact same behaviour with respect to convergence of sequences, and so do all topologies that lie inbetween them. So we have many topologies on $Y^X$ that have the behaviour that sequences converge iff they converge pointwise.
So the sequence variant cannot function as the definition. It is a nice property to have, but not enough to define the topology. If you really want to do it via that route, then you have to use nets, there is no escaping that.
Comment: Thanks! In the same spirit,  when talking about the topology of uniform convergence and the topology of compact convergence, are the convergences in both cases also for nets? If the convergences are for sequences, they cannot uniquely determine their topologies?
Comment: I suspect so. But with uniformities one does not specify just convergence but uniform convergence. And I'm not aware (but this is just my ignorance!) of a Kelly like theory for when a "uniform convergence space" uniquely defines a uniformity (and not just a topology; note that in general a topological space can have many compatible uniformities, just like a metrizable space and metrics)


Is it appropriate to treat n-point Likert scale data as n trials from a binomial process?

Question: I've never liked how people typically analyze data from Likert scales as if error were continuous & Gaussian when there are reasonable expectations that these assumptions are violated at least at the extremes of the scales. What do you think of the following alternative:
If the response takes value $k$ on an $n$-point scale, expand that data to $n$ trials, $k$ of which have the value 1 and $n-k$ of which have the value 0. Thus, we're treating response on a Likert scale as if it is the overt aggregate of a covert series of binomial trials (in fact, from a cognitive science perspective, this is actually an appealing model for the mechanisms involved in such decision making scenarios). With the expanded data, you can now use a mixed effects model specifying respondent as a random effect (also question as a random effect if you have multiple questions) and using the binomial link function to specify the error distribution.
Can anyone see any assumption violations or other detrimental aspects of this approach?
Comment: Do you know of any published research that looks at the relative merits of using likert scales as intervals vs ordinal data? Perhaps, the flaws of treating them as interval level scales are not serious enough to warrant a complex approach. If that is the case then your approach may simply be a wild goose chase.
Answer: I don't know of any articles related to your question in the psychometric literature. It seems to me that ordered logistic models allowing for random effect components can handle this situation pretty well.
I agree with @Srikant and think that a proportional odds model or an ordered probit model (depending on the link function you choose) might better reflect the intrinsic coding of Likert items, and their typical use as rating scales in opinion/attitude surveys or questionnaires.
Other alternatives are: (1) use of adjacent instead of proportional or cumulative categories (where there is a connection with log-linear models); (2) use of item-response models like the partial-credit model or the rating-scale model (as was mentioned in my response on Likert scales analysis). The latter case is comparable to a mixed-effects approach, with subjects treated as random effects, and is readily available in the SAS system (e.g., Fitting mixed-effects models for repeated ordinal outcomes with the NLMIXED procedure) or R (see vol. 20 of the Journal of Statistical Software). You might also be interested in the discussion provided by John Linacre about Optimizing Rating Scale Category Effectiveness.
The following papers may also be useful:

Wu, C-H (2007). An Empirical Study on the Transformation of Likert-scale Data to Numerical Scores. Applied Mathematical Sciences, 1(58): 2851-2862.
Rost, J and and Luo, G (1997). An Application of a Rasch-Based Unfolding Model to a Questionnaire on Adolescent Centrism. In Rost, J and Langeheine, R (Eds.), Applications of latent trait and latent class models in the social sciences, New York: Waxmann.
Lubke, G and Muthen, B (2004). Factor-analyzing Likert-scale data under the assumption of multivariate normality complicates a meaningful comparison of observed groups or latent classes. Structural Equation Modeling, 11: 514-534.
Nering, ML and Ostini, R (2010). Handbook of Polytomous Item Response Theory Models. Routledge Academic
Bender R and Grouven U (1998). Using binary logistic regression models for ordinal data with non-proportional odds. Journal of Clinical Epidemiology, 51(10): 809-816. (Cannot find the pdf but this one is available, Ordinal logistic regression in medical research)
Comment: Mixed effects ordinal logistic regression is also available in R with the ordinal package and clmm().
Answer: If you really wish to abandon the assumption of interval level data for likert scales I would suggest that you assume the data to be a ordered logit or probit instead. Likert scales usually measure strength of response and hence higher values should indicate a stronger response on the underlying item of interest.
Suppose that you have a $H$ item scale and that $S$ represents the unobserved strength of response on the item of interest. Then you can assume the following response model:
$y = 1$ if $S \le \alpha_1$
$y = h\ $  if $\alpha_{h-1} < S\  \le \alpha_h$ for $h = 2, 3, ..H-1$
$y = H\ $  if $\alpha_{H-1} < S  <\  \infty$
Assuming that $S$ follows a normal distribution with an unknown mean and variance would give a ordered probit model.
Answer: One concern would be that by using this approach you're imposing a specific relationship between the mean $np$ and the variance $np(1-p)$ of the response. For the kind of surveys Likert scales are often used in - e.g. you choose one of five categories from between "Strongly agree" to "Strongly disagree" with respect to some statement or other - it feels wrong to me. For instance I'd expect a ten-point scale to give roughly the same distribution of responses as a five-point scale if you collapse adjacent pairs of categories: for a response $y$ & common $p$ $$\Pr_{n=4}(Y=y)\neq\Pr_{n=9}(Y=2y)+\Pr_{n=9}(Y=2y+1)$$ I recall some research that seems to bear this out: Coelho & Esteves (2006), "The choice between a five-point and a ten-point scale in the framework of customer satisfaction measurement".
Answer: You could use the binomial approximation in a 5-pt Likert scale if you combined the agree and strongly agree into one group & the disagree and strongly disagree into another.  Of course, you still need to decide where the neutrals go.  I would put the neutrals in any one group, use the normal approximation to the binomial (provided you have more than 40 responses), and develop confidence intervals on the proportions of each group (see any standard stat. text on how to get conf. intervals on proportions coming from a binomial distribution with the normal approximation).  Then, I would put the neutrals in the other group, and redo the confidence intervals. If I get the same conclusion from both, then there is a potential conclusion.  Otherwise, I don't see how the binomial can be used with Likert data.
Answer: If I understood correctly, this paper suggests a very similar approach to what you have described, suggesting that yes, indeed, Likert-like data can arise from a binomial process.
Full Ref: Allik, J. (2014). A mixed-binomial model for Likert-type personality measures. Frontiers in Psychology, (5) 371
Comment: Welcome to the site! Could you add a full reference for that paper? It's standard practice here because links tend to go dead.
Answer: Actually I am preparing a paper in which I am using your approach of treating a response on a likert item as if it is the overt aggregate of a covert series of binomial trials.
In my paper the binomial distribution is used in order to explain the shape
of the observed frequency distributions. The rationale behind this approach is given by two assumptions. In many applets, showing how the binomial distribution comes into existence, one has repeated independent Bernoulli trials by a single ball falling through an array of pins. Each time a ball falls onto a pin, it will bounce to the right (i.e. a success) with probability p or to the left (i.e. a failure) with probability 1-p. After the ball falls through the array, it lands in a bin labeled by the corresponding number of successes. In my paper the process of decision making is also seen as a series of repeated independent Bernoulli trials in which, at each trial, the subject decide to agree or not to agree to the statement in question. The two assumptions read as follows.
(i) At each independent Bernoulli trial the subject makes a decision to agree with probability p or not to agree (disagree) with probabiliity 1-p.
(ii) If five categories of response are available for the statement, then the number of times a Bernoulli decision is made regarding the decision to agree or not to agree (disagree) is equal to 4 (5-1).
The final choice for a specific response category is given by the following rules.

If in all (four) cases a Bernoulli decision of agreement is made, then the response 'strongly agree' will be given.
If in three cases a Bernoulli decision of agreement is made, then the response 'agree' will be given.
If in two cases a Bernoulli decision of agreement is made, then the response 'undecided' will be given.
If in only one case a Bernoulli decision of agreement is made, then the response 'disagree' will be given.
If in no case a Bernoulli decision of agreement is made, then the response 'stronglly disagree' will be given.

A similar reasoning can be given using 'disagree' decisions.
In order to obtain a binomial distribution, the scoring of the response categories is as follows.
strongly disagree = 0, disagree = 1, neutral = 2, agree = 3, strongly agree = 4
These two assumptions lead to a binomial distribution for the response frequencies provided that there are no systematic differences between the respondents.
I hope you can agree. I would appriciate very much if you could improve my english in the above text.
Comment: This is an interesting & creative proposal, but I'm skeptical of it. In both your version & in ordinal logistic regression as suggested, eg, by others on this thread will require the proportional odds assumption. However, OLR will allow the thresholds / cutpoints b/t the categories to vary more flexibly, I believe, whereas they will be determined by the binomial parameters $p$ & $n$ in your scheme. This assumption would have to be verified against the data, & I suspect, would lead to problems. (BTW, the -1 did not come from me.)
Comment: I have removed your older reply. Please note that my comment was not intended as a negative remark; one-line replies are generally not very informative and arguable answers are to be preferred (but see our [FAQ](http://stats.stackexchange.com/faq)).


Why is $1=\mathbb{P}_i(\bigcup_{n\geq k}\left\{X_n=i\right\})=1$ for any $k\in\mathbb{N}$?

Question:

Let $(X_n)_{n\in\mathbb{N}_0}$ be an irreducible and recurrent Markov chain with state space $E$ and Transition Matrix $P$. Then it is $1=\mathbb{P}_i(\limsup_{n\to\infty}\left\{X_n=i\right\})$ for all $i\in E$, where
    $$
\mathbb{P}_i(\limsup_{n\to\infty}\left\{X_n=i\right\})=\mathbb{P}(\limsup_{n\to\infty}\left\{X_n=i\right\}|X_0=i).
$$

Using the Definition of the limes superior and the continuity of measures it is
\begin{align}
1&=\mathbb{P}_i(\limsup_{n\to\infty}\left\{X_n=i\right\})\\
&=\mathbb{P}_i(\bigcap_{k=0}^{\infty}\underbrace{\bigcup_{n\geq k}\left\{X_n=i\right\}}_{\downarrow\text{ in }k})\\
&=\lim_{k\to\infty}\mathbb{P}_i(\underbrace{\bigcup_{n\geq k}\left\{X_n=i\right\}}_{\downarrow\text{ in }k})\\
&\implies 1=\mathbb{P}_i(\bigcup_{n\geq k}\left\{X_n=i\right\})~\text{ for any }k\in\mathbb{N}.
\end{align}
To be honest, I do not understand the last implication. Could you please tell my why this implication follows?
Comment: You could sure check how your questions was displayed in the browser before posting it.
Comment: @barakmanos Sorry, I corrected it, now it is displayed in the right way.
Answer: The definition of recurrent is that given any initial starting position $x_k$ the probability that $X$ will return to $x_k$ is $1$. This is exactly that the event $\{X_n=x_0\}$ will occur for some $n>k$.
Comment: Not exactly--the difference being any return vs some return after some given time.
Comment: To be honest, I still cannot see why from $1=\lim_{n\to\infty}\mathbb{P}_i(\bigcup_{n\geq k}\left\{X_n=i\right\})=1$ and $\bigcup_{n\geq k}\left\{X_n=i\right\}$ decreases in $k$ it follows that $\mathbb{P}_i(\bigcup_{n\geq k}\left\{X_n=i\right\})=1$ for any $k\geq 1$.


Custom MigrateMap to sync by field or property, e.g. SKU

Question: Existing situation: MigrateSQLMap
Normally with migrate API, a migration will use MigrateSQLMap to identify imported rows with existing entities.
This means: A database table named like migrate_map_* will be created for each migration. The * part of the table name is based on the migration machine name. This table associates primary key of the source data (e.g. a primary key column of a csv file) to entity ids.
Whenever a row is to be imported, Migrate API will look into the respective migrate_map_* table, and check if a row with this id was already imported, and if the imported entity still exists. If it does, it will update this existing entity, and update the value last_imported in the migrate map table. If it does not, it will create a new entity, and create a new entry in the migrate_map_* table.
What I want instead: Map to existing entities.
Now what if instead of creating new entities, I would like to update existing entities which were previously created with another mechanism, unknown to Migrate API? E.g. these might have been created manually, or with a home-grown migration script.
In my case, these entities are commerce products, which were created with a custom script which is to be replaced with Migrate API.
The idea is:

Compute an SKU from the imported csv row.
Find out if a product with this SKU already exists.

If yes, update.
If no, create a new product.

If possible, save the import timestamp somewhere.

Solutions I can think of so  far
I can imagine two possible solutions.

A custom migrate map class SkuMigrateMap extends MigrateMap.
Seeing how many abstract methods MigrateMap has, this could be quite a lot of work.
Use MigrateSQLMap, but prefill the table based on existing products.

Question
Is there an existing or recommended solution for this somewhere?
Answer: The map class doesn't (and shouldn't) know anything about either your source or your destination - its job is simply tracking the relationships between their keys.
I've done this in the migration's prepareRow(), doing an explicit lookup for a matching destination object, and if found saving that destination ID to the map and returning FALSE to prevent further processing. Look at how migrate_d2d maps user accounts based on email:
// On initial import, if this email address already exists, just map to the
// existing uid and don't allow it to be deleted. When updating, we can
// take the existing uid from the map instead of querying for it. Make sure
// when updating an imported user that we don't apply this logic.
if (empty($row->migrate_map_destid1)) {
  $new_uid = db_select('users', 'u')
             ->fields('u', array('uid'))
             ->condition('mail', $row->mail)
             ->execute()
             ->fetchField();
  // If we haven't mapped the admin account based on email address, map it
  // directly to the destination admin account.
  if (!$new_uid && $row->uid == 1) {
    $new_uid = 1;
  }
}
elseif ($row->migrate_map_needs_update == MigrateMap::STATUS_IGNORED &&
        $row->migrate_map_rollback_action == MigrateMap::ROLLBACK_PRESERVE) {
  $new_uid = $row->migrate_map_destid1;
}

if (!empty($new_uid)) {
  $hash = isset($row->migrate_map_hash) ? $row->migrate_map_hash : NULL;
  $this->map->saveIDMapping($row, array($new_uid), MigrateMap::STATUS_IGNORED,
    MigrateMap::ROLLBACK_PRESERVE, $hash);
  $this->rollbackAction = MigrateMap::ROLLBACK_PRESERVE;
  return FALSE;
}

Comment: Ok! This looks promising. I will give it a try.
Comment: Is there any reason this variable is named `$new_uid`? It really is the uid of an existing user, so it is not really new is it?
Comment: True - I don't recall how it acquired the name $new_id when I wrote it years ago.
Comment: Ok, now next problem: On rollback, the updated entities are deleted, instead of the old revision being restored.
Comment: See https://www.drupal.org/node/2778639
Comment: Hmmm one thing I don't understand: The $this->map->saveIDMapping() happens even if the row already has $row->migrate_map_destid1. If I understand correctly this means that the mapping already exists. Why then save it again? It does not really change does it?
Comment: I had to do it differently.. does the code in the other answer look reasonable?
Answer: I found that in my case I had to do it a little differently than Mike Ryan suggests. This is not a right vs wrong, it simply depends on the intended behavior.
The problem was that with Mike Ryan's solution the existing legacy products would have been left as they are and not updated.
The solution below is actually easier. It does not require to create a migrate mapping from this user code. Instead all you do is set $row->migrate_map_destid1 = $existing_product_id.
Note that all the lines dealing with revision messages are not really necessary, but I find them useful.
Also note that this solution is not setting $this->rollbackAction = MigrateMap::ROLLBACK_PRESERVE. This would prevent the updated legacy products from being rolled back. More on this further below, step II.
Step I: Modifications to the migration class.
class MyMigration extends MigrationBase {

  /**
   * @var int[]
   *   Format: $[$sku] = $product_id
   */
  private $productIdsBySku;

  /**
   * @param array $arguments
   */
  function __construct(array $arguments) {
    [..]
    $this->productIdsBySku = db_select('commerce_product', 'cp')
      ->fields('cp', array('sku', 'product_id'))
      ->execute()
      ->fetchAllKeyed();
    [..]

    // The following only makes sense if you continue reading further below, step II.
    $this->destination = new MyMigrateDestination();
  }

  function prepareRow($row) {

    if (!parent::prepareRow($row)) {
      return FALSE;
    }

    $sku = $this->rowBuildSku($row);

    if (isset($this->productIdsBySku[$sku])) {
      // Product with same sku exists.
      $existing_product_id = $this->productIdsBySku[$sku];
      if (empty($row->migrate_map_destid1)) {
        // Product exists, but is NOT in the migrate map.
        $row->migrate_map_destid1 = $existing_product_id;
        $row->revision_log_message = 'Migrate: Update legacy product.';

      }
      // Possibly comparing string vs integer, so using == and not ===.
      elseif ($row->migrate_map_destid1 == $existing_product_id) {
        // Product exists, and is in the migrate map, with correct id.
        $row->revision_log_message = 'Migrate: Update already-imported product.';
      }
      else {
        // Crazy case: Product is mapped, but to wrong id.
        // This means that something went wrong in the past.
        // @todo Log this problem?
        return FALSE;
      }
    }
    else {
      // Product with this SKU does not exist yet.
      if (empty($row->migrate_map_destid1)) {
        // This is really a new product.
        $row->revision_log_message = 'Migrate: Create new product.';
      }
      else {
        // The migrate map suggests this is an update. But the product to be
        // updated does not exist. Weird.
        // Let migrate module decide what to do.
        $row->revision_log_message = 'Migrate: Create product, which was already mapped.';
      }
    }

    return TRUE;
  }

  function prepare(\stdClass $product, \stdClass $row) {
    [..]
    if (isset($row->revision_log_message)) {
      $product->log = $row->revision_log_message;
    }
    [..]
  }

Now, this solution still has a problem.
On rollback, the updated legacy products will be deleted instead of reverting to the old pre-migrate revision.
Step II: Custom migrate destination class.
Solution: A custom migrate destination class with an overridden bulkRollback method. (Actually in the code above I cheated, and it already contains the code to add this destination in the migration class.)
This overridden bulkRollback() decides for each product (entity) to be rolled back whether it should be deleted or an old revision restored.
It uses a heuristic to find an old revision, but this only works in my own special case. You likely need to do something else! More about this further below, step III.
class MyMigrateDestination extends \MigrateDestinationEntityAPI {
  [..]

  /**
   * @param int[]|string[] $ids
   *
   * @return bool
   */
  public function bulkRollback(array $ids) {
    migrate_instrument_start(__METHOD__);
    $this->prepareRollback($ids);

    $q = db_select('commerce_product_revision', 'cpr');
    $q->condition('cpr.product_id', $ids);

    // @todo You need to be creative and find a different criterion here.
    $q->condition('cpr.type', 'product');

    $q->fields('cpr', array('product_id', 'revision_id'));
    $q->orderBy('cpr.revision_timestamp');
    // This gets the youngest revision.
    $rvids_by_id = $q->execute()->fetchAllKeyed();

    migrate_instrument_start('revert revisions');
    foreach ($rvids_by_id as $product_id => $revision_id) {
      $entity = entity_revision_load('commerce_product', $revision_id);
      if (FALSE === $entity) {
        unset($rvids_by_id[$product_id]);
        continue;
      }
      $entity->revision = TRUE;
      $entity->log = "Revert via migrate rollback.";
      entity_save('commerce_product', $entity);
    }
    migrate_instrument_stop('revert revisions');

    $ids_to_delete = array_diff($ids, array_keys($rvids_by_id));

    migrate_instrument_start('entity_delete_multiple');
    $deletion_success = FALSE !== entity_delete_multiple($this->entityType, $ids_to_delete);
    migrate_instrument_stop('entity_delete_multiple');

    $this->completeRollback($ids);
    migrate_instrument_stop(__METHOD__);

    return $deletion_success;
  }

}

Part III: Criterion for finding the old pre-migrate revision.
Now there is one piece of homework left for the esteemed reader.
The query above relies on a specificity of my personal use case. In my personal own use case, the migration would change the bundle of legacy entities. This makes it easy to distinguish between revisions before and after the migration was introduced.
    $q->condition('cpr.type', 'product');

However, even with this specificity, this only works because I "hacked" the commerce_product_revision table by adding a "bundle" column, using a module I cooked up for this purpose. I suspect that this is a rather exotic scenario.
Now you need to figure out another way to distinguish product revisions from before and after the migration, and work it into the query.


exp(A+B) = exp(A)exp(B) for matrices proof

Question: In this thread, On the proof: $\exp(A)\exp(B)=\exp(A+B)$ , where uses the hypothesis $AB=BA$?, it was mentioned that absolute convergence is required for swapping sums. What theorem is used precisely?
Answer: I think actually absolute convergence is only mentioned in the original question that is linked in the question you linked: https://math.stackexchange.com/a/356763/688699
Anyway if you're talking about rearranging an infinite sum then this is just the Riemann Series Theorem.
In particular (quoting from Wikipedia) let $X$ be a topological vector space. For example, this could be an additive matrix group, which we can see as $\mathbb{R}^{n}$ for some $n$. Then a series $\sum_{n=0}^{\infty} x_{n}$ is called unconditionally convergent if it converges to some point $x\in X$ and any rearrangement of the order of summation produces a series converging to $x$ also.
Then the Reimann Series Theorem says that, for $X=\mathbb{R}^{n}$, a series is unconditionally convergent if and only if it is absolutely convergent.
For more details see: https://en.wikipedia.org/wiki/Unconditional_convergence
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/1413770)
Comment: @MattSamuel I have added the details from the link


How do I interpret unmet dependencies error messages?

Question: We recently discovered that our clients are running into issues when installing Drupal using our custom default profile. I managed to fix some initial errors like missing libraries, but this other problem stumped me.

Drupal\Core\Config\UnmetDependenciesException: Configuration objects provided by custom_profile have unmet dependencies: core.entity_form_display.media.document.default (field.field.media.document.field_document, field.field.media.document.field_media_in_library, media.type.document), core.entity_view_display.node.page.default (field.field.node.page.field_content_keywords, field.field.node.page.field_header_image, field.field.node.page.field_header_video_url,
field.field.node.page.field_hide_overlay_title,
field.field.node.page.field_meta_tags,
field.field.node.page.field_secondary_title,
field.field.node.page.field_social_media_image,
field.field.node.page.field_title_link,
field.field.node.page.field_title_placement,
field.field.node.page.layout_builder__layout,
metatag),
filter.format.rich_text_editor_limited (entity_embed), pathauto.pattern.default_media_pattern (pathauto)
in Drupal\Core\Config\UnmetDependenciesException::create() (line 100 of core/lib/Drupal/Core/Config/UnmetDependenciesException.php).
Drupal\Core\Config\UnmetDependenciesException::create('custom_profile', Array) (Line: 522)
Drupal\Core\Config\ConfigInstaller->checkConfigurationToInstall('module', 'custom_profile') (Line: 132)
Drupal\Core\ProxyClass\Config\ConfigInstaller->checkConfigurationToInstall('module', 'custom_profile') (Line: 177)
Drupal\Core\Extension\ModuleInstaller->install(Array,) (Line: 83)
Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array,) (Line: 1660)
install_install_profile(Array) (Line: 700)
install_run_task(Array, Array) (Line: 571)
install_run_tasks(Array, NULL) (Line: 118)
install_drupal(Object) (Line: 48)

I searched our code base for the files listed above. The core.entity_* files are located in the /profiles/custom/custom_profile/config/install directory, but the field.field.node.page.* files are all in the /modules/custom/custom_core/config/install directory.
Which of those files does Drupal think are missing, the core.entity.* files or the fields in the parenthesis?
Answer: The dependencies in parentheses are the ones the exception is reporting as missing.
Comment: But their yml files are there in the codebase, just in the module directory. Maybe it doesn't know to look for those there?
Comment: I think I've answered the question as written. Obviously there are more questions to ask.


On the Grothendieck ring of varieties

Question: The Grothendieck group of varieties $K_0(\textrm{Var}_k)$ over a field $k$ is the Abelian group generated by isomorphism classes of quasi-projective $k$-varieties, subject to the scissor relation (under which $[Y]=[Z]+[Y\setminus Z]$ for every closed subvariety $Z$ of a variety $Y$). It actually is a ring with product given by $[X]\cdot [Y]=[X\times_k Y]$.
I am trying to better understand this ring, and I have some questions on it:

How can one prove that the generating set (of isomorphism classes of quasi-projective $k$-varieties) is actually a set and not a proper class?
Is $[\emptyset]$ in this ring? It seems to be the only reasonable choice for an (additive) identity element. What is the additive inverse $-[Y]$ of a generator $[Y]\in K_0(\textrm{Var}_k)$?
Not every $A\in K_0(\textrm{Var}_k)$ is represented by a variety. How do we write explicitly such an element?

I accept any suggestion on how to think about this ring. Thank you!
Answer:
They can all be seen as subschemes of some $\mathbb{P}^n$, hence of $\coprod_{n \geq 0} \mathbb{P}^n$. More generally, one can show easily that - up to isomorpism - there is only a set of finite type schemes over $k$.
Sure, $\emptyset$ is projective, and yes, $[\emptyset]$ is the zero in the ring (since $[\emptyset]=[\emptyset]+[\emptyset]$ is a scissor relation). The multiplicative unit is  $[\mathrm{Spec}(k)]$. The additive inverses are introduced formally in this construction of the Grothendieck ring. If $Y$ is a variety, then (usually) $-[Y]$ is not of the form $[Z]$ for a variety $Z$.
I think that $-[\mathrm{Spec}(k)]$ is not the class of a variety. Otherwise $[X]+[\mathrm{Spec}(k)]=[\emptyset]$ for some $X$, but this can certainly not be deduced by any scissor relation (perhaps I will add a more convincing proof later).
Comment: Can someone add a proof for 3.? I have tried several attempts to define a homomorphism from $K_0(\mathrm{Var}_k)$ to a simpler ring such that the classes of varieties get mapped to a proper subring, but didn't succeed so far.
Comment: Dear Martin, thanks for your answer. As for 1-2, I am still wondering how to deal with the convention that $\dim \emptyset=-\infty$... Also, for a variety $Z$, how can $-[Z]$ be the class of a variety? Is there an example in which this happens (and $Z$ is nonempty)?

On the Grothendieck ring of varieties


How to remove the create prefix text when adding new content?

Question: Tried a couple of attempts and no luck with function framework_preprocess
<code>function framework_preprocess_ask_a_question(&$vars, $hook) {
  if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'ask_a_question') {
      $variables['title'] = 'Ask a new question';
   }
}
</code>
Content type is called "Ask a Question" want to change the title from "Create Ask a Question" to "Ask a new question" (removing the create text set by default)
Comment: Is this a template or a form? Which module provides this?
Comment: Its in the template as the community informed me.
Answer: You can use hook_form_FORM_ID_alter().
You could also use hook_form_BASE_FORM_ID_alter() or hook_form_alter() if you preferred or it fit better with your other custom code and requirements.
You would do something like this in a custom module:
<code>/**
 * Implements hook_node_FORM_ID_alter().
 */
function MODULENAME_form_ask_a_qustion_node_form_alter(&$form, &$form_state) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    drupal_set_title('Ask a new question');
  }
}
</code>
Or if you want to do multiple content types:
<code>/**
 * Implements hook_node_BASE_FORM_ID_alter().
 *
 * Alter all node forms.
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    $title = '';
    switch ($form_id) {
      case 'ask_a_qustion_node_form':
        $title = 'Ask a new question';
        break;
      case 'other node type_node_form':
        $title = 'Other title';
        break;
    }
    if ($title) {
      drupal_set_title($title);
    }
  }
}
</code>
There is also the node add title module that allows you to set the title of the add form per content type.
At a quick glance over the code of that module though I see a few issues so I personally wouldn't use it at this stage, although I will open some issues to try to get them fixed.
Comment: I was hoping not to make another custom. But I can make one module with multiple content type each with its own function call right?
Comment: Yeah, or just use hook_form_BASE_FORM_ID_alter() instead and you only need the one function. I updated the answer with an example.


randomization/permutation test for mean > 0

Question: I'd like to know if the following procedure is a valid way to test if the mean of a population is greater than zero, based on a random sample of observations:
1) Calculate the sample mean
2) On each iteration of a large number of iterations, randomly flip or maintain the sign of each observation and recompute the mean.
3) Calculate the proportion of the means computed on the randomized data that are greater than or equal to the sample mean.
As I understand it, this procedure is valid if the observations reflect differences between paired samples.
I'm specifically interested in knowing if this procedure is still valid if the observations do not reflect the difference between paired samples.
Comment: Flipping signs in your permute step would correspond to an assumption (under the null) that the distribution was symmetric. This often makes sense when comparing paired data (e.g. consider measurements performed before and after some intervention and the assumption under the null that the treatment does nothing at all; flipping signs is simply interchanging before/after labels, which makes sense if the treatment has no impact on the distribution of the value within pairs).  For one-sample, it might sometimes make sense to assume symmetry under H0 but might otherwise be a surprising assumption
Comment: if you want to test if the sample mean is greater than 0, why wouldn't you just stop at step 1 and compare it to 0?
Comment: You haven't fully described a test yet: what exactly would you do with that proportion of means greater than the sample mean?
Answer: Restating Glen_b's comment as an answer: the procedure is valid if you can assume that the distribution (under the null) is symmetric.


is it ok to write php code in laravel's blade?

Question: is it ok to write php code in laravel's blade?
this is my code
  <?php

    $orders = order::where('user_id', '=', Auth::user()->id)->get();
    $counts= $orders->count();
    $totalPrice = 0;

    for ($i = 1; $i <= $counts ; $i++) {
        $totalPrice += $order->cart->totalPrice;
    }

    echo $totalPrice;

  ?>

Answer: Is it possible? Definitely.
Should you? Most probably not. Laravel is based on the MVC pattern, which strives to separate business logic from the views. I think it is way better to use a controller for retrieving the data and passing it to a view, after which you use blade templating in said view to display the data (which in this case just means replacing <?php echo ... ?> with {{ ... }})
There are a number of advantages for keeping  the business logic and views separate that you're missing out on, amongst others:

Reusability, when the view is just used for displaying any generic list of items, it can be used in multiple places. If it contains specific logic like this one, the reusability is hurt a lot. The same goes for the logic, if it were in a separate controller it would be reusable.
Modularity, when working with Laravel most people will expect business logic to be in a controller (separation of concerns), by putting it in a view you are making it harder to find and you are also requiring the change of a view while it might only be the logic that is changing. Modularity also allows multiple people to work on separate modules at the same time without them having to affect eachother.
Readability/Clarity, having the logic be in a method (with describing name and documentation) inside a controller (with again a describing name and documentation) will tell another developer what that code does and makes it easier for him to read said code and earlier mentioned view (from which you could call the method).
Answer: Short answer: No
Longer answer: Blade is a templating engine which renders the view of your application.  Code like that should reside in the modal.  Placing logic into your View is spaghettifying your code and will come back to bite you.
Answer: Definitely not! because all of this structures designed to split your code logic from the view, this is what we call MVC, And the goal of this design is:

MVC decouples the various components of an application, developers are able to work in parallel on different components without impacting or blocking one another.


Why doesn't measurement error in the dependent variable bias the results?

Question: When there is measurement error in the independent variable I have understood that the results will be biased against 0. When the dependent variable is measured with error they say it just affects the standard errors but this doesn't make much sense to me because we are estimating the effect of $X$ not on the original variable $Y$ but on some other $Y$ plus an error. So how does this not affect the estimates? In this case can I also use instrumental variables to remove this problem?
Answer: When you want to estimate a simple model like
$$Y_i = \alpha + \beta X_i + \epsilon_i$$
and instead of the true $Y_i$ you only observe it with some error $\widetilde{Y}_i = Y_i + \nu_i$ which is such that it is uncorrelated with $X$ and $\epsilon$, if you regress
$$\widetilde{Y}_i = \alpha + \beta X_i + \epsilon_i$$
your estimated $\beta$ is
$$
\begin{align}
\widehat{\beta} &= \frac{Cov(\widetilde{Y}_i,X_i)}{Var(X_i)} \newline
&= \frac{Cov(Y_i + \nu_i,X_i)}{Var(X_i)} \newline
&= \frac{Cov(\alpha + \beta X_i + \epsilon_i + \nu_i,X_i)}{Var(X_i)} \newline
&= \frac{Cov(\alpha ,X_i)}{Var(X_i)} + \beta\frac{Cov(X_i,X_i)}{Var(X_i)} + \frac{Cov(\epsilon_i,X_i)}{Var(X_i)} + \frac{Cov(\nu_i,X_i)}{Var(X_i)} \newline
&= \beta \frac{Var(X_i)}{Var(X_i)} \newline
&= \beta
\end{align}
$$
because the covariance between a random variable and a constant ($\alpha$) is zero as well as the covariances between $X_i$ and $\epsilon_i, \nu_i$ since we assumed that they are uncorrelated.
So you see that your coefficient is consistently estimated. The only worry is that $\widetilde{Y}_i = Y_i + \nu_i = \alpha + \beta X_i + \epsilon_i + \nu_i$ gives you an additional term in the error which reduces the power of your statistical tests. In very bad cases of such measurement error in the dependent variable you may not find a significant effect even though it might be there in reality. Generally, instrumental variables will not help you in this case because they tend to be even more imprecise than OLS and they can only help with measurement error in the explanatory variable.
Comment: I have a simple question here: what if the νi, which is the measurement error in the dependent variable, is correlated with the independent variable of interest? I would imagine there are plenty of possibilities that this can happen and social desirability bias can be an example. If the survey respondents had a social desirability bias when responding to the dependent variable questionnaire(s), and if that desirability was related to the independent variable, let's say age or gender (which could be arguably related to social desirability), what happens in terms of endogeneity then?
Answer: Regression analysis answers the question, "What is the AVERAGE Y value for those who have given X values?" or, equivalently, "How much is Y predicted to change ON AVERAGE if we change X by one unit?" Random measurement error doesn't change the average values of a variable, or the average values for subsets of individuals, so random error in the dependent variable will not bias regression estimates.
Let's say you have height data on a sample of individuals. These heights are very precisely measured, accurately reflecting everyone's true stature. Within the sample, the average for men is 175 cm and the average for women is 162 cm. If you use regression to calculate how well gender predicts height, you estimate the model
$\mathit{HEIGHT = CONSTANT + β * GENDER + RESIDUAL}$
If women are coded as 0 and men as 1, $\mathit{CONSTANT}$ is the female average, or 162 cm. The regression coefficient $\mathit{β}$ shows how much height changes ON AVERAGE when you change $\mathit{GENDER}$ by one unit (from 0 to 1). $\mathit{β}$ equals 13 because people whose value for $\mathit{GENDER}$ is 0 (women) have a mean height of 162 cm while people whose value for $\mathit{GENDER}$ is 1 (men) have a mean height of 175 cm; $\mathit{β}$ estimates the average difference between men's and women's heights, which is 13 cm. ($\mathit{RESIDUAL}$ reflects the within-gender variance in height.)
Now, if you randomly add -1 cm or +1 cm to everyone's true height, what will happen? Individuals whose actual height is, say, 170 cm will now be reported as being 169 or 171 cm. However, the average of the sample, or any subsample, will not change. Those whose actual height is 170 cm will average 170 cm in the new, erroneous dataset, women will average 162 cm, etc. If you rerun the regression model specified above using this new dataset, the (expected) value of $\mathit{β}$ will not change because the average difference between men and women is still 13 cm, regardless of the measurement error. (The standard error of $\mathit{β}$ will be larger than before because the variance of the dependent variable is now larger.)
If there's measurement error in the independent variable rather than the dependent variable, $\mathit{β}$ will be a biased estimate. This is easy to understand when you consider the height example. If there's random measurement error in the $\mathit{GENDER}$ variable, some men will be erroneously coded as female and vice versa. The effect of this is to reduce apparent gender differences in height, because moving males to the female group will make the female mean is larger while moving females to the male group will make the male mean smaller. With measurement error in the independent variable, $\mathit{β}$ will be lower than the unbiased value of 13 cm.
While I used a categorical independent variable ($\mathit{GENDER}$) for simplicity here, the same logic applies to continuous variables. For example, if you used a continuous variable like birth height to predict adult height, the expected value of $\mathit{β}$ would be the same regardless of the amount of random error in adult height measurements.
Answer: Another way to see this is an M-estimation argument. In general, OLS is consistent and asymptotically normal for data $(Y_i, X_i)$ coming from a model that satisfies $\mathbb E(Y_i|X_i) = X \beta$ and some mild regularity conditions, with $\hat \beta_\text{ols} \to \beta$. See Chapter 7 of [1], for example. Using Andy's notation from above, since $\mathbb E(\tilde Y_i|X_i) = X \beta$, we're in luck and the standard results apply.
[1] Boos, Dennis D, and L. A Stefanski. Essential Statistical Inference. Vol. 120. Springer Texts in Statistics. New York, NY: Springer New York, 2013. https://doi.org/10.1007/978-1-4614-4818-1.


SassCSS undefined variable usando RGBA

Question: Quando tento usar uma variável de um arquivo .scss, com uma variável funciona e outra não:
_templateColors.scss
$blue-dark : #0277bd !important;
$gray-light : #f5f5f5 !important;
$gray-dark : rgba(51,51,51,0.08) !important;

Arquivo que usa essas cores:
@import "../../../core/static/scss/_templateColors.scss";

#left_nav{
    background-color: $gray-dark;
}

Quando uso as variáveis $blue-dark e $gray-light funciona normal, porem o a $gray-dark não.
Erro:
Error: Undefined variable.
  ╷
4 │     background-color: $gray-dark;

Comment: Cara isso não é SASS isso é SCSS, pode ser alguma config do seu compilador
Comment: Não consegui reproduzir o seu problema...
Comment: Editei e coloqueis SassCSS.
Comment: Relacionado: [Qual é a diferença entre SASS e SCSS](https://pt.stackoverflow.com/q/54453/3774)
Answer: Fiz uma cópia do arquivo templateColors para a mesma pasta do outro arquivo e deu certo. Aparentemente deve ser pq o sass não estava "assistindo"(wathcing) o diretório do template.

SassCSS undefined variable usando RGBA


Integral of Reciprocal Of Polynomial Always $0$?

Question:
Prove that $$\int_{|z|=r}\dfrac{1}{P(z)}=0$$ where $P(z)$ is a polynomial with degree $2$ or higher, and all the zeros of $P(z)$ are contained in $|z|<r$.
Comment: Do you know Cauchy's integral theorem?
Comment: Contained in what? Also, can $P$ have complex coefficients?
Comment: I imagine the zeros are constrained to have $|z|<r.$
Answer: Here's an integration path that should prove helpfull. Let $\gamma_{\varphi,R}$ be the path

(Part $\gamma^1_{\varphi}$). Starts at $z_0=re^{i\varphi}$ and goes along the circle $|z|=r$ counter-clockwise until it reaches $z_1=re^{-i\varphi}$.
(Part $\gamma^2_{\varphi,R}$) Then proceeds from $z_1$ parallel to the real axis until it reaches $z_2 = Re^{-i\theta}$
(Part $\gamma^3_{\varphi,R}$) Continues by going along the circle $|z|=R$ clockwise until it reaches $z_3 = Re^{i\theta}$
(Part $\gamma^4_{\varphi,R}$) Finally goes back to $z_0$ parallel to the real axis.

Then show that

$\oint_{\gamma_{\varphi,R}} \frac{1}{P(z)} \,dz = 0$. Hint: Does the integrand have any poles within the area enclosed by that path?
$\int_{\gamma^1_{\varphi}}  \frac{1}{P(z)} \,dz \to \oint_{|z|=r} \frac{1}{P(z)} \,dz$ as $\varphi \to 0$. Use that the path $\gamma^1_{\varphi}$ converges to the path $|z|=r$.
$\int_{\gamma^3_{\varphi,R}} \frac{1}{P(z)} \,dz \to 0$ as $R \to \infty$. You'll need that $P$ has degree two or higher for that.
$\int_{\gamma^2_{\varphi,R}} \frac{1}{P(z)} + \int_{\gamma^4_{\varphi,R}} \frac{1}{P(z)}\,dz \to 0$ as $\varphi \to 0$. Use that $\gamma^1_{\varphi,R}$ and $\gamma^4_{\varphi,R}$ converge towards the same line $[r,R]$, but run through it in different directions.

Putting it all together, the situation is that if you let $\varphi \to 0$ and $R \to \infty$ then $$
  0 = \oint_{\gamma_{\varphi,R}} \frac{1}{P(z)} \,dz =
  \underbrace{\int_{\gamma^1_\varphi} \frac{1}{P(z)} \,dz}_{\to \oint_{|z|=r} \frac{1}{P(z)} \,dz} +
  \underbrace{\int_{\gamma^3_{\varphi,R}} \frac{1}{P(z)} \,dz}_{\to 0} +
  \underbrace{\int_{\gamma^2_{\varphi,R}} \frac{1}{P(z)} \,dz +
  \int_{\gamma^4_{\varphi,R}} \frac{1}{P(z)} \,dz}_{\to 0}
$$
from which you can then conclude that indeed $$
  \oint_{|z|=r} \frac{1}{P(z)} \,dz = 0
$$


Need to loop through an array and set each value one at a time to a class in Javascript

Question: I want to loop through an array, and set the values of that array as "ID's" using javascript.
Here is the array of US states
var data =
    [
        'alabama',
        'alaska',
        'arizona',
        'arkansas',
        'california',
        'colorado',
        'connecticut',
        'delaware',
        'florida',
        'georgia',
        'hawaii',
        'idaho',
        'illinois',
        'indiana',
        'iowa',
        'kansas',
        'kentucky',
        'louisiana',
        'maine',
        'maryland',
        'massachusetts',
        'michigan',
        'minnesota',
        'mississippi',
        'missouri',
        'montana',
        'nebraska',
        'nevada',
        'newhampshire',
        'newjersey',
        'newmexico',
        'newyork',
        'northcarolina',
        'northdakota',
        'ohio',
        'oklahoma',
        'oregon',
        'pennsylvania',
        'rhodeisland',
        'southcarolina',
        'southdakota',
        'tennessee',
        'texas',
        'utah',
        'vermont',
        'virginia',
        'washington',
        'west Virginia',
        'wisconsin',
        'wyoming'
    ]

"grabbing the class" let noID = document.getElementsByClassName("card-title");
"for loop trying to grab each html element with the class name, and set the ID to one of the states in the array"
Ex: element # 1 with class name "card-title" needs an #id of "alabama"
element # 2 with a class name "card-title" needs an id# of "alaska"
for(let i = 0; i<noID.length; i++){
    for(states of data){
        let stateName = states;
        noID[i].setAttribute("id", stateName);
}

}
Comment: Please provide all the code including the HTML, here we are assuming the count of states and "cards" is the same.
Answer: Do you mean to do this?
var data = [ 'alabama', 'alaska', 'arizona', 'arkansas', 'california', 'colorado', 'connecticut', 'delaware', 'florida', 'georgia', 'hawaii', 'idaho', 'illinois', 'indiana', 'iowa', 'kansas', 'kentucky', 'louisiana', 'maine', 'maryland', 'massachusetts', 'michigan', 'minnesota', 'mississippi', 'missouri', 'montana', 'nebraska', 'nevada', 'newhampshire', 'newjersey', 'newmexico', 'newyork', 'northcarolina', 'northdakota', 'ohio', 'oklahoma', 'oregon', 'pennsylvania', 'rhodeisland', 'southcarolina', 'southdakota', 'tennessee', 'texas', 'utah', 'vermont', 'virginia', 'washington', 'west Virginia', 'wisconsin', 'wyoming' ];

let noID = document.getElementsByClassName("card-title");

for (let i = 0; i < noID.length; i++) {
    noID[i].setAttribute("id", data[i]);
}


Drawing without replacement - prob. for an Ace followed by an Ace?

Question: Given a standard 52-cards deck:
You are extracting cards from the deck without replacement, until you get an "Ace" for the first time. What is the probability that the next card will be "Ace" too?
I've already seen the following Q&A:
Probability of drawing an Ace: before and after
According to that thread, the answer should be:
 $$\frac{4 \cdot 3}{52 \cdot 51} = \frac{1}{221}$$
But the official solution says that the answer is:
$$\frac{4}{52}$$
which doesn't make sense IMHO. They solved it only with intuition or "mind trick", as they wrote..
My calculation:
Assuming that the 1st card is Ace, then:
$$\frac{4 \cdot 3}{52 \cdot 51} = \frac{1}{221}$$
Assuming that the 2nd card is Ace, then:
$$\frac{(52-4) \cdot 4 \cdot 3}{52 \cdot 51 \cdot 50} = \frac{24}{5525}$$
We notice a pattern here.
Having the 1st Ace at the $k$'th draw, then the probability (for a second Ace after that) is:
$$
p_1 = \frac{ {_{52-4}P_{k-1}} \cdot 4 \cdot 3 }{ {_{52}P_{k-1}} \cdot {_{52-k}P_{2}} }
$$
We need to consider the least-possible scenario - we draw 48 non-Ace cards, then:
$$
p_2 = \frac{48! \cdot 4 \cdot 3}{ {_{52}P_{50}} } = \frac{1}{270725}
$$
So, the required probability is:
$$\begin{align}
p &= p_2 + \sum\limits^{48}_{k=1} p_1 \\
&= p_2 + \sum\limits^{48}_{k=1} \frac{ {_{48}P_{k-1}} \cdot 4 \cdot 3 }{ {_{52}P_{k-1}} \cdot {_{52-k}P_{2}} }\\
&= \frac{1}{270725} + \frac{1696}{20825}\\
&= \frac{1297}{15925}\\
&\cong 0.081444
\end{align}
$$
But my answer is far from either the official solution and from the answer in that thread.
Comment: The question you link to is different.  It is asking "what's the probability that the second drawn is an Ace?"  The answer to that is certainly $\frac 4{52}$ as there is no difference between the second card drawn and the first.  Of course, if you specify that the first card drawn was (or was not) itself an Ace then the probability changes.
Comment: @lulu I think that I understand your view on the matter. So what did I calculated?
Comment: I think your method ought to work.  To be precise:  I just wrote a code which first computes $p_k$, the probability that the first A is observed on the $k^{th}$ draw, and then calculates the probability that the next draw is also an A.  I believe this is what you were doing as well.  My code returned $\frac 1{13}$ as the total.  Doesn't convey a lot of insight, I understand.
Comment: @lulu Indeed you're right! I posted an answer which shows where were my mistakes and include a code that proves it to be equal to $\frac{1}{13}$.
Answer: We use a  fairly crude counting approach, in order to rely minimally on intuition. There are $\binom{52}{4}$ equally likely ways to choose the positions of the $4$ Aces. We now count the "favourables."
Maybe the first two Aces are in positions 1 and 2. That leaves $\binom{50}{2}$ for the rest.
Maybe they are in positions 2 and 3. That leaves $\binom{49}{2}$ for the rest.
Maybe they are in positions 3 and 4. That leaves $\binom{48}{2}$ for the rest.
And so on, up to positions 49 and 50, leaving $\binom{2}{2}$ for the rest. That gives probability
$$\frac{\binom{50}{2}+\binom{49}{2}+\cdots+\binom{2}{2}}{\binom{52}{4}}.$$
The numerator can be simplified in various ways. My favourite is to count the number of ways to choose $3$ numbers from the first $51$. This can be done in $\binom{51}{3}$ ways.  But the smallest number can be $1$, leaving $\binom{50}{2}$ ways to choose the other two. Or the smallest can be $2$, and so on. We get the number of favourables obtained above.
Our probability is therefore $\frac{\binom{51}{3}}{\binom{52}{4}}$. This simplifies to $\frac{1}{13}$.
Comment: Great argument and very well written. +1.
Comment: I like this approach! +1. Could you please elaborate regarding how you simplified the numerator?
Comment: I think that I understand it now. That is a very cool solution..!
Answer: Your Error
First of all Andre has posted a very nice answer. Already Upvoted it.
I am trying to look at where all you have gone wrong. Too long for an comment, so posting it here.
Let us look at the last case. You have $48!$ ways of the non-ace cards. Now the remaining cards are all aces anyways. So the question of multiplying this by $4 \cdot 3$ does not arise. Since we do not care about the last 2 cards, the denominator will have to be just $50!$.  Similarly, the case before that might need to rectified.
Comment: @Dor   Yes, right.  A good approach would be you post an answer yourself, instead of editing the post. I'll surely upvote it.
Comment: Indeed you are right about the last term! In the other 48 terms, the mistake was different. I'll add info in my original post. Thanks! +1
Answer: Here is a bijection between set of all permutation with the first Ace followed by an Ace and set of all permutations with the first card being an Ace
$$B^nAAX <-> AB^nAX$$
where A stands for an Ace, B for not an Ace, $0\leq n \leq 48$  and $X$ contains $2$ Aces and $48-n$ non-Aces. Hence the probability of an Ace following the first Ace is equail to the probability of the first card being Ace which is equal to $$4/52=1/13$$
Probabilistically, conditioned on the location of the second ace, the first ace is uniformly distributed on locations before the second ace - hence probability of it being the first or the last in that sequence are equal.
Comment: Nice! I was going to go back and  try to explain that the fact my fraction simplified to $\frac{4}{52}$ was not an "accident." You have done it, in the strongest (natural bijection) sense.
Comment: I started thinking along the lines of bijection after seeing your result ;).
Comment: Yes, it was kind of shouting look at me, look at me.
Answer: Fixing my original calculation
Thanks to Shailesh, we now know that the expression
$$
p_2 = \frac{48! \cdot 4 \cdot 3}{ {_{52}P_{50}} }
$$
Should be replaced with:
$$
p_2 = \frac{48!}{ {_{52}P_{48}} }
$$
Because that after extracting 48 non-Ace cards, we'll necessarily have the second card as Ace.
Moreover, I had a tiny mistake in the denominator. Instead:
$$ {_{52}P_{k-1}} \cdot {_{52-k}P_{2}} $$
It should be:
$$ {_{52}P_{k-1}} \cdot {_{52-(k - 1)}P_{2}} $$
(All the $k$ indexes should be shifted by $(-1)$)
I wrote a Python code which shows that this solution works either:
<code># Python 2.7.6
import math
from fractions import Fraction

f = math.factorial

def nPr(n,r):
    return f(n) / f(n-r)

p = Fraction(0)

for k in range(1, 49):
    p += Fraction(nPr(48, k-1) * 4 * 3,
                nPr(52, k-1) * nPr(52 - (k-1), 2))

p += Fraction(f(48), nPr(52,48))

print p # Outputs 1/13 :)
</code>
Thank you all for your effort! :)
Comment: Well done, Dor, We all learn with each other's help.