How to handle session for anonymous users for CSRF tokens?

Question: I need to provide list of CSRF tokens in drupalSettings for every anonymous user so JS can make safe requests to api endpoints.
The CSRF service mentions the need for session to exist for the seed but I am not clear about how to create the session correctly. I tried various approaches but none seem to work correctly.
So far I have tried:
<code>if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
// or
\Drupal::service('session_manager')->start();
// or
\Drupal::service('session_manager')->save();
// or
\Drupal::service('session_manager')->regenerate();
// or
\Drupal::service('session')->start();
// or
\Drupal::service('session')->migrate();
</code>
I am trying this in my route controller hook_page_attachments_alter.
This is my code:
<code>/**
 * Implements hook_page_attachments_alter().
 */
function foo_page_attachments_alter(array &$attachments) {
  // Needed for persistent, per-user, csrf tokens.
  $session = \Drupal::request()->getSession();
  if ($session->isStarted() === FALSE) {
    $session->start();
  }
  // or
  \Drupal::service('session_manager')->start();

  /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */
  $csrf = \Drupal::service('csrf_token');

  $attachments['#attached']['drupalSettings']['foo']['tokens'] = [
    'pathA' => $csrf->get('/pathA'),
    'pathB' => $csrf->get('/pathB')
  ];

  $session->save();
  // or
  \Drupal::service('session_manager')->save();
}
</code>
Comment: In a controller you should have a session started in the request object, see http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/StackMiddleware/Session.php#n53, but you might need to store a value in the session to make the session id permanent (stored in a cookie).
Answer: So the solution to this problem is that something has to be saved into the session :)
<code>  if (\Drupal::service('session')->isStarted() === FALSE) {
    \Drupal::service('session')->start();
    \Drupal::service('session')->set('foo', 'bar');
  }
  \Drupal::service('csrf_token')->get('baz');
</code>
Also, there is no need to call save() method.


Navbar moves when putting in html code

Question: I'm having some trouble with my online portfolio. I have the page set up to where my nav is on the right side of the page and an image I'm using as a background in the same div. I am trying to give my portfolio an introduction text but when I put it in the nav bar moves down. Is there a way to fix this?
Here is my code:

@import url('https://fonts.googleapis.com/css?family=Fjalla+One');
@import url('https://fonts.googleapis.com/css?family=Titillium+Web');
*{
    margin: 0 auto;
    padding: 0;
}
#wrapper {
    margin: 0 auto;
}

#background {
    display: block;
    background-image: url(images/profile/Untitled-1.jpg);
    background-repeat:no-repeat;
    background-size:contain;
    -webkit-filter: grayscale(80%); /* Safari 6.0 - 9.0 */
    filter: grayscale(80%);
    margin: 0 auto;
    border: 1px solid black;
}

header {
    margin-left: 10px;

    padding-left: 10px;
    padding-top: 10px;
    padding-bottom: 10px;
}
p {
    display: block;
    width: 20%;
    font-size: 40px;
    color: antiquewhite;
    padding: 0;
    margin: 0 auto;
}

body {
    background-color: black;
}

footer{
    color: antiquewhite;
}

h1 {
    font-family:'Fjalla One', sans-serif;
    color: floralwhite;
    font-size: 300%;
}
ha {
    display: block;
    width: 50%;
    font-family:'Titillium Web', sans-serif;
    color: floralwhite;
    font-size: 100%;
}

nav {
    display: block;
    margin-left: 80%;
    border: 2px solid orange;
    margin-bottom: 40%;
}
li{
    display: inline-block;
    padding: 20px;
    margin: 9px 0px;
    border-radius: 50px 0px 0px 50px;
    border: 2px solid white;
    width: 250px;
    height: 50px;
    text-align: center;
    text-shadow: 2px 2px black;
    font-size: 150%;
    font-family: 'Fjalla One', sans-serif;
    background-color: dimgray;
    position: relative;
    -webkit-transition-duration: 0.5s;
    /*    standard syntax*/
    transition-duration: 0.5s;
    -webkit-transition-property: transform;
    /*    standard syntax*/
    transition-property: transform;
}
/* tabs will extend to left slightly*/
.stretch:hover {
    -webkit-transform: translateX(-25px);
}

/*    standard syntax*/
    transform: translateX(-8px);
}

@keyframes extend{
    from {width: 200px; left:0px;}
    to   {width: 600px; left: 200px;}
}

li:hover{
    /* tabs will extend to left slightly*/
    -webkit-animation-name: "extend";
    -webkit-animation-duration: 2s;
     animation-direction: reverse;
}

a:link {
    text-decoration: none;
    color: antiquewhite;
}

a:visited {
    text-decoration: none;
    color: antiquewhite;
}

a:hover {
    text-decoration: none;
    color: antiquewhite;
}

a:active {
    text-decoration: none;
    color: antiquewhite;
}
 <!DOCTYPE html>

       <link rel="stylesheet" media="screen" href="home.css">
       <title>Tavyon Richardson</title>
       <meta charset="utf-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0" >

Tavyon Richardson

Hey!Welcome to my webiste. Here, you can see everything from my life story, to my my recent projects and resume.

About me

Courses

Projects

Blog

Resume

             last updated November 2016

Comment: where do you want to add the text too?
Comment: Please add a [mcve]
Comment: i wanted to add the text next to the nav element
Answer: You would either need to put the text under the navbar in the actual html or use position: fixed; in css. You could also use top:; and left:;.

Navbar moves when putting in html code


doesn't display on Chrome for Android

Question: I have a navbar in my site which I am testing out on mobile. For some reason, the images I have as part of the navigation menu don't display on Chrome for Android. I don't have the issue when I use a different browser or when I view the site on my laptop. Unfortunately I don't have an iPhone to test on.
The site uses materialize.css.
Here's an example of a navigation menu image which isn't being displayed:

            Home

I tried using the devtools remote device debugger to see what was in the console, there are no error messages or 404's or anything. I've got no idea what to do!
Any help is appreciated. I can provide more info if needed.
Thank you!
EDIT: I've added a snippet. Unfortunately I'm not sure how to load images into jsfiddle so it's not going to be exactly possible to reproduce the error. Again, it looks fine on my browser and in responsive mode. In Chrome for Android, the 's disappear.
Fiddle:https://jsfiddle.net/hermana/z2b9L1nv/26/
Comment: Providing a working code snippet or codepen link would help you and others to help  you.
Comment: did you check in desktop browser with responsive mode ?
Comment: @Alex it works in responsive mode, but not on the actual device.
Comment: @ellen upload a demo or share a snippet for checking more that issue
Comment: @Alex See update. Thank you!
Answer: Your file has no extension like .jpg or png, and also your class attribute values in the Image need a closing double quotation " so that src attribute will be separated from class value
Comment: sorry I changed the file path before making it public. My img does have an extension and a closing quote - that was a typo. I'll try to add a snippet to make the problem more clear

doesn't display on Chrome for Android


How to change style in a Leaflet's imageOverlay apart from opacity?

Question: I would like to change the style of an ImageOverlay in Leaflet. As I saw from the imageOverlay instance apart from setUrl, setBounds, setOpacity methods there seems to be a setStyle method which only seems to work with opacity or with limited css attributes.
f.i
imageOverlay.setStyle({
    opacity: 0.5
})

this works fine as expected.
For instance how would I change the borderColor or color or fill properties? I have used
imageOverlay.setStyle({
   borderColor: '#FF0000 blue'
})

but no style is applied.
Below I give an example. I have two buttons implementing two functions. SetOpacity that works fine and setBorderColor that does not work.
Any recommendations are welcome.

#mapid {
  height: 100vh;
}

body {
  margin: 0px;
  padding: 0px;
}
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.css">

<button onclick='setOverlayOpacity()'>ChangeOpacity</button>

<button onclick='setOverlayBorderColor()'>Change Border Color</button>

Answer: The setStyle() method of L.ImageOverlay is not documented on purpose, and only for compatibility for L.FeatureGroup.setStyle(), which is mainly meant for setting style options for L.Path, not CSS rules.
In fact, the current implementation of L.ImageOverlay.setStyle() method only sets the opacity:
setStyle: function (styleOpts) {
    if (styleOpts.opacity) {
        this.setOpacity(styleOpts.opacity);
    }
    return this;
},

I think that what you want to do is to use L.ImageOverlay.getElement(), which returns a HTMLImageElement and then access its style property, e.g.:
myOverlay.getElement().style.border = '2px solid red';

Alternatively, use the className option to assign a CSS class to the ImageOverlay's HTMLImageElement, and add CSS rules accordingly.


Hibernate design: persistent data plus temporary run-time classes

Question: The question is this.
I have a number of persisted objects that I'll pull using Hibernate.
But during the application lifetime I'll create a few objects that
do not live outside the running time of an app.
They are temporary, for example contain user's choices, and they also hold
links to the persistent objects(tables). But as soon as application exited,
there's no need in them so temporary objects are destroyed.
How do you think, should those objects be persisted in the same database where normal data is kept?
For example, they may be kept in temporary tables and on exit the data will be erased.
Or they may be created only in memory. Which is better?
Answer: You generally don't persist transient objects, unless there are a lot of them gobbling up memory and/or the objects are accessed only rarely, at which point the memory freed by not having them in memory can be used better.
In my opinion, the basis of every design should be simplicity. As simple as possible while as complex as required. Adding Hibernate to those objects adds complexity and potential for trouble, and if it's not necessary then don't do it.


What is Associate Member in Cricket?

Question: I have heard there are some countries in Cricket which are called as Associate countries (or members) So what is Associate member in Cricket? What criteria do they have to maintain?
Answer: From icc-cricket.com:

Associate Members:
Associate Members are the governing bodies for cricket of a country recognised by the ICC, or countries associated for cricket purposes, or a geographical area, which does not qualify as a Full Member, but where cricket is firmly established and organised (37 Members)

An associate member must maintain the following criteria along with other administration requirements of the national governing body:

Have a minimum of 16 senior teams and 16 junior teams playing in a structured competition or competitions.
Must have access to at least 8 cricket grounds, 4 of which must have a permanent pitch

The main reason for why they do not qualify as a Full Member is that they are non-Test-playing nations. Associates are eligible to play in the ICC World Cricket League. Top 6 associate members of league are awarded ODI and T20I status and are allowed to play against the Full Members.
Here is the list of ICC Member Countries 2013/2014 PDF

Footnotes:
Source: 1. Wikipedia 2. ICC Associate Membership Criteria & Guidelines (PDF)

What is Associate Member in Cricket?


Com fazer posts no Facebook com Python?

Question: import facebook

token = 'meu token'

graph = facebook.GraphAPI(token)
graph.put_object("me", "feed", message="Hello, World!")

Amigos,
Estou utilizando Ubuntu e Python 2.7 e 3.5.2
O seguinte erro ocorre:
"graph = facebook.GraphAPI(ACCESS_TOKEN)
AttributeError: module 'facebook' has no attribute 'GraphAPI"
Já pesquisei em aqui mesmo no Stack Overflow mas nenhuma resposta resolveu meu problema.
Instalei o Facebook-SDK daqui:
http://facebook-sdk.readthedocs.io/en/latest/install.html
Alguma sugestão?
Comment: Tente baixar um código já pronto e construir seu aplicativo à partir dele.
Comment: import facebook -> no modo interativo nao da erros
Comment: from facebook import GraphAPI -> tambem nao ocorre erros
Comment: @CypherPotato, alguma sugestao de codigo?
Comment: Tente sobrecarregar a função ```GraphAPI```: ```facebook.GraphAPI(access_token='your_token', version='2.2')```
Comment: @CypherPotato, eu fiz mas o erro foi o mesmo!
Comment: Ed, http://pt.stackoverflow.com/questions/142790/login-no-facebook-com-python . Não é bem como fazer posts mas é relacionado. No entanto usar sdk é o indicado
Answer: Se estiver usando Ubuntu ou Debian, execute estes comandos para voltar a funcionar.
sudo pip uninstall facebook
sudo pip uninstall facebook-sdk
sudo pip install facebook-sdk

Para outros sistemas operacionais, apenas remova o facebook e facebook-sdk e instale apenas o facebook-sdk
Então execute o programa. Observe que o módulo facebook é obsoleto e seu substituto é o facebook-sdk.
Fonte da resposta
.
Comment: sudo pip uninstall facebook -> Cannot uninstall requirement facebook, not installed
Comment: Tudo que eu queria era conseguir um script python para postar no facebook... que erro chato!

Com fazer posts no Facebook com Python?


Hierarchical Tree Table (sql) Query from one table

Question: Situation
I have a table the contains partnumbers that are in a hierarichal tree structure.
partno is the parent and partno_item is the child however this changes as the child can become the parent of another part and moves to the partno column.
The table looks basically as follows (I left out some columns as well the first which contains the internal unique key)

╔═════════╦═════════════╗
║ partno  ║ partno_item ║
╠═════════╬═════════════╣
║ 123-01  ║ 1234-01     ║
║ 123-01  ║ 1234-02     ║
║ 123-01  ║ 1234-03     ║
║ 1234-03 ║ 1234-04     ║
║ 1234-04 ║ 1234-05     ║
╚═════════╩═════════════╝
I would like to search for a specific part and have all its children and grandchildren shown.
In this case I search for 123-01 and I would like to get a result similar to this.
Preferable with an additional column that shows you the level in the hierarchy

╔═════════════╦═══════╗
║ partno_item ║ level ║
╠═════════════╬═══════╣
║ 1234-01     ║     1 ║
║ 1234-02     ║     1 ║
║ 1234-03     ║     1 ║
║ 1234-04     ║     2 ║
║ 1234-05     ║     3 ║
╚═════════════╩═══════╝
How can I achieve this with a query?

Update: RDBMS is Sybase ASE
Comment: You should state which Sybase product you are using (ASE, Anywhere, IQ) as the SQL functions vary between products
Answer: This procedure getItems should do what you want:P
See code
The result looks like this:
partno  partno_item
123-01  1234-01
123-01  1234-02
123-01  1234-03
1234-03 1234-04
1234-04 1234-05
123-02  1234-06
partno_item     lvl
1234-01 1
1234-02 1
1234-03 1
1234-04 2
1234-05 3

Edit: Moved the code into the answer
-- src table
create table #src(
  partno      varchar(10),
  partno_item varchar(10)
)

insert #src(partno, partno_item) values('123-01', '1234-01')
insert #src(partno, partno_item) values('123-01', '1234-02')
insert #src(partno, partno_item) values('123-01', '1234-03')
insert #src(partno, partno_item) values('1234-03', '1234-04')
insert #src(partno, partno_item) values('1234-04', '1234-05')
insert #src(partno, partno_item) values('123-02', '1234-06')

select * from #src
go

-- get items
create procedure getItems
  @partno     varchar(10)
as
  declare
    @lvl      int

  select @lvl = 1

  -- tmp table
  create table #tmp(
    partno_item varchar(10),
    lvl         int
  )

  if exists(
    select partno from #src where (partno = @partno)
  ) begin
    insert #tmp(partno_item, lvl)
    select distinct partno_item, @lvl from #src where (partno = @partno)

    while exists(
      select distinct s.partno_item
      from #src s, #tmp t
      where (t.lvl = @lvl)
        and (t.partno_item = s.partno)
    ) begin
      select @lvl = @lvl + 1    -- increase lvl

      insert #tmp(partno_item, lvl)
      select distinct s.partno_item, @lvl
      from #src s, #tmp t
      where (t.lvl = @lvl - 1)
        and (t.partno_item = s.partno)
    end
  end

  select * from #tmp
  truncate table #tmp
  drop table #tmp
go

-- exec
exec getItems '123-01'
go

truncate table #src
drop table #src
drop procedure getItems
go

Comment: please post your code into the answer; external links are generally discouraged (eg, 3 yrs from now this question/answer still exists but the external link is broken/missing)


What is the number of ways to represent the $n$ element set as a union of distinct non-empty subsets

Question: edit: I do not mean the number of partitions $B_n$ here.
The title says it all. The n element set is $[n]=\{1,2,\dots,n\}$. One representation (the one using the most sets) for example is the union of all non-empty subsets (it uses $2^n-1$ sets) and it is the only one that uses this many sets.
edit: To give an upper bound one can use $$\sum_{i=1}^{2^n-1} {2^n-1\choose i}=2^{2^n-1}-1$$
Answer: I venture the following:
Each subset of $[n]$ can be encoded as a  binary string of length $n$. The set ${\cal S}$ of these strings has $2^n$ elements. Each union of different subsets of $[n]$ corresponds to a subset of ${\cal S}$. Such a subset $A$  is admissible if for each $i\in[n]$  at least one word $w\in A$ has a $1$ at place $i$.
The number of admissible subsets $A\subset{\cal S}$ can be found by an inclusion-exclusion process: There are $2^{2^n}$ subsets of ${\cal S}$, and $2^{2^{n-1}}$ of them contain only words beginning with a $0$. Similarly, there are $2^{2^{n-2}}$ subsets of ${\cal S}$ containing only words beginning with $00$, and so on. It follows that the total number $N_n$ of admissible subsets is given by
$$N_n=\sum_{k=0}^n{n\choose k}(-1)^k 2^{2^{n-k}}\ .$$
Exactly half of these subsets contain the forbidden word $(0,0,\ldots,0)$ corresponding to the empty subset of $[n]$. It follows that the answer to your question is $N_n/2$.
For $n=2$ one obtains $N_n=10$; so there should be $5$ unions of the envisaged kind. They are encoded as
$$\{(11)\},\quad \{(01),(10)\},\quad \{(01),(11)\},\quad\{(10),(11)\},\quad\{(01),(10),(11)\}\ .$$
The sequence $(N_n)_{n\geq1}=(2,10,218,64594,\ldots)$ is sequence A000371 at OEIS. Look there for more material about this sequence.
Answer: Here is a variation of the method of inclusion-exclusion, using more directly Möbius inversion. For any finite set $S$ define $f(S)$ to be the number of subsets $C\in\mathcal P(S)\setminus\{\emptyset\}$ with $\bigcup C=S$, so that you are asking about $f([n])$. We know beforehand that $f(S)$ will only depend on $|S|$, but that will follow from what we compute anyway. Now for every $C\in\mathcal P(S)\setminus\{\emptyset\}$, one has that $\bigcup C$ is some subset of $S$, so
$$
  \sum_{T\subseteq S}f(T)=|P(S)\setminus\{\emptyset\}|=2^{2^{|S|}-1}=g(S).
$$
Having called the value in this formula $g(S)$, we can use Möbius inversion for the poset of subsets of any finite set$~X$; it says that if for all $S\subseteq X$ one has $g(S)=\sum_{T\subseteq S}f(T)$, then one can solve this system of equations for $f$ as $f(S)=\sum_{T\subseteq S}(-1)^{|S\setminus T|}g(T)$; here the factor $(-1)^{|S\setminus T|}=\mu(T,S)$ is the Möbius function for this poset. Concretely your problem is solved by the formula
$$
  f([n])=\sum_{T\subseteq[n]}(-1)^{|S\setminus T|}g(T)=\sum_{k=0}^n\binom nk(-1)^{n-k}2^{2^k-1}.
$$
The values for $n=0,1,2,\ldots$ are $1,1,5,109,32297,\ldots$, and it is OEIS3465. My answer is of course equivalent to that by Christian Blatter, only the division by $2$ was built into the function $g$ right away.
I might note that for practical computation, any initial part of a sequence $(b_n)_{n\in\mathbf N}$ defined by alternating summation of the form $b_n=\sum_{k=0}^n\binom nk(-1)^{n-k}a_k$ can be found by starting with $(a_0,a_1,a_2,\ldots)$, and repeating the operation of taking finite differences to form a sort of inverted Pascal triangle, each entry being the difference of the one to its upper right minus the one to its upper left; the left edge of the triangle will then give the sequence $(b_0,b_1,b_2,\ldots)$. In this concrete example one starts with $a_n=2^{s^n-1}$:
$$
  \begin{matrix} 1 &   & 2 &   & 8 & & 128 & & 32768 \\
                   & 1 &   & 6 &   &120 & & 32640 \\
                   &   & 5 &  & 114 & & 32520 \\
                   &   &  & 109 &  & 32406 \\
                   &   &  &   & 32297.\\
  \end{matrix}
$$
Answer: The number of ways to partition an $n$-set into $k$ pieces is called the Stirling number of the second kind, $\genfrac\{\}{0pt}{} nk$ (there are lots of other notations). What you are looking for is the Bell numbers:
$$
B_n = \sum_{k \ge 0} \genfrac\{\}{0pt}{} nk
$$
There is no simple formula for either one.
(The notation for Stirling numbers is like binomial coefficients but with braces instead of parentheses).
Comment: Maybe I stated it too ambigous, I did not mean the number of partitions.
Comment: I think the OP wants unions, not partitions (i.e., the union need not be a disjoint union).


Bilinear Functions Not Isomorphic to xy

Question: Wolfram Alpha lists $z=xy$ as an example of a bilinear function. Are there any others that aren't this form of some product of two objects?
Comment: Also I think isomorphic is the wrong word here
Comment: Should I take it out? I was trying to ask if there was anything that doesn't satisfy same property (is isomorphic) as xy in this way, but maybe I'm comfortable enough with the word isomorphism yet.
Comment: Also, why is z=(0*x)(y) a counterexample?
Comment: Groups can be isomorphic, rings can be isomorphic, graphs can be isomorphic, vector spaces can be isomorphic. But I have never heard of two functions being isomorphic, and I still don't understand what you mean by this.
Comment: I think I misused isomorphic, my bad.
Comment: @rbird ok. I BADLY didn't understand isomorphism. Now that I'm beginning category theory i think I have a better idea of it, but haven't pondered. Although I have a hand waving notion that maybe if you define a universal property for multiplication, which are unique up to isomorphism...
Answer: Given $v,w \in \mathbb{R}^n$ (column vectors) and an $n \times n$ matrix $A$. Then $f:\mathbb{R}^n \times \mathbb{R}^n \to \mathbb{R}$ defined by $f(v,w)=v^tAw$ is a bilinear function.
Given a bilinear function $f:\mathbb{R}^n \times \mathbb{R}^n \to \mathbb{R}$.
Fix vector $v$ and then $f(v,\cdot):\mathbb{R}^n \to \mathbb{R}$ is linear so you can find a matrix $A_v$ so that $f(v,w)=A_vw$ for all $w$ in particular this matrix has to be $1 \times n$ so it's a row-vector. Pick the standard basis for $\mathbb{R}^n$: $e_1,e_2,\ldots, e_n$ then
call $A_i=A_{e_i}$ for each $i=1,\ldots,n$ and define $n \times n$ matrix $A$ with rows $A_1, \ldots, A_n$. Note that $$Aw=\begin{bmatrix}A_1w\\ A_2w\\ \vdots \\ A_nw\end{bmatrix}$$
Any $v\in \mathbb{R}^n$ has $v=\sum v_i e_i=\begin{bmatrix}v_1 \\ \vdots \\ v_n\end{bmatrix}$ so
$$v^tAw=\sum v_iA_iw=\sum v_i f(e_i,w)=\sum f(v_ie_i,w)=f\left(\sum v_i e_i,w\right)=f(v,w)
$$
So all bilinear forms on a finite dimensional vector space can be defined by a matrix product.
Answer: Consider for any matrix $A=(a_{ij})\in M_{m,n}(K)$ a bilinear function defined by
$$
f(x,y)=\sum_{i=1}^m\sum_{j=1}^na_{ij}x_ix_j.
$$
Comment: That is not bilinear. $$f(x,y_1+y_2)=2x+(y_1+y_2)-x(y_1+y_2)$$ $$\neq f(x,y_1)+f(x,y_2)=(2x+y_1-xy_1)+(2x+y_2-xy_2)$$
Comment: @mr_e_man Thank you, edited!

Bilinear Functions Not Isomorphic to xy


Difference of Means for Stopwatch Times (independent t-test ?)

Question: I want to conduct a t-test for the difference of means between two samples, but the data are times (i.e., taken from a stopwatch). Is Student's T appropriate here ? I question this because I am not convinced that time follows a normal distribution. (Binomial ?)
Many thanks for your assistance here ! I am a great fan of the community, and this is my first question posed.
Notes:
i. No, I couldn't find this anywhere on here or elsewhere, but welcome links.
ii. No, these are not time-series data.
Answer: The standard 2-sample t test is appropriate provided the times in each sample are independent and can be described by a normal distribution. If the data are skewed or there are outliers, you may be able to transform the data (square root, log, etc.) to fix this. Otherwise there are analogous non-parametric tests that might be applicable.
Comment: Great, thanks ! This is exactly what I was hoping to hear. Also good to know that transformations are appropriate in this instance. Thank you for the reply.


Question about chord progressions and scales

Question: recently I watched a Youtube Short of a short Bossa Nova chord progression, with the chords in order as follows:

Cm9 -> Fm7 -> Dm7b5 -> G7b13 -> Cm9

So I looked up the C minor scale. From there I figured that Cm9 would be the I degree, and Fm7 the iv degree.
Then I searched for a Dm in the scale, but the only D chords in the C minor scale are the ii degree (Ddim) and III degree (D#).
Since there is no Dm chord in the Cm scale, I wanted to ask: where does this chord come from? I found myself wondering the same thing with that G7b13 chord, since the Cm scale only contains a Gm chord.
I'm sure I have a fundamental misunderstanding of chord progressions, so any help would be greatly appreciated! :)
Comment: Questions such as this seem to come along around once a week. There must be plenty of duplicates to it. Chords do not have to belong to the diatonic notes of a particular key.
Comment: @Tim sorry about that… I was just very confused about this specific chord progression
Answer:
where does this chord come from?

A D minor chord in the key of C minor comes from chromatic alteration.  The pitches are D, F, and A.  But the diatonic sixth degree of  C minor is A flat, not A natural.  By raising the A flat to A natural, you can obtain a D minor chord in C minor.
However, the chord you're asking about isn't a D minor chord.  It's a diminished chord, or perhaps more precisely an extension of that chord.  Classical theory calls it a half-diminished seventh chord, because the fifth is diminished but the seventh is not.  Notice the "♭5" portion of the chord symbol.  This specifies that the fifth of this chord is a diminished fifth above D, namely A flat, which is the diatonic sixth degree of the C minor scale.
I am not sure why jazz theory abandoned, as they seem to have done, the degree symbol for diminished chords and half diminished seventh chords.  I (as a primarily classical musician) find Dø7 more concise and easier to read than Dm7♭5.  But I'm not in the target audience, so my opinion should perhaps be discounted somewhat.
(Some may want to go into the confusing discussion of whether one is talking about the C natural minor scale, or harmonic minor, or melodic minor.  The harmonic minor and melodic minor are best thought of as chromatic alterations of the natural minor scale, consistent with their notation using accidentals.  Therefore, even if you prefer to think of D minor as coming from the melodic minor scale, I would still say that it is the result of chromatic alteration.)
One of the oldest chromatic alterations in the books is the raising of the leading tone in final cadences when the diatonic seventh degree of the scale is a whole step below the tonic.  This long predates tonal harmony and in fact was one of the main factors leading to the development of harmonic theory.  For this reason, one of the basic rules in harmonic theory is that when there's a chord built on the fifth degree of the scale (G in this case) the third is raised if the following chord is built on the tonic (C in this case) -- as well as in some other situations.  This gives us a major triad (or a dominant seventh chord).  In this case, it gives us G7♭13 instead of Gm7♭13.  You could call this "using the harmonic minor scale" for that chord, but either way it is an example of chromatic alteration.
Answer: The Dm7b5 is the chord built on the second degree of C minor. The triad built on D in C minor is diminished, it is D-F-Ab but if you extend it to a 7th chord it becomes D-F-Ab-C which has two names, D half-diminished or Dm7b5. It is not a full diminished 7th because a full diminished 7th would be all m3 intervals and have a Cb instead of a C.
As for the G7b13, that chord which in its basic form is simply a G7 is the V7 dominant chord in C minor, which is created by using the harmonic minor scale with a B natural instead of a Bb. That allows you to have a dominant to tonic relationship in minor keys instead of just Vm to Im, or Gm to Cm. The b13 is simply an upper chord extension added for color and complexity.
This makes the entire progression Im9-IVm9-IIm7b5-V7b13-Im9. If you are familiar with 2-5-1 progressions at all this is the way they are typically done in minor keys, with the m7b5 instead of the m7 for the 2 chord,
One more comment, the 3rd degree of Cm is Eb, not D#. C minor has three flats, one of which is Eb, but no sharps. When in doubt, each letter only gets used once.
Answer: 'So I looked up the C minor scale'. That's the beginning of where it went wrong!
You found the natural minor scale - with 3 flats, the relative minor to E♭ major. Trouble is, there are two more C minor scales, the notes of all which get used in pieces in key C minor. So, the first five notes of all those are C, D, E♭, F, G. But the remaining notes are all the chromatics from A♭ through to B♮. And the 'wrong' notes you quote will be found in there somewhere!
There's also this misconception that all notes in a piece in a particular key must be from that key. Not true, by any means. A common ploy is to use those notes from the parallel key - here, C major. Which gives composers a much larger selection of notes with which to play - literally. In fact, looking at many pieces, all 12 chromatic notes are up for grabs, with various excuses (theoretical reasons) as to why they can be and are used.


Is there an integral for $\pi^4-\frac{2143}{22}$?

Question: In Ramanujan's Notebooks, Vol 4, p.48 (and a related one in Quarterly Journal of Mathematics, XLV, 1914) there are various approximations, including the close (by just $10^{-7}$),
$$\pi^4 \approx 2^4+3^4+\frac{1}{2+\Big(\frac{2}{3}\Big)^2} = \frac{2143}{22}$$
We can also easily calculate $\pi^3 \approx 31.0062$ and know that,
$$ \int_0^1 \frac{x^4(1-x)^4}{1+x^2} \mathrm{d}x = \frac{22}{7} - \pi $$
$$ \int_0^1 \frac{x^8(1-x)^8(25+816x^2)}{28\cdot113(1+x^2)} \mathrm{d}x = \frac{355}{113} - \pi $$

Q: Are there then analogous integrals for these early approximations of $\pi^k$,

$$ \int_0^1 f(x)\, \mathrm{d}x = \pi^2 -\frac{1+2\times113}{23} $$
$$ \int_0^1 f(x)\, \mathrm{d}x = \pi^3 - 31 $$
$$ \int_0^1 f(x)\, \mathrm{d}x = \pi^4 -\frac{2143}{22} $$
Comment: Silly answer, if you let $f(x) = \pi^4 - \tfrac{2143}{22}$, then $\int_0^1 f(x) ~ dx $ would be equal to what you want.
Comment: I know that $\displaystyle\int_0^\infty\,\frac{t}{\exp(t)-1}\,\text{d}t=\frac{\pi^2}{6}$ and $\displaystyle\int_0^\infty\,\frac{t^3}{\exp(t)-1}\,\text{d}t=\frac{\pi^4}{15}$.  It is easy to manipulate these two integrals to get something of the forms $\displaystyle\int_0^1\,f(x)\,\text{d}x=\pi^2-\frac{227}{23}$ and $\displaystyle\int_0^1\,f(x)\,\text{d}x=\pi^4-\frac{2143}{22}$.  However, frankly, I don't think that these integrals will be meaningful.
Comment: Presumably you want an  integral of  P/Q from A to B where P and Q are polynomials with integer coefficients and A,B are rational, I know that the square of pi comes up in some such integrals that need complex residue theory to evaluate,. e.g. P=1, Q=1/(1+x^4) for x from 0 to infinity.You might try looking at some of these.
Comment: @Batominovski: Perhaps something more difficult, like  $\displaystyle\int_0^1 \frac{P(x)}{Q(x)} \mathrm{d}x$ where $P(x), Q(x)$ are polynomials with integer coefficients analogous to the examples. Just to see if it can be done.
Comment: Let $\mathbb{A}$ be the field of algebraic numbers.  You question reduces to finding $s_1,s_2,\ldots,s_n\in \mathbb{A}$ and $t_1,t_2,\ldots,t_n\in\mathbb{A}$ such that $\sum_{i=1}^n\,s_i\ln\left(t_i\right)=R(\pi)$, where $R(x)\in\mathbb{A}[x]$ is of degree at least $2$.  I conjecture that this is impossible.
Comment: $$\pi^2-\frac{355}{36}=\sum_{k=1}^\infty\frac{4}{((k+1)(k+2)(k+3))^2}$$
http://math.stackexchange.com/a/1644137/134791
Answer: The answer is yes.  The method is detailed in the paper by S. K. Lucas.  The approximate fractions are obtained from truncating the exact continued fraction of the respected numbers, so the signs are alternating.  We first give a few examples.
Results
For $\pi$
The continued fractions are
$3, 22/7, 333/106, 355/113, 103993/33102, \dots$.
\begin{align}
\pi - \frac{333}{106}
&=
\int_0^1 \frac{x^4 \, (1-x)^5 \, \left(74 \, x^2-53 \, x+21\right)}{106 \left(x^2+1\right)} \, dx.
\\
\frac{355}{113} - \pi
&=
\int_0^1 \frac{x^{10} \, (1-x)^8 \, \left(886+95\,x^2\right)}{3164 \left(x^2+1\right)} \, dx.
\end{align}
For $\pi^2$
The truncated continued fractions are $9, 10, 69/7, 79/8, 227/23, 10748/1089, \dots$,
\begin{align}
\pi^2-\frac{69}{7}
&=
\int_0^1
\frac{4 \, x^{4} \, (1 - x)^3 \left(64 x^2 -39 x + 25\right)}
{13 \, (1 + x^2) }
\log(x^{-1}) \, dx \\
&=
\int_0^1
\frac{24 \, x^{6} \, (1 - x)^2 \left(119 - 72 \, x^2\right)}
{191 \, (1 + x^2) }
\log(x^{-1}) \, dx.
\end{align}
\begin{align}
\frac{79}{8} - \pi^2
&=
\int_0^1
\frac{4 \, x^6 \, (1-x)^3 (49 - 51 x + 100 x^2)}
{17 \, (1 + x^2) }
\log(x^{-1}) \, dx \\
&=
\int_0^1
\frac{4 \, x^3 \, (1-x)^4 (25 + 2254 x^2)}
{743 \, (1 + x^2) }
\log(x^{-1}) \, dx \\
&=
\int_0^1
\frac{
24 \, x^5 \, (1-x)^2 \left[37 \, (x^2 + 1) - 73 \, x\right]
}
{ 73 \, (1 + x^2) }
\log(x^{-1}) \, dx
\end{align}
\begin{align}
\pi^2-\frac{227}{23}
&=
\int_0^1
\frac{4 \, x^{19} \, (1 - x)^4 \left(61847 x^2+87524\right)}
{8559 \, (1 + x^2) }
\log(x^{-1}) \, dx.
\end{align}
For $\pi^3$
The truncated continued fractions are
$31, 4930/159, 14821/478, \dots$.
\begin{align}
\pi^3-31
&=
\int_0^1
\frac{8 \, x^5 \, (1-x)^2 \, \left(324889-120736 \, x^2\right)}
{445625 \, (1 + x^2) }
\log^2 x \, dx\\
\frac{4930}{159}-\pi^3
&=
\int_0^1
\frac{4 \, x^{10} \, (1-x)^4 \, \left(695774836+470936528857 \, x^2\right)}
{470240754021 \, (1 + x^2) }
\log^2 x \, dx.
\end{align}
For $\pi^4$
The truncated continued fractions are
$97, 195/2, 487/5, 1656/17, 2143/22, \dots$.
\begin{align}
\pi^4-97
&=
\int_0^1
\frac{240 \, x^{4} \, (1 - x)^{2} \,\left(3522267 x^2+1681375\right) }
{3221561 \, (1 + x^2) }
\log^3(x^{-1}) \, dx
\\
\frac{195}{2}-\pi^4
&=
\int_0^1
\frac{192 \, x^{6} \, (1 - x)^{2} \, \left(5657688 x^2+3056473\right) }
{3641701 \, (1 + x^2) }
\log^3(x^{-1}) \, dx.
\\
\pi^4-\frac{487}{5}
&=
\int_0^1
\frac{15 \, x^{8} \, (1 - x)^{2} \, \left(3293858975 x^2+746556831\right) }
{278611172 \, (1 + x^2) }
\log^3(x^{-1}) \, dx.
\\
\frac{1656}{17}-\pi^4
&=
\int_0^1
\frac{480 \, x^{7} \, (1 - x)^{4} \, \left(8555775811 x^2+2883779820\right) }
{39703971937 \, (1 + x^2) }
\log^3(x^{-1}) \, dx.
\\
\pi^4-\frac{2143}{22}
&=
\int_0^1
\frac{480 \, x^{31} \, (1 - x)^{4} \, \left(4071997316165706379 x^2+175446796437023645180\right) }
{1199623593846005571607 \, (1 + x^2) }
\log^3(x^{-1}) \, dx.
\end{align}
Method
The idea is simple.
We basically combine the following identities.
(1)
\begin{align}
\int_0^1
\log^{s-1}\left( x^{-1} \right) x^k \, dx
= \frac{(s-1)!}{(k+1)^s}.
\end{align}
For an even $s$
(2a)
\begin{align}
\int_0^1
\frac{ \log^{s-1}(x^{-1}) \, x }{1+x^2} \, dx
&=2^{-s} \int_0^\infty
\frac{ t^{s-1} }{ e^t + 1 } \, dt \\
&=2^{-s} \int_0^\infty
t^{s-1} \left( e^{-t} - e^{-2\,t} + e^{-3t} - \cdots \right) \, dt \\
&= \frac{ (s-1)! \, (2^s - 2)}{4^s} \zeta(s) \\
&=
\frac{ (1-2^{1-s}) \, |B_s| }{2 \, s} \, \pi^s.
\end{align}
where $\zeta(s)$ is the Riemann zeta function,
$B_s$ is the Bernoulli number, which is rational.
The last step is well known.
Similarly, for an odd $s$,
(2b)
\begin{align}
\int_0^1
\frac{ \log^{s-1}(x^{-1}) }{1+x^2} \, dx
&=\int_0^\infty
\frac{ t^{s-1} \, e^{-t} }{ e^{-2t} + 1 } \, dt \\
&=\int_0^\infty
t^{s-1} \left( e^{-t} - e^{-3\,t} + e^{-5\,t} -\cdots \right) \, dt \\
&= (s-1)! \, \left(1-\frac{1}{3^s}+\frac{1}{5^s}-\cdots \right) \\
&=
(s-1)! \, \beta(s) = \frac{|E_{s-1}|}{2^{s+1}} \, \pi^s,
\end{align}
where
$E_s$ is the Euler number,
which is also rational.
This means
\begin{align}
\frac{\pi}{4}
&=
\int_0^1
\frac{ 1 }{1+x^2} \, dx, \\
\frac{\pi^2}{48}
&=
\int_0^1
\frac{\log\left( x^{-1} \right) x}{1+x^2} \, dx\\
\frac{\pi^3}{16}
&=
\int_0^1
\frac{\log^2\left( x^{-1} \right) }{1+x^2} \, dx\\
\frac{7\,\pi^4}{192}
&=
\int_0^1
\frac{\log^3\left( x^{-1} \right) x}{1+x^2} \, dx.
\end{align}
Now suppose we have a polynomial $P(x) = Q(x)(1 + x^2) + R(x)$,
and we want
$$
\int_0^1
\frac{ \log^s(x^{-1}) \, P(x) } { 1 + x^2 }
\, dx
= \pi^s - A,
$$
where $A$ is an approximation of $\pi^s$ (we have assumed the possible sign, the case of negative sign is similar).  To satisfy this equation, we demand,
\begin{align}
\int_0^1
\frac{ \log^s(x^{-1}) \, R(x) } { 1 + x^2 }
\, dx
&= \pi^s \\
\int_0^1
\log^s(x^{-1}) \, Q(x)
\, dx
&= - A,
\end{align}
This requires
\begin{align}
R(x)
&=
\begin{cases}
\dfrac{ 2^{s+1} } { |E_{s-1}|}
     & \mathrm{for\; odd\;} s \\
\dfrac{ 2 \, s } { (1-2^{1-s}) \, |B_s| } x
     & \mathrm{for\; even\;} s
\end{cases}
\\
\sum_{n=0} \frac{ (s-1)! }{(n+1)^s} q_n &= -A,
\end{align}
where
$Q(x) = \sum_{n=0} q_n \, x^n$.
Using these to rules to design $P(x)$, we get the above formulas.  Particularly, we studied the form
\begin{align}
P(x)
=
x^u \,(1-x)^v (a \, x^2 + b \, x + c).
\end{align}
For a particular set of $u$ and $v$, the constraint for $R(x)$ determines two parameters, say $b$ and $c$. The constraint for $A$ determines $a$.  We then check if $a \, x^2 + b \, x  + c$ is nonnegative definite.  We then vary $u$ and $v$ to seek a simple combination of $a$, $b$ and $c$.
Comment: Mmm...has someone thought about using these ideas to give an alternative proof $\pi^s$ is irrational for positive $s$? It would be quite pointless since we already know $\pi$ is transcendental. That said, I think another proof using Beukers'-like methods would be a fun endeavor.
Comment: Maybe you'd be interested in this [related question](http://math.stackexchange.com/questions/1649890/is-there-a-series-to-show-22-pi42143)?


How to know which partition/volume is which EBS volume?

Question: On an EC2 instance, I have a few partitions that look like these:
/dev/nvme1n1     15G   48M   15G   1% /data/mongo2
/dev/nvme2n1     15G  4.7G   11G  32% /data/docker
/dev/nvme3n1     15G  3.4G   12G  23% /data/mongo

And then the corresponding EBS volumes, one of which looks like this:

I'm trying to figure out which mounts map to which EBS volumes. It used to be the case that the "Attachment information" matched or was similar to the device, but it no longer seems to be the case with nve.
Is there any way to match these besides keeping track myself of the mounts? thanks
Answer: There are a few different methods depending on what OS you're using.

With Amazon Linux AMI 2017.09.01 or later (including Amazon Linux 2), you can run the ebsnvme-id command as follows to map the NVMe device name to a volume ID and device name

sudo /sbin/ebsnvme-id /dev/nvme1n1

Which will provide output like this:

Volume ID: vol-01324f611e2463981
  /dev/sdf

For Linux kernels 4.2 and later you can do the following:
First, install nvme-cli.  It is the  NVMe command line package.
Next you can run a command similar to this:
sudo nvme id-ctrl -v /dev/nvme1n1

NVME Identify Controller:
  vid     : 0x1d0f
  ssvid   : 0x1d0f
  sn      : vol01234567890abcdef
  mn      : Amazon Elastic Block Store
  ...
  0000: 2f 64 65 76 2f 73 64 6a 20 20 20 20 20 20 20 20 "/dev/sdf..."

The links below provide additional details.
References
NVME EBS Volumes
How to Find EBS Volume ID for NVME Volume
Comment: Awesome. I'm running amazon linux and the first command was exactly what I wanted. Thanks!
Comment: Is there an equivalent command for NON-nvme instances? ebsnvme-id is super handy for NVMe instances, but what non-NVMe instances?


HTTP Client Manager $request->getStatusCode() == 200 return?

Question: When I read this HTTP Client Manager docs on Drupal, I don't understand why it returns the $build when $request->getStatusCode() == 200, is that supposed to be not equal 200? I also copy and paste the code from Drupal docs.
<code>public function posts($limit, $sort) {
    $build = [
      '#theme' => 'mymodule_posts_list',
      '#posts' => [],
    ];

    $request = $this->httpClient->request('GET', 'http://api.example.com/posts', [
      'limit' => $limit,
      'sort' => $sort,
    ]);

    // This is the Part I don't understand.
    if ($request->getStatusCode() == 200) {
      return $build;
    }

    $posts = $request->getBody()->getContents();
    foreach ($posts as $post) {
      $build['#posts'][] = [
        'id' => $post['id'],
        'title' => $post['title'],
        'text' => $post['text'],
      ];
    }
    return $build;
  }
</code>
Comment: I suspect that the condition here should be != 200... e.g. return an empty array of posts if the api does not get a valid response.
Comment: Thank you, CG Monroe
Answer: The information from https://www.drupal.org/docs/contributed-modules/http-client-manager/introduction was wrong and was updated, now:
<code>   if ($request->getStatusCode() != 200) {
      return $build;
    }
</code>


Percentage of failed devices.

Question: According to one of the Western Electric rules for quality control, a produced item is
considered conforming if its measurement falls within three standard deviations from the
target value. Suppose that the process is in control so that the expected value of each
measurement equals the target value. What percent of items will be considered conforming,
if the distribution of measurements is
(a) Normal($u, \sigma$)?
(b) Uniform(a, b)?
Please hint me.
Answer: For the case $X \sim Norm(\mu, \sigma),$ you want
$$P\{-3\sigma \le (X - \mu) \le 3\sigma\}.$$
Standardize and use normal tables. The answer is near 100%.
Draw a sketch.
For $Y \sim Univ(a,b)$, you have no tables, but finding
probabilities from a sketch of the density function is
trivial (areas of rectangles). Note that $\mu = E(Y) = (a+b)/2$,
the midpoint of the interval that contains all of the probability.
Also, $\sigma^2 = (b-a)^2/12$, and take the square root
to get $\sigma$.
I don't know whether you are expected to
use simple calculus to get $\mu$ and $\sigma^2,$ of whether
this information is given in your book.
If you're having trouble drawing a sketch here, start with
a specific example, maybe let $a = 1$ and $b=3$. Hint: The
uniform has no "tails."
I'll check later today to see whether you accepted this answer
of left a comment asking for clarification.

Percentage of failed devices.


Is the shadow of the earth coming up almost matching in size with the moon a coincidence?

Question: The fool that I am, today was the first time I wondered how come the shadow of the earth is almost same in size as the moon. I mean, as I was looking at the crescent moon in the evening, it came upon me that the crescent was like this:

and not like this:

neither do we see as the moon like this:

Of course, this must be because the sizes of moon and earth along with the distance between them. However my question is if this is a mere coincidence, one of the many things that makes planet earth unique or is there a deeper relation between the sizes, masses, distance ? Is there any mathematical equation involving the gravitational constant that describes this fact ?
Comment: As Carlos explained the Moon's crescent is not about Earth's shadows. If you have a telescope take a look at Venus. When it is relatively close to Earth you will see a similar crescent. This is due to Venus being closer to the Sun than we are, and the crescent shows because only a small part of Venus' surface visible to us is sunlit. For example Mars never shows a thin crescent, because we are always mostly between Mars and Sun. OTOH, when viewed from the Earth, the Moon and the Sun do cover nearly the same angle. This is a coincidence. But it gives us awesome solar eclipses.
Answer: When you see a crescent moon, the dark part of the Moon is not the shadow of the earth: it is the "the dark side of the Moon", i.e. the side of the Moon that is not currently lightened by the Sun.

The inner curve of what you are actually looking is not a circle but an ellipse.
The shadow of Earth in the Moon is what you see in a Lunar eclipse, and it does not match the size of the Moon.


Mudar a cor do label de acordo com estado da tela

Question: Estou tendo problemas para mudar a cor do conteúdo de um label, de acordo com o estado da minha tela (habilitado/desabilitado).
Gostaria de saber como eu faço para poder fazer com que ele mude a cor.
Fiz um exemplo bem simples (sem me preocupar com as melhores práticas de organização e etc)
Exemplo simplificado do código:
package cor;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MudaCor extends JFrame implements ActionListener
{
    public final int DESABILITADA = 0;
    public final int HABILITADA = 1;
    public int estadoTela = DESABILITADA;

    public JPanel jpBotoes = new JPanel();
    JTextField tx1 = new JTextField();
    JTextField tx2 = new JTextField();

    private JButton botao01 = new JButton("Habilita");
    private JButton botao02 = new JButton("Desabilita");

    private String conteudo = "Teste de cor";

    public MudaCor()
    {
        setTitle("Tela de teste");
        setSize(400, 300);
        add(posicaoComponentes());
        habilitaComp(false);
        estilo(conteudo);//metodo estilo
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public String  estilo(String estilo)
    {
        String x = "  Teste de cor  "; //roxo
        String y = "  Teste de cor  ";//verde

        if(estadoTela != DESABILITADA)
        {
            return conteudo = x;
        }

        else
        {
            return conteudo = y;
        }
    }

    public JComponent posicaoComponentes()
    {
        JPanel painel = new JPanel();
        painel.setLayout(null);
        JLabel label = new JLabel(estilo(conteudo));
        painel.add(label);
        label.setBounds(170, 150, 100, 25);
        painel.add(tx1);
        tx1.setBounds(130, 30, 150, 22);
        painel.add(tx2);
        tx2.setBounds(130, 70, 150, 22);

        getContentPane().add("South", jpBotoes);
        jpBotoes.setLayout(new GridLayout(1, 2));
        adicionaBotao(botao01);
        adicionaBotao(botao02);

        return painel;
    }

    private void adicionaBotao(JButton botao)
    {
        jpBotoes.add(botao);
        botao.addActionListener(this);
    }

    public void habilitaComp(boolean status)
    {
        if(estadoTela == DESABILITADA)
        {
            tx1.setEnabled(status);
            tx2.setEnabled(status);
        }

        else
        {
            tx1.setEnabled(status);
            tx2.setEnabled(status);
        }
    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {

        if (ae.getSource() == botao01)
        {
            habilitaComp(true);
        }

        else if (ae.getSource() == botao02)
        {
            habilitaComp(false);
        }
    }

    public static void main(String[] args)
    {
        MudaCor cor = new MudaCor();
        cor.setVisible(true);
    }
}

Comment: Com "mudar de cor", você quer dizer mudar a cor do fundo somente, ou tambem a cor da fonte,?
Comment: Outra coisa, Frame não tem estado "desativado". E somente visivel ou não visivel.
Comment: @diegofm  Me expressei mau, quando digo habilitado/desabilitado, me referi aos componentes que estão dentro do frame (no caso os textField), eu quero mudar só a cor da fonte dentro do label.
Answer: Antes de tudo quero deixar  dois alertas sobre seu código:

Sempre inicie a tela dentro da Event-Dispatch-Thread, pois a API do swing não é Thread-Safe, e toda a interface precisa iniciar dentro desta unica Thread. Nesta resposta explica melhor o motivo para isto e eventuais problemas que podem ocorrer. Esta outra resposta mostra algumas maneiras de como iniciar a aplicação dentro desta Thread.
Evite usar layout absoluto, a API do swing provê de vários Layouts Managers para facilitar a vida do programador na hora de criar telas, além de tornar a tela flexível a diferentes tamanhos de monitores e resoluções, sem que seja necessário isso ser tratado diretamente no código. Layout absoluto irá quebrar a aparência da sua aplicação, dependendo do monitor onde a aplicação for executada.

Para alterar cor da fonte de um JLabel, basta utilizar o método setForeground(), mas mesmo adicionando isso no seu código, ele jamais altera a variável estadoTela e o parâmetro status do método habilitaComp, que é o que você está usando para alterar o status do componente, jamais é usado.
Fiz algumas alterações no seu código, para que a cor seja alterada conforme o valor booleano passado no método habilitaComp, não há necessidade de criar constantes:
public void habilitaComp(boolean status)
{

    tx1.setEnabled(status);
    tx2.setEnabled(status);
    label.setForeground(status ? new Color(74, 45, 86) : Color.GREEN);

}

Com essa mudança, o método estilo e as constantes que você criou para controlar o estado deixam de ser necessárias, já que cria complexidade desnecessária para algo que dá para fazer utilizando operação ternária.
Comment: essa condição ternaria, ela poderia ser usada para fazer algo parecido, só que para um "componente" do tipo Image icon ? Assim seria possível trocar o caminho de uma imagem de acordo com o "status" dos componentes?
Comment: Deu certo, muito obrigado ! E sobre os layouts, eu geralmente uso GridBagLayout fiz assim pra tentar fazer mais simples, apesar de realmente não ser o certo !
Comment: @G.Araujo veja a edição, da pra simplificar mais ainda, nem precisa de condicional.
Comment: @G.Araujo claro! no lugar do `status` você coloca uma condição qualquer que resulte em booleano, no lugar das cores, você coloca os dois caminhos que deverão ser aplicados, onde a direita do `:` é o caminho quando a condição for true, e a esquerda o caminho quando a condicao for false :)
Comment: obrigado, já deu "uma luz" essa explicação, vou tentar !
Comment: eu fiz iconeEndereco = new ImageIcon(getClass().getResource(status ? "/imagens/iconeAbaEndereçoDesabilitado.png" : "/imagens/iconeAbaEndereçoHabilitado.png"));   e tive que chamar o método antes de adicionar os componentes (o que eu acredito não ser o certo), e mesmo assim, ele só seta uma imagem, ele não troca conforme o "status".. alguma dica ?
Comment: @G.Araujo não estou entendendo o que você está fazendo. O que eu sugeri foi no lugar de `label.setForeground(status ? new Color(74, 45, 86) : Color.GREEN);` você poderia fazer `label.setIcon(new ImageIcon(status ?  : ));`. Se não for desse jeito dentro do `habilitaComp`, não vai funcionar.
Comment: eu crie o objeto iconeEndereco do tipo Image Icon, porque eu estava tentando fazer isso (trocar os ícones) de um tabbedPane, ai eu estava fazendo  tabbedPane.addTab("Endereços", iconeEndereco, abaEnderecos()); eu acredito que label não pode ser adicionado no tabbedPane, ou tem jeito de converter ?


Proving the Product of Two Open Sets in ℝ is Open

Question: I'm working on a proof which aims to show that for two open sets $A$ and $B$ in ℝ, the set $AB$, defined by $$AB = \{xy | x\in A, y \in B\}$$, is open. I'd like to ensure my proof is valid. Here's the proof I've formulated:
Let $x \in A$ and $y \in B$. Given that both $A$ and $B$ are open, there exists $\epsilon >0$ such that $(x-\epsilon, x+\epsilon) \subset A$ and $(y-\epsilon, y+\epsilon) \subset B$.
For the next part, I'm assuming $x > \epsilon > 0$ and $y > \epsilon > 0$. I believe that if either $x$ or $y$ is negative, we can handle it in a similar way.
We know that $(x-\epsilon)(y-\epsilon) < xy < (x+\epsilon)(y+\epsilon)$, which gives us $xy - \epsilon y - \epsilon x + \epsilon^2 < xy < xy + \epsilon y + \epsilon x + \epsilon^2$.
Since $(xy + \epsilon y + \epsilon x + \epsilon^2) - xy = (x+y + \epsilon)\epsilon > (x+y - \epsilon)\epsilon = xy - (xy - \epsilon y - \epsilon x + \epsilon^2)$, if we pick $\delta =(x+y - \epsilon)\epsilon$, then $D(xy, \delta) \subset AB$ where $D(xy, \delta) = \{z \in ℝ| d(xy, z) < \delta\}$.
I would appreciate it if anyone could provide some insights or corrections. Thanks!
Comment: It might be good to show your steps going from the inequality after "which gives us" and your claim that your defined $\delta$ satifies your final containment statement. Also you do not define $D(xy,\delta)$ [I assume you mean a ball around point $xy$ ?]
Comment: You must also take care of the case $xy=0.$
Comment: $$AB=\bigcup_{x\in A}xB$$ It's enough to show that $xB$ is open $\forall x\in A$
Comment: @SouravGhosh Thanks! Im aware of the proof. I just had this idea and would like to make sure it's right
Comment: @AnneBauval Ah yes. Thank you. Do you think the case where $x>0$ and$ y>0$ is valid? If so then I think the case where $xy=0$ is similar right?
Comment: @SouravGhosh if $x=0$ and $B\ne\varnothing,$ $xB$ is not open.
Comment: WinnieXi What you wrote is valid for the case $xy\ne0$ (split in 4 subcases), but the case $xy=0$ remains to be written. Actually, if $x\ne0$ then $xy\in xB\subset AB$ solves the question more rapidly, and similarly if $y\ne0$ $xy\in Ay\subset AB,$ so there only remains to treat the case $x=y=0.$
Comment: @AnneBauval Correct. I was aware of this fact. Multiplication by a non zero vector induces a homeomorphism.
Comment: (by a non zero *scalar*, but the problem is precisely the opposite case: multiplication by the scalar $0$). So, you were aware that your comment above was wrong.
Answer: Since any open set in $\mathbb{R}$ is a countable union of  disjoint open intervals, it would be enough to prove the proposition for the case when A and B are of the form $(a,b)$ and $(c,d)$ respectively. But then for any $xy\in AB$ (where $x\in A,y\in B$) we have a neighbourhood $(x(y-\epsilon),x(y+\epsilon))$ contained in $AB$ for small enough $\epsilon >0$. So $xy$ is an interior point and the result follows.
PS. We have to keep in mind the signs of $a,b,c,d$ because minus sign can flip the resultant interval or neighbourhood.


In what scenario the framework should not be used?

Question: I have the first meeting with my project manager and she assigned me a project which to be start soon. She explained to me few points related project e.g. technology, functionality, end user expectation etc.

MVC based web application
Not to use any framework
Server Side : use only Java, servlet, jsp
UI : Javascript, jQuery can also be used
integratation with existing project (at later stage)

There is one point i can not understand why she asked me to not to use any framework although i could not ask why. Does anybody clarify ? If i use any framework like spring then will it create any problem while integration with existing project.
Comment: Servlet and JSP are already frameworks. You can perfectly implement MVC with just that: your model are Java objects, you views are JSP, your controller are Servlet. You don't necessary need more at first.
Answer: I can recognize 2 sub questions in your question.

In what scenario the framework should not be used?
why she asked me to not to use any framework?

Answer 1
I can imagine situation when you don't need any framework. It is if you have to create extremely simple 1-2 screen application without any security, access rules and probably without DB based persistence. This means that IMHO framework-less application is good as a student exercise just to understand how things work.
Answer 2
She is ... not professional enough. I am sorry to say it but this is pretty obvious. To implement MVC without framework you have to perform a lot of dirty work. I believe that the key reason for this strange requirement is "integratation with existing project" that is probably created without any framework, so PM thinks that framework could bother you during this integration.
Moreover, product manager should never dictate R&D how to implement project. Project manager can politely ask to implement certain set of features.
I am sorry if my answer is helpful.
Comment: +1 for *I am sorry if my answer is helpful*:)
Comment: Alex, Thank you for your time. Well i can't comment over her professionalism but i think she has almost 10 years of industry experience.
Comment: @user1010399, please accept my condolences. Professionalism is not always a function of years in field. She has almost 10 years of experience? And I have almost 20 years of experience. So what? I just expressed my opinion. Try to ask what the reasons are. Probably they exist (although I do not believe in this).
Comment: All due respect, this mentiality deserves a fat -1 for the simple reason of keeping Stack Overflow attractive for non-constructive questions which doesn't belong at Stack Overflow in first place. Just do not post answers to non-constructive questions. If you can't resist it, look for a discussion forum.


(Enumerable) set of natural numbers might not be effectively enumerable

Question: It is well known that a set of natural numbers, although trivially enumerable, might not be effectively enumerable. I am trying to understand this fact intuitively. What is the decisive element in the definition of effectively enumerable, which involves algorithm, that makes some enumerable set not effectively enumerable?
Comment: *Every* subset of $\Bbb N$ is enumerable.
Answer: Every subset of $\Bbb N$ is enumerable. The "decisive element" that makes a set of integers not effectively enumerable is the absence of an algorithm enumerating it. As Asaf's answer points out, the existence of such sets is by a cardinality argument: there are only countably many algorithms, but uncountably many sets of integers.
Answer: The easiest and least constructive way of seeing this is to remember that there are only countably many algorithms. So only a countable collections can be effectively enumerable.
But there are uncountably many subsets... so most sets of natural numbers cannot be effectively enumerated.


module diagram .

Question: First, sorry for this ugly diagram, my arrow button is broke.
\begin{matrix}
& & F & & \\
&& \ \downarrow{f} &&\\
M&\overset{g}\twoheadrightarrow & N &\to& 0
\end{matrix}
row is exact, $f,g$ are $R$-homomorphisms and $F$ free. That is $f:F\to N$ and $g:M\to N$,
I am asked to prove that there exist $h: F\to M$ such that $gh=f$.
This is what I got so far.
$F$ free so $Im(f)$ is a free submodule of $N$. $g$ is surjective so $Im(g)$ must contain $Im(f)$, hence the preimage of $g(Im(f))$ is subset(submodule?) of $M$.
It feels like i am almost done(assuming any of this is correct) but i can't seem to finish the argument.
Comment: Unclear what you're asking.
Comment: I think what problem i am trying to solve is pretty clear. I want to show that there exist an homomorphism h: F--M s.t gh=f. I need help with finishing my argument or suggestions on how to solve the problem.
Comment: See your question now - is the editing correct?
Comment: What are you using as your definition of "free"?
Comment: thank you, almost correct. f: F--N.    @ Brian. that F admits a basis
Comment: Also, should the sequence be $M\to N\to O$ or $M\to N\to 0$?
Comment: It should be the latter
Answer: Consider an $R$-basis $(e_i)$ of $F$. For each $i$, because $g$ is surjective, there is an element $m_i \in M$ such that $g(m_i) = f(e_i)$. Define $h\colon F \to M$ by taking $h(e_i) = m_i$ and extend linearly to an $R$-module homomorphism. It's part of the definition (or one definition) of freedom that you can do so. Because the $R$-module homomorphism $f\colon F \to N$ is determined entirely by what it does to the $e_i$, and you now, by definition, have $(g \circ h)(e_i) = f(e_i)$ for each $i$, you have $g \circ h = f$.
Comment: Thank you, i am unsure about what the following means though, "extend linearly to an R-module homomorphism"
Comment: The elements of $F$ can all be written as finite linear combinations $\sum_i r_i e_i$, where the $e_i$ are a basis and the $r_i$ are elements of $R$, all but finitely many equal to zero. For our new map $h$ to be $R$-linear (that is, an $R$-module homomorphism), we must have $h\big(\sum_i r_i e_i\big) = \sum_i r_i h(e_i) = \sum_i r_i m_i$, and given that we've already set $h(e_i) = m_i$, demanding this linearity now determines the map completely. That's what's nice about (and in fact the definition of) free modules and bases.

module diagram .


Difference between ClassName variable(arg1); and ClassName variable = ClassName (arg1);

Question: How do you call these 2 different ways bellow and how are they different?
ClassName variable(arg1);

and
ClassName variable = ClassName(arg1);

Comment: Direct initialization and copy initialization. See [here](http://www.gotw.ca/gotw/036.htm).
Answer: ClassName variable(arg1);

This is direct-initialisation. Assuming it's a class type, the object is initialised by passing the arguments to a suitable constructor. It's an error if there is no suitable constructor.
ClassName variable = ClassName(arg1);

This is copy-initialisation. Conceptually, it creates and direct-initialises a temporary; then initialises  the variable by copying or moving the temporary. It's an error if there is no suitable move or copy constructor.
In practice, the copy or move is likely to be elided, so the result will be identical to direct-initialisation - except that there must still be an accessible move or copy constructor, even if it's not actually used.
Answer: case 1:
ClassName variable(arg1);
//will initialize variable directly with the type constructor

case 2:
ClassName variable = ClassName(arg1);
//should initialize variable directly with a copy of the rvalue
//however because of RVO optimiziation this is tha same as case 1

RVO is an optimization from the compiler that removes unnecessary calls to construct/copy/destruct and in this case they are the same.


What do I miss here so that my asp:Repeater does not work?

Question: I have this class:
public class RateResultsSummary
{
    public RateResultsSummary(string labelText, string dataText)
    {
        LabelText = labelText;
        DataText = dataText;
    }

    private string _labelText;
    public string LabelText
    {
        get { return _labelText; }
        set { _labelText = value; }
    }

    private string _dataText;
    public string DataText
    {
        get { return _dataText; }
        set { _dataText = value; }
    }
}

My .aspx page contains:

        <form id="form1" runat="server">

        <fieldset id="fsetSummaryLeastCostOption" runat="server" style="width: 200px;" visible="false">
        <legend>SUMMARY LEAST COST OPTION</legend>
        <asp:Repeater ID="repSummary" runat="server">
            <ItemTemplate>
             <asp:Label ID="lblLabel" runat="server"
              Text='<%# ((RateResultsSummary)Container.DataItem).LabelText %>'></asp:Label>
            <asp:Label ID="lblData" runat="server"
Text='<%# ((RateResultsSummary)Container.DataItem).DataText %>'></asp:Label>
                 <asp:Label ID="lbl" runat="server" Text="Some static text"></asp:Label>

            </ItemTemplate>
        </asp:Repeater>
    </fieldset>

        </form>

And I bind it in such a way:
 protected void Page_Load(object sender, EventArgs e)
    {

        List<RateResultsSummary> lstRateResultDataSource = new List<RateResultsSummary>();
        lstRateResultDataSource.Add(new RateResultsSummary("Carrier: ", "Xxx"));
        lstRateResultDataSource.Add(new RateResultsSummary("Mode: ", "Yyyy"));
        lstRateResultDataSource.Add(new RateResultsSummary("Service: ", "Zzz"));
        lstRateResultDataSource.Add(new RateResultsSummary("Transit: ", "Ccccc"));
        lstRateResultDataSource.Add(new RateResultsSummary("Total Cost: ", "Kkkkk"));

        repSummary.DataSource = lstRateResultDataSource;
        repSummary.DataBind();

    }

And I get an empty page only.
Do I miss something?
Thanks
Comment: Looks fine to me...  Is there any other code on the page that could be causing issues?  Have you tried setting a breakpoint on the line you call databind and make sure it is hit and that lstRateResultDataSource has items? hahaha nevermind I just saw the answer below I missed the visible too!
Answer: You miss the
visible="false"

in third line on ...fieldset id="fsetSummaryLeastCostOption"...


Finding the result of the polynomial

Question: The question is that: Given that $x^2 -5x -1991 = 0$, what is the solution of $\frac{(x-2)^4 + (x-1)^2 - 1}{(x-1)(x-2)}$
I've tried to factorize the second polynomial like this:
$\frac{(x-2)^4 + (x-1)^2 - 1}{(x-1)(x-2)}
=\frac{(x-2)^4+x(x-2)}{(x-1)(x-2)}
=\frac{(x-2)((x-2)^3+x)}{(x-1)(x-2)}=\frac{(x-2)^3+x}{(x-1)}$
However I could not solve it with the given equation $x^2 -5x -1991 = 0$. I know that direct substitution may work, but I think that there is a neat solution to this polynomial. Thanks in advance!
Edited:
I've found the way to solve it with the help of lhf
$\frac{(x-2)^4+(x-1)^2-1}{(x-1)(x-2)}=\frac{((x-2)^2+1)((x-2)^2-1)+(x-1)^2}{(x-1)(x-2)}=\frac{(x^2-4x+5)(x-1)(x-3)+(x-1)^2}{(x-1)(x-2)}=\frac{(x^2-4x+5)(x-3)+x-1}{(x-2)}=\frac{(x^2-4x+5)(x-2)-x^2+4x-5+x-1}{(x-2)}=\frac{(x^2-4x+5)(x-2)-(x-2)(x-3)}{(x-2)}=x^2-5x+8$
Answer: Hint:
$\dfrac{(x-2)^4 + (x-1)^2 - 1}{(x-1)(x-2)}$ simplifies to $x^2 - 5 x + 8$
Comment: Got it, and I've found out the way to do it thanks!
Comment: but I want to know that how can you simplify it so quickly, for me the result is not obvious at all
Comment: I've post my method at the bottom of the question, is it the way you do with it?
Comment: @Someonethatisbadatmath, your original method works: $(x-2)^3+x$ cleary has $x=1$ as a root.
Answer: Try making the question simpler.
Let $t=x-2$ then $x-1$ will become $t+1$. So the question
$$\dfrac{(x-2)^4 + (x-1)^2 - 1}{(x-1)(x-2)}$$
changes to
$$\dfrac{t^4 + (t+1)^2 - 1}{t(t+1)}$$
$$\implies\dfrac{t^4 + t²+1+2t - 1}{t(t+1)}$$
$$\implies\dfrac{t^4 + t²+2t}{t(t+1)}$$
$$\implies\dfrac{t(t²-t+2)(t+1)}{t(t+1)}$$
$$\implies t²-t+2$$
$$\implies (x-2)²-(x-2)+2$$
$$\implies x²+8-5x$$
Now,
$$x²-1991-5x=0$$
Or
$$x²-5x=1991$$
So
$$x²+8-5x=1991+8$$
$$=1999$$

Finding the result of the polynomial


Restoring /etc/init.d/apache2 on Ubuntu 10.04

Question: In my web-server configuration troubleshooting I went through a process of uninstalling apache2 and reinstalling it. I accidentally removed the file /etc/init.d/apache2 which is responsible for starting and stopping the apache service.
I've tried reinstalling the apache2.2-common package which is supposed to place the file, but it is still not present.
How can I do a complete reinstall of Apache? The standard apt-get remove and apt-get install doesn't give me that file back.
Comment: possible duplicate of [How to force a re-install from deb repository after local package screw-up?](http://serverfault.com/questions/188622/how-to-force-a-re-install-from-deb-repository-after-local-package-screw-up)
Answer: sudo apt-get -o DPkg::Options::="--force-confmiss" --reinstall install apache2.2-common

This will let you replace config file with out purging package.
To remove package use
sudo apt-get purge apache2.2-common

and then install apache the normal way:
sudo apt-get install apache2

I hope this helps
Comment: Yes, it's back!!! :D
Answer: You don't need to delete the package first. Just reinstall it:
sudo apt-get install --reinstall apache2.2-common

Comment: Does not fix my problem, but thanks.
Comment: It would if I put in the right package name. :)
Comment: Read this line of my question: `"I've tried reinstalling the apache2.2-common package which is supposed to place the file, but it is still not present."` That did not solve the problem.


How to get location(affinity zone) or name cluster(fabric service)

Question: I am currently using web api of fabric service.
Need to get the location(affinity zone) for fabric service cluster.
i.e to determine in which location the current cluster is located through code(c#)
in web API.
Or else i need the name of cluster where the web API is hosted.
In the webrole or cloud service it was possible using the
https://management.core.windows.net/{0}/services/hostedservices
but i cannot find any way for cluster.
Answer: I'm not sure if this helps, but have a look at the ServiceEventSource that is created for a project. The ServiceMessage method shows you a lot of the information that is available from the service context.
ServiceMessage(
    service.Context.ServiceName.ToString(),
    service.Context.ServiceTypeName,
    service.Context.ReplicaId,
    service.Context.PartitionId,
    service.Context.CodePackageActivationContext.ApplicationName,
    service.Context.CodePackageActivationContext.ApplicationTypeName,
    service.Context.NodeContext.NodeName,
    finalMessage);

You could also look at the FabricClient class
Comment: No it did not helped
Answer: After all the research i did it with

    <Parameter Name="Zone" Value="Eusa" />

This is added in PackageRoot > Config > Setting


Master Detail page for taxonomy terms

Question: I'm essentially trying to recreate the results of this question, but using taxonomy terms instead of nodes.
I have my master view (a list of taxonomy terms from a vocab') item-view, which has the term ID (TID) and I've re-written it to link to the other view item-details/[tid].
On the detail view I have a contextual filter of Taxonomy term: Term ID (to match the field in the other view) and my Argument Input settings match those in the previous answer (namely: 'From Panel Argument' for the list box 'Taxonomy term: Term ID source', then 'First' from Panel argument.)
But on the page (item-page) that holds both views in separate columns, it just links through to the detail view, at item-details/[tid], opening the url in the browser rather than enacting that special drupal magic that makes it appear in the right hand column.
Does this not work with Terms and TIDs? Or have I missed something?
Comment: What are the urls/paths for your two pages? The one with and without terms?
Comment: @Letharion The Master page is at `item-view` and the links of there point to `item-details/[tid]`, the detail view is at `item-details/[tid]` for each item.
Answer:
The Master page is at item-view and the links of there point to
  item-details/[tid], the detail view is at item-details/[tid] for each
  item.

In reality the links on the master page shouldn't link to the details view, but just to the current page with /[tid] appended.
Comment: And as to the previous answer (nodes), there you added the panel content as a view (a slight oversight). Better is to add it as a view pane (which you already set up), and then you do not have to send it the argument, it will just pick it up on the content pane itself, so one less configuration to do.

Master Detail page for taxonomy terms


When is norm surjective mod an ideal for global fields?

Question: Given $K/k$ Abelian, for which ideals of $\frak p\unlhd\cal O_k$ will we have $N^K_k:\cal O_K\rightarrow\cal O_k/\frak p$ surjective?  $k$ is an algebraic number field.
In his article "On the norm groups of global fields", Stern wrote that the norm function is never surjective for Abelian local extensions of global fields.  Can surjectivity still be salvaged if we are looking mod an ideal?  In particular, if the ideal is either small enough, or has certain properties (like not being ramified), then this should be possible: especially since the latter group is finite.
I am getting a feeling this is either completely obvious, or else there is some higher-level terminology in which my question should be rephrased to get an answer.  Thanks!
Comment: What is $\mathcal O_{\mathcal K}^x$?  The fractional ideals of $K$?  Or the units of the ring of integers of $K$?
Comment: Thank you, the x was a typo.  Just $\cal O_K$.
Comment: I'm gonna try it, give me like 20 minutes.  Just checking: do you mean $\mathfrak p$ to be a prime ideal of $\mathcal O_k$, or any old ideal?
Comment: Ideally, we want to find all ideals which have this surjectivity: not just the prime ones.  But if primes are all we can show, that will work too.
Comment: In fact, if one of the primes dividing p is ramified, then surjectivity cannot be shown...
Comment: Ohh, but why not?
Comment: Sorry, this comment was hidden behind the "Show 1 more comment" button.  But I think I figured it out: please look over my answer to make sure I am not missing something fundamental.  If there's any way I can award you points for trying, let me know.
Comment: [deleted comment]
Answer: Denote by $N$ the norm in the finite extension of number fields $K/k$. Because the norm of an integral element is an integral element, $N$ restricts to a map  $O_K$ -->$O_k$, still denoted by $N$. If $Q$ is a prime ideal of $O_K$ lying above a prime ideal of $ P$ of $O_k$, $N ( Q) = P^f$ (where $f$ is the inertia degree) is contained in $ P$, hence induces a map $O_K / Q $--> $O_k /  P $. But these residue fields are finite , hence the norm is surjective. Finally, your original map $O_K$-->$O_k / P $ is surjective because it factors through $O_K / Q $-->$O_k / P $. Note that we don't need $K/k$ to be abelian, not even Galois.
If $K / k$ is an abelian extension of local fields, then local CFT says that the norm index $(k^* :N(K^*))$ equals the degree $[K : k]$. For an abelian extension of global fields, see e.g. the question « Index of norm group of a global field », posted by Jack Yoon, May 9'16.
Answer: Possibly partial answer; at least someone please look over and see if I am missing something:
If $\frak p = \frak p_1^{e_1}\cdots\frak p_r^{e_r}$, then by CRT, surjectivity of $\cal O_K\rightarrow\cal O_k/\frak p$ is equivalent to surjectivity of each of the $\cal O_K\rightarrow\cal O_k/\frak p_i^{e_i}$.  So it suffices to show this for $\frak p$ prime power.
Now if $\frak p$ lifts to $\frak (P_1\cdots\frak P_r)^e$ (ramification degree is the same because the extension is Galois), then $N(\frak P_i) = \frak p$ is in the kernel of the above map; so it suffices to assume that $N:\cal O_K/\frak P_1\cdots\frak P_r\rightarrow\cal O_k/\frak p$, and both groups are finite.
In such a case, it is a standard argument that the induced norm map ($\frak P_i\mapsto\frak P_1\cdots\frak P_r$) will be surjective.  However, if $\frak p$ is ramified, then the $N$ map sends $\frak P_i$ to $(\frak P_1\cdots\frak P_r)^e$, and so it equals the induced norm map ^e.  In this case, if ($e, |\cal O_k/\frak p|$) $\neq$ 1 [which I believe happens every time the extension is ramified?], then we only get the set of $e$-th powers in $\cal O_k/\frak p$, and so the map is not surjective.
Tracing backwards, given an ideal $\frak p$ we can figure out whether or not the norm map mod that ideal is surjective.
Comment: I assume you're trying to show that for any coset $a + \mathfrak p$, for $a \in \mathcal O_k$, that there exists a $b \in \mathcal O_K$ with $N_{K/k}(b) - a \in \mathfrak p$.
Comment: The norm is a multiplicative map, right?  If you're taking the norm from $\mathcal O_K$ to $\mathcal O_k$, and then reducing modulo $\mathfrak p$, then you're just looking at a function, not a homomorphism.
Comment: Yes, that is what I am trying to show.  I will think about the "function" vs. "homomorphism" tomorrow: perhaps it affects applicability of the CRT?
Comment: I think it affects implications of words like "kernel."  Also, are you perhaps confusing the ideal/global norm with the finite field norm?  Those are different things.


Deny direct access to files but allow from index.html

Question: I have a simple SPA with followed structure:
.htaccess
index.html
router.php
temp ┑
     ├─ error.tmp
     ├─ form.tmp
     └─ post.tmp
js ──┑
     └─ m.js

How to deny direct access to templates but allow access them from index.html?
This way doesn't helps:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://example.com [NC]
RewriteRule ^temp/(.*)\.tmp$ - [F,L]

ErrorDocument 403 /index.html
ErrorDocument 404 /index.html

Comment: @MrWhite by `fetch()` from m.js
Comment: @DennisNolte You could use "access control", however, the OP isn't wanting to block _all_ HTTP access, so it's not necessarily any easier doing it that way than using mod_rewrite. (The reference link alone isn't sufficient as that would simply block _all_ HTTP access.)
Comment: How are these `.tmp` files being used from `index.html`?
Comment: Cant you disable access to the files not via rewriteengine, but instead via access control directly?
https://httpd.apache.org/docs/2.4/howto/access.html
Uncertain why you would use the rewriteengine for that task.
Comment: @DennisNolte `Deny from all` but `Allow from ...` what?
Comment: https://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess/
for example (random google first entry)
Comment: @MrWhite looks like there is no approach to protect files from direct access...
Comment: Yes, you can protect files from direct access - as mentioned in my answer. However, it is not 100% reliable, which I've also discussed in my answer. However, you need to state in your question how these files are being accessed - this is crucial to determining how to block access. You've stated in comments that the `.tmp` files are accessed from the client, using JavaScript. What about the other files? If a file doesn't need to be accessed from the client at all then it is trivial to block.
Answer:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://mydomain\.com [NC]
RewriteRule ^temp/(.*)\.tmp$ - [F,L]

If you want to deny "direct access" (ie. when the user types the URL directly into the browser's address bar) then you need to remove the first condition that checks whether the Referer header is not empty. On "direct requests", the Referer is always empty - so the above will not block them.
However, the reason for the condition in "normal" hotlinking protection is because the client may not send a Referer even when one is expected. Without that conditon then these legitimate clients will be blocked also.

allow access to them from index.html

If you specifically only want to allow access from index.html and no other client-side file then change the condition to match this exact Referer. For example:
RewriteCond %{HTTP_REFERER} !=https://example.com/index.html

...by fetch() from m.js

However, if you are fetching these resources via an XMLHttpRequest - in which you are constructing the entire HTTP request, then there is no need to check the HTTP Referer (although you could inject a Referer header). Instead, you would send a custom header, such as X-AJAX (or perhaps override the User-Agent) in the request and check for this instead. For example:
RewriteCond %{HTTP:X-AJAX} !yes
RewriteRule ^temp/(.*)\.tmp$ - [F]

Then set the X-AJAX: yes HTTP request header when constructing your XMLHttpRequest.
(No need for the L flag in addition to F.)
Comment: `RewriteCond %{HTTP_REFERER} !=https://example.com/` - works
Comment: Yes, that is correct, there is no `Referer` header on direct requests. This is why I suggested removing the first condition (`RewriteCond %{HTTP_REFERER} !^$`). However, you appear to have possibly two different requirements. **1.** Preventing `.tmp` files being called directly - which are called by an AJAX request? **2.** Preventing static resources being called directly.
Comment: For any AJAX request (#1), you should be sending a custom HTTP request header (eg. `X-AJAX`) and checking for this (or the absence of) in order to block access (not the `Referer`), as mentioned in the 2nd part of my answer. The `Referer` is less reliable. For static resources (#2) you need to check the `Referer`, as mentioned in the first part of my answer. Bear in mind that checking the `Referer` is not 100% reliable, as user-agents may simply not send it (for any requests). And this is easy to circumvent - so this is not a "security" thing.
Comment: I've updated my answer with an example if you are using JS "AJAX".
Comment: There is another internal and external sources files as images, scripts ect. And also I make ajax requests to router.php
Comment: with these rules I get 403:
RewriteCond %{HTTP_REFERER} !=https://example.com/index.html [NC]

RewriteRule ^temp/(.*)\.tmp$ - [F,L]
Comment: Not sure what you mean by "internal and external sources files"? If you are making ajax requests to other endpoints then you need to modify the `RewriteRule` _pattern_ to accommodate these. For static resources like images, CSS etc. then use standard hotlinking and check the HTTP Referer.
Comment: "with these rules I get 403" - What `Referer` header is being sent on the request?
Comment: Referer is `https://example.com/`
Comment: Then use that instead. The HTTP Referer is the referring "URL". So, if `index.html` is not present on the "URL" then it should be omitted. Although, what if you were to request `https://example.com/index.html` instead? Or do you block that? Or do you set a custom `Referer` header when making the AJAX request?
Comment: but the files are again accessible via a direct link
Comment: So, in what way did it "work" before? In a direct request, the `Referer` is _empty_. If you only have that one conditon (and the correct regex in the `RewriteRule`) then it can only block direct requests since the condition will be successful. What is the `Referer` header when observing the network traffic under a direct request?
Comment: and there is no `Referer` header in case of file direct request


How to use sample and seq in a dplyr pipline?

Question: I have a dataframe with two columns, low and high. I would like to create a new variable that is a randomly selected value between low and high (inclusive and equal probability) using dplyr. I have tried
library(tidyverse)

data_frame(low = 1:10, high = 11) %>%
    mutate(rand_btwn = base::sample(seq(low, high, by = 1), size = 1))

which gives me an error since seq expects scalar arguments.
I then tried again using a vectorized version of seq
seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))

data_frame(low = 1:10, high = 11) %>%
    mutate(rand_btwn = base::sample(seq2(low, high, by = 1), size = 1))

but this does not give me the desired result either.
Comment: `data_frame(low = 1:10, high = 11) %>%
    rowwise() %>%
    mutate(rand_btwn = base::sample(seq(low, high, by = 1), size = 1))`
Comment: @bouncyball That works. Thanks!
Answer: To avoid the rowwise() pattern, I usually prefer to map() in mutate(), like:
set.seed(123)
data_frame(low = 1:10, high = 11) %>%
  mutate(rand_btwn = map_int(map2(low, high, seq), sample, size = 1))
# # A tibble: 10 x 3
#      low  high rand_btwn
#    <int> <dbl>     <int>
#  1     1    11         4
#  2     2    11         9
#  3     3    11         6
#  4     4    11        11
#  5     5    11        11
#  6     6    11         6
#  7     7    11         9
#  8     8    11        11
#  9     9    11        10
# 10    10    11        10

or:
set.seed(123)
data_frame(low = 1:10, high = 11) %>%
  mutate(rand_btwn = map2_int(low, high, ~ sample(seq(.x, .y), 1)))

Your Vectorize() approach also works:
sample_v <- Vectorize(function(x, y) sample(seq(x, y), 1))

set.seed(123)
data_frame(low = 1:10, high = 11) %>%
  mutate(rand_btwn = sample_v(low, high))

Comment: `rowwise()` creates an unnecessary grouping, and was meant (see `help("rowwise")`) to be used with `do()` that I'm even more wary of (package author recently stated he hasn't used `do()` in years, because there are usually clearer ways of doing things). That being said, it works. And it's even not less clear. And I'm all for whatever works
Comment: These are great solutions. What is your reasoning for avoiding `rowwise()`?


What are dependencies in the context of a user role in Drupal 8?

Question: In the process of wrapping my head around Drupal 8's configuration system (which is awesome, by the way), I came across this:
YAML file (from core/modules/user/config/install/user.role.authenticated.yml)
<code>id: authenticated
label: 'Authenticated user'
weight: 1
langcode: en
status: true
is_admin: false
dependencies: {  }
</code>
Now of course I understand module dependencies, but what might be set here as a dependency for a user role configurable and what would it mean?
Thanks!
Comment: Nothing. This is a config entity and each config receives dependencies array. But user role has none since it's just the id and label basically.
Comment: Hi, Ivan. That was my assumption until I saw the (apparently unnecessary) entry in the user module file and thought perhaps something interesting might be going on. Guess not. :) Thanks!
Comment: But that does not mean you cannot provide dependencies as you please. You can have some specific user role that should depend on some content type for example.
Comment: @IvanJaros OK, now it's interesting again. Can you expand on that a bit? If I were to specify a content type as a dependency of a role, is it also up to my module to handle that dependency (to make it mean _something_), or are there built-in effects?
Comment: The content type(node type) is a config entity so you would export it into config file too, the same as the user role, and you would provide the content type config entity as a dependency in your user role so the content type would be imported before the role. The content type(or dependency to be more precise) has to  be defined by some module. The user role can be put into config/optional directory which would mean it would be installed only if the content entity was already present.
Comment: That's so... sensible. Gotta say, the more I understand config entities, the more I like them. Thanks for the explanation. I'm sure this is basic stuff for you, but it's gold for someone like me just starting on the D8 path. Would you mind posting as an answer?
Comment: @othermachines I'm sure Ivan won't mind me pointing out that he asked a lot of questions here when he was starting out in D8; reading his [questions](http://drupal.stackexchange.com/users/21641/ivan-jaros?tab=questions&sort=newest&page=3) from bottom to top makes for a pretty good tutorial of sorts, some really great insights and potential gotchas in there :) (also check out [berdir](http://drupal.stackexchange.com/users/31/berdir)'s answers in the [8 tag](http://drupal.stackexchange.com/search?tab=votes&q=user%3a31%20%5b8%5d) for a lot of priceless info)
Comment: @Clive Oh, I agree and I certainly have been... Reading and checking things out, that is. Thanks -
Answer: As Ivan Jaros said, all config entities can have dependencies on modules and other config entities, both automatically derived based on code (e.g, a field depends on its field storage and entity bundle it is added) and manually set (in an enforced sub-array with the same structure)
Dependencies ensure that the required dependencies are installed and they are installed in the right order. Which is important if you import a new node type with fields, display configurations, views that list them and so on.
User roles currently don't have automatically derived dependencies, but they actually should have. They should depend on the modules that provide the used permissions, which is a bit tricky since permissions don't give you that information especially not for dynamic ones that depend on node types, filter formats and so on. That's why the key is always empty for them.
We should open a core issue to try and track this better, that would allow roles to clean up permissions when e.g. a node type is deleted or a module is installed. But it's not a major problem since nothing happens if those permissions don't exist anymore.. it's just a string and if nothing asks for it, then nothing happens with it. The only problematic thing is that you a) end up with cruft in those config objects and b) the permissions could get active again when you e.g. delete a node type and add again with the same name. You might not expect your permissions configurations to survive that.


Optimal solution to a statistical decision problem

Question: Setup
I'm trying to find condition(s) that characterize the solution to a statistical decision problem. The environment is as follows.

$\Omega$ is a finite set of states of the world.
A decision maker has prior $f_0$ about the distribution of states.
$g(\cdot|\omega)$ is a conditional distribution of signals when the realized state is $\omega$

The decision problem has two stages:

Stage 1: the decision maker decides how many observations to draw from $g(\cdot|\omega)$; each observation incurs a constant cost of $c$.
Stage 2: the decision maker makes a decision to maximize an objective function $\phi(a,\omega)$, where $\phi$ is strictly concave in $a$ for each $\omega$.

Let $n\in\mathbb Z_+$ be the number of observations, and denote the posterior (obtained using Bayes' rule) by $f_n$. Given the concanvity assumption, there is a unique decision $a^*(n)$ that is optimal in stage 2. Then the decision problem can be formulated as
$$\max_{\;n\in\mathbb Z_+} \sum_{\omega\in\Omega}f_n(\omega)\phi(a^*(n),\omega)-cn.\tag{1}$$
Question
As stated, the problem is pretty general. I was wondering if there are the conditions (analogous to first and second order conditions for optimization problems in calculus courses) that characterize the solution to $(1)$? If not, what minimum extra structures does the problem need in order to have one?
Answer: This is a mixed integer and convex problem.  The general way to solve problems of your type is to solve for the optimum value $val(n)$ for each $n$, and then take the best $n$. However, I think your problem is not clearly specified and is actually more complicated than you give (see below).

The definition of $f_n(\omega)$ is unclear to me.  I think this would actually depend on the observations, call them $\{S_1, \ldots, S_n\}$ and assume they are discrete for simplicity. In that case, the problem is more complicated since the choice of $a$ does not just depend on $n$, it also depends on the observations $\{S_1, \ldots, S_n\}$.
So you would have:
\begin{align}
&f_n(x, s_1, \ldots, s_n)  \\
&=Pr[\omega=x|S_1=s_1, \ldots, S_n=s_n] \\
&= \frac{Pr[S_1=s_1, \ldots, S_n=s_n|\omega=x]Pr[\omega = x]}{\sum_{y\in\Omega} Pr[S_1=s_1, \ldots, S_n=s_n|\omega=y]Pr[\omega=y]}
\end{align}
So if you choose a given $n \in \{0, 1, 2, \ldots\}$, you observe $S_1, \ldots S_n$ and then choose $a\in\mathcal{A}$ to maximize $\sum_{x \in \Omega} f_n(x, S_1, \ldots, S_N)\phi(a, x)$. In that case, the expected utility given you choose $n$ is:
$$ val(n) = E\left[\max_{a \in \mathcal{A}}\left[\sum_{x\in\Omega}f_n(x, S_1, \ldots, S_n)\phi(a,x)\right]\right] - nc $$
where the expectation is with respect to the random $S_1, \ldots, S_n$ observations given you choose to look at $n$ of them (and so the choice of the optimal $a$ depends on the realizations of $S_1, \ldots, S_n$).

If the $\phi(a,x)$ function satisfies $0 \leq \phi(a,x) \leq \phi_{max}$ for all $(a,x) \in \mathcal{A} \times \Omega$, then you can restrict attention to values $n$ that satisfy $\phi_{max} - nc \geq 0$. So you only need to consider non-negative integers $n$ that are less than or equal to $\phi_{max}/c$. So compute $val(n)$ for $n \in \{0, 1, \ldots, \lfloor \phi_{max}/c\rfloor\}$, then pick the maximizing $n^*$.
Comment: You cannot exchange the expectation and the $\max$. For example, let $S$ be uniformly distributed in $[0,1]$.  Then $E[\max_{a\in\mathbb{R}} (5 - (a-S)^2)] = E[5] = 5$. But $\max_{a\in\mathbb{R}} E[5 - (a-S)^2] = \max_{a\in\mathbb{R}} [5 - a^2 + a - 1/3] = 59/12 \approx 4.91667 < 5$.   In general, since $f(a,S) \leq \max_{x\in A} f(a,S)$, we have $E[f(a,S)] \leq E[\max_{x \in A} f(a,S)]$ for all $a$, and so $\max_{a\in A}E[f(a,S)] \leq E[\max_{x\in A} f(a,S)]$.
Comment: Typo in comment above, I meant "since $f(a,S) \leq \max_{x\in A} f(x,S)$, we have $E[f(a,S)] \leq E[\max_{x\in A} f(x,S)]$ for all $a$ and so $\max_{a\in A} E[f(a,S)] \leq E[\max_{x \in A} f(x,S)]$.
Comment: Thanks for the answer `:)` I have a follow-up question: In the equation for $val(n)$ where the expectation is over $S_1,\dots,S_n$, given how $f_n$ is defined, do we not get the following result: $$\begin{aligned}val(n)&=E\left[\max_{a\in\mathcal A}\left[\sum_{x\in\Omega} f_n(x,S_1,\dots,S_n)\phi(a,x)\right]\right]-nc\\&=\max_{a\in\mathcal A}\left[\sum_{x\in\Omega}E[f_n(x,S_1,\dots,S_n)]\phi(a,x)\right]-nc\\&=\max_{a\in\mathcal A}\left[\sum_{x\in\Omega}f_0(x)\phi(a,x)\right]-nc,\end{aligned}$$ which would suggest optimal $n^*=0$? Did I err somewhere in my reasoning?
Comment: Oh yes. Thank you very much! That typo did not cause any confusion though.
Answer: This problem is studied in Stigler (1961), "The Economics of Information," Journal of Political Economy, Vol. 69.
The literature quickly moved away from this model because in most settings the agent does not choose a fixed number of draws at the outset but rather sequentially chooses whether to incur cost c to get an additional draw.
Comment: Stigler (1961) studies how search and advertising may lead to dispersion in prices. I can see the relevance to my problem *in general*, but I'm not sure how his paper informs the current problem *in particular*. Would you please kindly help me see the connection?


Invoke java using JavaScript inside JavaFX. Is it possible?

Question: I am using WebEngine & WebView from JavaFX. Now I want to execute Java using javascript running inside WebEngine.
My question is if it is possible to do so and if yes any hints.
I want do something like below

Now if I call the runSampleJava() inside WebEngine it will execute that code.

Points to be noted

This is not about Rhino JavaScript engine for java
I know it is possible to inject java object, eg: JSObject window = (JSObject) webEngine.executeScript("window"); and so on. But this is not what I am looking for.
Comment: Maybe this helps: http://www.nusphere.com/kb/jscoreref/javobj.html
Comment: @Fildor it is way beyond the problem :-(
Answer: I didn't manage to create Java instances but the thing I managed to do is to push object instances created in Java into JavaScript and call back to them.
So my Java-Code looks like this:
JSObject win = (JSObject) engine.executeScript("window");
win.setMember("jHelper", new JavaHelper());

JavaHelper example (must be public):
public static class JavaHelper {
    public int newInteger(int input) {
        // ...
    }
    public Random newRandom() {
        // ...
    }
}

And then then in JavaScript:
function bla() {
  var number = jHelper.newInteger(1234);
  var random = jHelper.newRandom();
  // ...
}

You can see my work where I communicate between Java and JavaScript back and forth at https://github.com/tomsontom/fx-ide/tree/master/at.bestsolution.javafx.ide.editor and in action at http://tomsondev.bestsolution.at/2012/10/29/eclipsecon-javafx-demo-app-videos/
Comment: I guess it would be a major security problem if the webview would be allowed to create arbitary objects and pass back and forth real java objects. So all I found was allowed to get passed between JavaScript and Java in webview are primitive types and strings (I use JSON from communicating with the Java-Side)
Comment: As I have already specified, I can do it already. And this is not exactly what I am looking for. 'Specially' I need to create object.
Comment: Agreed with that security flaw.