Roman Numeral Analysis - Tonicization of relative major key in minor key

Question: I have a passage that I am trying to analyse with roman numerals:

The passage is in B minor, but the section in question briefly tonicizes D major - the relative major key.
My question is, how can this section be best analysed with roman numerals? (I would imagine something like "V/?" "I/?" would be better than simply writing "VII" "III".)
Answer: I recommend trying to clearly show the functional role of each chord with your labels. So for this example, you have two options:

VII7–III
V7/III–III

The first option is not wrong, but it doesn't clearly show what the relationship between the VII chord and the III chord actually is.
The V7/III label, however, makes this very clear: here is a dominant of a temporary tonic, and now we move to that temporary tonic.
For this example, I would recommend Option 2 every time.
Answer:
My question is, how can this section be best analysed with Roman numerals? (I would imagine something like "V/?" "I/?" would be better than simply writing "bVII" "III".)

I wouldn't choose bVII-III, but V/I B (D!) or V7/iii ...  both are adequate.
Like most minor pieces this passage in B-minor includes the relative major chord D = III. You will encounter this "modulation" which is actually only a short extension to the relative key by its secondary dominant A7->D (V7/III) in almost every choral by Bach or tune by Handel's Concerti Grossi in minor. As the melody doesn't remain for more than some bars in this new key it's better to say V7/III than V7/I of D, but it wouldn't be wrong, both analyses would be accepted and understood.
(b.t.w. every other degree can be reached by its secondary dominant, also in a major key!
e.g.:
In C major you often find an analogous situation: starting with the tonic C and leading to the relative key/chord like C-G-C-E7-Am-C7-F ... which is I-V-I-V7/vi-vi-V7/IV etc)
Answer: Rather depends how briefly! Originally in key B minor, that chord would be designated as i. Making any D in that section III.
However, if the section modulated to feels like D major, then D could be I, lasting until the piece is fimly back into B minor again. If it's such a brief modulation - several barss only - it's best left so that D = III.
Not sure where "♭VIII" would feature, though.
Comment: You would indeed. A is the dominant of D, thus V/III is a good label.


Building a compound probability distribution

Question: I want to build a probability distribution for a "shock" variable. I want to show that there are p% chances of no shock, and (100-p)% chances of shock- in which case, shock is distributed according to some continuous pdf f(x). I have absolutely no ides how to do it. Please help. Thanks for any suggestions in advance.
Answer: As non-statician I dislike percentages and my $p$ stand for your p%.
Maybe something like: $$X:=US$$ where $U$ and $S$ are independent random variables.
This with $P(U=1)=p$ and $P(U=0)=1-p$ and with $S$ having PDF $f$.
$U$ somehow states whether there is a shock or not.
$S$ somehow "measures" a shock (and is probably meant to be positive).
$X$ is (if $p>0$) not continuous and for $x\geq0$ we have $$P(X\leq x)=(1-p)+pP(S\leq x)$$
Comment: Thanks for your help drhab.
So, does it mean that if there is a probability of 0.75 (p) of shock, and 0.25 (1-p) for no shock, when shock is uniformly distributed over [0,1], then: overall probability of getting a shock of measure 0.33 will be:
P(X<0.33)=0.25+0.75*0.33=0.4975?
Comment: Not the probability of getting a shock of measure $0.33$, but the probability of getting a shock *less than* $0.33$ will equalize that.
Comment: Thank you so much drhab. You have been a great help.
Comment: You are very welcome.


Cors Api Google Maps

Question: Estou desenvolvendo um sistema feito em Silex/PHP e o frontEnd dele esta sendo feito em AngularJs, tenho um método nele que estou querendo que ele faça uma busca na API do Google Maps para me retornar uma determinada rota, mas toda vez me retorna o seguinte erro:

O cabeçalho da requisição:

Se eu habilitar o cors com a extensão do Chrome funciona perfeitamente:

Tenho um index.php onde todas as requisições passam por ele, então inserir o seguinte:

Já tentei de tudo mas nada funciona, alguém já passou por isso ?
Comment: Não adianta adicionar os headers do CORS no seu site, o navegador vai verificar eles no endereço da API, ou seja, no endereço do Google, o qual você não tem controle. O que você precisa é ver o manual da API do google para ver o que está incorreto, mas pelo pouco que li já adianto que o uso do Distance Matrix é proibido pelo google para qualquer uso que não seja exibir a informação em um mapa do google maps.
Comment: Mas se eu pegar a url e colar no navegador ele me retorna o xml ou json normal.
Comment: Isso porque você abriu a URL no navegador manualmente, por ajax é diferente, o navegador bloqueia requisições ajax entre domínios diferentes a menos que ele libere o acesso pelo CORS. E como eu disse, você deve verificar o manual das APIs do Google, lá você deve encontrar o como fazer corretamente, incluindo a aquisição de uma chave de acesso que o Google usa para controlar acesso as APIs dele e em que casos pode ou não usar as APIs dele.
Comment: Leandro, OK. Vou verificar aqui.
Comment: Leandro não consegui ainda, mas só uma dúvida se eu habilitar o cross origin do chrome ele funciona !
Comment: Não se engane, o que esta extensão faz é desativar o recurso de segurança do navegador, ele faz o navegador funcionar como se o servidor respondesse com os headers do CORS, isso nunca deve ser usado como referência para se criar um programa.
Answer: A API do Google não suporta nem CORS nem JSONP, então você terá que fazer um proxy com o php. Algo assim:
$http.get('goog.php').then(
    function(res){
        console.info(res);
        if(res.status == 200){

        }
    }, function(error){
        //mensagem de erro
        console.info(error);
    }
);

PHP:
<?php
$url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=SUA_KEY';
$returned_content = get_data($url);

header('Content-Type: application/json');
echo $returned_content;

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
?>

Se não tiver curl, usa alguma outra forma.

Cors Api Google Maps


How to correctly use regex in ruby test

Question: In a test, there is a random number at the end of a function output. I need to use regex. When I check the output manually, it works as intended. But my tests don't pass. Here's how it looks:
assert @tester.image == "http://loremflickr.com/300/300?random=#{/\d{1,3}/}"

The end of the url contains 1-3 digits. Example:
...random=476

How can I use regex properly in this context?
Answer: You can use assert_match and avoid having to handle manually that procedure, making that more verbose. If your regular expression works fine, then:
assert_match /http:\/\/loremflickr\.com\/300\/300\?random=\d{1,3}/, @tester.image

Or for not having to escape specific characters:
%r{http://loremflickr\.com/300/300\?random=\d{1,3}}

Comment: Sorry, I forgot escaping the dot. Edited. Thanks!
Comment: First example worked after adding \ before .
`assert_match /http:\/\/loremflickr\.com\/300\/300\?random=\d{1,3}/`

How to correctly use regex in ruby test


php,mysql,html - Display SQL query(conjunction) properly in HTML

Question: I want to display the name of the doctor that will only recur once and his specialization for the proper limit of it. I have here my query
select a.emp_fname,a.emp_lname,b.hcp_name, c.*, d.*,e.spec_type
from ehr_employee a
inner join ehr_c_hcp_emp c
on a.emp_id=c.emp_id
inner join ehr_hcp b
on b.hcp_id=c.hcp_id
inner join ehr_c_doc_spec d
on d.emp_id=a.emp_id
inner join ehr_specialization e
on e.spec_id=d.spec_id

Whereas the ehr_c_hcp_emp has
hcp_emp_id emp_id hcp_id (Conjunction for the employee and hcp table).
And the ehr_c_doc_spec has doc_spec_id emp_id spec_id (Conjunction for the employee and specialization table). Why is that because the doctor/employee can be in 1 or more different hospitals and can have 1 or more specialization.
The query above display this result
emp_fname   emp_lname   hcp_name   spec_type
John        Doe         Hospital   Cardio
John        Doe         Clinic     Cardio
John        Doe         Hospital   Psych
John        Doe         Clinic     Psych

I have my php-html code written in while like this
 <?php
$sel_admin = "*The query above*";
$rs_admin = mysql_query($sel_admin);
while($row = mysql_fetch_array($rs_admin))
{
  echo"
 ";
  echo "" .$row['emp_fname']." ".$row['emp_lname']. "	";
  echo "" .$row['hcp_name']. "	";
  echo "" .$row['spec_type']. "	";
  echo"
";
}
  ?>

And it just produce just like the query above
What I want to achieve is something like this in a single row
John Doe    Hospital    Psych
            Clinic      Cardio

NOTE: I also have many data like that i just displayed it like that visualization
Comment: so add some code to only output a name if it's different from the previous row. `$prev = null; while(...) { If ($prev != $cur_name) { output name; $prev = $cur_name }}`
Comment: I think that will display them on two separate rows??
Comment: then you'd need even more code to count how many dupes there are and issue appropriate rowspan headers.
Comment: Can you please elaborate the `output name;` you've said?
Answer: My personal solution would be create simple result set builder, something like this. Then you could do another foreach in row. Question is, do you want or not new row for each record. Because then @marc-b answer is correct and works for multipage.
$tableData = [];
$sqlData = [
    0 => [
        'userId' => 3,
        'name' => 'Joe',
        'group' => 'Good'
    ],
    1 => [
        'userId' => 3,
        'name' => 'Joe',
        'group' => 'Bad'
    ]
];

foreach ($sqlData as $item) {
    if (!isset($tableData[$item['userId']])) {
        $tableData[$item['userId']] = [
            'name' => $item['name'],
            'groups' => []
        ];
    }

    $tableData[$item['userId']]['groups'][] = $item['group'];
}

$tableData = [
    3 => [
        'name' => 'Joe',
        'groups' => [
            0 => 'Good',
            1 => 'Bad'
        ]
    ]
];


Question in My Son's Math Training Worksheet that Has Me Completely Baffled

Question: I am not sure what title to put as the question really has both me and my son confused.  It says this:
"If PLUS equals 68, what does MINUS equal?"
and the choices are:
A. 102  B. 76  C. 120  D. 46
and the answer provided in the answer key was 76.
Maybe someone here has encountered some problem with a similar logic?  We are utterly confused at where to start with the solution and have tried researching about inverse, etc.
Hoping someone can help with this.  Thanks :)
Comment: The most baffling thing is why anyone would call this "math training".
Comment: Let $A=1$, $B=2$,...,$Z=26$. Now add the letters of each together. You will get:
$$PLUS\implies P+L+U+S=16+12+21+19=68$$
$$MINUS\implies M+I+N+U+S=13+9+14+21+19=76$$
Comment: It's a bit like calling crosswords "author training".
Comment: Thanks everyone for your quick replies. It is amazing how helpful everyone in this community is :)  @rschwieb: I completely agree.  And the funny thing is I just found out that the person who gave this "training material" got this from a Math Olympiad book which is currently being sold lol
Answer: Sum up the positions of the letters in the alphabet beginning with

$A = 1 \Rightarrow$
$$PLUS = P+L+U+S = 16+12+19+21=68$$
Comment: OMG thank you so much for answering this.  I guess we have been too concentrated on numbers and solving stuff that this completely flew by.


Show User Information in Block from View

Question: I have a block that shows some data from the User area (People) in Drupal 7. I have a rewrite setup that shows "VACANT" if there is no user selected for the content type. When logged in, I see users for 3 of the 4 contents I have created, which is correct. When logged out, I see VACANT for all of the contents.
Is there some restrictions on showing User data to the public? How can I make a certain Role visible to everyone?
EDIT::: Thanks to @Clive: View user profiles [x] for anonymous.
Comment: There's a 'view user profiles' permission (or something very similar), is that enabled for anonymous users?
Comment: I'll check that here... just got the "Additional uncaught exception thrown while handling exception" error I am dealing with now :|
Comment: @Clive make that an answer and I'll give you some points!
Answer: Go to <code>/admin/people/permissions</code> and tick the "View user profiles" permission for anonymous users:


Cannot attach Event listener to canvas?

Question: I've got some very simple code that attempts to attach an event listener and call a function on mousemove, so that I can find the mouse position within a canvas element:
canvas = document.getElementsByTagName('canvas');
canvas.addEventListener('mousemove', on_canvas_move, false);

function on_canvas_move(ev) {
    var x = ev.clientX - canvas.offsetLeft;
    var y = ev.clientY - canvas.offsetTop;
    $('#status').html(x +', '+ y);
}

However I get the error: Uncaught TypeError: Object # has no method 'addEventListener'
What exactly is going on here?
Comment: This just needs a comment- use document.getElementsByTagName('canvas')[0].
Answer: getElementsByTagName() returns a nodeList (like an array of DOM objects) so you need to designate which element in that nodeList you want to add the listener to.
And secondly, your event handler on_canvas_move() also has the same issue as canvas.offsetLeft would be trying to read the .offsetLeft property on the nodeList, not on the DOM element.  That would give you an undefined value and trying to do math with undefined gives you NaN.
To add just one:
canvas = document.getElementsByTagName('canvas');
canvas[0].addEventListener('mousemove', on_canvas_move, false);

function on_canvas_move(ev) {
    var x = ev.clientX - this.offsetLeft;
    var y = ev.clientY - this.offsetTop;
    $('#status').html(x +', '+ y);
}

Or, to add all of them:
canvas = document.getElementsByTagName('canvas');
for (var i = 0; i < canvas.length; i++) {
   canvas[i].addEventListener('mousemove', on_canvas_move, false);
}

function on_canvas_move(ev) {
    var x = ev.clientX - this.offsetLeft;
    var y = ev.clientY - this.offsetTop;
    $('#status').html(x +', '+ y);
}

Comment: Thank you. If you could perhaps quickly clarify why I'm getting NaN on x,y values?
Comment: @Megh - for the same reason.  `canvas.offsetLeft` is trying to get `offsetLeft` on an array, not on a DOM element in that array.  I updated my answer to show a new version of `on_canvas_move()`.
Comment: Technically it returns a NodeList, not an array.
Comment: @Dennis - technically correct and I've edited my answer to use that term, though it doesn't change the solution.
Answer: document.getElementsByTagName() returns you an array - you should either loop it and bind the listener, or point to the element you need:
document.getElementsByTagName('canvas')[0].addEventListener( ... )

An advice - when you don't know what's going on, figure it yourself by printing out stuff to console - console.log(canvas) would have told you.
Comment: The `.getElements` with a plural should have also told.

Cannot attach Event listener to canvas?


How can I split the body field to insert content between the first and the second paragraph?

Question: I have a node which shows content from the body field. I want to add a another paragraph or a block between between the first and the second paragraph, after the first
 and before the second
 tag.
But in my template to output the body there's only {{ content.body }}.
Drupal 7 had something like block in block. How can I do the same in Drupal 8?
Comment: You are probably referring to https://www.drupal.org/docs/7/modules/block-in-block/insert-ads-within-article-bodies, right? And your question actually is **How can I insert ads within article bodies**?, right?
Answer: I resolved my issue, using solution below
    {% set Paragraphs = node.body.value|split('
') %}
  {% set paragraphHalf = (Paragraphs|length / 2)|round %}

  {% if paragraphHalf %}
    {% for paragraph in Paragraphs %}
      {% if paragraphHalf == 1 or loop.index % paragraphHalf == 1 -%}

      {% endif %}
      {{ paragraph|raw }}

      {% if loop.last or loop.index % paragraphHalf == 0 -%}
      {{ insert item }}
      {% endif %}

    {% endfor %}

  {% endif %}


Where to place if statement in a loop when checking values of a dictionary

Question: person_language = {
    'john' : ['python' , 'c'],
    'sarah' : ['python' , 'html'],
    'jason' : ['java'],
    'michael' : ['javascript'],
    }

for person,languages in person_language.items():

    print(f"{person}'s favourite language are:")

    for language in languages:
            print(language)

Noob Alert
I can't figure out where to use if statement to print 'is' when there is only one value for a key (e.g. java), and 'are' when there are multiple values for a key (e.g. python, html).
The output I want is:
    john's favourite language are:
    python
    c
    sarah's favourite language are:
    python
    html
    jason's favourite language is:
    java
    michael's favourite language is:
    javascript

Answer: for person,languages in person_language.items():
    verb = 'is' if len(languages) == 1 else "are"
    print(f"{person}'s favourite language {verb}:")

Answer: for person,languages in person_language.items():
    print("{}'s favourite language {}:".format(person, "is" if len(languages) == 1 else "are"))
    for language in languages:
            print(language)

or
for person,languages in person_language.items():
    print("{person}'s favourite language {'is' if len(languages) == 1 else 'are'}:")
    for language in languages:
            print(language)

The format method can be useful in this case because you can add an if statement in it if the length of languages is equal to 1.
But you can use it the same in f string with changing the " to ' inside the curly brackets.


Standard error of regression and of predictions in python (these are available in R)

Question: I'm working with R and confirming my results in Python with the overwhelming majority of the work matching between the two quite well. There are two outputs coming out of R that I'm not seeing how to get in Python and for now I'm looking for pre-packaged calls but if I have to do it manually so be it. Still, I would expect the pre-packaged calls to be available since practically everything else that is in R is in Python.
First question: How do you get the R 'Residual standard error'(see the red box) in Python?
Here is the R code and below that the results:
fit_1a <- lm(rpaapl~rpsp, data=df_returns)
summary(fit_1a)

Here is the Python/statsmodels.ols code and below that the results:
est_1a = smf.ols(formula='rpaapl ~ rpsp', data=xl).fit()
print(est_1a.summary())

$\color{red}{\text{So how can I get this residual standard error in Python?}}$
Second question: How do you get the R 'standard error of each prediction' in Python?
Here is the R code and below that the results:
forecast_1d <- data.frame(predict(fit_1a, newdata=data.frame(rpsp=mrp), se.fit=TRUE))
forecast_1d

Here is the Python/statsmodels.ols code and below that the results:
df_1d["estimate"] = est_1a.predict(df_1d)
print(type(est_1a.predict(df_1d)))
df_1d["estimate"]

$\color{red}{\text{So how can I get these standard errors for each prediction in Python?}}$
Please note that the est_1a object has a bunch of values but I'm not finding the standard error. Also, est_1a.predict only returns a timeseries so the predict call does not seem to calculate the standard error (se.fit in R). Any help is much appreciated.
Answer: To the last part
Several models have now a get_prediction method that provide standard errors and confidence interval for predicted mean and prediction intervals for new observations.
pred = results.get_prediction(x_predict)
pred_df = pred.summary_frame()

some examples are in this gist https://gist.github.com/josef-pkt/1417e0473c2a87e14d76b425657342f5
Comment: Thank you very much. I believe that is it. Much appreciated.
Answer: For your first question, I think what R calls the "residual standard error" is the square root of the scale parameter:
np.sqrt(est_1a.scale)

Comment: Thank you, that is correct. What remains now is my second question. Any info is most appreciated.


How many sets can you get by taking closures, complements, and intersections?

Question: The Kuratowski closure-complement problem yields 14 sets which can be formed by taking the closure and the complement of a single set. But if I want to also include such sets as the frontier or boundary, I also need to be able to take intersections between previously generated elements. In this case, how many different sets can you get?
Comment: Could you explain your example of such a set?
Comment: @user134824 I may have to retract that statement; my hope was to express $S'=\{x:x\in\overline{S\setminus\{x\}}\}$ in terms of these operations, and then use $\omega^\omega$ under the order topology. But I don't think limit points can be written in terms of these operations.
Comment: (Note that applying the limit point operation to $\omega^\omega$ $n$ times yields the set of all ordinals whose lowest exponent in cantor normal form is at least $n$.)
Comment: @MarioCarneiro yes Kuratowski proved that limit points cannot be expressed in terms of the three operations.  The proof appears at the very end of his 1922 paper, an English translation of which can be found at http://www.mathtransit.com/1922_kuratowski_english.pdf.
Answer: This question has a long history in the literature.
1. (1922) Kuratowski proves that infinitely many distinct sets can be generated from one set under closure, complement and intersection.  His proof appears on the middle of page 197 in his paper Sur l'Opération $\bar A$ de l'Analysis Situs (in French). Here it is in English:

Consider the operation $\varphi(A)=A\cap\overline{\overline A\setminus A}$.
  Let $B$ be a totally ordered set of order type $\omega^\omega$.
  Let $a\in B$ and define $A=B\setminus\{a+\omega$, $a+\omega^3$,
  $a+\omega^5,\ldots\}$.
It is easy to see that, under the order topology, $\varphi(A)$
  consists of the elements of $A$ of the form $a+\omega^n$ with
  $n\geq2$, $\varphi(\varphi(A))$ those of the form $a+\omega^n$ with
  $n\geq4$, and so on.  The operation $\varphi(A)$ thus leads to an
  infinite number of distinct sets.

(This was taken from my full translation of Kuratowski's paper.)
2. (1944) Citing reference 1, McKinsey and Tarski reproduce Kuratowski's construction on page 169 in their paper The Algebra of Topology.
3. (1966) The last part of Problem 5349 (Amer. Math. Monthly, proposed 1965 p. 1136, solved 1966 pp. 1132-1134) essentially asks readers to find a subset of the closed unit interval that generates infinitely many distinct sets under the three operations. J. C. Morgan II cites both 1 and 2 in his published solution.
4. (1977) W. J. Blok presents two examples on page 363 of his paper The Free Closure Algebra on Finitely Many Generators, one of which shows that infinitely many distinct sets can be generated starting with a finite seed set. References 1 and 2 are cited.
5. (1998) John Rickard presents the first published example of a set of reals (under the usual topology) that satisfies the condition in his solution to Problem 10577 (Amer. Math. Monthly, proposed 1997 p. 169, solved 1998 pp. 282-283). No previous solutions are cited.
6. (2004) David Sherman cites reference 1 then gives a proof similar to Kuratowski's on page 9 of the 2004 arXiv preprint of his 2010 Monthly paper Variations on Kuratowski's 14‑Set Theorem. The same proof appears in the final paper, except there Sherman adds that while his seed set distinguishes infinitely many operations (in the monoid generated by the three operations), it fails to distinguish all of them. This serves as a nice lead-in to the section on closure algebras that follows.
7. (2006) Without citing any references, Bruce Burdick's published solution of Problem 11059 (Amer. Math. Monthly, proposed 2004 p. 64, solved 2006 p. 83) reproduces the finite seed set example from reference 4.
8. (2008) After citing 1, 2 and 4 on page 34 of their paper The Kuratowski Closure-Complement Theorem, Gardner and Jackson give an example showing it is possible to generate an infinite family by repeatedly applying just the two set operations of closure and set difference to a single seed set.
9. (2010) The question was asked here.


Service provider only for certain routes - Laravel

Question: I'm building a page builder in laravel. The frontend renders "blocks" that are added to a page in my admin. I figured that the best way to make sure these blocks are available everywhere I need them is to load them in a View Composer which works great;
<code>View::composer('*', function ($view) {
    $blocks = Page::where('url', url()->current());

    return view()->with(['blocks', $blocks]);
});
</code>
However, this attempts to load blocks for frontend routes and for admin routes. Is there any way to make sure they're only loaded for routes on the frontend?
I've split my routes in to separate files like this;
<code>// lets me use an admin.php for my admin routes, instead of web.php
$this->mapAdminRoutes();

protected function mapAdminRoutes()
{
    Route::prefix('admin')
         ->middleware('admin')
         ->namespace($this->namespace)
         ->group(base_path('routes/admin.php'));
}
</code>
I did find this question when googling

Binding a Laravel service provider on specific routes

but that still loads the service provider on all routes - just defers the view composer (which works for that OPs performance concerns).
Answer: A middleware is better for this type of things, as you can apply it to whichever route/group of routes you want.
Comment: Having to register service provider each time a specific route is accessed is much worse. This is the perfect use for a middleware.
Comment: Are there any downsides to using many middlewares at a time? I'm already using a few on my frontend (web, auth etc).
Comment: not really as long as you don't have any time consuming tasks being performed in the middleware.


Should I practice on developing Hand Independence from the start?

Question: So I started learning Piano a month ago, and it was hard getting my left hand involved in the beginning. Eventually I figured out that its more manageable if I just map both my hands to the beat rather than handling them individually.
Past week I came across a video about Ragtime and noticed how both hands play a different melody in them(often with different time signatures). Came across another video about how to develop hand-independence and the suggested route is playing the same melody on both hands but shifting it 1 bar.
So I feel I might be developing a bad habit by forcing both hands to play a single piece and it would be harder down the road to change my muscle memory, if I don't correct this behaviour now.
Any thoughts or suggestions?
EDIT - In order to make my current approach more clear. I am not playing the same melody with both hands. I am not sure how to put my current approach it words.
As an example if I need to play 4 quarter notes A,B,C,D on my right hand, and C,E,A,C on Left. I divide the piece in the form of (A,C),(B,E),(C,A),(D,C) and map the notes that need to be played on different beats. I don't practice each hand separately after I memorize the initial notes/flow of what needs to be played
Comment: Do you make both hands play the same melody, just an octave or more apart?
Comment: I'm not entirely sure what you mean when you describe what you're doing now, but synchronising both hands to the beat rather than to each other seems like an excellent approach. You can fix synchronisation between the hands later quite easily, in this stadium the beat would be much more important.
Comment: Do you mean you play the same with both hands? If so, it's doing each hand no favours, as each will have twice as much to learn/play.
Comment: I am not playing the same melody with both hands. I am not sure how to put my current approach it words.

As an example if I need to play 4 quarter notes A,B,C,D on my right hand, and C,E,A,C on Left. I divide the piece in the form of (A,C),(B,E),(C,A),(D,C) and map the notes that need to be played on different beats. I don't practice each hand separately after I memorize the initial notes/flow of what needs to be played.
Comment: @AnonyMous That's exactly the opposite of what I understood. Please disregard my previous comment.
Comment: I'll have to note that none of my 3 piano teachers ever mentioned the importance of practicing hands separately. They never even brought it up as an option, from what I recall.
Answer: Yes.
My piano teacher always insisted that I practise each hand separately before playing with both hands together. I would divide the piece into manageable practise sections, and focus on one of the sections, first practising the right hand, beginning at a very slow tempo (using a metronome) and gradually increasing. Then I would do the same thing for the left hand.
The right hand should always plays the part of the right hand, and the left hand should always play the part of the left hand. Do not play the part of the left hand with the right hand, and vice versa: that is pointless and makes you work more than twice as hard. The goal is to commit the part of each hand to muscle memory, so you don't have to think about individual hands when you combine them.
So, after I played the section about a hundred times with the right hand, and about a hundred times with the left hand, and have each part committed to muscle memory, I would combine them and play with the both hands at the same time, again, starting at a very slow tempo and gradually increasing.
When I started to play the organ, I would do the same with feet. So, it would be: right hand alone, left hand alone, feet alone, right hand with feet, left hand with feet, and only then both hands and feet together.
This approach is rather slow and demands a lot of patience, but the results are guaranteed. In my case, since I was only practising about 30-45 minutes every day, it would take several days, maybe a week, before I could play the piece with both hands, and several weeks before I could do it well.
When you can fluently play the part of each hand on its own, playing with both hands together is not a very difficult step. You don't need to think like this: "when the left hand plays G, the right hand plays B", it all comes to you naturally, because you have both hands committed to muscle memory in advance: the left hand is completely independent from the right hand, the only thing keeping them in sync is your sense of beat and the fact you're playing music and not just mechanically typing on the keyboard.
As you make progress over the next year or two, you will notice that you don't need to practise each hand separately nearly as much as you did when you were a total beginner, and at some point, you will be able to read music with both hands from the beginning. But that is for the future, for now, focus on each hand alone before combining them.
Answer: I am a firm believer in playing the hands together as much as possible.  It has been my observation that beginning students learn slower and are less musical when they first practice with the hands separate.
In addition, when playing together, the hands help the other learn coordination and independence faster. The hands teach one another.
Always strive to be musical rather than robotic.
Comment: For some, it's enough of a challenge to read what one hand needs to do at a time. From answers and comments here, there seems to be two camps - learn separately, or learn together. Quite opposing!
Answer: Work through the pieces and exercises in your instruction book, and practice in the way your teacher tells you too, which will doubtless include getting a section perfect with separate hands before 'putting it together'.
You are not at a stage of piano-playing where you can usefully invent your own learning strategy.  Stop over-thinking it and just do what you're told!
Answer:
Both hands or one hand, both will help.
Technical difficult passages one hand.
Whenever possible both hands, slowly measure by measure.
Don't always begin from the top of the page.
Start from the ending and put it together.


The SelectionKey.attach() method

Question: Please give me the concept of the atach() method. Could I work with NIO without atach() method?.
I have read that with this method we can attach any object in a determined SelectionKey, but, I don't find a motive for this, because after registering my SocketChannel within Selector with the READ and WRITE operations, I could read or write toward or from some socket without attaching a buffer, when the Selector tell me that there are read keys, to write I could create a bytebuffer and fill it and write to the socket, and to read I could create a bytebuffer too.
Then, why the programers use atach() method when they register their channels with READ or WRITE operations?
SocketChannel cliente=SocketChannel.open(localhost);
cliente.configureBlocking(false);
Selector selector=Selector.open();
SelectionKey key=cliente.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
//the programers ByteBuffer buf=ByteBuffer.allocate(100); key.attach(buf);

...............................
...............................

selector.select();
Set<SelectionKey> readyKeys=selector.selectedKeys();
Iterator<SelectionKey> iterator =readyKeys.iterator();

while(iterator.hasNext()){
        SelectionKey key2=iterator.next();
        iterator.remove();
        if(key2.isReadable()){
            SocketChannel cliente2=(SocketChannel)key2.channel();
            ByteBuffer buf=ByteBuffer.allocate(100) //The programers: ByteBuffer buf2=(ByteBuffer)
                                                    //key2.attachment();
            cliente.read(buf);
        }
        if(key2.isWritable()){
            SocketChannel cliente2=(SocketChannel)key2.channel();
            ByteBuffer buf=ByteBuffer.allocate(100) //The programers: ByteBuffer buf2=(ByteBuffer)
                                                    //key2.attachment();
            buf2.put("Hello Server".getBytes("UTF-8"));
            cliente2.write(buf2);
        }
    }

Answer:
please only give me the concept of the atach() method

There is no atach() method. There is however an attach() method: "Attaches the given object to this key. An attached object may later be retrieved via the attachment method. Only one object may be attached at a time; invoking this method causes any previous attachment to be discarded. The current attachment may be discarded by attaching null."

I want to know only that please. Could I work with NIO without atach() method?

Yes, assuming you mean the attach() method.

Indeed thank you for answer my question. I have read that with this method we can attach any object in a determined SelectionKey, but, I don't find a motive for this, because after registering my SocketChannel within Selector with the READ and WRITE operations, I could read or write toward or from some socket without attaching a buffer, when the Selector tell me that there are read keys, to write I could create a bytebuffer and fill it and write to the socket, and to read I could create a bytebuffer too.

You could indeed, and you would be creating a lot of buffers, one per read, when you should be creating one per channel and associating it via the SelectionKey.attach() method.

Then, why the programers use atach() method when they register their channels with READ or WRITE operations?.

To associate some context with the channel. The attachment can be just a buffer, or it can be some kind of context object that contains a buffer, or two, and maybe a session identifier, user credentials, all sorts of things.

The SelectionKey.attach() method


Duplicating (copying) a core data record and related records

Question: I am writing an app that allows the user to create a "questionnaire", then add questions to it.  I am using core data to store the info.  I have created a questionnaire entity and have a "one to many" relationship with question entities.  My question is, if want to allow the user to duplicate (copy) an entire questionnaire, questions and all what's the best way to do that?
So to be clear:
I have:
Questionnaire record ---> Question 1 record - Question 2 record - Question 3 record
and I want the user to be able to duplicate this and end up with this:
Questionnaire record ---> Question 1 record - Question 2 record - Question 3 record
Questionnaire (copy) record ---> Question 1 record - Question 2 record - Question 3 record
Answer: You just insert a new managed object and then set all its values to the same thing as the original object. If you're using a specialized subclass for your managed object, you could even write a simple helper method (example assumes managed object is named Questionnaire, change accordingly):
<code>-(Questionnaire*)copyQuestionnaire
{
  NSManagedObjectContext* ctx = [self managedObjectContext];
  // Obviously use the correct entity name...
  Questionnaire* newCopy = [NSEntityDescription insertNewObjectForEntityForName:@"Questionnaire" inManagedObjectContext:ctx];
  // Now just copy your properties, for this example we'll assume
  // a simple relationship called 'questions'
  [newCopy setQuestions:[self questions]];

  // We return a retained copy since our method name starts
  // with 'copy'
  return [newCopy retain];
}
</code>
Answer: You said you want to duplicate an entire questionnaire, so assuming what you want is actually something like this:
Questionnaire ---> Question 1 - Question 2 - Question 3
Questionnaire (copy) ---> Question 1 (copy) - Question 2 (copy) - Question 3 (copy)
Then what you need is a deep copy. You can write something based on this NSManagedObject category, assuming you set your relationship's ownership rules properly on your data model.


Explicit type conversion vs using type rules

Question: Suppose that I have this program :
#include <iostream>

using namespace std;
int main() {
    unsigned int n, i;
    double sum = 0;
    cout << "\n No. of terms: ";
    cin >> n;
    for( i=1; i<=n; i++ ) {
        sum += i/(i+1.0);       //// THE LINE IN QUESTION
    }
    cout << " Sum = " << sum;
    return 0;
}

It calculates sum of series : 1/2 + 2/3 + 3/4 .. to n/n+1.
Now i want to ask that in the for loop where i wanted to assign int value to double variable sum, i can do that by two ways :

method 1: sum += i/(i+1.0)
method 2: sum += (double) i/(i+1)

Which is faster or better way?
Ligth races in orbits : What i mean is that which method should be used.
Comment: Stop tagging this as C! Your code is clearly C++ code. Do not tag spam.
Comment: @FUZxxl : stop downvoting for no reason. Tagging is not spamming. After all it applied to C too. only that i had to write a snippet in C (that would make it open to a larger comm.) Please know about what you speak. Thanks for answer btw.
Comment: Maybe someone will correct me, but AFAIK there's no issue in posting two separate questions, even if they are about the same thing in two different languages. No tag spamming, happy users.
Comment: Method one contains one conversion from `int` to `double`, one floating point addition and one floating point division. The other contains two floating point conversions, one integer addition and one floating point division. I don't think there is much of a difference speed-wise.
Comment: You might want to look up the topic of [premature optimisation](http://stackoverflow.com/questions/516160/planning-for-efficiency-early-vs-premature-optimization).
Comment: @FUZxxl: There are same numbers of  `int` to `double` conversion in both methods (and I agree with conclusion).
Comment: @Jarod42 In the first method, `i` only needs to be converted once and every decent compiler sees that.
Comment: @TimKrul I haven't downvoted you. I'm currently preparing an answer, please standby for the time. Please realize that C and C++ are distinct languages and I'm sick of all the people being blatantly ignorant about that. Pick one language and you get an answer for that language. This site is not a "provide an answer for as many languages as possible" type service.
Comment: @FUZxxl But there are people who browse through particular tags .. like only C, or C++. My prob applies to both, and i hope to pose the question to more people, so that i may get better answers. I am in no way saying C and C++ are same.
Comment: @TimKrul Adding wrong tags to attract more people is the exact definition of "tag spamming." Yes, your problem can be formulated for both C and C++ but you chose to do so for C++ so this is a C++ question now. You cannot ask the question for both.
Comment: Pick a language and stick with it for goodness's sake. Then explain what you mean by "faster" or "better", or this'll be closed as subjective.
Answer: As a rule of thumb, such minor differences aren't likely to matter. There is a difference of one or two cycles out of the roughly 20 or so cycles (most taken by the division) this is going to take, if there is one at all.
These are the operations your two methods perform:
Method 1
a   = (double)i; // convert to double
b   = 1.0;       // load double
c   = a + b;     // double addition
sum = a / c;     // double division

Notice that we only have to do one conversion to double as the compiler can do an optimization called common subexpression elimination. On many machines (like x86) you cannot simply add a floating point constant to a number, you have to load the constant into a floating point register first so I count that as an extra instruction. If you are doing this in a loop, the 1.0 needs to be loaded only once though.
Method 2
a   = (double)i; // convert to double
b   = i + 1;     // int addition
c   = (double)b; // convert to double
sum = a / c;     // double division

Here we need to do two conversions but we can save a floating point load and we can replace a floating point addition with a cheaper integer addition.
Machine code
Here is amd64 assembly for both methods:
method1:
        pxor     %xmm0, %xmm0      // clear result register
        movsd    .one(%rip), %xmm1 // load 1.0
        cvtsi2sd %edi, %xmm0       // convert int to double
        addsd    %xmm0, %xmm1      // double addition
        divsd    %xmm1, %xmm0      // double division

.one:
        .double 1.0

method2:
        pxor     %xmm0, %xmm0      // clear result register
        pxor     %xmm1, %xmm1      // clear register for i + 1
        cvtsi2sd %edi, %xmm0       // convert int to double
        addl     $1, %edi          // increment
        cvtsi2sd %edi, %xmm1       // convert int to double
        divsd    %xmm1, %xmm0      // double division

Both methods seem to be pretty equal in terms of operations. I recommend you to benchmark this if you want to be sure.
Answer: Method one results in two conversions from integer to double, one double addition, and one double division.
Method two results in a conversion from integer to double, an integer addition, converting the integer result to double, and one double division.
It's fairly likely that the compiler will optimize two identical conversions of integer to double in method 1. I don't believe that a compiler will ever optimize the first method down to the second one, due to integer overflow-related issues, so I'll just assume a reasonably intelligent compiler that can execute the obvious optimization.
So we have:

Convert integer to double
Double addition
Double division

Versus:

Convert integer to double
Integer addition
Convert integer to double
Double division

So the difference between the two methods reduces to a double addition operation versus integer addition and conversion of integer to double.
Regarding "which one is faster": the difference is not directly comparable, so this will depend entirely on whichever CPU is going to execute this. I don't know of any empirical evidence that all CPUs will handle one or the other set of operations always faster than the other one.
Regarding "which one is better": the better approach is the one that you think is more readable, and maintainable. That's because whichever approach turns out to be faster in practice, the "faster" part will so insignificant, on modern CPUs, that it can be practically ignored, and the remaining factor to consider is simply readability and maintainability; and insofar which one of the two approaches is more readable or maintainable, this is going to be purely a matter of one's taste.
Unless, of course, one has to implement something like this in certain very narrow, tailored, situations where every nanosecond matters, and a huge pile of money depends entirely on the proposition that "faster=better". In which case the only way to obtain the answer is to rigorously benchmark the execution profiles of both methods on your target hardware platform, and figure out by yourself which one is "better".


TCP port mapping / proxy with AWS

Question: I have several services running on a single AWS instance on different ports:

rabbit   :5672
rabbitMQ :15672
elastic  :9200
a few others

I have a jumpbox on AWS which handles all incoming requests. I had looked into HAProxy on the jumpbox but a pure AWS solution would be better.
The end goal here is to point incoming requests on standard ports based on their subdomains to potentially separate instances internally or the same instance with different ports:
eg.
a request to staging.example.com:5672 would go to instance A:5672
a request to development.example.com:5672 would go to A:5673
I'm looking for a solution using the AWS stack, but struggled to find something applicable. Since rabbit uses the amqp protocol, http hostname resolution does not appear to be an option, and as far as I can tell there is no simple straight incoming_hostname:incoming_port -> instance:port mapping using the ELB, but I am very new to the AWS stack.
Comment: Your question isn't entirely clear. Is your "jumpbox" a reverse proxy or a bastion host? Are you looking for a suggestion on how to set up a reverse proxy to services on a single machine with the services running on different ports?
Comment: @Tim whoops - it's a bastion host. The current setup has 2 environments on the same machine running duplicate services on different ports (ie default and default + 1). Normally, this would be trivial with separate endpoints for each environment (ie multiple bastion hosts OR reverse proxies), but for the time being I just wanted to see if it was an easy solution to run both env's on the same vpc
Answer: The only thing that "might" do what you want is using ELB+Lambda to process those requests, but it's not worth the effort.
The proper way would be to use nginx or haproxy as you've already mentioned.
Comment: Thanks, I was worried that might be the case. I think a slight re-architecture and nginx and/or haproxy is the way to go.

TCP port mapping / proxy with AWS


How do I create a jump link to a paragraph item?

Question: I'm trying to create a jump link to the paragraph item. This is what I tried

create a compact display of the page just printing out a title and short summary.
using the advanced text formatter I created a link in this index

It takes me to the paragraph page. I figure that I can use a token in the advanced text formatter to create an anchor link from the compact display to the detailed display. Then I have to work out how to add the anchor to the detailed display.

How do I create a link with the delta as the anchor e.g. /abc/test.html#1?
How do i create the anchor on the detailed display?
Answer: Perhaps Paragraphs Table of Contents module is good enough for what you describe.
From the project page

If you have long pages on your site, then it helps visitors if you can provide in-page navigation, or a table of contents.
If you build your long pages with the Paragraphs module, then you can use Paragraphs Table of Contents to provide the in-page navigation. There is one link in the table of contents (ToC) for each paragraph on the page.


How to get selected text of a select in a vue component

Question: I am using Laravel 7 and Vue.js 2.
I would like to catch the selected text when the user changes the selected option.
This is my component:
<template>

            <title-form v-model="titleForm" :titleMessage="titleForm"></title-form>

            Select a dev:

            <select required v-model="user.devs" class="form-control" id="devs" @change="onChangeDev($event)">
                <option v-for="dev in devs" :value="dev.id" :key="dev.id">
                    {{ dev.name }}
                </option>
            </select>

            Assign a task to {{ selectedDev }}:

            <button type="button" class="btn btn-primary" @click="assignTask()">Assign Task</button>

            Remove a task from {{ selectedDev }}:

            <button type="button" class="btn btn-primary" @click="removeTask()">Remove Task</button>

            Show in progress task assigned to {{ selectedDev }}:

            <button type="button" class="btn btn-primary" @click="showTasksInProgress()">Show In Progress Tasks</button>

            Show all cross-team projects (no need to select a dev):

            <button type="button" class="btn btn-primary">Show Cross-Team Projects</button>

            Show the PM of {{ selectedDev }}:

            <button type="button" class="btn btn-primary">Show PM</button>

</template>

As you can imagine, I want to pass dev.name. I tried creating a method called onChangeDev passing the parameter $event but unfortunately when I alert the text I visualize undefined. So I am asking myself if there is a way to do that using Vue. Can help?
Answer: event value holds the value of an option. your code will alert the id of a user, which you set the value of an option (:value="user.id") if you will alert like (alert(e.target.value)).
Value holds the value :)
Following code would do what you expect ;)
    onChangeDev(e) {
      const selectedDevId = e.target.value;
      const name = this.devs.filter((dev) => dev.id == selectedDevId)[0].name;
      alert(name);
    }

But it has O(N) time complexity due to filter mthod usage. Probably you can make it faster binding more data to the option and then fetching it from DOMElement...
Comment: It works but can you show me how I can make it more faster binding more data to the option and fetching from DOMElement?
Comment: Sure!!! 1) You may set the `:value="user.name"` then the e.target.value would be the name
Comment: 2) serialize your object, put this string as a value and then deserialize the value in your handler (https://pastebin.com/DvvXVb25)
Comment: 3) use your own approach of select html component. Build your component based on another html elements, which behaves exactly the same as native html select or even better. This approach is highly recomended whether you should customize select's layout
Comment: 4) use another people 3rd option made components (https://vue-select.org/ for example)       Sry for late answer. I'm too sleepy now :D
Comment: 5) Almost forgot to show DOMElements data-attributes implementation: https://pastebin.com/cXrf7jhg. It still has O(N) due to DOMElements iteration time complexity, but here N is not number of all devs, but number of html options elements (it's always less or equal to devs length).


simple horizontal equal div's

Question: Ok, I'm setting up a mini-page and I want it to be 100% scalable so I'm trying to use only %.
But I don't get the "items" to take the 33% width and distribute is over the 80% of "content".
What am I doing wrong?

body, html{
    width: 100%;
    height: 100%;
}

.menu{
    width: 20%;
    height: 100%;
    background: #fff;
    float: left;
}

.content{
    width: 80%;
    height: 100%;
    background: #eee;
    float: left;
}

.bottom{
    position: absolute;
    bottom: 0;
}

.item{
    width: 33%;
    float: left;
}

.red{background: red;}
.blue{background: blue;}
.green{background: green;}

menu

content

left

mid

right

Answer: Try like this: Demo
.content{
    position: relative;
}

.bottom{
    width:100%;
}

.item{
    box-sizing:border-box;
}

Comment: I think it's worth noting that setting `position: relative` on `.content` solves a separate issue that the submitter  probably didn't (yet) know about.

simple horizontal equal div's


Conformal metric

Question: I'm trying to solve the following :

Let $D$ be a simply connected region stricly included in $\mathbb{C}$. Let $\mathbb{D}$ be the open unit disk. Let $f \in \text{Hol}(D)$ be a bounded function with zeroes at $w_1, w_2, ...$. Show that
  $$ \sum\limits_{n \geq 1}\big| h'(w_n)\big| \text{dist}(w_n, \partial D)$$ converges, where $h : D \rightarrow \mathbb{D}$ denotes the Riemann map, $\text{dist}$ is the euclidean distance and $\partial D$ is the boundary of $D$.

Using the following result on conformal metrics :
$$ h^* \tau(z) \leq \frac{2}{\text{dist}(z, \partial D)}$$
where $\tau$ is the hyperbolic (poincaré) metric and $z \in D$, I got
$$ \frac{2}{1- \big| h(z)\big|^2}\cdot \big| h'(z)\big| ~\leq~ \frac{2}{\text{dist}(z, \partial D)}.$$
Hence
$$ \text{dist}(z, \partial D)\big| h'(z)\big| ~\leq~ 1- \big| h(z)\big|^2.$$
Therefore
$$ \sum\limits_{n \geq 1}\text{dist}(w_n, \partial D)\big| h'(w_n)\big| ~\leq~ \sum\limits_{n \geq 1}\Big(1- \big| h(w_n)\big|^2\Big).$$
In my humble opinion (I have not worked out the details yet the check if it works) using compact exhaustion of $D$ it must be possible to use the fact that there only is a finite number of zeroes in each compact subset of $D$ to show that $\big| h(w_n)\big|^2$ tends to 1. But I don't see how to show that $\big| h(w_n)\big|^2$ tends to 1 fast enough for the series to converge.
So far I have not used the fact that $f$ is bounded, which worries me a little. I don't know how to put this hypothesis to use.
I would be really thankful if you guys could avoid give the answer right away. A hint would be welcome though.
Answer: Consider the function $F = f \circ (h^{-1}) \in H^{\infty}(\mathbb{D})$, and recall the conditions on the zeros of a nonconstant bounded holomorphic function on the unit disk. You will also need the fact that the unit disk is bounded.

The zeros of $F$ are the $h(w_n)$. By the Blaschke condition, we have
$$\sum_{n = 1}^{\infty} \bigl(1 - \lvert h(w_n)\rvert\bigr) < +\infty.$$
Since $1 - \lvert h(w_n)\rvert^2 = \bigl(1 + \lvert h(w_n)\rvert\bigr)\bigl(1 - \lvert h(w_n)\rvert\bigr) \leqslant 2\bigl(1 - \lvert h(w_n)\rvert\bigr)$, it follows that
$$\sum_{n = 1}^{\infty} \bigl(1 - \lvert h(w_n)\rvert^2\bigr) < +\infty,$$
and the inequality $\lvert h'(z)\rvert\cdot \operatorname{dist}(z,\partial D) \leqslant 1 - \lvert h(z)\rvert^2$ then yields the assertion.

Conformal metric


Appending Multiple Fields In Twig

Question: I'm attempting to append two fields with some text in the middle. Using the changed date and a plain, core, text field, I can do something like this, and it works:
{{ node.changed.value|date('m.d.y') ~ ' | By, '}}{{ content.field_author_name.0 }}

However, if I attempt to do that in a single tag, the changed date, and the 'By' text is output, but I don't get the author name field.
{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ content.field_author_name.0 }}

Is that not valid twig syntax, or is there something else needed to get that to work in a single statement?
Answer: When using {{ content.field_author_name.0 }} it works because field is rendered with the twig.
The ~ operator converts all operands into strings and concatenates them. Given that content.field_author_name.0 is a render array you need point to the string value of this field. To do this you can inspect it with the devel or twig_vardumper module using dump(content.field_author_name.0). More about debugging twig templates: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates#s-viewing-variables
Assuming that field_author_name is simple text field with the Plain text formatter, this should work:
{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ content.field_author_name.0['#context'].value }}

To display node creator name you can use this:
{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ node.uid.entity.name.value }}

Comment: That clears it up for me. I had dumped that variable out and seen the context array and value field and assumed it should be pulling the value behind the scenes. Didn't realize the ~ operator was converting the value directly to a string before Drupal got ahold of it.
Answer: To get the author name you can use {{ node.Owner.name.value }} or {{ node.uid.entity.name.0.value }}.
Try with:
{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ node.Owner.name.value }}

Appending Multiple Fields In Twig


Changing limits wen integrating with exponential of normally distributed variable

Question: I am working on an exercise which requires calculating the expected value of :
$
E[e^{\mu + \sigma Z} \mathbb{1}_{Z > -d}]
$
Calculating the expected value of the $e^{\mu + \sigma Z}$ variable and using the properties of the indicator function, I have reached the point:
$
\frac{1}{\sqrt{2\pi}}e^{\mu + \frac{\sigma ^2}{2}} \int_{-d}^{\infty} e^{-\frac{(z - \sigma)^2}{2}}dz
$
However, looking at solutions the following steps is taking $ \sigma$ and moving it into the limit of the integral as follows:
$
\frac{1}{\sqrt{2\pi}}e^{\mu + \frac{\sigma ^2}{2}} \int_{-d - \sigma}^{\infty} e^{-\frac{z^2}{2}}dz
$
I am unsure which property has been used here and I was wondering if anyone could point me in the right direction to understanding this switch?
Answer: I think I have figured it out, so leaving it here for anyone having a similar question in the future:
If we were to use a change of variable:
let y = $z - \sigma$ then $dy = dz \Longrightarrow \frac{dy}{dz}=1$
Calculating the new limits, we have:
$
z= -d \Longrightarrow y = -d - \sigma
$
$
z = \infty \Longrightarrow y = \infty
$
This would bring the second result.


Looping a section of code with different variables in python?

Question: I am designing a quiz which has to save three different scores to a file. How would I loop this and are you able to change the variable names? For example, the first time it loops, score1, then score2 then score3.
Thanks For the help in advance
Comment: Can you show us your code and what have you tried otherwise it is very difficult to answer.
Comment: Is this homework, and have you tried anything?
Answer: You can use a dictionary, with the three values indexed with keys, and change a variable who contains the current key's name.


Non-Config Menus

Question: I have this requirement where I would need to create a menu every time a user creates a new instance of a custom entity I'm building. One can easily do this with Menu::create() on entity creation, but there is one problem: Menus are configuration.
When one creates a menu either programmatically or via menu admin, it creates "unexported configuration" of that menu that lives in the DB. The next time code is deployed and those menus aren't exported to code, those menus either get deleted (if empty) or halt the deploy (if there are menu links present).
I was hoping to preserve the menu functionality (menu management, etc.) but have them not be config. Is there a way to create menus that aren't configuration?
Answer: Not exactly. You could theoretically build non-config menus with a custom module, but I don't think that's what you want to do.
You can, however, keep the menus as config, but keep them from being exported / imported. You can use two contrib modules to do this.
The first module, Config ignore is required. This module allows to set config files that should be ignored when importing config via its UI at admin/config/development/configuration/ignore. Some example configuration for your situation might look like:
system.menu.*
~system.menu.main
~system.menu.admin

The first line will tell config_ignore to prevent all menu configs from being imported. The second line tells it to unignore the main menu configuration, the third line tells it to unignore the admin menu configuration. This would prevent any of your on-the-fly menus from being deleted during import, but allow you to keep the main and admin menus managed via your configuration. Obviously, you can also unignore any number of additional menus.
One minor issue with config_ignore is that it only prevents configuration from being imported, it doesn't stop them from being exported. So, for example, if you were to pull your prod DB down to your local environment and then export your config, all of the configuration for those new menus will be exported to the sync directory. All of those configuration files will be ignored on the import end so it doesn't hurt, but I don't like having a bunch of extra config in my sync directory that 1. isn't used and, 2. isn't an accurate representation of the actual state of the menus.
The second module, Config Split is optional, but I like to use it in this situation to help keep things tidy; it solves the minor issue with config_ignore that I mentioned in the last paragraph.
Config split lets you split some configuration from the main sync directory to other directories. The main way I've used this is to split out environment specific configuration to environment specific directories. For example, I have one split for my local environment, a second for staging, and another for prod. However, config_split also allows you to use a special database storage, instead of a file directory, if you don't define a split directory, i.e. leave that field empty. This is a great feature because you can use it to route all of the menu configuration files, the files that you're ignoring with config_ignore, to the special database storage. This keeps them out of your sync directory, thus removing all that clutter!
To use this special database storage, navigate to Config Split's UI at /admin/config/development/configuration/config-split and Add A Configuration Split Setting. First, give it a label, e.g. Database Storage. Second, in the COMPLETE SPLIT section, enter settings in the Additional Configuration field that are identical to what you entered in the config_ignore settings. For example:
system.menu.*
~system.menu.main
~system.menu.admin

That's it. Boom! The menus that you programmatically created on prod won't be deleted when you deploy. The configuration for those items now lives totally in the database.

Non-Config Menus


React Native: Possible unhandled promise rejection (id: 0) TypeError: Network request failed

Question: I'm getting the following error: Possible unhandled promise rejection (id:0): Network request failed.
enter image description here
I am trying to convey a review with text and a picture in firebase. In ReviewsScreen.js display and acceptance of data is implemented, in Fire.js processing and sending. I think somewhere in Fire.js the error lies but I have no ideas what the problem is
ReviewsScreen.js
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  TouchableOpacity,
  Text,
  SafeAreaView,
  Image,
  TextInput,
 SafeAreaViewBase
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons'
import {h, w} from '../../constants'
import Fire from '../../Fire'
import ImagePicker from 'react-native-image-picker';

const options = {
  title: 'Select photo',
};

export default class ReviewsScreen extends Component {
  state = {
    text: '',
    image: null
  }

pickImage = () => ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);

if (response.didCancel) {
  console.log('User cancelled image picker');
} else if (response.error) {
  console.log('ImagePicker Error: ', response.error);
} else {
  // You can also display the image using data:
  // const source = { uri: 'data:image/jpeg;base64,' + response.data };

  this.setState({
    image: response.uri
  });
}
  });

  handleReview = () => {
Fire.shared.addReview({text: this.state.text.trim(), localUrl: this.state.image}).then(ref => {
  this.setState({text: '', image: null})
  this.props.navigation.goBack()
}).catch(error => {
  alert(error)
})
  }

  render() {
return (
  <SafeAreaView style={styles.container}>
    <View style={styles.header}>
      <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
        <Icon name='md-arrow-back' size={24} color='blue'/>
      </TouchableOpacity>
      <TouchableOpacity onPress={this.handleReview}>
        <Text style={{fontWeight: '500'}}>Добавить</Text>
      </TouchableOpacity>
    </View>

    <View style={styles.inputContainer}>
      <Image source={require('./img/avatar.jpg')} style={styles.avatar}/>
      <TextInput
        autoFocus={true}
        multiline={true}
        numberOfLines={1}
        style={{flex: 1}}
        placeholder='Нам важно ваше мнение!'
        onChangeText={text => this.setState({ text })}
        value={this.state.text}
      >
      </TextInput>
    </View>

    <TouchableOpacity style={styles.photo}
      onPress={this.pickImage}>
      <Icon name='md-camera' size={32} color="#D8D9D8"></Icon>
    </TouchableOpacity>

    <View syle={{marginHorizontal: 32, marginTop: 32, height: 150}}>
      <Image source={{uri: this.state.image}} style={{ marginTop: 32, alignSelf: 'center', width: '50%', height: '50%'}} />
    </View>
  </SafeAreaView>
    )
  }
}

Fire.js
import firebaseConfig from './config'
import firebase from 'firebase'

class Fire {
  constructor() {
      firebase.initializeApp(firebaseConfig);
  }

addReview = async ({ text, localUri }) => {
  const remoteUri = await this.uploadPhotoAsync(localUri);

  return new Promise((res, rej) => {
      this.firestore
          .collection("reviews")
          .add({
              text,
              uid: this.uid,
              timestamp: this.timestamp,
              image: remoteUri
          })
          .then(ref => {
              res(ref);
          })
          .catch(error => {
              rej(error)
          });
  });
  };

uploadPhotoAsync = async uri => {
  const path = `photos/${this.uid}/${Date.now()}.jpg`;

  return new Promise(async (res, rej) => {
      const response = await fetch(uri);
      const file = await response.blob();

      let upload = firebase
          .storage()
          .ref(path)
          .put(file);

      upload.on(
          "state_changed",
          snapshot => {},
          err => {
              rej(err);
          },
          async () => {
              const url = await upload.snapshot.ref.getDownloadURL();
              res(url);
          }
      );
  });
};

get firestore() {
   return firebase.firestore();
}

get uid() {
    return (firebase.auth().currentUser || {}).uid;
}

get timestamp() {
    return Date.now();
}
}

Fire.shared = new Fire();
export default Fire;

Comment: Anytime you get unhandled promise rejection error that means you have an issue with handling error somewhere in the code. Try wrap your functions in try-catch blocks in async-await blocks.
Comment: @Uladzislau Rusy, did you find the problem ?
Comment: still any answeres? stuck at same. @ula
Answer: You wrote "localUrl" instead of "localUri":
Fire.shared.addReview({text: this.state.text.trim(), localUrl: this.state.image}).then(ref => {


Drupal site not behaving - process of elimination

Question: I have two versions of a Drupal site running on my local dev environment. Site X boots perfectly; site Y doesn't - rather than running index.php, install.php is called.
So far, I've:

Stepped through site Y with a PHP debugger; index.php does not seem to be called at all.
Pointed site Y at the database for site X to see whether there were database corruption issues; seemingly, there weren't.
Swapped out the .htaccess file in site Y for the .htaccess file in site X. No joy.

What should I try next?
Answer: Does settings.php exist in site Y and does it have the correct database information?
Also, are these two seperate drupal installs, or one drupal install setup multisite?
Comment: What if you try backing up that database, and dropping in a blank settings.php (copied from default.settings.php) and run the install process, does it connect to the right database then?
Comment: Thanks! This didn't quite work but I've now got site Y booting. I'm getting Access Denied messages, though, and the theme isn't loading - I think this might be something to do with site Y being built in a Wintel environment; I use OSX. I'll keep plugging away, but would appreciate any inspired insights :)
Comment: ok, turns out it was a pretty standard D6 perms issue - set the perms on each folder in sites/ for site Y to the same as the perms for site X, et voila. tks for your help, Kevin :)
Comment: Thanks.

settings.php does exist in site Y, and it seems to have the correct database information. When I point site X at the database for site Y, site X boots.

These are two separate, single-site Drupal installs.
Answer: the above provides a walkthrough, so question answered.


How may I allow users to embed a view within a CKEditor text field?

Question: I'm working on a site that includes a number of service pages (think practice areas in a law firm site) and each service has a number of identical content components (call to actions, legal disclaimers, etc) that are not always in the same order.
It would be awesome if there was a way for my content editors to add these components within the body field in any order they see fit. I believe the CKeditor Blocks module could accomplish this for static content, but for dynamic content I don't see a solution.
Sometimes the body looks like this;
<code>{{ Paragraph }}
{{ Related Services }}
{{ Paragraph }}
{{ Call to Action }}
{{ Legal Disclaimer }}
</code>
and other times it's formatted like this;
<code>{{ Paragraph }}
{{ Paragraph }}
{{ Call to Action }}
{{ Related Services }}
{{ Legal Disclaimer }}
{{ Paragraph }}
</code>
Specifically, the service content type has a 'related services' entity reference field and users need to include links to these nodes within the body of the page. Typically, if I knew these links were always presented at the end of the body, I'd just create a contextual view and present the results on the page (panels).
What are my options here? I've given some thought to using Paragraphs, but that introduces more work than I'm interested in investing at the moment.
Comment: Paragraphs actually solves this problem very well and alleviates you from trying to make WYSIWYGs inject things and structure its not that great at. They can add X components to a node, change the order, and you can use Views as well (Views Reference Field).
Comment: I love the idea of panels, but I do it find it very cumbersome to interdigitate different paragraph types for the use case of a content body. Lots of UI in the way. I'm a markup snob, so dealing with all the Paragraphs/entity templates gets labor intensive as well. Have any resources for improving the UX of Paragraphs?
Comment: ^ "the idea of paragraphs" rather.
Comment: One way to do a view is to use a token. https://www.drupal.org/project/token_embed_views
Answer: As far as embedding a view into CKEditor, you can use a formula with Token Embed Views and or Token Insert:

https://www.drupal.org/project/token_embed_views
https://www.drupal.org/project/token_insert


Enable backgroundCSS option when Saving PDFs of webpages with Selenium

Question: I'm trying to "Print as PDF" a set of webpage reports repeatedly with a Selenium ChromeDriver script in Python.  As you can see below, if we have the "Background graphics" option selected, the header of the report renders perfectly.
However, when I run Selenium, I cannot figure out how to set the parameter for background graphics. The saved PDF will instead look like this:
Here is a minimally reproducible script that I've been attempting to run:

import selenium
from selenium import webdriver
import json
from time import sleep
import os

chrome_options = webdriver.ChromeOptions()
settings = {
    "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
    "selectedDestinationId": "Save as PDF",
    "version": 2,
    #"cssBackground": 2,
    }

prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings), }
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')
CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=CHROMEDRIVER_PATH)

driver.get("https://dash.gallery/dash-multipage-report/")
sleep(3)
driver.execute_script('window.print();')
sleep(5)
driver.quit()

I've done some digging on Chromium's documentation and I believe that I've found the cssBackground setting here.  Additionally, there's a BackgroundGraphicsModeRestriction in this file that might be affecting things?  I found what I thought would be a useful lead to setting the value in this StackOverflow post but I can't seem to put the pieces together and check that "Background graphics" box from the start.  Any help that you can provide would be incredibly appreciated as I'm pretty stuck here.  I've also tried rendering my page's CSS with -webkit-print-color-adjust:exact; but it doesn't seem to capture the entire background.
Answer: OP has probably moved on, but this was the first option when I googled, so just in case anyone else is looking for this, using the links above and a little further digging, I found this:
https://github.com/chromium/chromium/blob/eadef3f685cd9e96e94fcb9645b6838b6d0907a8/chrome/browser/resources/print_preview/data/model.js
There's a bunch of settings there, including cssBackground. For each setting, there's a key. For cssBackground, it's isCssBackgroundEnabled.
cssBackground: {
        value: false,
        unavailableValue: false,
        valid: true,
        available: true,
        setByPolicy: false,
        setFromUi: false,
        key: 'isCssBackgroundEnabled',
        updatesPreview: true,
      },

I set this to True, and it worked for me.
settings = {
"recentDestinations": [{
        "id": "Save as PDF",
        "origin": "local",
        "account": "",
    }],
"selectedDestinationId": "Save as PDF",
"isCssBackgroundEnabled": True,
"version": 2,
}

Answer: The default for headless printing should be background ON (i.e. i would not attempt to switch it off) but that could be that I always have it generally on though for this test had switched it off in a prior run and I kept my browser open just in case OFF would be respected?.

So using Edge (as its part of Windows Renting), I ran with a generous 6 seconds delay, to write the HTML as run time HTML2PDF regeneration:-
"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --print-to-pdf="C:\mydata\report.pdf" --virtual-time-budget=6000 https://dash.gallery/dash-multipage-report
Report.pdf

Naturally if Edge was default PDF handler it would have popped up there in a new tab, so that second line could have been.
Timeout 6 & "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" "C:\mydata\report.pdf"


Are vocal training apps like Vanido effective in learning to sing?

Question: I have a question about vocal training apps like Vanido. This app (and many similar ones) are based on daily training in singing scales. It also gives you a feedback on how far you are from any given note.

I've played musical instruments in the past, but have never trained to sing. As an analogy to learning to play guitar or piano, the approach looks correct: just play (sing) a lot of scales and arpeggios daily, watch the quality, gradually increase complexity (range, speed).
But I'm wondering if there is something that escapes the "voice as a musical instrument" analogy and if vocal training should be approached differently from musical instrument training.
Answer: In my opinion apps are not the way to go for either.  Here is my reasoning.
Based of your description and my experience with some apps, these can never provide meaningful feed back on you technique or issues you may have with your body, posture, pressure, etc.  Not to say that AI and sensor integration can't evolve that far, but it's not there yet.  A real human who has been through the training can interact with you and correct minor issues that could lead to major issues years later.  Like thumb over the neck for guitarists.  Proper bowing for a violinist, etc.  Some of these issues can be corrected by sight, some require touch.
Learning to play an instrument correctly requires more than just getting notes in tune.
However, most instruments I can think of are "external" to the body.  Because of this you can, to some degree, get the correct posture by viewing videos and other inputs.
The voice is "internal" to the body.
My experience is as a sting player since age 4; violin, classical bass, guitar, and may other similar instruments, mandolin, dulcimer, etc.  I recently began classical voice lessons.  The process is completely different (at least in my opinion) from guitar or violin.  Your teacher can't stick a finger in your throat and check the tension of the vocal folds, or tell if you're holding your breath or releasing too soon.  There are important factors in vocal training.  There is so much to learn to sing correctly, and not cause damage to your vocal chords.  I would be surprised if an app can help with that.  Rather that just being in tune, if the app could determine if you are stressing your voice by analyzing the quality of the note that would be meaningful.  But just giving you an in/out of tune mark is meaningless when it comes to true vocal training.  There are times when the quality of the voice is more important than exact intonation.  Of course over time you want both to be correct but singing in tune with bad technique could lead to cysts on your vocal chords and other serious medical issues.


Validação de URL regex

Question: Boa tarde. Eu preciso fazer uma validação de URL usando javascript. Eu tenho a seguinte regex:
<code>/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@@!\$&'\
(\)\*\+,;=.]+$/gm
</code>
Acontece que se eu digitar por exemplo: www.teste ela valida. O que eu precisava era que fosse validado também .com, .br, ou qualquer outra extensão com no mínimo 2 caracteres. Como posso adicionar isso na minha regex?
Comment: [Aqui](https://stackoverflow.com/q/8667070) tem várias opções, e veja que é uma regex mais complicada que outra, já que validar URL com regex [não é tão simples assim](https://mathiasbynens.be/demo/url-regex). De qualquer forma, eu tiraria o segundo ponto do trecho `(?:\.[\w\.-]+)+` (ficando apenas `(?:\.[\w\-]+)+`, ou ainda `(?:\.\w+)+`, senão a regex vai aceitar vários pontos seguidos, [veja](https://regex101.com/r/zYD81N/1/) (não vi se tem mais coisas pra arrumar)
Comment: A questão é que `www.teste` é uma URL válida conforme a RFC 3986, assim como `teste`, `/home`, `john@due`, etc. Se não deseja validar esses valores, aconselho que você edite a pergunta e descreva exatamente quais seriam os valores válidos.
Comment: Apenas por curiosidade, e se a pessoa tiver um dominio com final `.io`, ou então um dominio com final `.eu`?
Comment: Possível duplicata de [Expressão regular pra validar urls](https://pt.stackoverflow.com/questions/220638/express%c3%a3o-regular-pra-validar-urls)
Answer: <code>^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:?#[\]@@!\$&'\
(\)\*\+,;=.]+$
</code>
Basta tirar uma barra :D. Testa essa que mandei acima.
Eu sempre utilizo o site regex101.com para testar. Entra lá pra você ver como funciona, ele te mostra o que cada parte do seu regEx está fazendo separando por cores, é bem intuitivo.
Comment: Essa regex considera que `www.teste` é válido, então acho que não corrigiu o problema: https://regex101.com/r/0xIv1P/1/
Comment: Essa regex está furada, validou `www.as!.com.!   ziriguidum.www.........1234@@@@@@@!!!####*())(+=-_;[]?`
Comment: mas se a pessoa digitar google.com, deve ser válido certo? ou deve ser obrigatório o www? @hkotsubo
Comment: Eu *acho* que google.com é válido, mas a pergunta diz que `www.teste` não é. De qualquer forma, a regex que está na pergunta já valida google.com - https://regex101.com/r/3KmlUd/1/
Answer: Tente usar essa expressão:
<code>^(?:https?:\/\/)?(w{3}\.)?[\w_-]+((\.\w{2,}){1,2})(\/([\w\._-]+\/?)*(\?[\w_-]+=[^\?\/&]*(\&[\w_-]+=[^\?\/&]*)*)?)?$
</code>
Você pode testar no link:
https://regex101.com/r/0xIv1P/2

Validação de URL regex


Conditional $first in mongodb aggregation

Question: I am trying to figure out if I can somehow combine $first and $ifnull or $cond in a mongodb aggregation method.
Assuming the following documents:
{ "_id" : 1, "item" : "box" , "code" : null }
{ "_id" : 2, "item" : "box" , "code" : "abcde" }
{ "_id" : 3, "item" : "box" , "code" : "abcde" }
{ "_id" : 4, "item" : "box" , "code" : null }

I then run the following aggregation method to group documents together:
db.items.aggregate([{
    $group : {
        _id : '$item',
        code :  { $first : '$code' }
    }
}])

My aggregation result is:
{ "result" : [ { "_id" : "box", "code" : null } ], "ok" : 1 }

I would like to know if there is a way to combine the $first operand with $ifnull or $cond in order to get the code field which is not null. So my result would look like this:
{ "result" : [ { "_id" : "box", "code" : 'abcde' } ], "ok" : 1 }

Cheers,
Answer:
Not in the way you want this to happen there isn't. You seem to be looking for a "conditional" way to evaluate $first and this just does not happen. All $ifNull can offer you is that where the field does not actually "exist" or otherwise evaluates to null then an "alternate" value is returned.
But you don't want this, and all it seems you basically want is to simply "filter" the possible results via a $match statement first:
db.items.aggregate([
    { "$match": { "code": { "$ne": null } } },
    { "$group": {
        "_id": "$item",
        "code": { "$first": "$code" }
    }}
])

But really, in your case and also unless you specifically need a "sort order" to come to the result, with a singular field you are better off just using $max as an operator, even if a $match stage does actually "still" optimize this by excluding any documents that actually "should not be" part of the desired result:
db.items.aggregate([
    { "$group": {
        "_id": "$item",
        "code": { "$max": "$code" }
    }}
])

So $match and $max in the $group is probably what you really want in this case. The $first operator usually only makes sense when you want multiple fields from the document as a result and then only usually after a $sort operation unless your documents expect a "natural" sort order as they appear on disk ( and we mean that exactly, things can move around ).
So consider what you actually want to do and implement accordingly.
Comment: using the $max operand solved it for me. The aggregation method considers a value to be greater than null, apparently. Thank you for this.


Get the list of Pods stuck in terminating state for more than 10 mins and remove them in Ansible

Question: I want to get the list of pods stuck in terminating state for more than 10 minutes using Ansible. Currently I am writing a script to do that but I feel there has to be a better way of doing the same. I plan to replace the describe pod command with delete one in the following code snippet.
# Command used to delete :  kubectl delete pod $PodName -n {{item}} --force --grace-period=0;
- name: get list of pods and remove the not ready ones
  shell: |
    noOfPODs=`kubectl get pods -n {{item}} | egrep "0/1|Terminating" | wc -l`;
    if [ $noOfPODs -gt 0 ];
      then
        kubectl get pods -n {{item}} | egrep "0/1|Terminating"   > {{ not_ready_pods_file }} ;
        while read line; do
          PodName=$(echo $line | awk {'print $1'})
          PodTime=$(kubectl describe pod $PodName -n {{item}} | grep Terminating | awk {'print $4'} | tr -d 'mhd)')
          if [ -z $PodTime ];
          then
            PodTime=$(echo $line | awk {'print $5'} | tr -d 'mhd')
          fi
          echo "$PodTime is PodTime"
          if [[ $PodTime == *s ]] ;
          then
            echo "PodTime in seconds"
          else
            if [ $PodTime -gt 10 ];
            then
              echo "\n$PodName" >> {{ deleted_pods_file }};
              kubectl delete pod $PodName -n {{item}} --force --grace-period=0;
            fi
          fi
        done < {{ not_ready_pods_file }}
    else
      echo 'No Pods in NOT READY or Terminating state';
    fi
  environment:
    KUBECONFIG: "./_kubeconfig/{{ env }}/kubeconfig"
  loop:
    - somenamespace

I tried using k8s_info in ansible but it gives a huge output which does not have time

- name: Search for all running pods
  k8s_info:
    kind: Pod
    field_selectors:
      - status.phase=Running
    kubeconfig: "./_kubeconfig/{{ env }}/kubeconfig"

Is there any better way of doing this ? like to do in Prometheus etc. Shell script will work but does not seem like the right way.
Answer: You could leverage go-template for this and do something similar to:
kubectl get pods --all-namespaces -o go-template --template '{{range .items}}{{if eq (.status.phase) ("Terminating")}}{{if gt (.status.startTime) ("2020-07-03T04:18:02Z")}}{{.metadata.name}}{{"\n"}}{{end}}{{end}}{{end}}'

{{if gt (.status.startTime) ("2020-07-03T04:18:02Z")}} should be replaced by your own time conditions.
Comment: Hey, yes it should do the same thing as the bash script you implemented, of course it may require some tweaking around the startTime and date calculation, also I am not 100% sure that time should be taken from status, maybe you should use the value from `conditions.lastTransitionTime`, but it is really up to your requirements.
Comment: thanks a lot @Adam Otto , for this amazing piece of code :). I will try this as well.  One question though, isn't it doing the same thing as the above shell script. I mean we are shortening our code here but the approach is same. Thoughts ? let me know if my understanding is wrong.


Why no alias record could be found when I'm trying to sql-sync the database?

Question: I'm trying to synchronize a production database to two development installations at once, instead of having the production database dumped twice.
In aliases.drush.inc file I'm defining a site-list alias as following:
$aliases['dev'] = array(
  'site-list' => array('@dev1', '@dev2'),
);

$aliases['prod'] = array(
  'uri' => 'default/prod',
  'root' => '/docroot/prod',
  'db-url' => 'mysqli://root:pass@localhost/prod',
);
$aliases['dev1'] = array(
  'uri' => 'default/dev1',
  'root' => '/docroot/dev1',
  'db-url' => 'mysqli://root:pass@localhost/dev1',
);
$aliases['dev2'] = array(
  'uri' => 'default/dev2',
  'root' => '/docroot/dev2',
  'db-url' => 'mysqli://root:pass@localhost/dev2',
);

Running a Drush command against any of these aliases works fine.
Running drush @dev status works fine too, and displays the status for both @dev1 and @dev2.
However, trying to execute drush sql-sync @prod @dev gives me the following error:

Error: no alias record could be found for @dev

Do you have any clues?
Comment: Unfortunately, this feature is buggy in Drush and will be removed. Check this out: http://drupal.org/node/1316378
Comment: What happens when you run `drush sql-sync @prod @dev1`? What happens when you run `drush sql-sync @prod @dev.dev1`?
Comment: @Remon You should place that as the answer and close this out then. Looks like you have the correct answer.
Answer: Seems that this feature is buggy in Drush and will be removed. Check this out: drupal.org/node/1316378
Answer: Drush 8+ expects a site alias file. For me it turned out that the drush/sites/self.site.yml didn't exist after I've run into a similar error. The alias file didn't got copied properly into a container.
You need to ensure that the alias file exists.

$ drush sql-sync @test @self -y
Error: no alias record could be found for source [error]
@test

Here's a nice article about Drush Site Aliases for Drupal 8 and Drupal 9 and how this actually is supposed to work in detail: https://drupalize.me/tutorial/drush-site-aliases?p=2458
Answer: copy the DB array from your settings to your aliases file.


How does twitters profile image uploader show an image preview on the client side

Question: We have recently added image uploading and cropping to our site using Fine Uploader; mixing a set of javascript libraries with a HTTP Handler.
It is working well however for larger images the client is forced to:

Wait a while until the image has been uploaded using the HTTP Handler
Download the image again so it can be used with JCrop
The image is downloaded at full size then resized to a smaller image on the client side by JCrop.

I noticed on Twitter selecting an image for your profile shows the image instantly; with apparently no server side interaction.
Does anyone know how twitter achieves this client side viewing of an image without uploading it to the server; or have any advice on smoothing out the aforementioned process?
Answer: Probably like this
http://jsfiddle.net/dmZTm/
<code>var URL = window.URL || window.webkitURL;

$("input").change(function() {
    var file = this.files && this.files[0];

    if (file) {
        var src = URL.createObjectURL(file);
        $("<img>", {
            src: src
        }).appendTo("body");
    }

});
</code>
Comment: @Click-Rex detect if the browser supports `.createObjectURL` like so: `var supportsCreateURL = !!(window.URL || window.webkitURL)`. Then in the logic you do `if( supportsCreateURL ) //show client side` `else //do server side preview`
Comment: @Click-Rex nope, just IE10, chrome, firefox (very likely safari 6 and latest opera as well). You need to use a fallback for older browsers - instead of setting `src` from `.createObjectURL`, you would set it from the server.
Comment: Marked as the correct answer; could you go into more detail on how you'd make it work with, say, IE7-9?


How to make base path available in views 3 Drupal 7?

Question: Without use of Views PHP module, I need to use base_path for a link. Although using views_php module, we can add it inside php code but is there any way without using this module OR we'll have to write code to create something like handler.
Currently available fields in my module are following:
 Content: Add comment link
Display the standard add comment link used on regular nodes, which will only display if the viewing user has access to add a comment.
 Content: All taxonomy terms
Display all taxonomy terms associated with a node from specified vocabularies.
 Content: Author uid
The user authoring the content. If you need more fields than the uid add the content: author relationship
 Content: Body
Appears in: node:page, node:article, node:event_calendar.
 Content: Comment count
The number of comments a node has.
 Content: Comment status
Whether comments are enabled or disabled on the node.
 Content: Delete link
Provide a simple link to delete the content.
 Content: Edit link
Provide a simple link to edit the content.
 Content: Event Date
Appears in: node:event_calendar.
 Content: Event Status
Appears in: node:event_calendar.
 Content: Has new content
Show a marker if the content is new or updated.
 Content: Image
Appears in: node:article.
 Content: Last comment author
The name of the author of the last posted comment.
 Content: Last comment time
Date and time of when the last comment was posted.
 Content: Last comment uid
The User ID of the author of the last comment of a node.
 Content: Link
Provide a simple link to the content.
 Content: New comments
The number of new comments on the node.
 Content: Nid
The node ID.
 Content: Path
The aliased path to this content.
 Content: Post date
The date the content was posted.
 Content: Promoted to front page
Whether or not the content is promoted to the front page.
 Content: Published
Whether or not the content is published.
 Content: Sticky
Whether or not the content is sticky.
 Content: Title
The content title.
 Content: Type
The content type (for example, "blog entry", "forum post", "story", etc).
 Content: Updated date
The date the content was last updated.
 Content: Updated/commented date
The most recent of last comment posted or node updated time.
 Content revision: Delete link
Provide a simple link to delete the content revision.
 Content revision: Link
Provide a simple link to the revision.
 Content revision: Log message
The log message entered when the revision was created.
 Content revision: Revert link
Provide a simple link to revert to the revision.
 Content revision: Title
The content title.
 Content revision: Updated date
The date the node was last updated.
 Content revision: Vid
The revision ID of the content revision.
 File Usage: Entity ID
The ID of the entity that is related to the file.
 File Usage: Entity type
The type of entity that is related to the file.
 File Usage: Module
The module managing this file relationship.
 File Usage: Use count
The number of times the file is used by this entity.
 FullCalendar: Google Calendar
Display events from a Google Calendar.
 Global: Contextual Links
Display fields in a contextual links menu.
 Global: Custom text
Provide custom text or link.
 Global: Math expression
Evaluates a mathematical expression and displays it.
 Global: View result counter
Displays the actual position of the view result
 Scheduler: Publish countdown
Time until the article will be automatically published
 Scheduler: Publish on
Date/time on which the article will be automatically published
 Scheduler: Unpublish countdown
Time until the article will be automatically unpublished
 Scheduler: Unpublish on
Date/time on which the article will be automatically unpublished
 Search: Score
The score of the search item. This will not be used if the search filter is not also present.

Answer: There is something in the view core.
If youre planning to output some field with base path, follow the steps to get an absolute path.

Click on the Field
Scroll down to REWRITE RESULTS
Check Output this field as a link checkbox
Check Use absolute path checkbox

If you're looking this for just a link Views PHP is a good choice.
If youre not happy with this method take a look at How to create a custom Views handler


How can I list all the pages of a Drupal site in csv format?

Question: My goal is to get a .csv file list of the titles/urls for all "pages" in a Drupal site, including all Views, panel pages, and nodes, etc.
Potential incomplete solutions:

Using the xmlsitemap module to generates xml then convert it to .csv format. This gets content types and menu links, but not views pages or panel pages or other cases. The downside here is that it only outputs the urls. It'd be nice to also have the titles.
Querying menu_links or menu_router tables. These list all the drupal paths, but not node paths or anything that requires the variable substitutions, ie "node/%".

I'm curious if there is a more straight forward way to do this. Any thoughts?
Comment: I found a similar question: http://stackoverflow.com/questions/2494411/how-to-get-all-paths-in-drupal-install
Though it doesn't provide a clear example solution.
Answer: I wrote a dirty script to query the node, menu_router, and menu_links tables: https://gist.github.com/dooug/b102a683d4e4854defba
This could be improved upon. The upside is that it includes "path,title" of all nodes, panel pages, view pages, etc. The downside is it includes all admin pages. Also, it includes lots of duplicates between the menu_links and menu_router tables. Please fork with your suggestions.