Shopware 6: Unexcpected behavior on custom product extension

Question: what exactly is the purpose or the expected behavior of the autoload parameter in CustomExtension->extendFields() OneToOneAssociation of a custom extension?
As i understand, with true the extension is always loaded, even if no has record, maybe as null
Expected
// debug source
...
product: Proxy
  [[Handler]]: Object
  [[Target]]: Object
    ...
    extensions:
      my_custom_extension: null

Actual
 // debug source
...
product: Proxy
  [[Handler]]: Object
  [[Target]]: Object
    ...
    extensions: {}

EDIT
// ProductFactoryProductExtension.php
<?php declare(strict_types=1);

namespace ItR22ProductFactory\Extension\ProductFactoryProduct;

use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityExtension;
use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToOneAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;

class ProductFactoryProductExtension extends EntityExtension
{

    public function extendFields(FieldCollection $collection): void
    {
        $collection->add(
            new OneToOneAssociationField(
                'productFactoryProduct',
                'id',
                'product_id',
                ProductFactoryProductExtensionDefinition::class,
                true
            )
        );
    }

    public function getDefinitionClass(): string
    {
        return ProductDefinition::class;
    }
}

// ProductFactoryProductExtensionDefinition.php
<?php declare(strict_types=1);

namespace ItR22ProductFactory\Extension\ProductFactoryProduct;

use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Field\BoolField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\FkField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\PrimaryKey;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\Required;
use Shopware\Core\Framework\DataAbstractionLayer\Field\IdField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\JsonField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToOneAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;

class ProductFactoryProductExtensionDefinition extends EntityDefinition
{
    public const ENTITY_NAME = 'product_factory_product';

    public function getEntityName(): string
    {
        return self::ENTITY_NAME;
    }

    public function getEntityClass(): string
    {
        return ProductFactoryProductEntity::class;
    }

    protected function defineFields(): FieldCollection
    {
        return new FieldCollection([
            (new IdField('id', 'id'))->addFlags(new Required(), new PrimaryKey()),
            new FkField('product_id', 'productId', ProductDefinition::class),
            (new BoolField('combinable', 'combinable')),
            (new JsonField('combinations', 'combinations')),
            new OneToOneAssociationField(
                'product',
                'product_id',
                'id',
                ProductDefinition::class,
                false
            )
        ]);
    }
}

EDIT #2
// sw-product-detail/index.js
...
Component.override('sw-product-detail', {
  ...

  /**
   *
   */
   loadProduct() {
      this.productCriteria.addAssociation('productFactoryProduct');
      this.$super('loadProduct');
   },
   ...
}

Answer: If you want data associated to an entity be fetched as well, in most cases the association needs to be actively added by calling Criteria::addAssociation. By setting autoload of the association field to true, the association is always added internally. Note that for OneToOneAssociation the default value of autoload is true.
Comment: thx for your answer, but even with `Criteria::addAssociation` the expected extension is still missing

`// extended component
loadProduct() {
            this.productCriteria.addAssociation('myExtension');
            this.$super('loadProduct');
        },`

`// debug
productCriteria: Criteria
 ...
   18: {association: 'myExtension', criteria: Criteria}

...
product: Proxy
  ...
  extensions: Object
    __ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
    [[Prototype]]: Object`
Comment: Please add the full contents of your `EntityExtension` and of your custom `EntityDefinition` to your original question. Otherwise we can only guess. One idea: Did you add the `ApiAware` flag to your field? `(new OneToOneAssociationField(...))->addFlags(new ApiAware())`
Comment: Done, see above. Btw, `ApiAware` what is that? Any link to shopware docu for deeper explanation?
Comment: See the [ADR](https://github.com/shopware/platform/blob/trunk/changelog/release-6-3-5-1/2021-01-25-added-api-aware-flag.md) regarding `ApiAware`. Since it looks like you're using the admin api it shouldn't be a concern though. At first glance the code looks good to me. You're overriding an existing component in the admin? Maybe share the code for the override as well. You can also look at the query to see if a join to the table of your custom entity is included: See https://stackoverflow.com/questions/73153309/how-to-debug-mysql-queries-from-admin-area-in-vue-js-component/73155120#73155120
Comment: Code snippet of overridden component see above. You say, with this code, the extension has to be loaded and available in the product props?
Comment: Yes, all looks good and data should be available as `product.extensions.productFactoryProduct` given `product_factory_product ` has corresponding entries. If it still isn't I would go ahead with process of elimination as described and check that the resulting query has joins on `product_factory_product`.


Three digit numbers $abc$ such that $26\mid a^2+b^2+c^2 $

Question: Find all three digit numbers $abc$ such that $26\mid a^2+b^2+c^2.$
I found this in a Olympiad question paper and was unable to solve it.
Comment: For each digit, compute its square mod 26.
Answer: Compute the squares of $0 \to 9$ mod $26$. You will get the list $0,1,4,9,16,25,10,23,12,3$. Now, you need three of these numbers to sum to $26$ or more. You will immediately get some answers:
$1 + 9+16=26$, giving $134,143,314,341,413,431$.
$1+0+25=26$,  giving $105,150,501,510$.
$4+25+23=52$, giving $257,275,527,572,725,752$.
$0+16+10=26$, giving $406,460,604,640$.
$4+10+12 = 26$, giving $268,286,628,682,826,862$.
$23+3+0= 26$, giving $709,790,907,970$.
That completes the list of numbers.
Comment: You left out 23 + 3 + 0 so 790 etc.
Comment: @fleablood thank you for pointing it out.
Answer: $1^2 = 1$
$2^2 = 4$
$3^2 = 9$
$4^2 = 16 \equiv -10 \mod 26$
$5^2 \equiv -1 \mod 26$
$6^2 \equiv 10 \mod 26$
$7^2 \equiv -3 \mod 26$
$8^2 \equiv 12 \mod 26$
$9^2 \equiv 3 \mod 26$
$0^2 = 0$.
$0 + x + (-x) \equiv 0 \mod 26$ so any number with the digits $(1,5,0),(4,6,0),(7,9,0)$ so the accounts for 12 answers.
Let's see what else...
$1 + 9 -10 = 4-1 - 3$  So all numbers with digits $(1,3,4)$ or $(2,5,7)$.  That accounts for 24 more answers.
I think that's all.


Change TrayIcon Tooltip from ProgressMonitorDialog

Question: I am using the Eclipse RCP trayitem, which is described in Vogellas tutorials.
The requirement now is not only to show the name of the app in the tooltip but also a percentage while doing lengthy operations.
I understand that the trayitem attribute is a private from ApplicationWorkbenchWindowAdvisor, so I added a getter and setter method.
The only thing missing is a possibility to access the trayitem instance from my ProgressMonitorDialog instance.
Can you tell me, how you would solve this puzzle?
Thanks
Answer: Since you can build a TrayItem around the SystemTray from any windows:
final Tray tray = window.getShell().getDisplay().getSystemTray();
TrayItem trayItem = new TrayItem(tray, SWT.NONE);

, do you have to access that TrayItem instance from ApplicationWorkbenchWindowAdvisor?
You could put it in a more accessible class or even build one where  and when you need it.

Speaking of showing percentage while doing lengthy operations, I just wanted to mentioned the latest tasks icons improvements in Eclipse3.6M6 (not system tray, but related at they now can provide a good status indicator). See Snippet 336 for an example.

TaskItem overlay image

The new API TaskItem#setOverlayImage(Image) allows clients to set an image to be displayed on top of the application button in the taskbar.

alt text http://download.eclipse.org/eclipse/downloads/drops/S-3.6M6-201003121448/images/overlayimage.png

TaskItem overlay text

The new API TaskItem#setOverlayText(String) allows clients to set a short text to be displayed on top of the application button in the taskbar.

alt text http://download.eclipse.org/eclipse/downloads/drops/S-3.6M6-201003121448/images/overlaytext.png

TaskItem progress

The new APIs TaskItem#setProgress(int) and TaskItem#setProgressState(int) allows clients to show progress indication in the application button in the taskbar.

alt text http://download.eclipse.org/eclipse/downloads/drops/S-3.6M6-201003121448/images/progress.png
Comment: Thanks! As far as I know within the ProgressMonitorDialog class/thread I have no display or window access....I tried also to open a messagebox with this class and it failed because of this. Or am I doing something wrong?
Comment: @Raven: I don't understand: a `Dialog` is a `Window`. the `getShell()` method should be available.
Comment: Caused by: org.eclipse.swt.SWTException: Invalid thread access
Thats the errormessage i get, after accessing the shell/display.
I am using the ProgressDialog from this tutorial: http://www.vogella.de/articles/EclipseJobs/article.html
Comment: @Raven, off course, you need to do it within the GUI Thread. See for instance http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg16800.html
Comment: Yes, this works, just I get two trayicons now :-(. The one which was already there plus the one in the lengthy operation. I thought getTrayIcon() would get the ONE and not create another one...
Comment: @Raven: true, that is an issue. You could try and find a way to store "globally" the first `TrayItem` created by `ApplicationWorkbenchWindowAdvisor` (through some kind of resources accessible through the shell). The idea remains: access to that `TrayItem` within the GUI thread.


How to execute login feature on Chrome browser

Question: Just using Behat with drupal 8 and facing problem with login behat script to run. Below are the my code :
behat.yml
default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Behat\MinkExtension:
      goutte: ~
      base_url: http://localhost:8080/drupal-dev/web
      javascript_session: selenium2
      browser_name: 'chrome'
      selenium2: ~
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: drupal
      drupal:
        drupal_root: web/
      region_map:
        navigation: ".navbar-header"
        navigation_collapsible: "#navbar-collapse"
        header: ".region-header"
        highlighted: ".highlighted"
        help: ".region-help"
        content: ".region-content"
        sidebar_first: ".region-sidebar-first"
        sidebar_second: ".region-sidebar-second"
        footer: ".footer"

login.feature
@javascript
Feature: login check

Scenario: user login is working
  Given I am on "/user"
  When I fill in "john" for "edit-name"
  And I fill in "john for "edit-pass"
  And I press "Log in"
  Then I should see "Add content"

While i execute the vendor\bin\behat then it will open the chrome browser and redirect to user login page but failed from second step. See below error message :
@javascript
Feature: login check

  Scenario: user login is working             # features\bootstrap\login.feature:4
    Given I am on "/user"                     # Drupal\DrupalExtension\Context\MinkContext::visit()
    When I fill in "john" for "edit-name"   # Drupal\DrupalExtension\Context\MinkContext::fillField()
      Form field with id|name|label|value|placeholder "edit-name" not found. (Behat\Mink\Exception\ElementNotFoundException)
    And I fill in "john" for "edit-pass" # Drupal\DrupalExtension\Context\MinkContext::fillField()
    And I press "Log in"                      # Drupal\DrupalExtension\Context\MinkContext::pressButton()
    Then I should see "Add content"           # Drupal\DrupalExtension\Context\MinkContext::assertPageContainsText()

--- Failed scenarios:

    features\bootstrap\login.feature:4

1 scenario (1 failed)
5 steps (1 passed, 1 failed, 3 skipped)
0m15.30s (17.82Mb)

And same feature file working fine and all steps passed if i replaced from @javasript to @api.
Comment: Have you already tried putting both? `@api @javascript`?
Comment: Do you maybe have BigPipe enabled?
Answer: Here's a @javascript tagged scenario that's working for me.
Feature: Login testing.

  @javascript
  Scenario: Testing the user cant login with bas credentials.
    Given I visit "user/login"
    And I fill in "name" with "foo"
    And I fill in "pass" with "bar"
    When I press "op"
    Then I should see an ".error" element

Comment: Big pipe module is enabled and see below error when try to execute your scenario :

1 scenario (1 undefined)
6 steps (1 passed, 1 undefined, 4 skipped)
0m18.60s (17.85Mb)

 >> default suite has undefined steps. Please choose the context to generate snippets:

  [0] None
  [1] FeatureContext
  [2] Drupal\DrupalExtension\Context\DrupalContext
  [3] Drupal\DrupalExtension\Context\MinkContext
  [4] Drupal\DrupalExtension\Context\MessageContext
  [5] Drupal\DrupalExtension\Context\DrushContext
Comment: Remove the unrelated steps. And see https://drupal.stackexchange.com/a/275652/15055
Comment: Which one is unrelated steps.  Please suggest if i was doing something wrong.
Comment: @VernitGupta – See my updated answer. You can also simply find it out yourself by removing steps one by one until you got it and then add all others back. Please try to solve this systematically yourself.
Comment: Updated answer and feature in my question are same. Same error received "Form field with id|name|label|value|placeholder "name" not found. (Behat\Mink\Exception\ElementNotFoundException)"
Answer: Just resolved the issue via changing selenium server version from 3.1 to 2.53


Suppose that $Y$ and $Z$ are independent. Prove that $X \sim f(1,v)$.

Question: This is what I'm supposed to prove...
Suppose that $Y$ and $Z$ are independent random variables with $Y \sim  z^2(v)$, and $Z \sim N(0,1)$, and $T = \frac{Z}{\sqrt{\frac{Y}{v}}}$. Let $X = T^2$. Prove that $X \sim f(1,v)$.
How would I start to prove this?
I know I should be using the theorem that states: If $U$ and $V$ are independent variable having square distribution with $V_1$ and $V_2$ degrees of freedom then $$F= \frac{\frac{U}{V_1}} {\frac{V}{V_2}}$$ is a random variable having an $F$ distribution for $f > 0$ and $g(f) = 0$ elsewhere.
Answer: $X=T^2=Z^2/(Y/v)$.  $Z^2$ is the square of a standard normal random variable, so it is $\chi^2$ with $1$ degree of freedom.  $Y$ is (I assume) $\chi^2$ with $v$ degrees of freedom.  Now, apply the theorem you mention above.


Is there an ATP 1000 that can end without a tie-break? Why not?

Question: Is there an ATP 1000 that can end without a tie-break? Why not?
It seems unfair to end with a tie break.
Comment: I think that your question need to be clarified a bit. I assume that by ATP 1000 you mean the [ATP World Tour Masters 1000](https://en.wikipedia.org/wiki/ATP_World_Tour_Masters_1000) tournaments. So are you asking whether some of the tournaments has the rule that the deciding set (i.e., the 3rd set) cannot end with a tiebreak, similarly as in Grand Slams (with the [exception of the US Open](http://sports.stackexchange.com/questions/5234/why-does-the-us-open-have-a-tiebreaker-for-the-fifth-set))?
Answer: According to the ATP Official Rulebook, all the ATP 1000 matches have a tie-break in the final set, even the finals:

ATP World
  Tour tournaments and the ATP Challenger Tour tournaments are governed by the
  ATP. Unless otherwise specified, all regulations are applicable to both ATP World
  Tour and ATP Challenger Tour tournaments.
         ATP World Tour tournaments
                Barclays ATP World Tour Finals (singles & doubles)
                ATP World Tour Masters 1000
                ATP World Tour 500
                ATP World Tour 250
  ...
  ...
  B.Matches – Number of Sets.
       1) Singles. All matches, including finals, shall be the best of three (3) tie-break sets

As for why, I assume they use tie-breaks in all of these non-slam tournaments for the same reason they don't play 5 sets: so that the whole tournament is less taxing on the players (this can happen without tie-breaks). They used to play 5 sets in the finals for the masters tournaments and stopped doing that because it would wear down players enough to where they wouldn't be able to consistently play all of the masters tournaments. To give an example, in 2006, Federer and Nadal both had to pull out of Hamburg after their long 5 set final in Rome. The next year, Masters 1000's were all reduced to 3 sets, which was possibly spurred by this incident. (Even back in 2006 though, all 5 sets were tie-break sets)


Funções com ajax fazem loop for parar de ser executado

Question: Tenho uma função que executa quando clico em um botão. Ao clicar, a função deve executar um loop for e se o valor daquele posição do contador do for corresponder a algum dos ifs então ele executa a função. Essas funções são todas chamadas ajax.
var checkbox_tipos = document.forms[1];

document.getElementById('gerar_dss').addEventListener('click', function(event){

    event.preventDefault();

    test : for (i = 0; i < checkbox_tipos.length; i++) {
        console.log(i);
        console.log(checkbox_tipos.length);

        if(checkbox_tipos[i].checked){
            console.log(checkbox_tipos[i].value);
            if(checkbox_tipos[i].value === 'dss_chuva'){
                console.log('entrou em chuva');
                dss_chuva();
                continue test;
            }
            if(checkbox_tipos[i].value === 'dss_cota'){
                console.log('entrou em cota');
                dss_cota();
                continue test;
            }
            if(checkbox_tipos[i].value === 'dss_vazao'){
                console.log('entrou em vazao');
                dss_vazao();
                continue test;
            }
        }
    }
});

function dss_vazao(){

    for (i = 0; i < checkbox_estacoes.length; i++) {
        if (checkbox_estacoes[i].checked) {
          estacao[i]=checkbox_estacoes[i].value;
        }
    }

    var ajax = new XMLHttpRequest();

    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4 && ajax.status == 200) {
            var data = JSON.parse(ajax.responseText);

            console.log(data.result);
            alert(data.result);
        }
    }

    ajax.open('POST', '../server/gerar-vazoes.php', true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    ajax.send('estacoes='+estacao+'&data_inicio='+data_inicio.value+'&data_fim='+data_fim.value+
        '&nome_arquivo='+nome_arquivo.value+'&observacao='+observacao.value+'&tipo='+tipo.value);
}

Fazendo testes, percebi que ao executar uma das funções o for para de rodar e, assim, não percorre continua com o loop. Procurando por aí vi o statemt "continue" e tentei aplicar mas não funcionou. O problema é: como fazer ele continuar? Desde já agradeço!
[EDIT 1]: Para melhor entendimento: o problema é que quando, no for, entra em uma das condições if e executa uma das funções o for não continua o loop. Exemplo: o for deveria rodar 3 vezes, mas na primeira volta do loop ao entrar em um dos ifs ele não continua as duas voltas que deveria fazer, como se o for fosse encerrado.
Comment: Eu não entendi perfeitamente seu problema, mas algum tempo atrás eu tive problemas com várias requisições sendo feitas dentro de um for. A minha dúvida foi essa: [Como esperar até que todas as requisições terminem?](https://pt.stackoverflow.com/questions/346752/como-esperar-at%C3%A9-que-todas-as-requisi%C3%A7%C3%B5es-terminem)
Comment: @Marconi obrigado. Fiz um edit, vê se dá pra entender melhor.
Comment: @Ramones ainda não ficou muito claro :/ ,mas você poderia passar o código completo no github ou algo assim e nos descrever os passos para entender o problema ? E sobre essas requisições Ajax recomendo fortemente o uso do JQuery em vez do XMLHttpRequest diretamente.
Answer: Resolvi o problema ao identificar que no for não havia o var na variável que serve de contador. Ao inserir o var funcionou como esperado.


How to use TinyMCE 4.5 with the WYSIWYG module?

Question: I am using the WYSIWYG module on Drupal 7, but the only TinyMCE editor I can use is version 3.5. I would like to use the version found here. How can I install this?
Answer: The previous version of the WYSIWYG module didn't support TinyMCE, but it does now.


How To Hide A Customizer Control in WordPress?

Question: I know contextual controls hide if for example the user navigates from the viewer certain pages.
But how can I achieve hiding a control under this scenario:
There is a type Select Control with an array of options from 1 to 6, Default being 1.
Then there are 6 type Text controls underneath. I want those controls (except for the first one) to be hidden on load and shown depending on what the user chooses from the Select control.
In other words the Select control determines the number of Text controllers the user would see.
I tried some JQuery which I am not very good at and the #customize-control_dadada... id's just would not obey.
I can't find any info on this matter, all I find is information about the contextual controls which are useful but do not seem what I need for this matter.
Any ideas? thank you in advance.
Answer: I was having the same issue as you. Try surrounding the #customize-control selector in a document.ready. For example:
<code>(function($) {
    $( function() {
        if ($('#customize-control-my-control').length) {
            // Do stuff
        }
    });
})(jQuery)
</code>
Put this javascript in a script that is queued on the admin side. To enqueue the script add this to your functions.php:
<code>add_action( 'admin_enqueue_scripts', 'admin_enqueue_scripts');

function admin_enqueue_scripts() {
    wp_register_script( 'admin-script', get_template_directory() . '/js/admin.js', array('jquery'), '1.0.0' );
    wp_enqueue_script('admin-script');
}
</code>
The above assumes the script is located in the current theme (get_template_directory). For plugin use: WP_PLUGIN_DIR . '/my-plugin';
Comment: I am not sure what I am missing, I have run this simple code `wp.customize( 'ttt_ttt_ttt', function( value ) {
        value.bind( function( to ) {

                $( 'li#customize-control-ttt_ttt_ttt' ).css( {
                    'display': 'none'

                } );

        } );
    });` with zero success. Any ideas joe? thank you for answering.
Comment: @Ulises - It looks like you might be trying to execute your code from the customizer script which I think I tried that as well. What worked for me was to add a separate script that is enqueued on the admin side. I updated my answer with how I did that. Let me know if that helps or not.


Lacking some steps in a proof regarding set of units of $\mathbb{Z}[\sqrt{3}].$

Question: I am trying to prove that:
$\mathbb{Z}[\sqrt{3}]^* = \{ x \in \mathbb{Z}[\sqrt{3}]: |N(x)| = 1 \}.$
Where $N$ is the norm function defined as follows:
Define the norm function $N:\mathbb{Q}[\sqrt{3}] \rightarrow \mathbb{Q}$ by $N(a_{1} + a_{2}\sqrt{3}) = \operatorname{det} \phi (a_{1} + a_{2}\sqrt{3}) = a_{1}^2 - 3 a_{2}^2.$
My trial is below:
Let $x \in \mathbb{Z}[\sqrt{3}]^*,$ then $x = a + b\sqrt{3}$ and there exists $y = c + d\sqrt{3} \in \mathbb{Z}[\sqrt{3}]^*$ such that $$xy = (a + b\sqrt{3})(c + d\sqrt{3})= (ac + 3bd) + \sqrt{3}(bc + ad) = 1,$$
Hence, $ac + 3bd = 1$ and $bc + ad = 0$
But then I do not know how to complete, could anyone help me please in continuing the proof?
Answer: Assuming that $\mathbb{Z}[\sqrt{3}]^*$ is the group of units of the ring $\mathbb{Z}[\sqrt{3}]$, here is a roadmap:

Let $U=\{ x \in \mathbb{Z}[\sqrt{3}]: |N(x)| = 1 \}$

Prove that $\mathbb{Z}[\sqrt{3}]^* \subseteq U$ using that $N(xy)=N(x)N(y)$

Prove that $U \subseteq \mathbb{Z}[\sqrt{3}]^*$ using that $N(x)=x\bar x$
Comment: what do you mean by $\bar{x}$, is it the conjugate? ... I managed to prove the second bullet but the third I am unable could you please show me its details?
Comment: @Confusion, $\pm1 = N(x)=x\bar x \implies 1 = x(\pm \bar x)$


/etc/sysconfig/network is ignored on CENTOS7

Question: I have a server with two NIC's. The default gateway has to be on a specific one, therefore I configured the GW via /etc/sysconfig/network. But obviousely, this is completely ignored by the NetworkManager
[root@node1 ~]# cat /etc/sysconfig/network
GATEWAY="10.100.20.1"
[root@node1 ~]# systemctl restart network
[root@node1 ~]# ip r s
default via 10.100.7.1 dev ens160  proto static  metric 1024
10.100.7.0/24 dev ens160  proto kernel  scope link  src 10.100.7.31
10.100.20.0/22 dev ens192  proto kernel  scope link  src 10.100.20.204

Any hints?
EDIT: Here are the interface configurations:
[root@node1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens192
DEVICE="ens192"
ONBOOT=yes
NETBOOT=yes
UUID="e634ce78-f5ea-4b3c-b3ea-1e40ef0b11ac"
BOOTPROTO=none
IPADDR="10.100.20.204"
NETMASK="255.255.252.0"
GATEWAY="10.100.20.1"
HWADDR="XXX"
TYPE=Ethernet
NAME="ens192"
DNS1="220.127.116.11"

[root@node1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens160
DEVICE="ens160"
ONBOOT=yes
NETBOOT=yes
UUID="bee8e636-80b4-45f3-9b74-eb9eb0fed38d"
BOOTPROTO=none
IPADDR="10.100.7.31"
NETMASK="255.255.255.0"
GATEWAY="10.100.7.1"
HWADDR="XXX"
TYPE=Ethernet
NAME="ens160"
DNS1="18.104.22.168"

And here's a part from messages that probably causes the Issue:
[root@node1 ~]# cat /var/log/messages | grep NetworkManager | grep "Nov  9" | grep "as default for IPv4" -A5 -B5
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> (ens192): device state change: ip-config -> ip-check (reason 'none') [70 80 0]
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> Activation (ens192) Stage 5 of 5 (IPv4 Commit) complete.
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> (ens160): device state change: ip-check -> secondaries (reason 'none') [80 90 0]
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> (ens192): device state change: ip-check -> secondaries (reason 'none') [80 90 0]
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> (ens160): device state change: secondaries -> activated (reason 'none') [90 100 0]
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> Policy set 'ens160' (ens160) as default for IPv4 routing and DNS.
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> Activation (ens160) successful, device activated.
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> (ens192): device state change: secondaries -> activated (reason 'none') [90 100 0]
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> NetworkManager state is now CONNECTED_GLOBAL
Nov  9 12:24:36 logging-02 NetworkManager[631]: <info> Activation (ens192) successful, device activated.
Nov  9 12:24:41 logging-02 NetworkManager[631]: <info> startup complete

Any idea what kind of "Policy" is mentioned there?
Comment: Check the configuration of each interface.
Comment: @EugeneM.Zheganin Reboot does not work either, and `systemctl` restart network should definitely do it...
Comment: I can just assure you that it's not ignored because I'm using it to configure the default gateway. May be it's the `systemctl restart network` is not enough to actually redefine the default gateway.
Answer: This worked:
[root@node1 ~]# cat /usr/share/doc/initscripts-9.49.17/sysconfig.txt | grep DEFROUTE
DEFROUTE=yes|no (set this interface as default route? yes is default)

I still believe that ignoring /etc/sysconfig/network is a bug in CentOS Linux release 7.0.1406 (Core)
Comment: Fixed my issue.  Just to make it clear to everyone: you must explicitly configure DEFROUTE=no in the config file for all other UP interfaces on your server for this to work properly.
I really hope /etc/sysconfig/network being configured is a bug (two years later?!?!!?), because having to configure a default route this way is absolutely ridiculous...
Answer: The best way I've done this is addd a static route file like I have two interfaces
eth0 = private on 10.10.11.10
eth1 = public on 188.8.131.52 (also the default route)

So if I want all internal traffic on the 10.0.0.0/8 subnet to go out eth0 I just add the following file
/etc/sysconfig/network-scripts/route-eth0
With the contents of
default 10.102.51.129 dev eth0
10.0.0.0/8 via 10.102.51.129 dev eth0

10.102.51.129 is my gateway for eth0


What is the most "general" definition of a Euclidean space?

Question: I'm finding conflicting definitions of Euclidean space. Rudin defines it specifically as the vector space $\mathbb{R}^k$ together with its standard inner product and norm structure. In other cases, I'm seeing it defined as the set of $k$-tuples in some unspecified set. Apparently, these are the same up to isomorphism, but what is the most "general" definition of Euclidean space (or spaces, since there seem to be multiples)?
Comment: As usual, the Wikipedia article [Euclidean space](https://en.wikipedia.org/wiki/Euclidean_space) has the information you need to know.
Answer: The author will specify the definition that will be used.  Not everyone states the same definition, because not everyone has the same uses in mind.
Note the textbook Loomis and Sternberg, where Euclidean space is written $E^n$ and $n$-tuples of reals is written $R^n$.  So in this version, $R^n$ is $E^n$ together with some additional structure.  So for example, $E^n$ by itself has no distinguished point "the origin" and no distinguished lines "the axes".
Comment: Is there a specific set from which the elements of $E^n$ are taken, though? In other words, is an intuitive understanding of Euclidean space "$\mathbb{R}^n$ with some added structure"?
Comment: So $E^2$ is what we find in the first part of Euclid's *Elements*.  Nowadays we would say that points and lines are undefined concepts, governed by certain axioms.


How to find and combine the Whole Chemical Compound string using regex within a LaTex

Question: For the string below:
Which one of following pairs of gases is the major cause of greenhouse effect?
A. \( C O_{2} \) and \( O_{3} \)
в. \( C O_{2} \) and \( C O \)
c. \( C F C \) and \( S O_{2} \)
D. \( C O_{2} \) and \( N_{2} O \)

I want something like:
Which one of following pairs of gases is the major cause of greenhouse effect?
A. \( CO2 \) and \( O3 \)
в. \( CO2 \) and \( CO \)
c. \( CFC \) and \( SO2 \)
D. \( CO2 \) and \( N2O \)

I used re.sub('[A-Z]_{[0-9]}', '<CHEM>', text) as an experiment so that I could combine the two. How could I combine the whole equation together? Each element is separated by a space and each element could be capitl letters and/or made of 1 or more alphabets. It could be something like:
\( Na Cl_{2} \) and \( Fe k_{3} cl  \) -> \( NaCl2 \) and \( Fek3cl  \)
Comment: What about CH4 ?
Comment: `C11H15NO2` is the answer!
Comment: IMO, You took a little too much C20H25N3O to say this kind of things.
Comment: @CasimiretHippolyte, what about it, other than it's a colourless, odourless gas that occurs abundantly in nature, the simplest member of the paraffin series of hydrocarbons that is among the most potent of the greenhouse gases?
Comment: @CarySwoveland but its step father is sh!!t, right?
Answer: You can use capture groups with re.sub:
re.sub(r'([A-Z][a-z]?)(_{([0-9]+)})? *', r'\1\3', text)

Try it online!
If you want to preserve the whitespace after the last element, you can use
re.sub(r'([A-Z][a-z]?)(_{([0-9]+)})?( *(?=[A-Z]))?', r'\1\3', text)

Try it online!
Explanation:
([A-Z][a-z]?)(_{([0-9]+)})? *
([A-Z][a-z]?)                             # Matches chemical names. Captures the name of the chemical in group 1.
             (_{([0-9]+)})?               # Matches a potential subscript. Captures the number in group 3.
                            *             # Matches trailing whitespace. This causes it to be removed
                           ( *(?=[A-Z]))? # Alternatively, match the whitespace, only if it's followed by a capital letter. This means that it will be removed only if it's followed by a chemical element.

Answer: You may write
rgx = r'(?<!\\\()[ _{}](?=[ A-Z\d _{}]* \\\))'

re.sub(rgx, '', str)

Demo
The regular expression can be broken down as follows.
(?<!            # begin a negative lookbehind
  \\\(          # match '\('
)               # end negative lookbehind
[ _{}]          # match a character in the char class
(?=             # begin a positive lookahead
  [ A-Z\d _{}]* # match zero or more characters in the char class
  [ ]\\\)       # match ' \)'
)               # end positive lookahead

I've put the space character in a character class ([ ]) merely to make it visible.
Answer: You can use
import re
text = r"\( Na Cl_{2} \) and \( Fe k_{3} cl  \)"
print( re.sub(r'\\\(\s*([^()]*?)\s*\\\)', lambda x: f'\\( {"".join(c if c.isalnum() else "" for c in x.group(1))} \\)', text) )

See the Python demo, see the regex demo. Details:

\\ - a \ char
\( - a ( char
\s*  - zero or more whitespaces
([^()]*?) - Group 1: any zero or more chars other than ), (
\s*\\\) - zero or more whitespaces, and then a \) string.

The lambda x: f'\\( {"".join(c if c.isalnum() else "" for c in x.group(1))} \\)' replacement replaces the match with \( , Group 1 with all non-alphanumeric chars removed and  \).


Error Bundler::HTTPError during request to dependency API

Question: I keep getting the following error when running bundle
Error Bundler::HTTPError during request to dependency API

Is this a rubygems issue or something else?
Also, I have read that adding
source "http://bundler-api.herokuapp.com"

in your Gemfile.  Will fix this problem.  So are the gems being fetching from heroku and not rubygems in this method?  How safe and stable is this?
Comment: This is solely(most definitely) underlying internet connection issue. Also this URL smells like phishing one.
Answer: This error could indicate that your connection to the internet was broken.
About the parameter to the method source in your Gemfile, I don't know nothing about that, but the url doesn't work, I recommend you avoid that. If you don't want to use a specific or particular repository to download your gems, you should use the "default" source "http://rubygems.org" instruction.
Comment: I waited a bit, and finally got it to work.  Thanks for the default source: rubygems that makes sense.
Answer: The answer to your question is here: https://groups.google.com/d/msg/rubygems-org/aBHBOCgH6UE/1p_Kde3BlGgJ
From what the author of that post says, the error is innocuous.
Answer: For me, changing the source in my Gemfile to the non-HTTPS URL worked:
http://rubygems.org
Probably not ideal, but something with https isn't working at my location today.
Answer: I don't think it is rubygems issue.
Check for these things:
1.Use the Source in Gemfile as https://rubygems.org.
2.Your Internet connection is not broken.(Sometimes,it happens because of that.)


Learning pick and finger-picking at the same time?

Question: I am picking up the guitar again, being now 30 and having played when I was about 9, and I'm a bit confused on what approach I should take while self-learning.
I would ideally like to play things along the line of Townes Van Zandt, Willie Nelson, and Elliot smith. I used to play classical, so I've never used a pick, and it feels off to me, and I'd rather play more finger-style with a small amount of picked stuff. Most beginner material is geared towards pick style.
Is it bad to approach both, and does anyone have any suggestions on how I should proceed?
Comment: First place to start would be to check out [hybrid picking](http://en.wikipedia.org/wiki/Hybrid_picking).
Comment: I have been learning some Elliott Smith stuff recently and a lot of it is harder than it sounds. He is often doing chords and melody lines simultaneously with a lot of non-standard chords. Look up some of his tabs, and remember thumb for E, A, and D string, index finger for G string, middle finger for B string, and ring finger for high E. Look into [Travis Picking](http://youtu.be/4t_VPUGh514) for more.
Comment: Yeah, that's a long-term goal of mine. He also has quite a bit of material that is picked, and with Willie, I've been inspired to try to get comfortable with that for when i get there. Thanks for the tips Charles.
Answer: I do not believe that learning both picking and finger-style concurrently will negatively impact your progress.
One of the hardest things to do when learning an instrument is to stay motivated. My advise is: grab onto whatever you can to stay excited and interested. There are so many things you can work on when you have time to practice that, especially in the beginning, you should ensure that what you are working on is fun.
That being said, taking some time to get used to the feel of a pick is going to be great for your overall experience with the guitar.
The pick and your fingers are tools that help you create sounds. Use those tools when and where they make the most sense. It's going to be hard to finger pick a Randy Rhoads solo…but it's also quite hard to use a pick when playing his song 'Dee'.
It was easier for me to learn complicated strumming patterns with a pick at first. Though eventually I found that there were a number of pieces that I preferred strumming with thumb and finger rather than a pick. As long as you are practicing with proper technique I don't think you can go wrong. Picking up the guitar is the most important step…take whatever path you can to get where you are going.
But if a pick is just not for you…you can always play the beginner material you have on hand without a pick.
Comment: @shootingstars I would say stick with what's comfortable. Neither one is better than the other, although the classical position is very ergonomic and makes some things easier to play.
Comment: @shootingstars: I totally agree with Charles. There really is no wrong way when it comes to this type of thing. What is typically thought is a good starting point for most people, but as you grow you end up in your own style. Experiment, put on the hat and see how it feels.
Comment: Thanks! I imagine it probably doesn't make too much difference, but holding a guitar "classical style" obviously feels more natural to me. Would an over-the-right leg approach be best for these styles, regardless of the picking bit? Justinguitar.com recommends the latter if not playing classical music.
Answer: It's like any musical instrument. They all have separate techniques even vocals. It's muscle memory at the end of the day. Tuning in to the specific movements of you body to act in accordance with the instrument. That is probably why people refer to instruments being a part of you during playing.
My advise for learning would be to practice both, but not too quickly that you forget what you learned previously. Play with one style for say a week or two. Then change to another for two weeks and then try and integrate them both together. Don't move on until you are comfortable that you have learned what you need.
Answer: I do this myself. I learnt on acoustic and electric guitar and never had a pick available (just never owned one!) for about the first 3 years of playing.
These days I'm fairly adept ad playing with fingers and with a pick. I'll often use a pick for chugging/strumming so as to save my fingernails getting worn, but when it comes to a solo, I tend to tuck the pick into the top of the scratch plate and play the solo with my fingers.
This allows a few techniques which aren't really possible when playing with a pick (well not for me) like playing 3 strings in immediate synch, and stopping them all at the same time too, van halen style tapping (I find this much easier without a pick), and fingers are free to adjust volume etc while playing so "violin" sound (volume down -> pluck string -> bring volume up), plus of course finger picking across strings.
I'd say learning to play with and without a pick would enrich your style as more things become possible/easy for you. The examples above are what works for me, it might be different stuff for you.
Answer: Short answer dont.
It takes a large amount of effort and practice to get total mastery over the picking action. My advice to you would be to descide on what kind of guitarist you want to be and to stick with the picking action that is best suited for the style of music you want to play.
It is better to have one picking action down good that being a jack of all trades and a master of none.
Comment: I have to disagree if you can learn different styles it will broaden your musical horizons playing with different techniques is a great way of increasing proficiency with any instrument. Different grip with drumming for example.
Comment: @shootingstars no not at all if you have the time during the song to adjust the grip off you plectrum to allow for finger playing faster songs maybe a problem. dropping the Plectrum maybe a concern haha!
Comment: @NathanTaylor Is it too much or confusing to try to learn both simultaneously, though?


On the notation of the likelihood function

Question: Let $X$ be a random variable realized as the event $(X=x)$.
The corresponding likelihood function is given by
$$\mathcal{L}_x:\Theta\rightarrow[0,1]$$
$$\theta\mapsto P(X=x|\theta)$$
for a space $\Theta$ of parameter configurations $\theta$.
In the literature, $\mathcal{L}_x(\theta)$ is sometimes written as $\mathcal{L}(\theta|X=x)$. I assume this is done to emphasize that the event $(X=x)$ is 'given'.
However, this notation leads to confusion, since
it suggests that $\mathcal{L}_x$ is a probability density ('conditioning' on the event $X=x$), which appears to not be true in general (cf. second answer in this thread on math.overflow).
So my questions are:

Is $\mathcal{L}(\theta|X=x)$ just 'overloading' the notation $f(\cdot|\cdot)$, or is there some hidden meaning/analogy to conditional probability $P(\cdot|\cdot)$ which I am missing?
Are there other areas in mathematics where $f(\cdot|\cdot)$ is used? Could you provide an example?

Currently, I think $\mathcal{L}(\theta|X=x)$ is a bad notational choice because it caused confusion for me when trying to understand the likelihood function.
Especially since at any point $\theta$, one has $\mathcal{L}(\theta|X=x)=P(X=x|\theta)$
Comment: In statistics is is common practice to list parameters and other relevant information to the right of a $|$ symbol. The $|$ symbol is not reserved for conditional probability. Some authors use $;$ instead of $|.$
Comment: For any $\theta$, one has $\mathcal{L}(\theta|X=x)=P(X=x|\theta)$. I find this very confusing. Especially in bayesian inference, one often encounters the expression $P(A|B)$ which is called 'likelihood'. Am I just to assume that this is what I called $\mathcal{L}(B|A)$? Also, I've read both 'prior likelihood' and 'posterior likelihood', but also 'prior probability' and 'posterior probability'. This is all very confusing to me and I don't really understand why one would make this distinction in the first place.
Comment: The point of the first form is that the likelihood function is viewed as a function of the parameter $\theta$ once data $x$ is observed. The constant that makes the PDF integrate (or sum) to unity is often omitted. (If you are maximizing the likelihood function to find $\theta$ that maximizes it, then that constant is not relevant.)
Answer: In classical (frequentist) statistics $\theta$ is unknown constant, thus there is no sense in viewing $L(\theta|X)$ in any probabilistic manner. As you can see in the linked thread, $L(\theta|X)$ does not even need to be integrated (w.r.t. $\theta$) to one. Hence, the more common notation is $L(\theta; X=x)$ or its shorthand $L(\theta; X)$ or $L(\theta; x)$, which just designates the fact that we view it as a function of $\theta$ over the parametric space $\Theta$, and regard the $X$ as constant $X=x$.
In the case you are Bayesian, then you usually denote the posterior distribution of $\theta$ by $f(\theta|...)$ or $p(\theta|...)$, not to confuse it with the classical likelihood function. But to this notation to make sense you must assume a prior distribution for $\theta$, $f(\theta)$. That is, from the very beginning you regard $\theta$ as a random variable and not as a constant.
Comment: (+1) for showing the Bayesian point of view.
Answer: Consider data $x = 8$ sampled from a binomial population with success parameter $\theta$ (unknown and to be estimated) and a known number of Bernoulli trials $n = 12.$
PDF. If it happens that $\theta = 0.5,$ then the PDF gives
you the probability of getting $X = 8:$
$$f(x |n=12, \theta=0.5) = {n \choose x}\theta^x(1-\theta)^{n-x}\\ = {12 \choose x}.5^x(1-.5)^{12-x} = {12\choose x}(.5)^{12},$$ for $x = 0, 1, \dots, 12.$
plot(0:12, dbinom(0:12, 12, 1/2), type="h",
     lwd=2, col="blue", ylab="PDF", xlab="x",
     main="PDF of BINOM(12, 1/2)")
 abline(h = 0, col="green2")

Likelihood. Now, if you have observed $x = 8$ and wish to find
the corresponding estimate $\hat \theta$ of $\theta,$
then the PDF, considered now as a likelihood function,
might be written as
$$\mathcal{L}(\theta|x,n) = \mathcal{L}(\theta|8,12)\propto \theta^x(1=\theta)^{n-x} = \theta^8(1-\theta)^4,$$
for $0 < \theta < 1,$
where the symbol $\propto$ (read 'proportional to') is
used as a reminder that the (now irrelevant) constant
${n\choose x}$ has been omitted.
Maximixing $\mathcal{L}(\theta|8,12)$ in $\theta$ we obtain the maximum likelihood estimate (MLE) $\hat\theta = x/n = 9/12 = 2/3.$
th = seq(0, 1, by=.01)
like = dbinom(8, 12, th)
plot(th, like, type= "l", ylab="Likelihood",
     xlab = "theta", lwd=2,
     main="Likelihood Function")
 abline(h=0, col="green2")
 abline(v=8/12, col="maroon")

mle = th[like==max(like)];  mle
[1] 0.67

Comparison. It is simple to say that the PDF and the likelihood
function are the 'same thing'. But not exactly true.

The PDF is a function of $x,$ for given
parameters $n$ and $\theta.$ As in the first plot above.

The likelihood function is a function of
unknown $\theta$ for known values $n = 12, x = 8.$
As in the second plot.

It not not surprising that
this difference in viewpoint gets shown explicitly in the notation.
Comment: I see. I think my confusion stems from seeing the term likelihood used in Bayes' formula $P(H|E)=\frac{P(H)}{P(E)}P(E|H)$. By itself, $P(E|H)=\mathcal{L}(H|E)$ is just a value, and from the above I deduce that its interpretation as probability/likelihood depends on what is assumed to vary. I always assumed that in Bayesian inference one has a *fixed* initial hypothesis $H$, whose probability of being true is 'updated' given some new evidence $E$. However, I don't see how $H$ varies. If you could answer how it does, this would be of great help. I will re-read the Wikipedia article for now.


Validando Valor

Question: Precisava validar um valor antes do mesmo ser enviado, como faço para o mesmo ser validado antes do envio, pq ele o mesmo ja esta enviando direto sem validar a soma do input.

<form  action="envia.php" method="post" class="form"  onSubmit="return soma();">

teste

Basta preencher o formulário abaixo

   Nome*
   <input type="text" name="nome" class="form-control" required>

   Email*
   <input type="text" name="email" class="form-control" required>

   Celular*
   <input type="text" name="cel" class="form-control" required>

   Cidade*
   <input type="text" name="cidade" class="form-control" required>

   3 + 11 = ?
   <input type="text" name="soma1" value="" class="form-control" required>

   <input type="submit" class="btn-default" value="Agendar">

Comment: coloque um name no form `name="form"`
Answer: coloque um name no form name="form"

function soma() {
 if (form.soma1.value == 14) {
     console.log("soma correta");
 }else{
     console.log("por favor informe o valor correto da soma");
     //para evitar o submit
     return false;
 }
}
<form name="form" action="envia.php" method="post" class="form"  onSubmit="return soma();">

teste

Basta preencher o formulário abaixo

   Nome*
   <input type="text" name="nome" class="form-control" required>

   Email*
   <input type="text" name="email" class="form-control" required>

   Celular*
   <input type="text" name="cel" class="form-control" required>

   Cidade*
   <input type="text" name="cidade" class="form-control" required>

   3 + 11 = ?
   <input type="text" name="soma1" value="" class="form-control" required>

   <input type="submit" class="btn-default" value="Agendar">

</form>

Outra forma: pelo id do elemento
script if (document.getElementById("soma1").value == 14){
HTML <input type="text" id="soma1" name="soma1" value="" class="form-control" required>

function soma() {
 if (document.getElementById("soma1").value == 14){
  alert("soma correta");
 }else{
  alert("por favor informe o valor correto da soma");
  return false;
 }
}
<form action="envia.php" method="post" class="form"  onSubmit="return soma();">

teste

Basta preencher o formulário abaixo

   Nome*
   <input type="text" name="nome" class="form-control" required>

   Email*
   <input type="text" name="email" class="form-control" required>

   Celular*
   <input type="text" name="cel" class="form-control" required>

   Cidade*
   <input type="text" name="cidade" class="form-control" required>

   3 + 11 = ?
   <input type="text" id="soma1" name="soma1" value="" class="form-control" required>

   <input type="submit" class="btn-default" value="Agendar">

</form>

Existe ainda mais uma forma:
Visto que, por conceito, pode haver mais de um formulário em um documento, os formulários são armazenados em arrays na propriedade document.forms[]. Um numero de índice dentro dos colchetes aponta para um dos elementos no array. Para acessar o primeiro formulário em um documento, a referencia é: document.forms[0]
Caso seu formulário seja o primeiro do documento seu script seria assim:
function soma() {
 if (document.forms[0].soma1.value == 14){
    console.log("soma correta");
 }else{
    console.log("por favor informe o valor correto da soma");
    return false;
 }
}

HTML
<form action="envia.php" method="post" class="form"  onSubmit="return soma();">
...........
...........

   3 + 11 = ?
   <input type="text" name="soma1" value="" class="form-control" required>

   <input type="submit" class="btn-default" value="Agendar">

</form>

Comment: @AndersonGaldino, essas são as formas de acessar as propriedades e métodos do objeto document com javascript, portanto não é má pratica.
Comment: agora entendi muito melhor, vou implementar dessa forma. só gostaria de saber se a forma que coloquei direto passando por form.soma1.value é uma má pratica?
Answer: segue mais uma alternativa, utilizando uma validação com HTML5.

var soma = document.getElementById("soma");
soma.addEventListener("input", function (e) {
  var msg = "";
  if (!e.target.value)
    msg = "por favor informe um resultado para a soma";
  else if (!/(14)/.test(e.target.value))
    msg = "por favor informe o resultado correto para a soma";
  e.target.setCustomValidity(msg)
});
soma.dispatchEvent(new Event("input"));
<form action="#" method="post" class="form">

    3 + 11 = ?
    <input id="soma" type="text" required>

    <input type="submit" value="Agendar">

</form>

Validando Valor


How to link another HTML file onto HTML

Question: I am trying to create an expand on click feature on my website. When the user clicks on the button, something is displayed.
I know I can use JS to make the div show up, but my HTML code is long, so I don't want to copy the entire thing there. I know I can also use the  tag, but I don't want my page to refresh.

 function findPressure() {
  var ifrm = document.createElement("iframe");
  ifrm.setAttribute("src","/Users/lunapark/Documents/antoine_equation/antoine_pressure.html");
  document.body.appendChild(ifrm);
 }

    <button onClick="findPressure()">Solve for Pressure</button>
    <button onClick="findTemp()">Solve for Temperature</button>

As you can see here, I used iframe, which I am not in favor of. Is there some way I can link the existing HTML to my main HTML and not have it refresh on a web page?
Comment: Try to use [ajax](https://www.tutorialspoint.com/ajax/what_is_ajax)
Comment: HTML files can't be linked like JS or stylesheets. You can use AJAX to load the content from the server.
Comment: Better Create one `` Element and Change its source on each button click.  - In this approach iframe will get refresh not the entire page.
Answer: Lots of ways of doing this - upgrade to Vue.js for example. Or jQuery load() is pretty good for this kind of thing too. https://api.jquery.com/load/
Comment: I'd rather recommend a simple `fetch`.

How to link another HTML file onto HTML


Como resgatar endereço de IP externo no Android?

Question: O endereço IPV4 local não é algo muito complexo de resgatar, dá para fazer isso usando a classe NetworkInterface. Porém além do local, existe também o IP externo, no qual percebi que algumas pessoas usam algumas APIs, como a do WhatIsMyIP, para retorno de informações referente a rede. No WhatIsMyIP existe a versão free, porém muito limitada.
Existe uma forma de resgatar IP externo sem necessidade de um serviço externo? Se sim, como poderia fazer isso? Se não, qual maneira viável de fazer isso?
Comment: Parece que [isto não é possivel](http://stackoverflow.com/a/6932465/5524514), já que quem fica a frente da rede é o roteador/modem. Alias, nem um computador é capaz de determinar o ip externo por si só atrás de um NAT.
Comment: @diegofm eu não tinha visto essa resposta do SOen! Talvez há algum serviço de baixo custo que possivelmente resolverá esse problema. Vou fazer algumas pesquisas. =P
Comment: Relacionado [Recuperar IP Externo sem serviços de terceiros](https://pt.stackoverflow.com/questions/166395/recuperar-ip-externo-sem-servi%c3%a7os-de-terceiros)
Answer: Como explicado nesta resposta não é possivel fazer isto sem depender de um serviço externo:

Não, não é possível. Sua máquina tem acesso apenas ao IP local, fornecido pelo serviço interno de DNS ou setado manualmente.
O IP externo é, na grande maioria das vezes, o fornecido pelo seu provedor para que você seja acessível via NAT (Network address translation), como na imagem abaixo:

NAT categorization according to RFC, Wikipedia
Neste caso você sempre irá precisar de um serviço externo que lhe diga, do ponto de vista dele, com qual IP você está se conectando.

Como obter o IP com serviços externos
Existem vários serviços de terceiros que disponibilizam isto, como por exemplo:

http://ip2country.sourceforge.net/
http://www.whatismyip.org/
https://wtfismyip.com
https://ipinfo.io/ip

No entanto todos eles tem pontos em comum, sendo um serviço de terceiros pode ocorrer de muitas pessoas ao redor do mundo usando uma hora o serviço parar, não estou dizendo para não usar, mas é sempre bom ter um fallback.
Eu diria que um bom caminho seria ter um servidor próprio, geralmente apps mobile usam internet, se o teu app vai disponibilizar acesso a algum dado online para o usuário o melhor seria fazer a checagem do IP neste momento no próprio servidor, um exemplo usando DefaultHttpClient:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://meuservidor/api/ip");

try
{
    HttpResponse response = client.execute(request);

    //Resposta, pode ser uma String
    EntityUtils.toString(response.getEntity());
}
catch (IOException e)
{
    Log.d("error", e.getLocalizedMessage());
}

No entanto se o aplicativo realmente não tem nenhum servidor por qualquer que seja o motivo, "não há mal algum" em usar serviços de terceiros, desde que haja pelo menos um fallback, por exemplo você tenta o serviço 1, se ele falha porque esta fora do ar, você tenta o serviço 2 e assim por diante.
Neste caso seria interessante também colocar um timeout bem curto para não parecer que o aplicativo é lento, por exemplo:
//Configura
HttpParams parameters = new BasicHttpParams();

int timeoutConnection = 2000;
HttpConnectionParams.setConnectionTimeout(parameters, timeoutConnection);

int timeoutSocket = 2000;
HttpConnectionParams.setSoTimeout(parameters, timeoutSocket);

DefaultHttpClient client = new DefaultHttpClient(parameters);

// Começa a requisição a partir daqui...
HttpGet request = new HttpGet(urlDoServico);

No geral o código ficaria assim:
String myIp;

String[] toppings = { "http://servico1.com", "http://servico2.com", "http://servico3.com" };

//Configura
HttpParams parameters = new BasicHttpParams();

int timeoutConnection = 2000;
HttpConnectionParams.setConnectionTimeout(parameters, timeoutConnection);

int timeoutSocket = 2000;
HttpConnectionParams.setSoTimeout(parameters, timeoutSocket);

DefaultHttpClient client = new DefaultHttpClient(parameters);

// Começa a requisição a partir daqui...
HttpGet request;

final Pattern regexValidateIp = Pattern.compile("^\\d{1,3}\\.d{1,3}\\.\\d{1,3}$");

for (int i = 0; i < services.length; i++) {
    request = new HttpGet(services[i]);

    try {
        HttpResponse response = client.execute(request);

        //Pode tratar a a resposta aqui
        String resposeData = EntityUtils.toString(response.getEntity());

        if (regexValidateIp.matcher(resposeData).find()) {
             myIp = resposeData;
             break; //Finaliza o loop
        }
    } catch (IOException e) {}
}

//Exibe o IP
Log.d("IP:", myIp);

Claro que é bom lembrar que alguns retorna JSON, outros retornam HTML, então talvez você possa pegar o header Content-Type e verificar isto, você pode colocar isto dentro de uma Thread ou algo assim, já que a checagem pode levar algum tempo.
Comment: Vlw Bro! Tmj...


How to create new TimeEntryValue in Rally

Question: I'm fairly new to the Rally API and JS, and Stackoverflow for that matter. I have been using Stackoverflow to answer all of my questions so far, but I can't seem to find anything about adding new TimeEntryValues.
I am building an app that allows to add new TimeEntryValues. I can add or load TimeEntryItems but for TimeEntryValues, I ever only seem to post the Hours field when looking at the trace in the browser.
Here is a simplified code that exhibits the same problem.
<code>    launch: function(){
    //For this example, pre-define Time Entry Reference, Date, and Hour value
    var myTimeEntryItem = "/timeentryitem/1234";
    var myDateValue = "2016-05-20T00:00:00.000Z";
    var myHours = 2.5;

    //Check if Time Entry Value (TEV) already exists
    var TEVstore = Ext.create('Rally.data.WsapiDataStore', {
        model: 'TimeEntryValue',
        fetch: ['ObjectID','TimeEntryItem','Hours','DateVal'],
        filters: [{
            property: 'TimeEntryItem',
            operator: '=',
            value: myTimeEntryItem
        },
        {
            property: 'DateVal',
            operator: '=',
            value: myDateValue
        }],

        autoLoad: true,
        listeners: {
            load: function(TEVstore, tevrecords, success) {
                //No record found - TEV does not exist
                if (tevrecords.length === 0) {
                    console.log("Creating new TEV record");

                    Rally.data.ModelFactory.getModel({
                        type: 'TimeEntryValue',
                        success: function(tevModel) {
                            var newTEV = Ext.create(tevModel, {
                                DateVal: myDateValue,
                                Hours: myHours,
                                TimeEntryItem: myTimeEntryItem
                            });

                            newTEV.save({
                                callback: function(result, operation) {
                                    if(operation.wasSuccessful()) {
                                        console.log("Succesful Save");
                                        //Do something here
                                    }
                                }
                            });
                        }
                    });
                } else {
                    console.log("TEV Record exists.");
                    //Do something useful here
                }
            }
        },
        scope: this
    });
}
</code>
Any hints what I am doing wrong are greatly appreciated.
Thanks
Answer: This is actually a longstanding defect in App SDK caused by a mismatch in the WSAPI attribute metadata and the client side models used for persisting data to the server.
Basically what's happening is the DateVal and TimeEntryItem fields are marked required and readonly, which doesn't make sense.  Really, they need to be writable on create and then readonly after that.
So all you need to do in your app is before you try to save your new TimeEntryValue just mark the DateVal and TimeEntryItem fields as persistable and you should be good to go.
<code>//workaround
tevModel.getField('DateVal').persist = true;
tevModel.getField('TimeEntryItem').persist = true;

//proceed as usual
var newTEV = Ext.create(tevModel, {
    DateVal: myDateValue,
    Hours: myHours,
    TimeEntryItem: myTimeEntryItem
});
// ...
</code>
Comment: In the code snippet, 'TimeEntryValue' should actually be 'TimeEntryItem' (as  your explanation says), but otherwise this workaround works great. Thanks.


how can I make date fields come out in other languages in webform with drupal 7

Question: using drupal 7 , and Webform 7.x-3.18 + 3-dev
I need my date field to come out in spanish, mes/dia/ano
but it keeps on coming out with month/day/year
How can I fix this?
thanks
Answer: fixed, I was logged in as an admin and had admin language set to english


Getting rid of print "" when using `display`

Question: I'm trying to create nice slides using jupyter notebook and RISE. One of my objectives is to display a pandas-dataframe in a Markdown cell in order to have some styling flexibility.
I am using the following code to display my dataframe in a Markdown cell:
{{Markdown(display(df_x))}}

After running this line, I get the following result:
image of dataframe displayed
I would like to get rid of the text printed below my dataframe (<IPython.core.display.Markdown object>).
I still haven't found a way to achieve this. Could someone give me a hand?
This is the library I'm working with:
from IPython.display import display

Answer: Not familiar with Markdown class so not sure why you need that but this text printed in the output cell is coming from the fact that this Markdown class is returning and object and since you're not assigning it to any variable the default behavior for the notebook is to run something like str(your_object) which correctly returns <IPython.core.display.Markdown object>.
So the easiest workaround would be to just assign it to some variable like this:
dummy_var = Markdown(display(df_x))

# or better yet:

_ = Markdown(display(df_x))

Comment: It worked great! I actually modified my code this way and it worked like a charm:

`{ { dummy_var = Markdown( display( df_x ) ) } }`
Comment: Glad it works @Roberto919 - if my answer solved your problem then please upvote it and mark it as a solution, thanks!
Comment: Sorry for the late answer @Karol Żak ... your answer did help me a lot and I have already upvoted it. However, my reputation is too low for the upvote to be registered :(   Sorry


How is voice processed in Elliott Smith's Angeles?

Question: I've been wondering how is the voice processed in Elliot Smith's song Angeles.
My guess is that it's duplicated (maybe recorded twice? That would already make them a little different) and then eqed differently, and pitch altered a bit differently on each channel.
I'd like to know if there's someone who could confirm this or complete it. Is it some known technique I'm not familiar with? If anyone has any sources where I could watch or read on similar approaches, I'd be thankful.
Thanks in advance.
Answer: From https://tapeop.com/interviews/118/recording-elliott-smiths-either-or/

The [first two solo] records were totally limited, and there was no
  choice about what to use [gear-wise]. Then I got an 8-track [Tascam
  38], and I had a choice between a couple of different mics. I got a
  compressor [Behringer Composer] and one of those [digital effects]
  boxes that will make any effect that you have the patience to try to
  program [Digitech TSR 24S]. Most of [Either/Or] was done at my house,
  some was done at Joanna's house on a 4-track, and some on 16-track in
  California...

So it looks like most of Either/Or the album that Angeles was on, was recorded with his Tascam 38. He always layers his voices though there's nothing too special about it, so either overdub or a separate track. Not sure why he used a Tascam 38, that's super old. Like 1982 old. Elliott Smith was a genius though, so he must've had his reasons.


tool to observe the .NET Remoting communication between applications?

Question: We have problem with the communiction between two applications. According to the software providers, the communication is akind of .NET Remoting. We just want to verify which program first closes the communication, hopefully it could shed light for further debugging.
Is there any tool to facilitate the observation of .NET Remoting communication?
Comment: Is it "a kind of remoting" (which could mean anything), or is it ".NET Remoting" (a specific technology)? Also: ethereal/wireshark
Comment: @Marc Gravell It is about .NET Remoting. The two applications are running on one box/computer. Is there any links to configuration of wireshark for such cases?
Comment: To be onset, I think you would do better to just describe the actual problem you are seeing...
Comment: @Marc I'm software user instead of programmer of the two softwares. The two applications are simply black boxes for me. One application is observed to change one of its states which COULD be due to the .NET Remoting communication to the other application, but we don't have much experience on this technology.
Comment: That is a tricky problem and I don't have an easy answer for you. Even access to the network protocol won't make it easy t see what is *actually happening*. This sounds like a problem for the developer/vendor, with access to tools, debugging symbols, etc
Answer: First: It isn't the end user's responsibility to figure this out: your software vendor(s) should be working together to figure out why these two applications are not communicating properly with one another.
My Answer: You can use Ethereal or Wireshark to monitor network connections and figure out which application is closing the network connection first.


Football fields that are approximately square

Question: According to Wikipedia, an association football pitch:

"…is rectangular in shape. The longer sides are called touchlines. The other opposing sides are called the goal lines. The two goal lines must be between 45 and 90 m (50 and 100 yd) and be the same length. The two touch lines must also be of the same length, and be between 90 and 120 m (100 and 130 yd) in length."

This seems to imply that it would be theoretically possible for a football club to build a stadium around a (valid) square pitch with dimensions 90m x 90m.
My question is are there any examples of prominent* football teams/matches using a pitch that is close* to square in shape?

*The words 'prominent' and 'close' are deliberately open to interpretation because I have no idea how common variation in pitch size/shape is, or what the degree of standardisation is at various competitive levels within the game.
Comment: The full [Laws of the Game](http://www.thefa.com/~/media/files/pdf/the%20fa%202015-16/laws-of-the-game-2015-16.ashx) include "The length of the touch line must be greater than the length of the goal line" (page 7). This means a pitch can't be square... but it can be 90.01m x 90.00m so your question basically still applies.
Comment: Also note that the Laws do not specify the field of play must be (exactly) horizontal. In lower competitions, you can find pitches which are visibly uphill. (But that is one of the reasons teams swap sides.)
Answer: No, it is highly unlikely that any prominent football teams use a pitch that is close to square in shape.
On page 7 of the 2015/16 FIFA Laws of the Game it states:

The length of the touch line must be greater than the length of the goal line.

This means that it is theoretically possible for a football field to be close to square (eg. 89m x 91m).
However, most clubs will try to construct a field as close as possible to international sizing to provide a consistent experience for players and spectators:

International matches
Length:

minimum 100 m (110 yds)
maximum 110 m (120 yds)

Width:

minimum 64 m (70 yds)
maximum 75 m (80 yds)

Many football associations will not allow clubs to participate in competitions with a field with dimensions that greatly differ from international sizes.
The FA, for example, for football clubs in England, suggests the following dimensions (which correspond to the minimum international size) in The FA Guide to Pitch and Goalpost Dimensions (pdf link) on page 3 (quoted from a table):

The FA Recommended Pitch Sizes
Over 18 (senior ages) (Age grouping)
11 v 11 (Type)
110 x 70 (Recommended size without runoff (safety area around pitch))
(Length x width (yards))

Many higher-level leagues have a number of criteria for entry aside from first-team performance, and one such criterion is ground facilities. This criterion includes not only dressing rooms, lighting and spectator seating, but also the quality of the field. A field with dimensions completely inconsistent with others in the league is likely to be seen as inadequate.
The reason that such a large range of sizes are still allowed, is that football is played in a variety of locations - some in which the land is not readily available to construct an international-sized pitch.
It may be possible to find a nearly-square pitch in recreational leagues in developing nations, but once a club has reached a semi-professional league (ie. a league in which some players receive some remuneration, but not enough to derive a steady income) it will have a pitch with dimensions that are very close to, if not consistent with an international-sized pitch.


A simple reason that $\text{Tor}(\mathbb{C}^{*}) \neq S^1.$

Question: Let $\mathbb{C}^{*}$ denote the group of nonzero complex numbers under multiplication, and $S^{1} \subset \mathbb{C}^{*}$ the subgroup of complex numbers of length one. Torsion elements of $\mathbb{C}^{*}$ are called roots of unity.
Show that $\text{Tor}(\mathbb{C}^{*}) \subset S^1.$ Now give a simple reason that $\text{Tor}(\mathbb{C}^{*}) \neq S^1.$
My question is:
1- I know from here Torsion subgroup of $\mathbb{C}^\times$ that the torsion elements are the roots of unity, but I do not know how to prove that $\text{Tor}(\mathbb{C}^{*}) \subset S^1.$ could anyone help me in writing a rigorous proof for that, please?
2- What is a simple reason that $\text{Tor}(\mathbb{C}^{*}) \neq S^1$?
EDIT:
My definition of $S^{1}$ is $\{ z \in \mathbb{C^{*}\ :\ |z|=1 }\}$
Comment: 2. There are irrational numbers.
Comment: @AnginaSeng do you mean in $Tor(\mathbb{C}^*)$ or in $S^1$ ?
Answer: Here is an algebraically concise way to answer your questions:

In general, if $f \colon G \to G'$ is a morphism of abelian groups it must map the source torsion subgroup to the target torsion subgroup, in other words $f[\mathrm{T}(G)] \leqslant \mathrm{T}(G')$. In your particular case, the absolute value map $z \mapsto |z|$ implements a morphism between the multiplicative groups $\left(\mathbb{C}^{\times}, \cdot\right)$ and $\left(\mathbb{R}^{\times}_{+}, \cdot\right)$, which means that it must map $\mathrm{T}\left(\mathbb{C}^{\times}\right)$ into the torsion subgroup of $(0, \infty)$. However, this latter group is totally ordered (by the standard order) and thus has trivial torsion. This means that $\mathrm{T}\left(\mathbb{C}^{\times}\right) \subseteq |\bullet|^{-1}[\{1\}]=\mathbb{U}$ (my notation for the circle group) and therefore that $\mathrm{T}\left(\mathbb{C}^{\times}\right)=\mathrm{T}\left(\mathbb{U}\right)$.
As an abelian group (even as a topological group), the unit circle $\mathbb{U}$ is isomorphic to the quotient $\mathbb{R}/\mathbb{Z}$ of the additive group $(\mathbb{R}, +)$ (this is intimately related to the complex exponential). It is very easy to show that $\mathrm{T}\left(\mathbb{R}/\mathbb{Z}\right)=\mathbb{Q}/\mathbb{Z}$, in other words the torsion subgroup of this latter quotient group is a proper subgroup. This entails the fact that the inclusion $\mathrm{T}(\mathbb{U}) \subset \mathbb{U}$ is proper (strict), otherwise the circle group $\mathbb{U}$ would itself be torsion (and we have seen it can't be, since it is isomorphic to a group strictly containing its torsion subgroup).
Comment: But the circle group in my question is defined as a subgroup of complex numbers so it is not totally ordered as $(\mathbb{R}^{\times}_{+},.)$ .... your point of view is not clear for me in $1.$
Comment: @Smart20 The circle group is of course defined as a subgroup of the multiplicative group of *nonzero* complexes (that is the only possible definition, all others being characterisations or isomorphic descriptions) and no one stated anything about it being totally ordered, it cannot be and doesn't have to be for the purposes of my argument. My point was that *morphism* necessarily takes torsion subgroups to torsion subgroups, so this applies in particular to the morphism given by the absolute value *(to be cont.)*
Comment: @Smart20 *(cont.)* morphism which allows you to infer that the *absolute value* of any torsion element in $\mathbb{C}^{\times}$ is a torsion element of $\mathbb{R}^{\times}_+$. It is at this stage that total orders come into play: since this latter multiplicative group of strictly positives is totally ordered, it necessarily has trivial torsion, which means that the absolute value of any torsion element of $\mathbb{C}^{\times}$ must be $1$. This is exactly the result you sought a proof of.
Answer: For a point $z=re^{i\theta}$ with $r>0$ and $\theta\in \Bbb R$ is torsion element if and only if $z^n=1$ for some $n\geq 1$. In particular, $z$ is torsion element implies $|z|^n=|z^n|=1$, so that $r=|z|=1$. Therefore, $z=re^{i\theta}$ is torsion if and only if $z=e^{i\theta}$ for some $\theta\in \Bbb R$ with $z^n=e^{in\theta}=1$. Now, we know that $e^{i\theta}=\cos(n\theta)+i\sin(n\theta)=1\iff\cos(n\theta)=1$ and $\sin(n\theta)=0\iff \theta=\frac{2m\pi}{n}$ for some $m\in \Bbb Z$.

Combining all these a non-zero element $z$ is torsion if and only if
$z=e^{i\frac{2m\pi}{n}}$ for some $n\in \Bbb N$ with $m\in \Bbb Z$.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/113031/discussion-on-answer-by-sumanta-a-simple-reason-that-texttor-mathbbc).


Comparando strings com switch em PHP

Question: A questão é esta:

Uma empresa irá dar um aumento de salário aos seus funcionários de
acordo com a categoria de cada empregado. O aumento seguirá a seguinte
regra:

Funcionários das categorias A e H ganharão 10% de aumento sobre o salário;

Funcionários das categorias B, D e E ganharão 15% de aumento sobre o salário;

Funcionários das categorias K e R ganharão 25% de aumento sobre o salário;

Funcionários das categorias S ganharão 35% de aumento sobre o salário;

Funcionários das categorias X e Z ganharão 50% de aumento sobre o salário.

Funcionários das demais categorias ganharão 5% de aumento sobre o salário.

Utilizando o comando "Switch", escreva um algoritmo em PHP para
receber categoria e salário atual, em seguida exiba o salário
reajustado de um empregado para exemplo.

Eu fiz este código:
<?php

$salario = 1045;
$salarioFinal = 0;
$percentagem = 0;

$categoria = 'A';

switch ($categoria) {
    case 'A' or 'H':
        $percentagem = $salario * 10 / 100;
        $salarioFinal = $salario + $percentagem;
        echo "Salário atual: $salario
";
        echo "Salário final: R$ $salarioFinal";
        break;

    case 'B' or 'D' or 'E';
        $percentagem = $salario * 15 / 100;
        $salarioFinal = $salario + $percentagem;
        echo "Salário atual: $salario
";
        echo "Salário final: R$ $salarioFinal";
        break;

    case 'K' or 'R';
        $percentagem = $salario * 25 / 100;
        $salarioFinal = $salario + $percentagem;
        echo "Salário atual: $salario
";
        echo "Salário final: R$ $salarioFinal";
        break;

    case 'X' or 'Z';
        $percentagem = $salario * 50 / 100;
        $salarioFinal = $salario + $percentagem;
        echo "Salário atual: $salario
";
        echo "Salário final: R$ $salarioFinal";
        break;

    default:
        $percentagem = $salario * 5 / 100;
        $salarioFinal = $salario + $percentagem;
        echo "Salário atual: $salario
";
        echo "Salário final: R$ $salarioFinal";
        break;
}

?>

O problema é que ele sempre pula para a condição default retornando:
Salário atual: 1045
Salário final: R$ 1149.5

ou seja, não está comparando a string conforme a variável $categoria = 'A'; declarada no começo do código.
Answer: Não dá erro (inicialmente eu achei que dava por isso respondi, na verdade o código faz exatamente o que deveria fazer, eu não sabia que o PHP permitia a sintaxe usada). Fiz de um jeito que é correto e de forma muito mais simplificada evitando repetição de código e depois de observar que não tem erro, a resposta fica só por conta da simplificação.
Todo o switch pode ser trocado por 1 linha, mas não alterei para não fugir do pedido no enunciado.
<?php
$salario = 1045;
$categoria = 'A';
switch ($categoria) {
    case 'A':
    case 'H':
        $percentagem = 10;
        break;
    case 'B':
    case 'D':
    case 'E';
        $percentagem = 15;
        break;
    case 'K':
    case 'R';
        $percentagem = 25;
        break;
    case 'X':
    case 'Z';
        $percentagem = 50;
        break;
    default:
        $percentagem = 5;
        break;
}
$salarioFinal = $salario + $salario * $porcentagem / 100;
echo "Salário atual: $salario
";
echo "Salário final: R$ $salarioFinal";

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Entenda que o break é justamente para dizer que encerrou a ação selecionada no switch. Se não tiver um ele continua executando o que está abaixo, então ele pode aceitar múltiplos case com a mesma ação. Dá até para fazer uma combinação de ter uma parte igual para vários, mas ter uma parte em cada case individual.
Não mudei mas o ideal seria ser mais organizado e ir progredindo todos pra frente ou para trás, um deles (o default - 5) quebrou a sequência lógica e fica menos legível. Parte de culpa é o enunciado.

Comparando strings com switch em PHP


Best way to manage custom ports in SELinux

Question: On RHEL 6.2, we're using httpd on a host as a front-end proxy for Tomcat on another host, and we also have mod_status configured to listen on a non-standard port to provide status info to a monitoring tool.  Therefore, we need httpd to 1) establish network connections, and 2) listen on a non-standard port.
The default targeted policy (currently in permissive mode) only allows httpd to listen on a defined list of ports (semanage port -l | grep http_port_t), and won't allow httpd to make outbound network connections.  aureport -a shows the AVC denials when httpd tries to bind to the custom status port, and when it tries to connect to the AJP ports on the other host.
I found two solutions, but one seems too permissive, and the other too brittle (i.e. likely to break upon policy upgrade).
"Broad" solution
I used audit2allow to generate a local policy source, then checkmodule to compile it, semodule_package to generate a policy package, and semanage to start enforcing it.  I then restarted httpd, and confirmed that no AVC denials were generated.  The local policy generated by audit2allow used the following grant:

allow httpd_t port_t:tcp_socket { name_bind name_connect };

which allows httpd to bind to any port (not just those listed in http_port_t), and to connect to any port.  The pro of this approach is that its contained in a local policy, and won't get overridden on the next yum update.  The con is that it grants more broad permission than is necessary; httpd can bind and connect to any port.
"Narrow" solution
The alternative for binding is to use the following command to add our custom port to the http_port_t list:

semanage port -a -t http_port_t -p tcp (custom-port-number)

I know I can see the list of ports under http_port_t using semanage port -l | grep http_port_t, but I don't know where this list is stored, and don't know if the next yum update with a new policy will overwrite the list.
The alternative for connecting is to use the following command to create a new port list:

semanage port -a -t ajp_port_t -p tcp 9010

and then create a local policy with the following:

allow httpd_t ajp_port_t:tcp_socket { name_connect };

Just like the augmented http_port_t list, I don't know if my new ajp_port_t list will survive installation of a new targeted policy version.
Answer: semanage creates new modules which are not under the control of the policy package. When the policy package is upgraded, these modules will remain and will be applied to the new policy when it is loaded.
Comment: Thanks!  I looked into this further and found that `semanage port` commands caused the creation or modification of `/etc/selinux/(policy-name)/modules/active/ports.local`.  I also was able to define a new port list (e.g. ajp_port_t) in a local policy, activate that policy, and then use semanage to populate ajp_port_t.


How to access to non unique subclass of every element during iteration with Selenium?

Question: I am iterating through elements on the website with XPath of each element.
//*[@id="app"]/div[1]/main/div[2]/section/div/section/div[4]/div[1]/div[X]

X values: from 1 to n. Where X is an ordinal number of the element.
xpath.getText() give me the name and price of current item.
I want to download the image also. Class name for the image isn't unique. It same for every element: "shop-card__image-block".
How to access"shop-card__image-block" for every element? I want to take the link to the image and download it with the name and price.
See the images.
First image
Second image
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Use element.findElement(By by) or element.findElements(By by) to get child element(s). See https://www.tutorialspoint.com/locating-child-nodes-of-webelements-in-selenium.
Answer: Code :
WebDriverWait wait = new WebDriverWait(driver, 30);
int divSize = driver.findElements(By.xpath("//*[@id='app']/div[1]/main/div[2]/section/div/section/div[4]/div[1]/div")).size();

for (int i = 1; i<= divSize; i++) {
    WebElement parentDiv = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='app']/div[1]/main/div[2]/section/div/section/div[4]/div[1]/div['"+i+"']")));
    WebElement image = parentDiv.findElement(By.xpath(".//descendant::div[contains(@class,'shop-card__image-block')]"));

    // now image is a web element, you can perform a click on it like image.click(); or any other operation.
}

now image is a web element, you can perform a click on it like image.click(); or any other operation.
trust this helps.
Comment: I made it already on this way:

`private By slika = By.tagName("img");`
`var linkSLike = driver.findElement(By.xpath("//*[@id=\"app\"]/div[1]/main/div[2]/section/div/section/div[3]/div[1]/div["+i+"]")).findElement(slika).getAttribute("data-src");`

Thanks anyway
Comment: Well, I wasn't aware of that. Since there wasn't any note/comment on your post. Anyway, Glad you made it to work.


On-line detection of changing in a time series

Question: I would like to know what is the best approach to detect on-line the occurrences of a new steps or changes in a time series.
I've attached a picture of the time series I'm talking about. I would be able to detect the step indicated by the red arrow.

Each data point is collected every 2 seconds and I need to detect the changes in the time series as quick as possible, i.e. considering at most 5 samples ahead and avoiding if it is possible the outliers.
I'm completely stumped on how I might be able to do this - any ideas?
I have read something on Bayesian Analysis but before studying in depth I would like to know if there are other useful approach in term of detection speed, robustness to outliers and detection accuracy.
Thanks for your help.
Comment: Possible duplicate of [Determine breakpoints in time series data where values change significantly](http://stats.stackexchange.com/questions/174906/determine-breakpoints-in-time-series-data-where-values-change-significantly)
Comment: @Aksakal This question differs from the apparent duplicate in that it requires the changepoints to be detected without looking too far ahead.
Comment: It's impossible to do. Look at x=1444739000. There's no way to distinguish this jump from the marked point in 5 secs. It takes at least 20 secs.
Comment: I know that it is impossible in 5 seconds, but I have written in 5 samples where each sample is taken every 2 seconds. But the problem is that I need to detect a abrupt changes (the beginning and the end) in a short time, where a time series has this changes only when there are an abrupt changes in the workload to.
Answer: Bayesian filter under the markov-chain assumption is the best tool for this kind of question. The basic idea is to use the past sampling to get your prior, then try to predict the current sample. The online detection is done by threshold on the prediction error.
Things like Kalman filter or particle filter is fairly easy to implement. Depending on what computer language you are familiar with, there are many parkage you can use out of the box.
Comment: Can you suggest me any example in R, applicable only a single vector which represents my time series?
Answer: The preferred approach is to use Intervention Detection procedures which can incorporate any appropriate ARIMA structure while isolating anomalies (pulses) . One can set the minimum, number in a group ( in your case 5 ) while also being able to optionally set a minimum change in step/level change that may be required in order to avoid false positives. The user simply specifies a level of confidence.
Answer: (Edited as per comments below)
Generalized fluctuation tests (GFL) (Kuan and Hornik 1995; Kuan 1998) and F tests (Hansen 1992; Andrews 1993; Andrews and Ploberger 1994) are of the most important classes of tests on structural change. Zeileis 2002 has reviewed such tests for monitoring structural change where new observations arrive over time.
References,

C.-M. Kuan and K. Hornik. The generalized fluctuation test: A unifying
  view.  Econometric Reviews, 14, 135-161, 1995.
C.-M. Kuan. Tests for changes in models with a polynomial trend.
  Journal of Econometrics, 84, 75-91, 1998.
B. E. Hansen. Tests for parameter instability in regressions with I(1)
  processes. Journal of Business & Economic Statistics, 10:321–335,
  1992.
D. W. K. Andrews. Tests for parameter instability and structural
  change with unknown change point. Econometrica, 61:821–856, 1993.
D. W. K. Andrews and W. Ploberger. Optimal tests when a nuisance
  parameter is present only under the alternative. Econometrica,
  62:1383–1414, 1994.
A. Zeileis, F. Leisch, K. Hornik, and C. Kleiber. strucchange: An R
  package for testing for structural change in linear regression models.
  Journal of Statistical Software, 7(2):1–38, 2002.

And try this implemented tool that performs online change detection?
strucchange: Testing, Monitoring, and Dating Structural Changes
Comment: This should be a comment.


Horário errado no MongoDB

Question: Quando coloco no schema do MongoDB:
created: { type: Date, default: Date.now }

A hora está com uma diferença de 3 horas a mais.
Como eu posso corrigir isso?
Answer: O MongoDB trabalha com UTC, ou seja, fuso horário sem ajustes. Você sempre terá que considerar isso na hora de usar Date.
Como no Brasil os fuso horários são de -3h e -4h você sempre verá as horas a mais do que a sua atual.
Infelizmente não há nenhuma maneira real para corrigir essa exibição dentro do MongoDB :(, mas se você pensar por outro lado isso também é bom, pois isso significa que você pode ter muitas aplicações em diversos fusos horários e todos eles podem trabalhar a partir de uma data fixa (UTC).
Comment: Obrigado Douglas.
Answer: Quanto à leitura, use timezone após a data. P.ex., Brasil GMT-3:00 fica -300. Veja exemplo:
{
        $project: {
            "iso_date_field": 1,
            "hour": { $hour: { date: "$iso_date_field", timezone: "-0300" } },
            "hour2": { $hour: { date: ISODate("2020-08-14T02:08:04.000-03:00"), timezone: "-0300" } },
            "hour3": { $hour: { date: new Date(), timezone: "-0300" } }
        }
}

Não sei dizer quanto à gravação, mas acho que se deve passar a data normalmente...
Answer: Já faz 7 anos a pergunta, mas caso alguém precise
created: { type: Date, default: () => Date.now() - 3*60*60*1000 }

isso pega a hora atual e coloca no item.
estou usando mongoDB atlas e trato isso na api em node.js
(explicando pq deram downvote sei lá pq, ent vim explicar esses pontos kk)

Horário errado no MongoDB


Rendering differences between browsers when using an SVG as a CSS list-style-image

Question: I have created a very simple SVG that is just a red circle to use as the list-style-image for my website. I got the idea for this from this SO answer: https://stackoverflow.com/a/19528768/201021
This solution works great except in Internet Explorer. In fact every other browser except IE renders the lists the same way. In IE the SVG image renders a bit larger and sometimes the edges are slightly cut off. See the examples below:
Internet Explorer:

Chrome:

Even with a fixed height & width set in the SVG file it does not render correctly in IE:

The edges are still sometimes cut-off and the markers don't appear to be vertically centered like they should be.
Even when the markers are very small it does not render correctly:

You can see the marker for the third level has edges cut-off.
Also, explicitly setting the height and width instead of using a viewbox means that the markers no longer auto-scale when the font-size is increased which is one reason I chose to go this route.

SVG code for redcircle.svg:
<?xml version="1.0"?>
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
    <circle cx="50%" cy="50%" r="50%" fill="red" />
</svg>

HTML:

            Bullet one

                Bullet level two

Bullet level three

CSS:
ul li {
  list-style-image: url("Images/redcircle.svg");
}

I can't really figure out why this is happening except that IE must be doing something different from the other browsers during the rendering of the SVG. Maybe the default size for a list marker in IE is larger or expandable?
I'm a bit at a loss at what to test as well. I've tried changing the viewBox values in the SVG but I've never written an SVG before so I'm not really sure what I'm doing.
Does anyone know why this is happening? Even better does anyone know a workaround to get the SVG to render the same in Internet Explorer?
Comment: See https://stackoverflow.com/questions/29932657/how-can-i-make-a-list-style-image-scale-with-the-lists-font-size-when-we-cant for similar issue. Solved by using :before pseudo element. For the clipping, simply make the circle a bit smaller inside the viewbox and try to make it a non-whole pixel radius at 1em to avoid some browser rendering issues.
Comment: @Ruskin that does indeed look like it will work. Unfortunately I'm no longer working on this project so it's a moot point now but the info is much appreciated. =)
Comment: Can you share your code that renders the images above? Your current code sample just creates one disk filling a window.
Comment: I've added the relevant HTML and CSS. Do note that the HTML is created from a jQuery rich text editor control (jquery-te), but that shouldn't matter.
Comment: Have you tried setting the `height` and `width` for the svg instead of using `viewbox`?
Comment: @imtheman By setting the height and width in the SVG it does make sure that the image doesn't render larger than the other browsers but it still doesn't work quite right in IE. It also loses the ability to have the markers auto-scale when the font size increases. (I've updated the question with examples.)
Comment: Possible duplicate of [How can I make a list-style-image scale with the list's font size, when we can't use glyph fonts?](https://stackoverflow.com/questions/29932657/how-can-i-make-a-list-style-image-scale-with-the-lists-font-size-when-we-cant)
Answer: try declaration of svg code like so:
<svg version="1.1" id="yourID" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="8px" height="8px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">

Set desired width and height instead of 8px, that should do, though i have no time to test it now, it should work)


Program Requires Optimization for Minimum Cost

Question: Here is the problem:
Cost analysis is an important part of engineering. When you are in practice, you may be asked to write programs to determine the minimum cost for a number of different potential circumstances. Your programs can be used as decision making tools for a project.
Consider the building of an airport with the runway being built on landfill. The contractor has two dump trucks, one with a capacity of 8 tons and the other with a capacity of 12 tons. The contractor uses the trucks to haul fill from a remote site to the airport location. The operating cost per trip for the 8 and 12 ton trucks is $14.57 and $16.26, respectively. One truck cannot make more than 60 percent of the total trips.
Write a program that develops the minimum cost for a given number of tons. Prompt the user to enter the total number of tons. Display the number of trips required for each truck and the total cost. Use a modular design for this program.
Here is my attempt:
<code>#include <stdio.h>

int main (void)
{
    double mass, sixtyPercentMass;
    int eightCount = 0, twelveCount = 0;

    printf("Enter the number of tons: ");
    scanf("%lf", &mass);
    sixtyPercentMass = 0.6 * mass;

    while((twelveCount*12) < sixtyPercentMass) {
        twelveCount++;
    }
    while((eightCount*8) < (mass - sixtyPercentMass)) {
        eightCount++;
    }

    printf("Total trips required: %d\n", (twelveCount+eightCount));
    printf("Number of 12-ton trucks required: %d\n", twelveCount);
    printf("Number of 8-ton trucks required: %d\n", eightCount);
    printf("Total cost: $%lf", (twelveCount*16.26 + eightCount*14.57));
    return 0;
}
</code>
Questions:

How would I account for wasting empty space in trucks?
Currently, if you have 1 left over, it wastes an entire truck. It would actually be cheaper to use a number of trucks that matches the required mass exactly.
How would I properly do the 60% threshold for total trips correctly?
It currently only does 60% of mass.

Pseudocode or a step in the right direction for the logic required would be helpful.
Comment: What is your question for the SO audience?
Comment: closing the question as too localized :-)
Comment: What does that mean, Aniket?
Answer: First, you need to separate out the problem from the program.  Attempting to solve for both in one step has you discovering what is needed for your problem as you are dealing with what is needed to get your problem running as software.
To optimize the minimum number of trucks, you should come up with a way that assures no unneeded trucks are used.  One way is to try out using the maximum number of smallest trucks, and "reduce" the solution by swapping out smaller trucks with bigger ones.  Another way is to use the largest trucks available and to then check for partially full trucks which could be substituted with smaller trucks.
However you approach the problem, it doesn't require a computer to figure it out.  Once you can solve the problem to some degree without a computer (even if the scheme is only in your head) then you can set down to the task of writing a program that would do the tasks necessary to implement your solution.
Starting out with the writing as the first step is very much like building a house by beginning to cut and hammer wood, and then wondering later how you're going to eat with no external doors, kitchen, power lines in the walls, etc.
Comment: Okay, I've decided to tackle question 2 as it is the bigger problem of the two. The issue is that I don't know how to solve the problem without the use of a computer. Honestly, it seems like a paradox to me. For example: suppose that I want to move 120 tons of mass. But how do I know the number of total trips?  I guess I can divide 120 by 12 to get 10 trips. And 60% of that would be 6 trips. (continued to my next comment)
Comment: But because I need 10 trips of 12-ton trucks, I am exceeding the 60% threshold, and therefore, I need to use 8-ton trucks. As soon as I start using 8-ton trucks, the original total number of trips increases and therefore, I know need to recalculate the 60% threshold which means that I might've been able to use 10 12-ton trucks after-all!
Comment: A percentage is is a percentage of _something_, since you haven't stated it yet, I'm going to assume that you must use no more than 60% 12 ton trucks.  In which case, you either start out with 8 ton trucks, remove a few, and see if that leaves you with more that 60% 12 ton trucks, or you work from the other end, combining 8 ton trucks into 12 ton trucks, and then checking the appropriate answer, or you just use that odd thing called Algebra and solve the problem without a loop to check and modify the possible answer.