Use jQuery to select certain element type in the same Div as another element

Question: I'm new to jQuery and have what I think is a basic question.  I've searched Google and the jQuery site for information on "parent" and "children" but I'm having trouble putting into words what I want to accomplish.
Let's say I have the following markup:

    <input type="text" value="John Doe" />
    clear

    <input type="text" value="Jane Doe" />
    clear

    <input type="text" value="Joe Smith" />
    clear

I essentially want to write a bit of jQuery that makes each "clearButton" link clear the value of its sibling input on click.  Is this possible given my markup?  Or do I need a unique identifier on each input or each div?  Is it possible to receive the click, and then use the "this" command to select the correct sibling input?  I put together a bit of my own code using sibling but it cleared all of the inputs at once.
Any tips or links to relevant info is greatly appreciated!
Thanks!
Answer: If the link is always next to the input field:
$('.clearButton').click(function() {
    $(this)          // the clearButton
          .prev()    // get the input field
          .val('');  // clear its value

    return false;    // disable default link action (otherwise # adds to url)
});

Comment: Thanks, Martin! Also I thank everyone else who provided solutions - I really appreciate the help.
Answer: Parent and Find, demo
$(document).ready(function () {
    $('.clearButton').click(function () {
       $(this).parent().find('input').val('');
    })
});

Answer: You probably just need to attach .first() to your code. it should look something like this:
$('.clearButton').click(function() {
    $(this).siblings().first().val('');
});

Answer: $('.clearButton').click(function () {
   $(this).sibling('input').val('');
});


Can not display user information?

Question: I want to display on the user account page the following information :

the status of the account.
the roles attached to the accounts.
registered since the ...
last connection on ...

The view displays all the information for the administrator account, but with an authenticated user I only have the following information :

the roles attached to the accounts.
registered since the ...

How to display all the information for the authenticated user ?

uuid: 88c79c78-6091-4edc-bcd7-464f3a5a3baf
langcode: fr
status: true
dependencies:
  module:
    - user
id: utilisateur_informations
label: 'Utilisateur informations'
module: views
description: ''
tag: ''
base_table: users_field_data
base_field: uid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: none
        options: {  }
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Trier par'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          items_per_page: null
          offset: 0
      style:
        type: default
        options:
          grouping: {  }
          row_class: views-teaser
          default_row_class: true
      row:
        type: fields
      fields:
        status:
          id: status
          table: users_field_data
          field: status
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Compte '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: boolean
          settings:
            format: enabled-disabled
            format_custom_true: ''
            format_custom_false: ''
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: user
          entity_field: status
          plugin_id: field
        roles_target_id:
          id: roles_target_id
          table: user__roles
          field: roles_target_id
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Rôles '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          type: separator
          separator: ', '
          entity_type: user
          plugin_id: user_roles
        created:
          id: created
          table: users_field_data
          field: created
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Membre depuis '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: timestamp_ago
          settings:
            granularity: 2
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: user
          entity_field: created
          plugin_id: field
        login:
          id: login
          table: users_field_data
          field: login
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Dernière connexion le '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: timestamp
          settings:
            date_format: short
            custom_date_format: ''
            timezone: ''
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: user
          entity_field: login
          plugin_id: field
      filters: {  }
      sorts: {  }
      title: 'Utilisateur informations'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments:
        uid:
          id: uid
          table: users_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          default_action: default
          exception:
            value: all
            title_enable: false
            title: All
          title_enable: false
          title: ''
          default_argument_type: raw
          default_argument_options:
            index: 1
            use_alias: false
          default_argument_skip_url: false
          summary_options:
            base_path: ''
            count: true
            items_per_page: 25
            override: false
          summary:
            sort_order: asc
            number_of_records: 0
            format: default_summary
          specify_validation: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          not: false
          entity_type: user
          entity_field: uid
          plugin_id: user_uid
        uid_1:
          id: uid_1
          table: users_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          default_action: default
          exception:
            value: all
            title_enable: false
            title: All
          title_enable: false
          title: ''
          default_argument_type: current_user
          default_argument_options: {  }
          default_argument_skip_url: false
          summary_options:
            base_path: ''
            count: true
            items_per_page: 25
            override: false
          summary:
            sort_order: asc
            number_of_records: 0
            format: default_summary
          specify_validation: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          not: false
          entity_type: user
          entity_field: uid
          plugin_id: user_uid
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - user
      tags: {  }
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders:
        metatag_display_extender: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - user
      tags: {  }

Comment: Have you actually created some authenticated user accounts and logged in with them?
Comment: @Kevin howbrook Yes and that's the problem.
Comment: hi, Any ideas ?
Answer: Remove your first contextual argument. You only need this one:
Comment: This does not change anything, even if I completely remove the contextual filter the problem is still there. In permissions, if I grant "Administer users" it works. I can not grant this permissions to users. How to do ?
Comment: Do you have other answers ?
Comment: does data show in the preview of the views UI ?
Comment: yes, because I am the administrator. If I connect with an authenticated user, I miss my question data. If I grant permission "Administer users", it works. But I do not want to grant this permission.
Answer: I imported your view and tried to do it via views module. But I believe you will need to do some custom coding for this. You need to set access permissions per field in Drupal 8.
To learn more about field permissions refer field_permissions example module in Examples module.

Can not display user information?


Css text styling with image

Question: I'm styling my letters using an image as the content of the letters.
The letters are small and the image big, and I would like to have more control over the image size. What is the css properties to do so?
<code> background-image: url(https://files.cargocollective.com/c2106023/Menu.jpg);
  background-size: contain;
 -webkit-text-fill-color: transparent;
 -webkit-background-clip: text;
 -moz-background-clip:text;
</code>
Comment: Please see [ask]. You should provide some HTML with your CSS in a demo snippet.
Comment: Are you saying you want the background image to be just big enough to be behind all the characters, but no bigger?
Comment: what I mean is I would like to resize my image to see what size I like. The other answer helped me figure it out. Thank you for your response.
Comment: Hi Isherwood. Thank you. I will do so next time.
Answer: To have more control over the size of the background image within the letters, you can adjust the background-size property to specific dimensions. Here's how you can modify your CSS:
<code>background-image: url(https://files.cargocollective.com/c2106023/Menu.jpg);
background-size: 50px 50px; /* Adjust the dimensions as needed */
background-repeat: no-repeat; /* Prevent the image from repeating */
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
-moz-background-clip: text;
</code>
For your case you can keep, background-size: 50px 50px; which sets the size of the background image to 50 pixels in width and 50 pixels in height. You can change these values according to your requirements to get the desired size for the background image.

Css text styling with image


R save FlexTable as html file in script

Question: I have a FlexTable produced with the ReporteRs package which I would like to export as .html.
When I print the table to the viewer in RStudio I can do this by clicking on 'Export' and selecting 'Save as webpage'.
How would I replicate this action in my script?
I don't want to knit to a html document or produce a report just yet as at present I just want separate files for each of my draft tables which I can share with collaborators (but nicely formatted so they are easy to read).
I have tried the as.html function and that does produce a .html file but all the formatting is missing (it is just plain text).
Here is a MWE:
# load libraries:
library(data.table)
library(ReporteRs)
library(rtable)

# Create dummy table:
mydt <- data.table(id = c(1,2,3), name = c("a", "b", "c"), fruit = c("apple", "orange", "banana"))

# Convert to FlexTable:
myflex <- vanilla.table(mydt)

# Attempt to export to html in script:
sink('MyFlexTable.html')
print(as.html(myflex))
sink()

# Alternately:
sink('MyFlexTable.html')
knit_print(myflex)
sink()

The problem with both methods demonstrated above is that they output the table without any formatting (no borders etc).
However, manually selecting 'export' and 'save as webpage' in RStudio renders the FlexTable to a html file with full formatting.  Why is this?
Answer: This works for me:
writeLines(as.html(myflex), "MyFlexTable.html")

Comment: Thanks - do you have any insights as to what `writeLines` is doing here?
Comment: it merely write the html string to the file. `cat` and `write` works as well.

R save FlexTable as html file in script


Why jumping into an instruction even if containing a JUMPDEST does not work?

Question: Here's my whole program. The reasoning behind it is the larger is the program on Ethereum, the more it costs money to load it (as the gas cost is per byte and quite high).
CALLER
CALLDATASIZE
ISZERO
PUSH1 0x07
JUMPI
PUSH3 0x5b6000
SSTORE

So I'm jumping into PUSH3 0x5b6000 but if we disassemble 0x5b6000 then it means
JUMPDEST
PUSH1 0x00

So since the evm opcode encoding is fully variable length (and all instructions being one byte long beside PUSHxx) and I'm jumping into a JUMPDEST, why does this transaction fails?
Where is it specified in the yellow paper that going to a JUMPDEST isn't the only requirement for a valid jump destination?
Comment: **Please notice that there's no program or tools for assembly a program completely written in Ethereum assembly.** It needs to be done completely by hand using an hex editor.
Comment: Why the downvote?
Comment: Note that this sort of jumping to the middle of instructions, while more common by the "masters" of the past, makes it incredibly hard for anyone to understand what's happening. However, the typical things to ask apply. Have you tried running it in a debugger?
Comment: @ThomasJager then it behave as in the question's transaction link described it which is `invalid jump destination` without telling why it's invalid. Please note that on Ethereum fees are very high compared to traditional cloud computing which is the reasoning behind having programs as short as possible.
Comment: It might be worth it to migrate this question to the [Ethereum StackExchange](https://ethereum.stackexchange.com).
Answer: I am not sure about which version of the yellow paper was available when this question was originally asked, but here is an excerpt from page 13 of the Istanbul version:

9.4.3. Jump Destination Validity. We previously used D as the function to determine the set of valid jump destinations given the code that is
being run. We define this as any position in the code occupied by a
JUMPDEST instruction.
All such positions must be on valid instruction
boundaries, rather than sitting in the data portion of PUSH operations
and must appear within the explicitly defined portion of the code
(rather than in the implicitly defined STOP operations that trail it).

And here is the geth source location for the code that implements an anasysis for this.


Como Pegar A Variável De Outro Component

Question: Tenho a seguinte situação:
utils-nav-usuario.component.html

  ESC - Sistema De Controle De Pizzaria -
  Usuário Logado: {{loginUsuarioParam}}
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Login

          Sair

utils-nav-usuario.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
  selector: 'app-utils-nav-usuario',
  templateUrl: './utils-nav-usuario.component.html',
  styleUrls: ['./utils-nav-usuario.component.css']
})
export class UtilsNavUsuarioComponent {

  loginUsuarioParam : string;

}

Tenho essa variável em meu Component e preciso ler essa variável em diversas partes do programa, mas como eu faço pra ler em outro Component por exemplo no exemplo abaixo.
pedido-avulso-create.component.ts
  abrirCaixa() {

    this.caixa.codigoUsuario = this.loginUsuarioParam;

    this.caixaService.saveCaixa(this.caixa)
    .subscribe (
      data => {
        if (data.status == 200) {
          this.toastr.success("Pedido Avulso", "Pedido Avulso Alterado Com Sucesso.");

        }
      },
      error => {
        if (error.status == 0) {
          this.toastr.error("Pedido Avulso", "Sem Conexão Com O WebService.");
        } else {
          this.error = error.json();
          this.toastr.error("Pedido Avulso", this.error.message);
        }
      }
    );
  }

Tenho esse método acima que está em outro Component é quero ler para jogar nessa classe alguém tem ideia como eu faço isso, eu tive a ideia de mudar esse nav como é usado em todas as telas criar um Module para ele mas agora não sei como usar a variável que está lá.
Answer: Existem duas possibilidades:
A primeira é se o componente que você quer ler a variável é filho do componente que tem a variável loginUsuarioParam (UtilsNavUsuarioComponent). Nesse caso você declara a variável loginUsuarioParam como @Input() no componente filho:
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
@Component({
  selector: 'app-pedido-avulso-create',
  templateUrl: './pedido-avulso-create.component.html',
  styleUrls: ['./pedido-avulso-create.component.css']
})
export class UtilsPedidoAvulsoCreateComponent {
  /* você pode declarar um valor padrão caso a variável não seja declarada no componente */
  Input() loginUsuarioParam = '';

}

E a outra opção é salvar em uma variável global ou no localStorage.
Comment: Vou testar aqui pra ver se vai funcionar.
Comment: acabei utlizando o LocalStorage que você falou, resolveu bem o problema que eu tinha, muito obrigado.
Comment: Beleza, qualquer coisa avisa aqui ;)
Comment: Deu meio certo, mais não fico muito legal não, pensei que ia funcionar meio diferente, porque em cada tela eu vou ter que fazer a mesma coisa e fica passando o parâmetro e criando um input() em cada Component.
Comment: Que bom, eu acredito que dependendo da situação seja melhor usar @Input() ou um controlador de estados ngstore.


Create relationship between node and menu link

Question: I would like to create a node with a menu link programmatically.  When the operation is complete, I would like the user to see the relationship between the node and the menu link under "Menu Settings" of the node.
I am aware of this post:
Programmatically create a node with a menu link
This shows the mechanics of creating a node and creating a menu link.  It does not show how to build the relationship between the node and menu link so it is available in "Menu Settings" of the node for a user working with the Drupal GUI.  How can I build this relationship?
Answer: To create a menu link for a node programmatically and to see it in the node edit form you have to connect the link uri to the node entity:
<code>$item = \Drupal\menu_link_content\Entity\MenuLinkContent::create([
  'link' => ['uri' => 'entity:node/' . $node->id()],
  'title' => 'Menu item for node ' . $node->id(),
  'menu_name' => 'main',
]);
$item->save();
</code>
Comment: This is moving in the direction -- thank you 4k4! I have tested this and it works with 'menu_name' = 'main'.  In my case I have three custom menus that I created in code.  One each for: English, Spanish and Chinese.  When I try to use one of these menu names, no entry exists in the node edit.  I looked at the configuration differences between 'main' and my three menus.  I noticed that 'locked: true' for 'main'. My three menus have 'locked: false'.  Could this have something to do with why I am having problems?
Comment: Please see my comment above @4k4.
Comment: I tested this again and set 'locked: true' when creating each of my three menus.  This was not the solution I hoped for.  The three menus are created as before.  There is still no data in "Menu Settings" of the associated nodes. @4k4
Comment: While there was a straightforward answer to your first question for the relationship, the follow-up about translation is difficult to answer in one post. There are different strategies to translate menus. The simple one is to translate the menu items. Different menus is a more advanced approach. One thing to check first, if you want to see the menu items of different menus you have to allow them in the configuration of the content type. And for the first approach, translating menu items in the node edit form, there is still an open issue https://www.drupal.org/project/drupal/issues/2648750
Comment: You are correct @4k4. I added my custom menus to the content type and English is now working well -- both the menu itself and the node edit menu settings. Spanish and Chinese are still an issue with node edit.  When I set 'menu_name' => 'spanish' and 'langcode' => 'es', the menu_link_content is created correctly in the spanish menu.  The node edit menu settings exists but always points to the english menu.  Could this be the issue you pointed out above?  I can't tell for sure.
Comment: Probably, did you try the patch?
Comment: Yes -- the patch works for my use case.  Thank you @4k4 for helping me fight through a few layers of this issue -- including applying a patch for the first time!


Dropdown menu, anchor doesn't work

Question: I have made a dropdown menu and it works fine, except the anchor (a href="#") does not work.
I think the script has something wrong, but I can't figure it out.
Can anyone can help me please?

        aaa

bbb

ccc

ddd

$(function($) {
    var li = $('.menu>.listMenu');
    li.addClass('off');
    $('.menu .on').find('.depth2Wrap').show();

    $('.menu>.listMenu>a').click(function() {
        var myArticle = $(this).parents('.listMenu:first');
        if(myArticle.hasClass('off')){
            li.addClass('off').removeClass('on');
            li.find('.depth2Wrap').slideUp(100);
            myArticle.removeClass('off').addClass('on');
            myArticle.find('.depth2Wrap').slideDown(100);
            li.removeClass('fir_sele');
        } else {
            myArticle.removeClass('on').addClass('off');
            myArticle.find('.depth2Wrap').slideUp(100);
            li.removeClass('fir_sele');
        }
        return false;
    });
});

Answer: Remove the following
 return false;

return false tells the browser not to complete the default action, which is following the link.
See What's the effect of adding 'return false' to a click event listener?

Dropdown menu, anchor doesn't work


What is the name of this scale based on the harmonic series?

Question: The following table lists the first 13 harmonics of the note C
Harmonic   Note   Unique note
-----------------------------
1          C      C
2          C
3          G      G
4          C
5          E      E
6          G
7          A#     A#
8          C
9          D      D
10         E
11         F#     F#
12         G
13         G#     G#

Ordering the unique notes gives:
C - D - E - F# - G - G# - A#
Does this scale have a name? Is it used? What is this scale called?
Comment: Can G# and A# be spelt as Ab and Bb?
Comment: Exactly what I was thinking. Certainly the Bb.
Comment: Why to the 13th harmonic?
Comment: Because I wanted to limit the scale to 7 notes
Comment: I would not say that it is a scale; not any series of notes is necessarily a scale.  Scales normally repeat in the next octave but the harmonic series has twice as many notes each time that you go up an octave.  Also, 7 is rather flatter than the usual A# / Bb.
Comment: If we just look at the proposed scale, we see it has two consecutive half-steps (F#-G-G#), which means it is outside the standard modes (Ionian, Dorian, etc), all of which are merely the "normal" scale with shifted starting note.
Answer: There are two different questions that could be read here, which it is not obvious (yet extremely significant) that they are different. One question is "what is the name of the scale consisting of the notes given by the first thirteen harmonics of C", and the other is "what is the name of the scale consisting of the notes C - D - E - F# - G - G# - A#", where the crucial point making these questions different is is that the pitches produced by the harmonics of C are not the same pitches as the ones we usually refer to by the letter names – for example the 'F#' given by the 11th harmonic of is in fact almost equidistant between an F and an F# in equal temperament, and so in my view it's substantially misleading to even give it a note name at all. The seventh and thirteenth harmonics are both also substantially far from the equal-tempered pitch they have been given the name of. So if you sat down at a keyboard and played the notes C - D - E - F# - G - G# - A# (or, as per the Wikipedia article referenced in the answer from Aaron (which does a good job of answering the second sense of the question as I've set out above), the Acoustic Scale C - D - E - F# - G - A - A#), you are not in any real sense playing the scale made up of the first 13 harmonics of C at all.
To do something towards answering the first possible sense of the question, to play this scale or use it in a piece we would have to make clear we are in the world of "microtonal" intonation. The composer Ben Johnston developed a notation which permits writing such notes (see the picture here https://en.wikipedia.org/wiki/Just_intonation#Staff_notation where the "F#" is notated as "up-arrow F") however I am not greatly familiar with his and others' work using these tunings so I don't know if there are any examples of this scale being used; certainly he has composed pieces in which notes tuned to these higher harmonics are used, and I would definitely be interested to know if there is an example where this scale occurs.
A final comment is that, whilst the 7th, 11th and 13th harmonics were signficantly far from any equal-temperament pitch, the D arising as the 9th harmonic is exactly a just perfect fifth above the G arising from the 3rd harmonic, since 9=3x3.
Comment: Amazing. You made me realize that - contrary to what I often heard while studying music theory - the notes of the major scale are _not at all_ based on the harmonic series (well, maybe except the second and the fifth).
Comment: Really helpful that you point out the difference between the "true" acoustic scale and the 12-TET approximation(s).
Comment: @hedgie That depends on what you consider "based on". When you write "major scale" you seem to mean the major scale in equal temperament. This temperament has only been the general standard for a little over a century. Earlier temperaments sacrifice some notes to have other notes much closer to "just intonation" (you can't have all notes, cf. syntonic and pythagorean comma). This leads to, for example, not all whole or all half tones being equal sized in early theory books. The notes from the scale _are_ based on the harmonic series, the route they took is just a whole lot longer.
Answer: The Musical Scale Search Tool offers four scales whose notes correspond to the OP, with only one -- C Minor Lydian -- containing the pitches in the order specified. The others would be permutations/modes of that scale.

G#/Ab leading whole tone  G#/Ab; A#/Bb; C; D; E; F#/Gb; G; G#/Ab;
C minor lydian    C; D; E; F#/Gb; G; G#/Ab; A#/Bb; C;
D arabian D; E; F#/Gb; G; G#/Ab; A#/Bb; C; D;
G neapolitan major    G; G#/Ab; A#/Bb; C; D; E; F#/Gb; G;

Ian Ring's website contains an extensive analysis of the minor lydian scale.
Since the OP scale is constructed in terms of the overtone series, it is in principle the Acoustic scale. However, as given on Wikipedia, the acoustic scale has A natural rather than Ab.
Two songs are referenced as using the acoustic scale (A-natural version) in this page from the University of Iowa:

"Blue Seven", by Sonny Rollins, (passage begins at [0:43])
"L'isle joyeuse", by Claude Debussy (passage begins at [4:32])
Comment: I really hear the whole-tone-ness.
Comment: @ibonyun Indeed, it's a Whole Tone scale with an added note.
Answer: Your scale is a mode of the scale that Wikipedia calls Neapolitan major. Unfortunately, Neapolitan major is a minor scale (at least, it harmonizes out to a minor triad at the root, not a major one) and the citations for that name are not very convincing. But you can find references to this scale more easily than yours, so it might be a good search term to know.
Wikipedia duplicates the name Aaron found for your mode: "Lydian minor". Again, this seems to be a name that someone invented and that is reproduced only in a few lists of scales. It seems to be a bad name to me -- shouldn't "Lydian Minor" at least have a b3 in it? But I'm sure that doesn't bother everyone the way it does me.
Names like these usually originated in scale books marketed towards rock guitarists; they represent a kind of folk terminology that hasn't passed into common use (because the scales are rarely used) and usually doesn't have any basis outside that. But all that might not bother you too much -- after all, everything has a name because someone decided to call it that, and names don't have to make logical sense.
It might also be useful to know that your scale is the same as the Carnatic melakata Rishabhapriya. This name connects your scale with real-world music-making rather than obsessive list-making, so it may be more helpful for you. A YouTube search throws up lots of South Indian performances of pieces in Rishabhapriya.
Comment: I gotta agree, "Lydian minor" seems like a misnomer to me. Maybe melodic major #4?
Answer: In xenharmonic theory, this scale is called an overtone scale, specifically "Mode 8 of the Harmonic Series" (Denny Genovese's term). To be precise, this assumes Just Intonation (pure ratios, not the tempered equivalent) and extending it to 15 (B).
Writing the scale as ratios, you get 8:9:10:11:12:13:14(:15:16), which is an Over-1 scale.
Some people do use it: guitarist Dante Rosati has refretted his guitar to play it, and calls it the "Diatonic Harmonic Series Scale" (see First Five Octaves of the Harmonic Series; this is the fourth octave), since its 8 notes are similar to the 7 notes of the usual diatonic scale.
Peter Hulen has composed some music using this scale (such as his dissertation, The Madman's Diary), and written a paper about how to use it with synthesized music.
See more compositions at Otones8-16.
This is one of the most interesting and practical overtone scales, since you get both very familiar chords such as the 4:5:6 major triad (8:10:12) and its extension to the barbershop tetrad (4:5:6:7), as well as more exotic harmonies, notably the 9:11:13:15 tetrad.


Elementary Optimization Problem

Question: I'm trying to solve this elementary calculus problem. It reads:
"You have written a compelling memoir called At My Limit: Learning Calculus During a Pandemic. According to your literary agent John, if you sell it at a price of 20 dollars per copy, 10,000 people will buy the book (resulting in a total income of 200,000 dollars). For every dollar you subtract from the book price, 4,000 additional people will buy the book. This also applies to fractional numbers of dollars. For example, if the book costs $19.90, 10,400 people will buy it.
1. If you are required to choose a book price of at least 10 dollars and no more than 15 dollars, determine the price that would result in the highest possible total income. Make sure to justify your answer using calculus, rather than intuition or techniques from other courses
2. If you are required to choose a book price of at least 5 dollars and no more than 10 dollars, determine the price that would result in the highest possible total income."
I've deduced that for part 1, if the price per book is 15 dollars, there will be 30000 buyers, and thus a total income of $450000.
If the price per book is 10 dollars, there will be 50000 buyers, and the total income will be $500000.
I don't know how I should go about setting up the equation and constraint, however.
Answer: Your income is $I = (20-x)(10000+4000x) = 200000+70000 x-4000x^2$
$$I' = 70000-8000x \overset{!}{=} 0 \quad \to x = 8.75$$
This price results in the maximum income and for the first interval it's the limit closer to this.

Elementary Optimization Problem


Read a tab delimited txt file and Display it in reverse order

Question: I have a tab delimited text file that uses a Classic ASP page to read it and display it from top to bottom.  Here is the text file:
Email                     Division      Course   TotalIncorrect Score   DATE_TIME
email@example.com    National      BI Course   5           40%     2014-01-23 16:38:55
email@example.com   B - H - J - L BI Course   5           100%    2014-01-31 14:56:34
email@example.com      D - F - K     BI Course   5           100%    2014-02-07 18:11:22
email@example.com    National      BI Course   5           40%     2014-01-23 16:38:55
firstname.lastname@example.com   B - H - J - L BI Course   5           100%    2014-01-31 14:56:34

Here is the ASP code which reads the txt file:
<%

Response.CharSet = "UTF-8"
dim import_file,counter,line,fso,objFile
import_file="QuizScores.txt"
counter=0
set fso = createobject("scripting.filesystemobject")

If (fso.FileExists("D:\Vignette\QuizScores.txt"))=true Then

set objFile = fso.opentextfile(server.mappath(import_file))

str_imported_data="
"
Do Until objFile.AtEndOfStream

line = split(objFile.ReadLine, vbTab)

if (counter Mod 2 = 0) And (counter = 0) then
  str_imported_data=str_imported_data&"
"
Elseif (counter Mod 2 = 0) Then
  str_imported_data=str_imported_data&"
"
Else
  str_imported_data=str_imported_data&"
"
end if

counter=counter+1
total_records=ubound(line)

for i=0 to total_records
  if ((i=0) or (i=6)) then
     str_imported_data=str_imported_data&""&line(i)&"	"
  else
     str_imported_data=str_imported_data&""&line(i)&"	"
  end if
next
  str_imported_data=str_imported_data&"
" & chr(13)
Loop
str_imported_data=str_imported_data&"
Project Systems Solution Real Property Course Test Scores

"

objFile.Close

response.Write str_imported_data
set fso=nothing

Else
  Response.Write("Test Scores File does NOT exist.")
End If

%>

I would like to have the asp page read the txt file but reverse the order so that the most recent record would appear at the top of the table and the oldest at the bottom.
Any help would be appreciated.  I am fairly new at ASP!
Thanks
Here is my REVISED CODE April 1st 2014:

<%
Response.CharSet = "UTF-8"
dim import_file,counter,line,fso,objFile
Dim array_line(), array_column()

import_file="QuizScores.txt"

set fso = createobject("scripting.filesystemobject")

If (fso.FileExists("D:\Vignette\QuizScores.txt")) Then

set objFile = fso.opentextfile(server.mappath(import_file))
counter=0
Do Until objFile.AtEndOfStream
    array_line(counter) = objFile.ReadLine
    counter=counter+1
    Redim Preserve array_line(counter)
Loop
objFile.Close
set fso=nothing

str_imported_data="
"
total_records=ubound(array_line)

for i_row=total_records to 0 step -1
    array_column = split(array_line(i_row), vbTab)

    if (i_row Mod 2 = 0) And (i_row = 0) then
        s_bgcolor = "bgcolor='#3C3C3C' style='font-weight: bold; color:white;'"
    Elseif (i_row Mod 2 = 0) Then
        s_bgcolor = "bgcolor='#EEEEEE'"
    Else
        s_bgcolor = "bgcolor='#FFFFE5'"
    end if

    str_imported_data=str_imported_data & "
" & vbCrLf

    for i_col = 0 to 6
        if ((i=0) or (i=6)) then
            str_imported_data = str_imported_data & "" & array_column(i_col) & "	" & vbCrLf
        else
            str_imported_data = str_imported_data & "" & array_column(i_col) & "	" & vbCrLf
        end if
    next 'i_col
    str_imported_data = str_imported_data & "
" & vbCrLf & vbCrLf
next 'i_row

str_imported_data = "
Project Systems Solution Real Property Course Test Scores

" & vbCrLf & str_imported_data

response.Write (str_imported_data)
Else
Response.Write("Test Scores File does NOT exist.")
End If
%>

Comment: Read it into an array / collection, reverse / sort it, then display it....
Comment: Thanks.  Conceptually I know that is what is required, but I am not quite sure how to go about doing it.  I was considering reading each row of the text file into a two dimensional array but like I said, my ASP skills are not quite at that level.
Answer: Untested but won't have many errors.
FYI: I recommend you notice the way I spaced things out; for more readable code.
Oh and if memory serves, putting "bgcolor" attribute into TR does not work in most browsers, which is why I moved it to the TDs.
<%
Response.CharSet = "UTF-8"
dim import_file,counter,line,fso,objFile
import_file="QuizScores.txt"
counter=0
set fso = createobject("scripting.filesystemobject")

If (fso.FileExists("D:\Vignette\QuizScores.txt")) Then

    set objFile = fso.opentextfile(server.mappath(import_file))
    counter=0
    Do Until objFile.AtEndOfStream
        array_line(counter) = objFile.ReadLine
        counter=counter+1
    Loop
    objFile.Close
    set fso=nothing

    str_imported_data="
"
    total_records=ubound(array_line)

    for i_row=total_records to 0 step -1
        array_column = split(array_line(i_row), vbTab)

        if (i_row Mod 2 = 0) And (i_row = 0) then
            s_bgcolor = "bgcolor='#3C3C3C' style='font-weight: bold; color:white;'"
        Elseif (i_row Mod 2 = 0) Then
            s_bgcolor = "bgcolor='#EEEEEE'"
        Else
            s_bgcolor = "bgcolor='#FFFFE5'"
        end if

        str_imported_data=str_imported_data & "
" & vbCrLf

        for i_col = 0 to 6
            if ((i=0) or (i=6)) then
                str_imported_data = str_imported_data & "" & array_column(i_col) & "	" & vbCrLf
            else
                str_imported_data = str_imported_data & "" & array_column(i_col) & "	" & vbCrLf
            end if
        next 'i_col
        str_imported_data = str_imported_data & "
" & vbCrLf & vbCrLf
    next 'i_row

    str_imported_data = "
Project Systems Solution Real Property Course Test Scores

" & vbCrLf & str_imported_data

    response.Write (str_imported_data)
Else
  Response.Write("Test Scores File does NOT exist.")
End If
%>

Comment: @ScotterMonkey Pushie you aren't ya, if he doesn't want to upvote you he doesn't have to, nought more desperate than asking for upvotes. Maybe once he get's your solution to work then he'll upvote it.
Comment: No Problem.  I will vote now because what you have added so far is very close and I will keep at it until I figure it out.
Comment: Thanks very much for providing me with this possible solution.  I have been trying it for a while now and am not able to get it to work.  One thing I wondered about is total_records=ubound(line).  line is not used anywhere else in the program.  Is there possibly another typo somewhere that I am missing?  Thanks again.
Comment: Ooops! total_records=ubound(array_line)
Comment: Please feel free to mark my code as solution. I can use the points :-)
Comment: I checked my log files and I am getting the following error message:  Type_mismatch:_'array_line' 80
Comment: Ah you probably need to dim array_line() before you start reading the file into array_line(). I recommend googling "vbscript arrays". I want to fall on the side of helping you without doing ALL the work :-)
Comment: There is a great tutorial here on how to set up and use arrays, including - make sure you read the part about using "preserve" so you can set up an array at the beginning to be "variable size" like this: dim array_line() and then later use redim. Here is the tutorial: http://www.tutorialspoint.com/vbscript/vbscript_arrays.htm
Comment: I am so close, but now I am getting the subscript out of range error - 800a0009|Subscript_out_of_range.  I have read your tutorial and dimmed the arrays but cannot see my error.
Comment: Did you use redim? Please show your code. You still haven't even upvoted my answer.
Comment: I will be pleased to vote and give you points once I get it to work.  Like I said, I am new to ASP so I have not quite figured out all of the nuances of arrays.  It appears as though that is the issue here.  My errors are related to the arrays not loading up properly.
Comment: Sorry. I never asked for votes before. Just the other day I got banned from asking questions because I asked a question in the wrong area and the only way to get my privileges back is to get votes. So yeah, I guess I was a bit desperate, heh. Sorry.
Comment: I am trying to vote up, but I need 15 reputations to be able to vote.
Comment: Please post your code that you have so far and I'll modify it to make it work. I was reluctant to do this for you ONLY because I thought it would inhibit your learning for me to do all of it for you. But if you want it, I'll do it. However, if you want to do it yourself, I recommend studying the link I gave you, particularly the part about REDIM and then figure out where to add REDIM in. Again, though, post your code if you want help and I'll give it.
Comment: @ScotterMonkey:  I added the revised code at the bottom of the original post.  Thanks for you help!
Comment: Change this to look like this (slight re-order):

Redim Preserve array_line(counter+1) :
array_line(counter) = objFile.ReadLine :
counter=counter+1

I'm putting that "+1" in there because I'm not sure if you can dim an array to be (0) in size.
SO this will work but it will also cause one last line at the end that is empty. Note the colons I put in to mean carriage return because this box won't let me format code.


Microservices - Security Implementation

Question: Is it better to handle security at a microservice level or at api-gateway level in microservice deployments? Are there scenarios where one would be more apt than the other?
Answer: From this article:

A major benefit of using an API Gateway is that it encapsulates the internal structure of the application. Rather than having to invoke specific services, clients simply talk to the gateway.

This simply means that clients talk to microservices through an API gateway and that gateway handles all the requests which comes for any of the underlying services.
So, I think that if you need to do any authorisation for a request, it is beneficial to do it at API gateway itself because this way, an unauthorised request never reaches your service.
But that can't be a complete a solution as well. Let's consider a service which actually authenticate a user. This service will always be accessed by users who haven't been authorised yet, so, it makes sense to implement security for this service at the service level instead of the API gateway.
Also, consider a service which create orders. What if any internal service can call this service and create an order, without requiring any token (or any other authentication process). Now this problem can be solved using many ways like:

Restricted network access to internal services, such at not other service except API gateway can access this service.
Add/Proxy the security token (like JWT) to all services and validate a request against that token in each of the service.

Of course this is a high level overview, are my thoughts and I am willing to see what others have to say.
Comment: Thank you Shubham! This is very useful
Answer: I'd say it's the common way tu use some kind of reverse proxy as security gateway, that generates some kind of security tokens, like SAML.
Otherwise for example, if you have some chained calls, like micro service user calls micro service transaction log, each and every microservice does the auth for itself again and again. This can get quite expensive.
Comment: Thanks Dudelilama

Microservices - Security Implementation


Confidence Intervals - distribution of a Pivot?

Question: I am working on some self study and have come across "The Pivot Method". It seems quiet abstract and I can't understand what the usefulness of the following statement is regarding pivots: The distribution of a pivot does not depend on the parameter of interest?
What exactly is a pivot and what is meant by the statement "the distribution of a pivot does not depend on the parameter of interest"?
Answer: A pivotal quantity is function of the sample observations and a parameter whose distribution is completely specified (does not contain any unknown parameters).
(1) For example, if $X_{1},X_{2},\cdots,X_{n}$ is a random sample from $N(\mu,5)$ and let $\bar{X}$ be the sample mean. Then the distribution of $\bar{X}-\mu \sim N(0,5)$, is completely specified, as there are no unknown parameters. The quantity $\bar{X}-\mu$ is a pivotal quantity.
(2) As another simple example, let $X_{1},X_{2},\cdots,X_{n}$ is a random sample from $N(\mu,\sigma^2)$ and let $\bar{X}$ be the sample mean. Then the distribution of $\frac{ \bar{X}-\mu}{\sigma/\sqrt{n}} \sim N(0,1)$. Here $\frac{ \bar{X}-\mu}{\sigma/\sqrt{n}}$ is a pivot.
(3) If $\bar{X}$ is the sample mean of a random sample of size $n$ obtained from normal population $N(\mu,\sigma^2)$, with $\sigma^{2}$ unknown,  the $t$-statistic defined by $\dfrac{\bar{X}-\mu}{S/\sqrt{n}}$ is a pivot because the $t$-distribution does not depend on the parameters $\mu$ and $\sigma$.
Comment: @tony1kenobi, I have added some examples, for more clarity. Hope you will find them useful.
Comment: Excellent examples (+1). Also if $X_i$ from $N(\mu,\sigma^2)$ then $(n-1)S^2/\sigma^2 \sim \mathsf{Chisq}(df = n-1)$ is pivot leading to asymmetrical CI for $\sigma^2.$
Comment: I understand that :-) I's amazing how many books/references don't actually say what is clearest regards 'pivots'. Thanks


Noncommutative rings and prime/maximal ideals

Question: Let $R$ a non-simple noncommutative ring, and let $\mathcal{I}$ the set of non-trivial (right, left) ideals of $R$, with the following property: "Every element $I \in \mathcal{I}$ is prime and/or maximal".
There exists an example of such $R$?
Comment: What does "(right, left) ideals of $R$" mean? You want us to choose either one? or you mean both, so that they are two-sided ideals? You should just say two-sided ideals, if you want to emphasize that.
Comment: When you say "noncommutative" do you mean "not necessarily commutative" like everyone else?  Or you want it to be not commutative?
Answer: Let $R=\mathbb H\times \mathbb H$ where $\mathbb H$ denotes Hamilton's quaternions.
It has four right ideals, all of which are two sided, two of which are trivial, and the other two are maximal and prime.
Comment: Thanks! The same occurs with $\mahtbb{H}^{n} = \underbrace{\mathbb{H} \times \ldots \times \mathbb{H}_{n \ \mbox{times}}$?
Comment: @674123173797-4 Yes, it does.


Any hints on how to show that this measure $\nu$ is finitely additive but not countably additive.

Question: Define the function $\nu: \mathcal M \to [0,\infty]$ by $\nu(A)=\infty$ if $0$ is in the closure of $A$ and $\nu(A) = 0$ otherwise. Prove that $\nu$ is finitely additive but not countably additive.
$\mathcal M$ is the set of Lebesgue measurable subsets of $\mathbb R$.
Any hints on how to show this?
Comment: @Mark I've edited my post. $\mathcal M$ is the set of Lebesgue measurable subsets of $\mathbb R$.
Answer: Hint: consider a sequence of measurable sets $A_n$ such that $0 \notin \overline{A_n}$ for any $n$ but such that $0 \in \dots$
Comment: ...but that $0 \in \bigcup_{i=1}^\infty A_i = \mathbb R$?
Comment: @AlJebr : the union doesn't need to be the entire real line, but yes, you want $0$ to belong to the (closure) of the union of the $A_n$.
Comment: Ok, so we want $0 \in \overline{\bigcup_{i=1}^\infty A_i}$?
Comment: @AlJebr : that's correct. Now you should be able to see why countable additivity fails!
Answer: $\nu(\{1/n\})=0$ for each $n\in \mathbb N$ but $0\ne \nu(\{1/n:n\in \mathbb N\}).$
For finite additivity use the fact that $Cl(\bigcup_{i=1}^nA_i)=\bigcup_{i=1}^nCl(A_i)$ for any $n\in \mathbb N$.
Comment: I think $\nu(\mathbb N)=0$ since $\mathbb N$ is closed in $\mathbb R$ and $0\notin \mathbb N$.
Comment: Yes. And  I didn't type what I was thinking. I have fixed it.
Answer: for a fail of countable additivity take any infinite sequence $S$ consisting of distinct points in $\mathbb{R} \setminus \{0\}$ and for which $0 \in \bar S$
Comment: Do you mean $0\notin \bar S$?


Sorting columns and selecting top n rows in each group pandas dataframe

Question: I have a dataframe like this:
mainid  pidx    pidy   score
  1      a        b      2
  1      a        c      5
  1      c        a      7
  1      c        b      2
  1      a        e      8
  2      x        y      1
  2      y        z      3
  2      z        y      5
  2      x        w      12
  2      x        v      1
  2      y        x      6

I want to groupby on column 'pidx'  and then sort score in descending order in each group i.e for each pidx
and then select head(2) i.e top 2 from each group.
The result I am looking for is like this:
mainid   pidx    pidy    score
  1        a      e        8
  1        a      c        5
  1        c      a        7
  1        c      b        2
  2        x      w        12
  2        x      y        1
  2        y      x        6
  2        y      z        3
  2        z      y        5

What I tried was:
df.sort(['pidx','score'],ascending = False).groupby('pidx').head(2)

and this seems to work, but I dont know if it's the right approach if working on a huge dataset. What other best method can I use to get such result?
Answer: There are 2 solutions:
1.sort_values and aggregate head:
df1 = df.sort_values('score',ascending = False).groupby('pidx').head(2)
print (df1)

    mainid pidx pidy  score
8        2    x    w     12
4        1    a    e      8
2        1    c    a      7
10       2    y    x      6
1        1    a    c      5
7        2    z    y      5
6        2    y    z      3
3        1    c    b      2
5        2    x    y      1

2.set_index and aggregate nlargest:
df = df.set_index(['mainid','pidy']).groupby('pidx')['score'].nlargest(2).reset_index()
print (df)
  pidx  mainid pidy  score
0    a       1    e      8
1    a       1    c      5
2    c       1    a      7
3    c       1    b      2
4    x       2    w     12
5    x       2    y      1
6    y       2    x      6
7    y       2    z      3
8    z       2    y      5

Timings:
np.random.seed(123)
N = 1000000

L1 = list('abcdefghijklmnopqrstu')
L2 = list('efghijklmnopqrstuvwxyz')
df = pd.DataFrame({'mainid':np.random.randint(1000, size=N),
                   'pidx': np.random.randint(10000, size=N),
                   'pidy': np.random.choice(L2, N),
                   'score':np.random.randint(1000, size=N)})
#print (df)

def epat(df):
    grouped = df.groupby('pidx')
    new_df = pd.DataFrame([], columns = df.columns)
    for key, values in grouped:
        new_df = pd.concat([new_df, grouped.get_group(key).sort_values('score', ascending=True)[:2]], 0)
    return (new_df)

print (epat(df))

In [133]: %timeit (df.sort_values('score',ascending = False).groupby('pidx').head(2))
1 loop, best of 3: 309 ms per loop

In [134]: %timeit (df.set_index(['mainid','pidy']).groupby('pidx')['score'].nlargest(2).reset_index())
1 loop, best of 3: 7.11 s per loop

In [147]: %timeit (epat(df))
1 loop, best of 3: 22 s per loop

Answer: a simple solution would be:
grouped = DF.groupby('pidx')

new_df = pd.DataFrame([], columns = DF.columns)

for key, values in grouped:

    new_df = pd.concat([new_df, grouped.get_group(key).sort_values('score', ascending=True)[:2]], 0)

hope it helps!
Answer: Another method is to rank scores in each group and filter the rows where the scores are ranked top 2 in each group.
df1 = df[df.groupby('pidx')['score'].rank(method='first', ascending=False) <= 2]


Proof $f$ is Differentiable.

Question: I have been looking through the stack and can not find a direct answer to this question. I recently read that we say $f$ is defferentiable on $I$, if $f$ is differentiable at every point on an open interval $I$. It almost reminds me of the rigorous deffinition of a limt, $\forall\epsilon>0\hspace{0.2cm}\exists\hspace{0.2cm}\delta=\delta(\epsilon)>0$ such that $0<|x-a|<\delta\implies|f(x)-L|<\epsilon$, and how we can use said definition to write all kinds of $\epsilon-\delta$ proofs regarding limits. Proving continuity, proving uniqueness of limits, so on and so forth.
My question is: What is the standard proof writing format (such as $\epsilon-\delta$ proofs for limits) for proving differentiability based of the rigorous definition of a derivative? Assuming there is a rigorous definition of a derivative similar to that of limits, please provide an example proof.
Comment: I would advise against the use of $\epsilon, \delta$ unless they are necessary. These kind of proofs are mostly used for theoretical results (like for proving theorems on algebra of limits, theorems on rules of differentiation) but should be avoided when dealing with concrete problems like evaluation of a limit or a derivative.
Answer: The derivative is a limit. You can just apply the definition of the limit to prove differentiability rigorously. Namely, a function $f$ defined on an open $U \subset \mathbb{R}$ is differentiable at a point $x_0 \in U$ if there is a real number $L$ such that for all $\epsilon>0$ there is a $\delta>0$ such that $0<|x-x_0| < \delta$ implies $\left|\frac{f(x) - f(x_0)}{x - x_0} - L\right| < \epsilon $.
You might wonder, why don't we ever use $\epsilon-\delta$ arguments with derivatives? Well, it's because we don't need to. The proofs of the differentiation rules (e.g., product rule, chain rule) require an $\epsilon-\delta$ argument, but after we've proven these theorems, we never need to use $\epsilon-\delta$ arguments again.
Comment: So there is really no use for proving in such a manner?
Comment: @NickPavini Yes, there is no use. But, we _could_ if we wanted to, and it is maybe good practice.
Comment: oh wow! lol, I am just getting into proofs really so I like the rigorous definition as it helps to see at thoroughly.:)
Answer: The derivative of a function $f:X \to Y$ with respect to a (cluster) point $a \in X$ is defined as
$$ \lim_{x \to a} \frac{f(x)-f(a)}{x-a},$$
or, equivalently, making $h=x-a,$ as
$$ \lim_{h\to 0}\frac{f(a+h)-f(a)}{h}.$$
So, for proving $f$ is differentiable at $a$, you have to show that limit exist.
Comment: so basically I can rely on $\epsilon-\delta$ proofs for differentiability?
Comment: Usually you show the limit exists by using properties of limits, as almost in every case proving this limit by $\epsilon - \delta$ is just too tricky
Comment: (+1) but I would really like to see how it would be done $\epsilon-\delta$ style.:)
Answer: My proof of derivative implies continuity:
Think about this: For all ϵ>0 there exists $δ>0$ such that $0<|x-c|<δ$ implies $|\frac{f(x)−f(c)}{x−c}|<ϵ$.
Start my proof: Since f is derivative at $c ∈ R$,
There exists δ>0 such that $0<|x-c|<δ$ implies $|\frac{f(x)−f(c)}{x−c}|=|f(x)-f(c)|\times \frac{1}{|x-c|}$.
We assign $ϵ=\frac{ϵ_1}{|x-c|}>0$, then $|f(x)-f(c)|*\frac{1}{|x-c|}<ϵ$ implies $|f(x)-f(c)|<ϵ=\frac{ϵ_1}{|x-c|}$.
Hence for all $ϵ>0$, There exists $δ>0$ such that $0<|x-c|<δ$ implies $|f(x)−f(c)|<ϵ$, i.e. we have $\lim_{x→c} f(x)=f(c)$.
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).

Proof $f$ is Differentiable.


Integer Programming with valid inequalities

Question: This question is mainly geared toward Operations Research field.
I have a large Mixed Integer Program (MIP). I found a set of facet and valid inequalities which supposedly should make the LP relaxation tighter.
The problem I ran into is that my original MIP obtains the optimal solution in less computational time compared with MIP+ valid inequalities formulation. I did many experiments. I am speaking of large instances.
My guess is that adding these valid inequalities and facets make solving the LP more time consuming. Hence, it's defeating the purpose because MIP + valid inequalities now takes more time.
These inequalities have interesting theoretical properties and I don't want to give up due to their poor performance computationally.
I think my question is how I can get around it and make MIP + valid inequalities faster or justify them?
Answer: I'm not sure you can (or should). Theoretical properties aside, the main purpose of valid inequalities is to tighten the LP bound so that the MIP solver both finds the optimal solution sooner (if you're lucky) and reaches provable optimality sooner (the main purpose). Some problems have inherently tight LP bounds, and those problems may not benefit from adding valid inequalities. Unless you are unsatisfied with your solution times without them, I doubt there's much to gain from using them.
If you are unsatisfied with solution times for the original model without the inequalities, and if you solver supports something like what CPLEX calls "lazy constraints", you could try adding the inequalities as lazy constraints. That might cause the solver to set the less promising ones aside at any given time and reduce the computational burden they add, while at the same time exploiting whatever tightening some of them provide. There's no guarantee that helps, though.
Comment: Thank you for your reply. I actually have another formulation which uses Lazy constraints. It gives better results for sparse graphs in my problem. You answer is very insightful as I think I should rather focus on the lower bound (minimization problem) of my problem and assess the performance of these valid inequalities in improving the lower bounds rather than the upper bound (i.e., feasible solution).
Comment: Another thing that came to my mind is to shut off the cuts generated by GUROBI/CPLEX. I just want to know if these valid inequalities improve my lower bound or not. However, Gurobi will add many cuts and for that reason it will possibly make my added cuts obscure.


Feeds Import csv - inline images

Question: I'm using the feeds module to import thousands of nodes into my Drupal 6 site (the source is a Drupal 5 site) and after figuring a few things out, it actually works really nicely! I just have one problem though, most of these nodes are supposed to contain inline images, and I'm wondering how to recover them as they don't come with the import...?
Thanks!
Answer: If the enable full html does not work try using Feeds Image Grabber
Answer: Under the settings of the importer (Feeds -> (Importer name ->) Processor -> Node processor -> Settings) is the Input format set to default? If so, is the default Filtered HTML? That might remove the images. You could you try changing this to Full HTML...

Feeds Import csv - inline images


How to read / write arraylist of custom object into internal storage in android

Question: In our application , we are getting pdf files from server. We store those files such as its content , file size , no.of pages etc. into array list. Now we are storing this array list into DB, sometimes we are getting out of memory error. How we can store this array list into internal storage for security.
Below is code:
<code>ArrayList<ScriptBean> scriptBeanArr = getScripts(scriptIds); ArrayList<ScriptBean> tempList = DbConnection.getdbObject(activityContext).updateScriptPdfToDB(scriptBeanArr));
</code>
Comment: Please give snippet of your code so that we can suggest you something.
Comment: In our code we have custom obj as scriptBean , which has multiple properties such as content , no of pages,file size etc. From server we are getting multiple pdf files. so we are storing into arraylist of scriptBean object and this arraylist we are storing into DB. Below is code:                                              ArrayList scriptBeanArr = getScripts(scriptIds);           ArrayList tempList = DbConnection.getdbObject(activityContext).updateScriptPdfToDB(scriptBeanArr));
Answer: You should let the class you'd like to write to disk implement Serializable. Then, serialize the class and write the bytes to a file on disk. Then you can read the bytes from the disk and deserialize them into an object.


How to write java.util.stream.Stream to StreamingResponseBody output stream

Question: I am working to build a REST API where a large amount of data from the Oracle database can be sent in chunks via streaming to client application (like a file download or direct stream).
I am getting Stream from JpaRepository as given below -
@Query("select u from UsersEntity u")
Stream<UsersEntity> findAllByCustomQueryAndStream();

But now challenge comes to write this stream to StreamingResponseBody Output stream
I tried by many ways but no success -
First Approach -
Stream<UsersEntity> usersResultStream = usersRepository.findAllByCustomQueryAndStream();

        StreamingResponseBody stream = outputStream -> {
            Iterator<UsersEntity> iterator = usersResultStream.iterator();

            try (ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {

                while (iterator.hasNext()) {
                    oos.write(iterator.next().toString().getBytes());
                }
            }
        };

Got Error -
java.sql.SQLException: Closed Resultset: next
    at oracle.jdbc.driver.InsensitiveScrollableResultSet.next(InsensitiveScrollableResultSet.java:565) ~[ojdbc7-184.108.40.206.jar:188.8.131.52.0]

Second Approach -
StreamingResponseBody stream = new StreamingResponseBody() {

            @Transactional(readOnly = true)
            @Override
            public void writeTo(OutputStream outputStream) throws IOException {

                Stream<UsersEntity> usersResultStream = usersRepository.findAllByCustomQueryAndStream();

                try (ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {

                    usersResultStream.forEach(user->{
                        try {
                            oos.write(user.toString().getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
            }
        };

Got Error -
org.springframework.dao.InvalidDataAccessApiUsageException: You're trying to execute a streaming query method without a surrounding transaction that keeps the connection open so that the Stream can actually be consumed. Make sure the code consuming the stream uses @Transactional or any other way of declaring a (read-only) transaction.

I have uploaded practice code at the below-given link -
Sample POC Link
I don't have any experience with the streaming related task so please help me with this.
If I am in the wrong direction than suggest any other approach to do this within Spring Framework. Please share any reference links if available.
Answer: Finally, I resolved the problem by using the service layer. Initially, I was writing the complete logic in Controller Class which was creating the issue.
Controller Class -
@RestController
@RequestMapping("/api")
public class UsersController {
    @Autowired
    private UserService service;

    @GetMapping(value = "/userstream")
    public ResponseEntity<StreamingResponseBody> fetchUsersStream() {

        StreamingResponseBody stream = this::writeTo;

        return new ResponseEntity<>(stream, HttpStatus.OK);
    }

    private void writeTo(OutputStream outputStream) {
        service.writeToOutputStream(outputStream);
    }
}

Service Class -
@Service
public class UserService {

    @Autowired
    private UsersRepository usersRepository;

    @Transactional(readOnly = true)
    public void writeToOutputStream(final OutputStream outputStream) {
        try (Stream<UsersEntity> usersResultStream = usersRepository.findAllByCustomQueryAndStream()) {
            try (ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {

                usersResultStream.forEach(emp -> {
                    try {
                        oos.write(emp.toString().getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Complete Code is available at github - https://github.com/bagesh2050/HttpResponseStreamingDemo
Still, I am willing for suggestions related to Http Streaming. Please provide if you have better ideas.
Answer: No sample shows "such complex" usage of StreamingResponseBody, and I fear it is "not possible" (at least I couldn't manage/fix it, with StreamingResponseBody and Stream query)
...but, what was possible:

Use findAll() (the normal unstreamed List-repo method) within StreamingResponseBody.
(But I understand the "need" of doing the web request asynchronously... and the db request "streamed"...)
Use Callable (async web request) and an @Async CompletableFuture<..> (async db request):
@RestController
@RequestMapping("/api")
public class UsersController {

   @Autowired
   private UsersRepository usersRepository;

   @GetMapping(value = "/async/users")
   public Callable<List<UsersEntity>> fetchUsersAsync() {
       Callable callable = () -> {
           return usersRepository.readAllBy().get();
       };
       return callable;
   }
}

..and a Repository like:
@Repository
public interface UsersRepository extends JpaRepository<UsersEntity, Integer> {

    @Async
    CompletableFuture<List<UsersEntity>> readAllBy();
}

(see spring-samples)
.. don't forget to @EnableAsync on your application/configuration:
@org.springframework.scheduling.annotation.EnableAsync
@SpringBootApplication
public class Application { ... }

Sorry, it is not even an answer, but my findings - too long for a comment.
The asynchronous web request can be achieved in various ways. (see https://spring.io/blog/2012/05/10/spring-mvc-3-2-preview-making-a-controller-method-asynchronous/, https://niels.nu/blog/2016/spring-async-rest.html, and even  not mentioned "reactive" api)


What is the appropriate way to use the Runge-Kutta method to calculate neural network node activities?

Question: I am a cognitive scientist, and am modelling a particular kind of neural network called a "masking field", where the change in activation of a particular node in the masking field is:
$${dy_i(t)\over dt} = -Ay_i(t) + [B - y_i(t)]P_i(t) - [C + y_i(t)]Q_i(t)$$
Where $A$, $B$ and $C$ are constants, $y_i(t)$ is the activation of node $i$, $P_i(t)$ is the net excitation to this node from other nodes, and $Q_i(t)$ is the net inhibition from other nodes. Excitation/inhibition from other nodes is dependent on their activation levels, which also change with time.
It is straightforward enough to model this iteratively in computer using Euler's method:
$$y_{in+1} = y_{in} + h\{-Ay_{in} + [B - y_{in}]P_{in} - [C + y_{in}]Q_{in}\}$$
where $h$ is the step size, and all $y_{i0}$ are known. For each step, I calculate all the $P_{in}$ and $Q_{in}$ for all nodes using node activations at timestep $n$, then calculate the activation values of all nodes for step $n+1$. The next step I can use all the updated activations to calculate all of the $P_{in+1}$ and $Q_{in+1}$, before calculating the $n+2$ activations, etc.
However, I wanted to see if using the Runge-Kutta fourth order method would give better results. My question is:
Q. When calculating the K1, K2, K3 and K4 values for a particular node $i$ using the Runge-Kutta method, do I recalculate $P_{in}$ and $Q_{in}$ when calculating each of the four K values, since the activations of all the other nodes are also changing? That is, I would calculate K1 for every node, and use all these K1 values to then calculate K2 values for every node, then use all these to calculate the K3s, and the K4s, before finally calculating the n+1 activations? Or should I treat $P_{in}$ and $Q_{in}$ as constant when calculating K1-4 for node $i$, so that I am only considering the change in activation of one node at a time?
Thankyou!
Answer: If you were to treat $P$ and $Q$ as constant during the step, then you would be better served by using the exact solution of
$$
\dot y+ay=b,\qquad a=A+P+Q, \;b=BP-CQ
$$
where the solution is
$$
y(t+h)=b+e^{-ah}(y(t)-b)
$$
which can be then used instead of the Euler step.

For the full Runge-Kutta method you got it right, you have to re-compute the $P$ and $Q$ in every stage. However, you can use much larger step-sizes than with the Euler method for the same accuracy. Improving the accuracy by a factor of $16=2^4$ requires 16 times the steps with the Euler method, but only a doubling of steps and thus function evaluations with RK4.


Form theming with templates

Question: Please could someone explain why the following doesn't work?
This is in the form build:
$form['#theme'] = 'some_form';

Here's the hook_theme function:
function MYMODULE_theme($existing, $type, $theme, $path) {
    return array(
      'some_form' => array(
        'template' => 'some-form',
        'variables' => array('form' => NULL),
      ),
    );
}

The template (some-form.tpl.php):

<?php print render($form); ?>

You can see the wrapper markup from the template file but the form is not being output.
Answer: Since you're attaching the #theme to an element, you need to user render element in your theme declaration in place of variables:
function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'some_form' => array(
      'template' => 'some-form',
      'render element' => 'form'
    ),
  );
}

After you clear the caches your template should start being used for that form.
See hook_theme() for more information.
Just another thought, if your template file is as trivial as just wrapping the form in a tag you can use the #prefix and #suffix properties on the $form object instead of using a theme at all:
$form['#prefix'] = '
';
$form['#suffix'] = '
';

Comment: Thanks Clive, doesnt appear to work though, just get a popup prompting me to download some random file??????
Comment: Would of done the other suggestion but the wrapper markup is going to be a bit more extensive than in this example.
Comment: Ah it might be because you had `tpl.php` at the end of the `template` property in `hook_theme()`...the theme engine adds that automatically so you don't need to. I've updated the answer. Remember to clear the caches after every change you make in `hook_theme()`
Comment: No sorry, not sure why I put that in that in the question but no tpl.php. Have corrected this now.
Comment: Hmmm can't think why, that's definitely the right way to do it. Try comparing your code to the examples on [Theming forms in Drupal 7](http://drupal.org/node/1067612) and see if you can find the discrepancy
Answer: Can you try to insert at the beginning of your TEMPLATE file.
<?php
  echo render( $form['form_id']);
  echo render( $form['form_build_id']);
  echo render( $form['form_token']);
  echo render( $form['options']['status']);
?>

Form theming with templates


How does rand() generate a sequence of random numbers from a single seed?

Question: In a loop it's enough to set the seed one time to get a sequence of random numbers. How does the function rand generate a lot of random numbers based on one seed only ?
Comment: How does Fibonacci generate a lots of numbers starting from just 1? There's a simple rule that leads from one element in the succession to the next one; and in the case of `rand` it is such that the numbers *look* quite random (both to the casual observer and according to some basic statistical tests).
Comment: related: [How does rand() work? Does it have certain tendencies? Is there something better to use?](http://stackoverflow.com/questions/3539398/how-does-rand-work-does-it-have-certain-tendencies-is-there-something-better)
Comment: you always get a sequence from rngs and actually it is an important feature of rngs that they always produce the same sequence given the same seed. After all they arent that random
Comment: https://en.wikipedia.org/wiki/Random_number_generation
Answer: All you need is an algorithm to turn one number into two numbers. One number becomes your next output, the other becomes your next seed. Such algorithms are quite simple. For example, you could multiply the number by two different primes and then reduce each mod 65536. That would produce two outputs from a single input.
An alternative method is even simpler:
1) Permute the seed by multiplying it by one number and adding a second number.  (For example, seed = seed * 214013 + 2531011;.)
2) Output only part of the new seed. (For example, return (seed >> 16)  &0x7ffff;.)
Answer: It is actually Pseudorandom, the numbers appear random but are not, they are deterministic since they can be predicted by the algorithm.  A truly random number cannot be predicted.  Using the same seed will produce the same sequence.  The standard specifies and algorithm, but the actual algorithm used will depend on the implementation.


Getting a fakepath when trying to upload a cv

Question: I'm trying to upload my resume to a company's website and I'm getting a C:\fakepath\myfilename,
Does this means that my file can't be uploaded to the website? or is it just for security reasons?
(I tried uploading with Microsoft Edge and Chrome)
Answer: When a file is chosen using an <input type="file">, the real path to the source file is not shown in the input's value attribute for obvious security reasons. Instead, the filename is shown, with C:\fakepath\ appended to the beginning of it. There are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is defined in the spec.
So, the browser shows the fake path for security reasons and it will not cause any issue with the file upload functionality. The file upload will work fine.
References:

Refer to the second point of the Notes section
FileUpload in Chrome giving some fake path value
FakePath issue in Chrome browser


Please explain the logic behind the truth values of these expressions

Question: Can someone explain the reasoning behind the answers given? We reviewed these in class, but I wasn't able to grasp the logic. Especially c, d, and e.

The domain of possible values for variables X and Y is {Jim, Ann, Sal, Pat, Tom}. The following facts define the values for which the
  child predicate is true. The child predicate is false for all other
  cases.
Evaluate each expression using the domain values and predicates as
  defined and indicate if the expression is true or false.
child (Ann,Jim)
child (Sal,Jim)
child (Pat,Ann)
child (Tom,Sal)

a. $(\forall X)$ child$(X,Jim)$
b. $(\exists X)\neg $child$(X,Jim)$
c. $(\forall X)(\exists Y)($child$(X,Jim) \rightarrow $child$(Y,X))$
d. $(\exists Y)(\forall X)($child$(X,Jim) \rightarrow $child$(Y,X))$
e. $(\exists X)(\forall Y)($child$(X,Jim) \rightarrow $child$(Y,X))$

a. FALSE (Reasoning: Any case that make it false? Yes, so FALSE)
b. TRUE (Reasoning: Any case that makes it true? Yes, so TRUE)
c. TRUE
d. FALSE
e. TRUE
Answer: Let me interpret $child(x,y)$ as "$x$ is a child of $y$", then:
(C) you have to check that every child of Jim has a child, Ann is a child of Jim and Pat is a child of Ann, good. Also Sal is a child of Jim and Tom is a child of Sal, nobody else is a child of Jim, so it is true.
(D) The interpretation of this one would be "there is someone who is a child of every child oj Jim". That someone can not be Jim because Jim is not a child of Ann (and Ann is a child of Jim), it can't
't be Ann because Ann is not a child of Sal, conversely it can't be Sal because Sal is not a child of Ann and finally it can't be Tom because he is not a child of Ann.
(E)The interpretation of this one would be "there is someone who verifies that if she/he is a child of Jim then everybody is a child of her/him", if yoy substitute Jim for your variable $x$ then the implication is true because the antecedent (Jim is a child of Jim) is false, so you found someone who verifies that, and so it is true.
Hope it is clear
Comment: I had to re-read your answer after sleeping on it, but your phraseology now makes more sense (even though I'm still having some difficulty). Thank you!
Comment: Yeah, probably i didn't express it quite well, my english is not so good, i need to improve it... Note that it always get harder to follow the logic structure of a proposition when you increases the number of alternating quantifiers (universal, existential, universal...), there is a whole arithmetic hierarchy behind which classifies the formulas based on their complexity. The typical example is the definition of limit of a function, most students find it hard to grasp at the beggining because we are not used to deal with propositions of our natural languages with three quantifiers alternated.


gpsd.socket for chrony does not work

Question: I tried to get more accurate time from gps data using ublox module and centos but it seems gpsd.sock does not work properly to get the data to chrony.
am I missing somthing ?
[root@info /]# cat /etc/chrony.conf
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
server 3.centos.pool.ntp.org iburst

# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift

allow

refclock SOCK /var/run/chrony.ttyS0.sock delay 0.5 refid GPS
refclock PPS /dev/pps0 lock NMEA refid PPS prefer trust

and there is no output in the chrony sources "GPS"
[root@info /]# chronyc sources
210 Number of sources = 6
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
#? GPS                           0   4     0     -     +0ns[   +0ns] +/-    0ns
#* PPS                           0   4     0   311   -382ns[ -613ns] +/-  538ns
^- 184.108.40.206                 3   8   173    17  +8684us[+8684us] +/-   71ms

[root@info /]# cat /lib/systemd/system/gpsd.socket
[Unit]
Description=GPS (Global Positioning System) Daemon Sockets

[Socket]
ListenStream=/var/run/gpsd.sock
ListenStream=0.0.0.0:2947
#SocketMode=0600
SocketMode=0755

[Unit]
Description=GPS (Global Positioning System) Daemon
Requires=gpsd.socket
# Needed with chrony SOCK refclock
After=chronyd.service

[Install]
Also=gpsd.socket
WantedBy=sockets.target

[root@info /]# cat /etc/systemd/system/multi-user.target.wants/gpsd.service
[Unit]
Description=GPS (Global Positioning System) Daemon
Requires=gpsd.socket
# Needed with chrony SOCK refclock
After=chronyd.service

[Service]
EnvironmentFile=-/etc/sysconfig/gpsd
ExecStart=/usr/sbin/gpsd -N -G $OPTIONS $DEVICES

[Install]
WantedBy=multi-user.target
Also=gpsd.socket

Answer: It looks like your refclock PPS line in /etc/chrony.conf is incorrect. it appears you're pointing it to the device when it should be pointed to where gpsd is expecting it, in the format it is expecting.
my two refclock socket lines look like this and it's working:
refclock SOCK /run/chrony.ttyUSB0.sock refid GPS precision 1e-1 offset 0.9999
refclock SOCK /run/chrony.pps0.sock    refid PPS precision 1e-7

your PPS line points to /dev/pps0. it's true, that's where it is, but that's not where you want Chrony to make the socket for gpsd to feed. that's what those two lines say. it's telling Chrony to make these two special socket files for gpsd to send data to. So you don't want Chrony to make a special socket file right on top of the real pps device in /dev/pps0.
This procedure is not simple and numerous online examples can be confisuing. the best step-by-step was right at the GPSD tutorial.

gpsd.socket for chrony does not work


Print a View Field in Twig

Question: I have to convert the following D7 to D8 in my view twig file. I tried the following but its not working.
D7 Code :
<?php print $view->result[$id]->field_field_document_upload[0]["rendered"]["#file"]->filesize; ?>

D8 code in Twig :
   {{ view.result[id].field_field_document_upload[0]["rendered"]["#file"].filesize }}

What's the issue
Comment: You'd have to debug it to validate that is the correct structure to use in the file.
Answer: It's impossible to say without knowing what exact template you are overriding, but you can't really convert your old PHP print statements to twig just like that.
What you can do however is put {{ dump() }} into your twig file, which is the twig equivalent to var_dump() in PHP. This will output all your available variables.
More info on {{ dump() }} here.

Print a View Field in Twig


How do you calculate $E[U_1 | U_1 > U_2]$ where $U_1$ and $U_2$ are independent Uniform RVs from $(0,1)$

Question: My attempt
$$E[U_1 | U_1 > U_2] = E[U_1 | U_1 - U_2 > 0] = \int_{0}^{1} u_1 f_{U_1|U_1-U_2}(a|b) du_1$$
The conditional density function is,
$$f_{U_1|U_1-U_2}(a|b) = \frac{f_{U_1,U_1-U_2}(a,b)}{f_{U_1-U_2}(b)}$$
So there are two things that I need to figure out. One is the joint distribution of $U_1$ and $U_1-U_2$ and the second is the marginal distribution of $U_1-U_2$. I know the latter is the triangular distribution from the convolution formula.
Where I'm having trouble is the joint distribution in the numerator.
My strategy is to first calculate the joint cdf and then take the derivative.
$$F_{U_1,U_1-U_2}(a,b) = P(U_1 \le a, U_1 - U_2 \le b) = P(U_1 \le a, - U_2 \le b - a) $$
If there was no negative in front of $U_2$ then I feel I could set up the double integral.
Motivation
I actually know the answer is $\frac{2}{3}$ because I know how to calculate $E[|U_1 - U_2|] = \frac{1}{3}$ which is a more straight forward problem to me, and then by using conditioning on $E[|U_1 - U_2|]$ get the answer to $E[U_1|U_1>U_2]$ which you can see here.
However, for this question I'm interested in how to directly calculate $E[U_1|U_1>U_2]$ using the definition of conditional expectation. All the stuff I've learned so far is $E[X|Y=y]$, that is conditional expectation where $Y$ is equal to a specific value, versus something like $X>Y$. Thanks for your help.
Comment: https://math.stackexchange.com/q/2685845/321264, https://math.stackexchange.com/q/3991381/321264
Answer: You are not conditioning over a random variable (or its sigma algebra), but rather over an event.
By definition for conditioning over a non-zero probability event:$$\begin{align}\mathsf E(U_1\mid U_1 > U_2) = &~\dfrac{\mathsf E(U_1\mathbf 1_{U_1>U_2})}{\mathsf P(U_1>U_2)}\\ =&~ \dfrac{\displaystyle \iint_{u>v} u~f_{U_1,U_2}(u,v)~\mathsf d (u, v)}{\displaystyle \iint_{u>v} f_{U_1,U_2}(u,v)~\mathsf d (u, v)}\\ =&~ \dfrac{\displaystyle \int_0^1\int_v^1 u~\mathsf d u~\mathsf d v}{\displaystyle \int_0^1\int_v^1 1~\mathsf d u~\mathsf d v}\\ \vdots~&\end{align}$$
Comment: Thank you so much for your guidance. Very interesting... I'm a beginner and so far my book has covered conditioning a RV on another RV... but I see the point you brought up, here this problem is conditioning on an event... I should have suspected something because usually $E[X|Y]$ is itself a RV but my question which conditions on the event $U_1>U_2$ ends up evaluating to a specific number, I believe 2/3. I will need to meditate on this answer... thank you!!


USPS API for Address Correction Response Question

Question: I want to use the USPS API https://www.usps.com/business/web-tools-apis/address-information-api.htm for correcting addresses typed into our application.
Specifically, I will add a little button next to the address that will allow the user send the typed address to the service and then confirm that that the returned address is the one they would like to replace it with.
I have seen other websites do this and I like it because the user has control over inserting errant addresses returned by USPS.  [I am not saying that the USPS data is bad; the likely scenario is that the entered address is so bad the USPS guessed wrong].
Anyway, I am looking at the response sample for the verify service:

I am observing that only one guess at the real address is returned.  Other services I have seen return multiple so the user can pick the best one.
Is there an option on the USPS API that will return multiple guesses for a single address?
Note: the Address ID='0' is for sending multiple addresses and being able to sort it out in the returned data.
Comment: I am having some similar issue where I get the following error "Multiple addresses were found for the information you entered, and no default exists."
Answer: The address you input contained the suite number (STE K) so there is no ambiguity with the result. It is a "precise match". If you remove the "STE K" from the input address, the response will contain a ZIP + 4, but the DPV parameters will indicate that the match is a "default match".  This type of match occurs with high rises and apartment complexes, where there is a main street address which has a "default" ZIP+4, but there is frequently a better "precise" response if an apartment or suite identifier is provided.  The precise response will typically have a different +4 and carrier route than the default response.


Module Not Found Error after library installation

Question: I am trying to use the Scratch library.
For example:
from scratch.probability import normal_cdf
from scratch.linear_algebra import Vector, dot
#...

I installed Scratch using pip install scratch but I receive this error: ModuleNotFoundError: No module named 'scratch'.
Can you help me?
Comment: `pip install scratch-probability` ??
Comment: try `pip install scratch` and see the [two notes](https://github.com/joelgrus/data-science-from-scratch#data-science-from-scratch) in the readme.
Comment: which OS are you using? Which python version? try `pip list` and see if `scratch` is somewhere in the result.
Comment: Yes in pip list I find scratch-probability but when I import it: from scratch-probability import normal_cdf
                ^
SyntaxError: invalid syntax
Comment: It might help to format your code as code, and to include other things you've tried an edited version of the question, rather than in comments.
Answer: pip install scratch will install this: https://pypi.org/project/scratch/
But I guess that what you want to use is that: https://github.com/joelgrus/data-science-from-scratch
The second one is not meant to be installed through pip but used directly in a clone of the project as documented in its README.
About pip install scratch-probability (https://pypi.org/project/scratch-probability/#description), as it's not documented, you need to go check the content of the tarball to know how the package inside are named (if they are what's expected).