Unable to install ... already exist in active configuration

Question: On Drupal 8.1 I keep running in those kind of messages when I try to activate a custom module or a custom feature that makes some modification to the basic page. (add fields).
It is really annoying...
Steps:

Clear database entirely
go to /install.php and choose Standard profile
Now that the site is running go to Extend
Select Feature - Basic page

Result:
Unable to install Feature - Basic Page, core.base_field_override.node.page.promote, core.entity_form_display.node.page.default, core.entity_view_display.node.page.default, core.entity_view_display.node.page.teaser, field.field.node.page.body, node.type.page already exist in active configuration.
Well yeah... that is what I want to do: Change those default settings!
Expected:
Be able to install my feature that makes some modifications to the basic page.
My Feature
Here is my Feature create with the Features module
It basically adds two fields, banner_image and background_image to the basic page
Files:
config
    install
        core.base_field_override.node.page.changed.yml
        core.base_field_override.node.page.created.yml
        core.base_field_override.node.page.promote.yml
        core.base_field_override.node.page.status.yml
        core.base_field_override.node.page.sticky.yml
        core.base_field_override.node.page.title.yml
        core.base_field_override.node.page.uid.yml
        core.entity_form_display.node.page.default.yml
        core.entity_view_display.node.page.default.yml
        core.entity_view_display.node.page.teaser.yml
        field.field.node.page.body.yml
        field.field.node.page.field_banner_image.yml
        field.field.node.page.field_image.yml
        field.storage.node.field_banner_image.yml
        language.content_settings.node.page.yml
        node.type.page.yml
feature_basic_page.features.yml
feature_basic_page.info.yml

Why this simple thing is not supported? Is it a bug? What should I do to be able to use my feature?
Comment: Use drupal [EasyInstall](https://www.drupal.org/project/easy_install)  module which  is used to  remove active configurations
Comment: +1 interesting module - worth a look - thank you @KarthikeyanManivasagam
Answer: With Drush, you can run drush config-delete module_name.settings to delete the configuration causing the error.
When not sure about what to delete, you can drush config-get | grep your-keywords  to find the correct name to feed config-delete with.
Comment: if you are not sure what "settings" do you have to delete, you should run "drush config-list"  to get the exact name of the configuration
Comment: I also discovered during my epic battle against Drupal that you can move those configs in a `optional/` folder to make it shut up. But I am not sure of all the implications...
Comment: @GuillaumeBois : the implications are that these optionnal configurations would be ignored if already installed, or if dependencies are not met. So, it can lead to further problems if the configuration is necessary for the module to work.
Comment: doesn't work with configs which depends on language, for example config that name is like `language/fr/module_name.settings`
Comment: Deleting `module_name.settings` did not fix the issue for me - but listing all the settings with `drush config-delete` and then identifying and deleting the culprits (fields added to a custom content type) like this `drush config-delete field.storage.node.field_my_custom_field` helped.
Answer: Use  the Easy Install module to purge the active configuration without using the Devel module or Drush. It works even if you have missed out the optional folder and the enforced option in the module's configuration files.

A module built to resolve and avoid the error "Unable to install already exists active configuration" when re installing/un installing the drupal 8 modules , it works even if the module's configs not contains enforced in yml and not added configs in optional folder. It purge the active configuration object of uninstalled modules and helps to remove configuration object while uninstalling a module without using Drush / Devel / Drupal Console / Features Modules.
Answer: For a Pantheon site, I used the following Drush commands.

On the Pantheon site, drush @pantheon.SITENAME.ENVNAME config-delete ERRORNAME
On the local site, drush config-delete ERRORNAME
Answer: This thing is not supported because a module may not replace a config entity that already exists with install config.
To add form and view mode configurations for an already existing node type, you have to implement this in code in hook_install().
Or you have to delete the node type first on your site, but then you also have to delete the content.
And no, this is not a bug, this is how it is defined to prevent loss of configuration.
Comment: This is very sad. In D7 this was possible (add fields to a basic page through a Feature). I still think it should be in D8 too. You say it is to prevent loss of configuration, but in reality, it simply adds configurations (fields, weight, label, etc.). Note that I also had this problem with my own custom modules.
Comment: No, it doesn't just add. the view and form displays are shared across all fields of a single node type. what happens if two modules try to add that file, who's going to win? What happens about existing fields that already are on the page type? what if the basic node type exists but with different settings than in your field? The behavior scenarios like that is not defined.  For a standalone feature, you're better off defining your own node type and to deploy this change on your own site, you don't need a feature module like in 7.x, you can just export the configuration and import it again.
Comment: @berdir this is very interesting.  So I am coming from this issue from trying to create a user profile feature that includes view and form notes.

So are you saying this can't be done in features because the user content type will have already existed and the feature is trying to enable that?

Is there some way to allow a feature to override this so that someone could enable a profile feature on an already existing site?
Comment: @kaleemclarkson user is not a content type but an entity type. The only way to do it is what I described, you have to implement code in hook_install() of your feature module to set form and view display configuration. Or use the profile module and define your own profile type there.
Answer: With drush en it works!
[profile_test]$ drush en feature_basic_page -y
The following extensions will be enabled: feature_basic_page
Do you really want to continue? (y/n): y
feature_basic_page was enabled successfully.   [ok]

EDIT: there is a way better solution now, see: How do I remove a configuration object from the active configuration?
Answer: Sometimes modules do  not cleanly uninstall. Trying to re-enable a newer version would cause then this issue.
Do a DB backup first and run the following:
drush @site.env sqlq 'DELETE FROM config WHERE name LIKE "%module_name%";'

Comment: How to do this in case of a multi-site database?
Answer: Let's say that you don't want to lose your settings for the module that somehow — on it's own — decided to become disabled. Do this:
(optional)
a) Backup your whole database. Put that someplace safe, just in case! ;-)
mysqldump -u {db_user} -p{db_pass} {database_name} > maybe-horrible-things-will-happen.sql
# HINT: no space after "-p"

b) Backup your whole Drupal config:
drush config:export --destination=/some/path/where/this-folder-will-be-created

Your sites current configuration will get dumped into this-folder-will-be-created.
SEE: https://drushcommands.com/drush-9x/config/config:export/ for more info.
ASIDE: a and b aren't really optional ... because Drupal 8 does bad things, for no good reason, all the time; you better have a backup!
(END optional)
STEP 1) Tell drush to open the config file for core.extension:
drush config:edit core.extension

ASIDE: This uses whatever editor your shell has set for the VISUAL environment var; mine is: VISUAL=vim
STEP 2) Add the missing keys under the module key. Here's an example:
module:
  commerce_square: -2
  action: 0
  address: 0
  # ... [lots of others] ...
  draggableviews: 0
  # ... [lots of others] ...
  media: 0
  # ... [lots of others] ...
  site_settings: 0
  # ... [lots of others] ...
  scss_compiler: 1
  views: 10
  demo_commerce: 1000
theme:
  bootstrap: 0

STEP 3) Save your edits and drush will proceed to do some horrifying Drupaly voodoo that magically re-enables your modules without losing your work.
ASIDE: I'm pretty sure that the : 0 but is the module weight because of the last entries in my config. I left three examples: scss_compiler, views, and demo_commerce, to illustrate the point.
Errors I saw.
If drush spits out an error like...
[error]  Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization.
  Configuration views.view.product_sorter depends on the DraggableViews module that will not be installed after import.

... then you'll need to add that key under module: also. I was trying to save site_settings and had no idea that draggableviews and media has also decided to go on holiday.
After adding media and saving the edit again, then I got the notification for draggableviews. Then after adding both media and draggableviews in the next go around, other bad things happened; read on...
If drush spits out an error like...
Table 'draggableviews_structure' already exists.

... then you might have to backup that table, delete the modules tables, and try again.
ASIDE: You can find out what the tables are for a given module by examining it's hook_schema() implementation, within it's module_name.install file. For example, the draggableviews.install file has this entry:
/**
 * Implements hook_schema().
 */
function draggableviews_schema() {
  $schema['draggableviews_structure'] = [
  //...
}

I didn't end up having to do that for the draggableviews_structure table, but here's how you'd go about that unpleasant task:

Dump the modules tables, then after you're sure you have the modules data, drop the modules tables.

mysqldump -u {db_user} -p{db_pass} {database_name} draggableviews_structure > draggableviews_structure.sql

mysql -u {db_user} -p{db_pass} {database_name} -e 'drop table draggableviews_structure'

re-edit the core.extension config; STEPs 1–3 above.
Answer: If you want to add configs to your custom module but they already exist in the active configuration, and for some reason you can't use drush to delete those configs (in my case because it's part of an install profile), and you are sure there won't be a problem with you overwriting the config, here's an approach to replacing those configs.
Add a new folder in your custom module, /config/hook_install and add your config .yml files in that folder, then in your module's hook_install.
use Drupal\Component\Serialization\Yaml;

/**
 * Implements hook_install().
 */
function mymodule_install() {

  // Replace these configs.  We're using code to do this, as they are already
  // installed.
  $config_files = [
    'language.types',
    'language.negotiation',
  ];

  foreach ($config_files as $config_id) {
    $raw_data = file_get_contents(drupal_get_path('module', 'mymodule') . '/config/hook_install/' . $config_id . '.yml');
    \Drupal::configFactory()->getEditable($config_id)
      ->setData(Yaml::decode($raw_data))
      ->save();
  }
}


Linux pppoe/pppd won't connect to Centurylink fiber

Question: Equipment:
Fedora 27 x86_64
Technicolor C2100T DSL modem/router
Unknown Centurylink ONT optical adapter`

I recently switched from CL 80mb DSL to CL 1000mb fiber, which still relies on pppoe.  I have always used a basic Linux Fedora machine as the router/firewall with the DSL modem in bridging mode.  The installer claimed no changes to my router would be needed when he arrived.  But when it came time to activate after the install, the Fedora pppd would not connect, even though the credentials didn't change from DSL to fiber.
Finally as he was getting anxious to move on to the next appointment, so I switched the C2100T modem in to routing mode to let it perform the ppp credentials, and everything worked fine; same credentials.  So I made some simple changes to the Fedora box to route through the modem and he left.  But in the week since, I'm still unable to find the correct solution to get back to bridging mode, and ultimately to remove the C2100T all together and hook the ONT directly to my Fedora box.
The only errors are messages like this in /var/log/messages:
Aug 24 16:59:24 murdock network[28969]: Bringing up interface ppp0: [ OK ]
Aug 24 16:59:24 murdock pppd[29379]: pppd 2.4.7 started by root, uid 0
Aug 24 16:59:24 murdock NetworkManager[685]: [1566683964.9027] manager: (ppp0): new Generic device (/org/freedesktop/NetworkManager/Devices/64)
Aug 24 16:59:24 murdock pppd[29379]: Using interface ppp0
Aug 24 16:59:24 murdock pppd[29379]: Connect: ppp0 /dev/pts/3
Aug 24 16:59:55 murdock pppd[29379]: LCP: timeout sending Config-Requests
Aug 24 16:59:55 murdock pppd[29379]: Connection terminated.
Aug 24 16:59:55 murdock pppd[29379]: Modem hangup
Aug 24 16:59:59 murdock pppoe[29380]: Timeout waiting for PADO packets
Aug 24 16:59:59 murdock pppd[29379]: Exit.
Aug 24 16:59:59 murdock pppoe-connect[29409]: PPPoE connection lost; attempting re-connection.

I know to remove the C2100T, I need to use VLAN tagging 201, which I've located recipies online for that, but without the ppp authentication working I'm stuck.
Here are some of the configuration files
/etc/chap-secrets
#Secrets for authentication using CHAP
# client        server  secret                  IP addresses

"email@example.com"      *       "password"

firewall ethernet cfg:
DEVICE=enp2s0f1
TYPE=Ethernet
BOOTPROTO=dhcp
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
NAME=p1p2
ONBOOT=yes
DNS1=127.0.0.1
DOMAIN=foddy.home
HWADDR=A0:36:9F:83:5E:61
DNS2=184.108.40.206
USERCTL=no
PROXY_METHOD=none
BROWSER_ONLY=no
IPV6_ADDR_GEN_MODE=stable-privacy

/etc/sysconfig/network-scripts/ifcfg-ppp0
USERCTL=no
BOOTPROTO=dialup
NAME=DSLppp0
TYPE=xDSL
ONBOOT=yes
PIDFILE=/var/run/pppoe-adsl.pid
FIREWALL=NONE
PING=.
PPPOE_TIMEOUT=80
LCP_FAILURE=3
LCP_INTERVAL=20
CLAMPMSS=1412
CONNECT_POLL=6
CONNECT_TIMEOUT=0
DEFROUTE=yes
SYNCHRONOUS=no
ETH=enp2s0f1
PROVIDER=DSLppp0
USER="firstname.lastname@example.com"
PEERDNS=no
DNS1=127.0.0.1
DNS2=18.104.22.168
DEMAND=no
IPV6INIT=no
IDLETIMEOUT=600
PERSIST=no

The firewall is run from Shorewall, I won't include those files here but I have no reason to believe they are involved.
Most of these files are essentially unchanged from when they ran fine in the DSL.
I really haven't been able to find any good diagnostic settings for the pppoe/pppd to give me verbose outputs to help debug things.
Does anyone have any guidance of what might be wrong or how to make progress?
Thanks
Brian
Comment: just a random note:
Aug 24 16:59:55 murdock pppd[29379]: LCP: timeout sending Config-Requests

your box (or isp) seems to be unable to do config request "syncing"
LCP is failing, so increase LCP debugging.
some search first hit link:
https://www.linuxquestions.org/questions/linux-networking-3/pppd-lcp-request-timeout-924198/
i would go for understanding how LCP works, increasing debugging of the whole PPP connection from your part, and read through the logs until you find the error.
Comment: I found some debugging options, but unfortunately they really don't tell me anything except its sending packets out and getting nothing back.
Comment: Is there a network tool that can sniff the packets sent from my modem?  Something along the line of a custom linux distribution that I can plumb in between the modem and ONT to capture the negotiation.   Its ethernet,  not IP, so it needs to work on raw ethernet packets.
Comment: This totally sounds like you are using the wrong (or no) VLAN tag. Add the correct VLAN tag to your NIC.
Comment: wireshark/tshark should be able to intercept the data from your fedora box to the, as for in between: most likely possible but never done that sorry.

you should have an /etc/ppp/options file where you can increase debug logging.
i think it was kdebug 7 which gives you the most info
you might be able to manually connect going the whole pppscript in a minicom terminal, eliminating an issue there already (which i am not sure might or might not work for you already)
once you are certain the serial connection works correctly use something like this to get verbose output:
Comment: /usr/sbin/pppd mtu 1492 ipcp-accept-local ipcp-accept-remote connect "/usr/sbin/chat -v -f /etc/ppp/pppscript"

for the authentication process.

Additionally it might be helpful (for others) to add your options here.
Comment: I put another Linux between the modem and ONT with 2 nic cards,  loaded network bridging, then wireshark could sniff packets issued from the modem and from my Linux router.   Conclusion... despite the modem bridge mode being in clan tagging 201, the tags are not there.   So next step is to figure vlan tagging in linux for the ppp interface.   Plenty of how to for standard nics, but haven't seen one applied to PPP yet.
Answer: According to this all traffic has to have a 201 vlan tag:
https://nickmooney.com/centurylink-fiber-bypass-modem/
Answer: I tried to put the 201 vlan tag through the old /etc/sysconfig/network-... scripts several different ways, but nothing seemed to work (and gave up for many months, using the external modem and NAT).  Finally I made another attempt using NetworkManager and it just worked.  Previously, I've always resisted using NM for complicated configurations like this, but in this case it worked.


Matlab: Monte Carlo Value at Risk - Rolling calculation (very basic)

Question: I have a stock index for which I need to compute the VaR using a MC simulation with the geometric brownian motion model as the stochastic process. This is my first try, disregarding the gbm, just to get familiar with the program and syntax:
x=logreturn; %file with 500 returns
mu=mean(x),
sigma=sigma(x),
rand=normrnd(mu,sigma,2000,1); %random normal distr numbers
VaR=quantile(rand,0.05); %95 percent VaR
VaR=-0.045

It's very basic and calculates the VaR only for one day, but I need to calculate the VaR for the first 250 days with a 250-day rolling window for mu and sigma.
Based on Ahmed's comment I tried to implement arrayfun and cellfun for the full function:
x=logreturn;
mu=movmean(x,250);
sigma=movstd(x,250);
mydata = normrnd(0,1,1,20000)
muforsample=arrayfun(@(v) mu*250, mu, 'un', false);
sigmaforsample=arrayfun(@(v) sigma*sqrt(250), sigma, 'un', false);
k=arrayfun(@(v) muforsample-(sigmaforsample.^2)/2, muforsample, sigmaforsample, 'un', false); %this line is faulty and gives an error message (too many input arguments)
t=1/504;
sqrtt=sqrt(t);
gbm=k*t+sigmaforsample*sqrtt; %didnt't try to fix this since I don't have a k
VaR=quantile(gbm, 0.05) %unchanged, needs cellfun too, right?

For k I need basically a value based on the corresponding muforsample and sigmaforsample so that I can calculate the gbm
Comment: Wow, `movmean` and `movstd` and friends look cool! Upgrading to 2016a to check them out.
Comment: 'But now normrnd doesn't work anymore.' Can you show the `normrnd` command that you tried? `mu` and `sigma` (from `movmean` and `movstd`) are now vectors the same size as `x`, so a single call to `normrnd(mu, sigma, ...)` can only return an array the same size as `mu` and `sigma`. If you want to generate 2000 draws from each sample in `mu`, you need [`arrayfun`](http://www.mathworks.com/help/matlab/ref/arrayfun.html): `r = arrayfun(@(m, s) normrnd(m, s, 2000, 1), mu, sigma, 'un', false)`, which will give you a cell array. Then `VaR = cellfun(@(v) quantile(v, 0.05), r)` should do the trick.
Comment: `normrnd(mu,sigma,2000,1)` is what I used, so the same command as in the 1-day calculation. Thank you for your answer, I'll try that!
Comment: @AhmedFasih your solution works, thank you very much! I tried to follow your solution for the gbm, with multiple arrayfuns. Could you maybe take a look at it? I'm way too untalented for coding :(
Comment: I don't think your `muforsample` is correct—`arrayfun` takes a function and then one or more arrays (and finally if necessary `..., 'un', 0` which is short for [`'uniformOutput', 0`](http://www.mathworks.com/help/matlab/ref/arrayfun.html#namevaluepairarguments)) and applies that function to each element of the array(s). Here's documentation on [anonymous functions](http://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html).
Comment: So `muforsample = arrayfun(@(v) mu*250, mu, 'un', false)` is equivalent to `muforsample = cell(size(mu)); for i=1:numel(mu); muforsample{i} = mu*250; end`. This means each element in the `muforsample` cell array is `250*mu`. I don't think this is what you want?
Comment: If you can describe the GBM algorithm in pseudocode, that'd help see what your code is trying to do.
Comment: Hi @AhmedFasih, thank you very much, again. I pretty much gave up on arrayfun and cellfun and tried for loops. I posted my solution (which works, surprisingly) as an answer.
Answer: Using a for loop is definitely easier than cellfun and arrayfun. Here's my solution:
% file with log returns until t(n-1)
x = logreturns;

t = 1/250;

% mu and sigma based on 250 returns, moving window
mu = movmean(x,250);
sigma = movstd(x,250);

% k for every cell
k = zeros(size(mu));
for i = 1:length(mu);
    k(i) = mu(i)*250 - (((sigma(i)*sqrt(250)).^2)/2);
end

% 0.99 or 0.95 VaR, quantiles based on 500,000 values
VaR = zeros(size(mu));
for j = 1:length(mu)
    VaR(j) = quantile(normrnd(0,1,1,500000) * sqrt(t) * ...
    (sigma(j) * sqrt(250)) + k(j) * t, 0.01);
end

This is the formula by the way:


Integrate $\int_D 2e^{-x^2}$ with $D = \lbrace (x,y) \in \Bbb{R}^2 | 0\le x \le 1, 0 \le y \le x \rbrace$

Question: I was given the following task but I don't know how to keep going.
The task is:

Integrate $\int_D 2e^{-x^2}$   with $D = \lbrace (x,y) \in \Bbb{R}^2 |
> 0\le x \le 1, 0 \le y \le x \rbrace$

I started with the following integral:
$$\int_0^1 \int_0^x 2\cdot e^{-x^2}dy\;dx$$
$$=\int_0^1  \left[2\cdot e^{-x^2} \right]_0^xdx$$
$$=\int_0^1  x\cdot2\cdot e^{-x^2}dx$$
I am stuck at evaluating this integral.
I assumed that $erf(x)$ will appear.
The thing is that my university published the solution:
$$\int_D 2e^{-x^2} = 1 - \dfrac{1}{e}$$
I would be very happy if someone could explain to me, what I did wrong.
Greetings,
Finn
Answer: In $I=\int 2xe^{x^2}dx$,
let $y=x^2$.
Then $dy = 2xdx$ so
$I=\int e^ydy$.
Comment: Oh.. Wow I feel pretty dumb now. Thanks a lot!
Comment: You are welcome. It's just the standard special case of $\int f'(x)e^{f(x)}dx = \int e^ydy = e^y = e^{f(x)}$ with $y = f(x)$.


Confused about the definition of EJB

Question: I am reading EJB 3 in Action and I came across this sentence

In very straightforward terms, Enterprise JavaBeans (EJB) is a platform for building portable, reusable and scalable business applications using the Java programming language.

Then in the next two paragraphs they make a difference of EJB as a component and EJB as a framework.
Further they say that when they talk about EJBs in the book they are referring to the server-side components that you use to build parts of your application.
I am confused about what EJB is, is it correct that EJB is a platform/framework, and the components and container are both included in that definition? And would it be more correct to say EJB components than just EJBs?
Answer:
I am confused about what EJB is, is it correct that EJB is a platform/framework,

Yes ... among other things.

and the components and container are both included in that definition?

Yes.

And would it be more correct to say EJB components than just EJBs?

That's debatable.  (And a pointless debate, IMO.)
The bottom line is that term EJB means lots of things depending on the context and who is talking.  When someone says "EJB" you have to consider the context to determine the meaning.  But, hey, human language is like that.

Confused about the definition of EJB


How to fix Filter selections on VIEW result pages

Question: 1] I am  using Exposed Filters (Page Display - not Block Display) in a view.
2] Sorting by three parameters: Materials, Machines, Industry(s)
3] Using Paging to deliver Results
4] Filters have "Remember last selection" turned off
5] Display>Page>Advanced:
AJAX (OFF - per other threads)
Caching (NONE - per other threads)
6] Drupal 8
Problem: Filter results are fine and not the problem. Filter selections change after initial page. (Illustrated here)
Regardless of browser - delivers same broken filter selections after page 1.
Help appreciated. Thanks!
Comment: Try to replicate this on a fresh install, if you can replicate it there, then it's clearly a bug. If not, then it's something up with your site. Maybe check browser console for JS errors.
Comment: Thanks No Sssweat. That at least gives me some place to start. I really did not know what to look at, so very much appreciated.
Comment: Also maybe try turning #4 on? I found a few similar issues [Exposed filter selections aren't remembered if query parameters are in the URL](https://www.drupal.org/project/views/issues/1248332) maybe you could try the patch in here. Also, another one ["Remember" feature of exposed filters doesn't work with AJAX and is generally fragile](https://www.drupal.org/project/drupal/issues/2939806)
Comment: I tried your (#4) selection to no avail. I'm going back to an older post backup to see if it exhibits the same behavior. Nothing like forensics! I'm not a programmer, but can at least do my part to narrow down what is going on. But some of the threads I have seen concur with what you are pointing out, mainly that other people have documented the behavior. Crazy thing is that it DID work at one time as expected. But updates have happened since that time. Thanks again No Sssweat.
Answer: I found a patch here (see note #5) that worked in my circumstance: https://www.drupal.org/project/drupal/issues/2897694#comment-12677908
Hopefully this can help someone else.


Diferença entre dois códigos

Question: O código 1, caso a variável num seja 1 ou 2 por exemplo, quando o conv() é chamado novamente e eu escolher a opção 3 de sair em seguida, roda o print Espero ter sido útil (: mas o programa não fecha, só da próxima vez que eu escolher a opção 3.
No código 2 o problema não ocorre, tudo funciona corretamente, eu queria saber qual seria a diferença que faz isso ocorrer.
Código 1
def conv():

print("\nEscolha umas das duas opcoes abaixo!\n[1] Metro para Centimetro\n[2] Centimetro para Metro\n[3] Sair")
num = input("")
if num == 1:
    met = input("\nDigite o metro\n")
    result = float(met)*100
    print("\nA resposta e >> " + str(result) + " centimetros\n\n")
    conv()
if num == 2:
    cen = input("\nDigite o centimetro\n")
    result = float(cen)/100
    print("\nA resposta e >> " + str(result) + " metros\n\n")
    conv()
if num == 3:
    print("\nEspero ter sido util (:\n\n")
    sair()
else:
    print("\nOpcao invalida\n\n")
    conv()

def sair():
    exit

conv()

Código 2
def conv():

print("\nEscolha umas das duas opcoes abaixo!\n[1] Metro para Centimetro\n[2] Centimetro para Metro\n[3] Sair")
num = input("")
if num == 1:
    met = input("\nDigite o metro\n")
    result = float(met)*100
    print("\nA resposta e >> " + str(result) + " centimetros\n\n")
    conv()
else:
    if num == 2:
        cen = input("\nDigite o centimetro\n")
        result = float(cen)/100
        print("\nA resposta e >> " + str(result) + " metros\n\n")
        conv()
    else:
        if num == 3:
            print("\nEspero ter sido util (:\n\n")
            sair()
        else:
            print("\nOpcao invalida\n\n")
            conv()

def sair():

exit

conv()

Comment: Esse código tem alguns problemas, só resolver isso não quer dizer que ele ficará certo. Funcionar é diferente de estar certo. Pra consertar teria que reescrever o código. Não sei nem se eu consigo explicar o motivo para precisaria ter um conhecimento que parece que ainda não ter.
Answer: O código tem muitos erros. O correto não é ficar criando esse monte de função, é criar um laço de repetição. E o if pode ser usado como um bloco só, prefira elif sempre que fizer sentido.
O código pode ser melhorado. Por exemplo a saída ser de acordo com uma condição do while, ou tratar o erro que seria gerado se digitar letras onde se espera números, mas não vou apresentar tantos conceitos novos. No momento tente aprender o while e o elif.
while True:
    num = int(input("Escolha umas das duas opcoes abaixo!\n[1] Metro para Centimetro\n[2] Centimetro para Metro\n[3] Sair\n"))
    if num == 1:
        met = input("\nDigite o metro\n")
        result = float(met) * 100
        print("\nA resposta e >> " + str(result) + " centimetros\n\n")
    elif num == 2:
        cen = input("\nDigite o centimetro\n")
        result = float(cen) / 100
        print("\nA resposta e >> " + str(result) + " metros\n\n")
    elif num == 3:
        print("\nEspero ter sido util (:\n\n")
        break
    else:
        print("\nOpcao invalida\n\n")

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Legal, obrigado pelas dicas.
Answer: Basicamente, a primeira opção gasta menos poder de processamento, pois o compilador passa direto pelas condições sem entrar em condicionais filhas.
Answer: Olá.
Bom, o código em si está falho e possui muitos erros de lógica, não é recomendado que sejam criadas funções se o código for pequeno, em geral, funções são usadas quando existem um determinado código que deve ser repetido em outras localidades, assim o mesmo fica mais legível e enxuto, facilitando modificações.
Neste caso, a função conv() nem a função que sai do programa sair(), contudo, em aplicações do gênero pode ser utilizado um laço de repetição que executará os comandos até a condição seja falsa, assim nos referimos ao laço While.
Segue abaixo um pequeno algoritmo para a resolução do problema.

Utilize um loop while igual a True.
Enquanto while for True, entre com a escolha do usuário para metros ou centímetros .
Verifique qual foi a escolha do usuário, se 1, então converta para Metros, se 2, então converta para centímetros, se 3, então sai do programa.

Diferença entre dois códigos


How to reindex a python array to move polyline starting point?

Question: I have a python array defining the points for a polyline P(x,y,z). I need to align the points with points on another polyline - to be precise, the point with index 0 on polyline 1 should be close to the point with index 0 of the second polyline.
Think of a polyline circle. How can I move the "index number" or rather rearrange the points in an array so that the index number of the points moves clockwise or counter clockwise by x points?
Klausb
Comment: do you mean shifting a list like: `[1,2,3] --> [2,3,1]` ?
Answer: To shift to left by x points(assuming x is less than the length of array):
newPolyline = polyline[x:] + polyline[:x]

To shift right:
newPolyline = polyline[len(polyline) - x:] + polyline[:len(polyline) - x]


Javascript : Issue in calculating dates

Question: I am trying to do the following
a) Get the number of ms passed from 01/01/1970 till now
b) Convert a) to number of days
c) Then add b) to 01/01/1970
d) I expected d) to be today
But the result is not right.
Today is Dec 01, 2017
From the above code snippet I get Nov 29, 2017
Can someone tell me what I am doing wrong and how to get the correct value ?
Code snippet
const a = new Date();
console.log('a ==> '+ a);

const b = a.getTime();
console.log('b ==> '+ b);

const c = b/86400000;
console.log('c ==> '+ c);

const d = Math.floor(c);
console.log('d ==> '+ d);

const e = new Date(1970);
e.setDate(d);
console.log('e ==> '+e);

Console.log

EDIT:
I updated my code snippet based on comments.
This code snippet below works but I would like to know whether there is something wrong in this snippet. Can some one eyeball this and let me know of a use case where this can go wrong ?
const a = new Date();
console.log('a ==> '+ a);

const b = a.getTime();
console.log('b ==> '+ b);

const c = b/86400000;
console.log('c ==> '+ c);

const d = Math.round(c)+1;
console.log('d ==> '+ d);

const e = new Date(1970, 0, 1, 0, 0, 0, 0);

console.log('e before setting up ==>'+e);
e.setDate(d);
console.log('e ==> '+e);

Comment: I guess it's because of `Math.floor`. It makes the rounding to previous complete day (because today isn't complete). The `new Date(1970)` is "1970 seconds since 1/1/1970 GMT+0", doesn't make sense. And finally, you need to account for timezone. This is what breaks the logic when you do `new Date`.
Comment: I think there is an issue with the number of days because 0 will be the previous month and 1 will be Jan 1, but you are working out days from Jan 1. So you need to add that 1 back on. And as for the second day needing to be added (i.e. 17502) I'm not too sure!
Comment: So you're trying to get today's date? There are easier ways to do that. ;)  What is you really want to do?
Comment: @Seanonymous Basically I would like to store today's date as a number which can then be stored in sqllite db. Also storing a date as number allows me to do sort operations. The database is sqllite db and it does not have a date datatype but only text (which is why I am storing the date as number)
Comment: `a` is set in local timezone, `e` is set in UTC+0. Perhaps not in this particular case, but it generally can cause discrepancies. To compensate, please use [`Date#getTimezoneOffset`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset).
Comment: yeah I think the extra day must have been a timezone thing, because you are now setting `e` to be midnight in local time, instead of +11 hours
Answer: I think you were better off with the Math.floor, so long as you're accounting for the timezone offset on both ends.
const a = new Date();
console.log('a ==> '+ a);

const b = a.getTime() + a.getTimezoneOffset();
console.log( 'b ==> '+ b );

const c = Math.floor( b / 86400000 );
console.log( 'c ==> '+ c );

const e = new Date( c * 86400000 - new Date().getTimezoneOffset() );

console.log( 'e ==> '+e );

Answer: The Date constructor that you are using is adding the local time zone offset:

Note: Where Date is called as a constructor with more than one argument,
the specified arguments represent local time. If UTC is desired,
  use new Date(Date.UTC(...)) with the same arguments.

console.log( d1 = new Date(1970, 0, 1, 0, 0, 0, 0), +d1 ) // "1970-01-01T05:00:00.000Z" 18000000 - time zone offset in milliseconds

console.log( d2 = new Date(0)                     , +d2 ) // "1970-01-01T00:00:00.000Z" 0 - no time zone offset

The new Date(), new Date(value), and some cases of new Date(dateString) constructors don't.

var date1 = new Date
console.log( date1, date1 + '' )   // "2017-12-02T01:03:19.967Z" "Fri Dec 01 2017 20:13:21 GMT-0500 (Eastern Standard Time)" - local date and time

var days = date1 / 864e5 | 0
console.log( days  )               // 17502

var date2 = new Date( days * 864e5 )
console.log( date2, date2 + '' )   // "2017-12-02T00:00:00.000Z" "Fri Dec 01 2017 19:00:00 GMT-0500 (Eastern Standard Time)"

Javascript : Issue in calculating dates


Why do we plot the standard error of the mean as both positive and negative?

Question: When we plot the mean of a variable on a scatter plot or a bar plot, why do we plot the standard error of the mean in both directions: positive and negative?
Comment: Note that a standard error only gives about $68\%$ coverage for normally distributed variables. It might be better to plot a $95\%$ confidence interval.
Answer: Because your estimated mean might differ from the true mean in either direction: it can be too high or it can be too low.
If you estimate the mean from your sample to be (e.g.) 3 and you also know that standard error (loosely speaking the average deviation of the estimate from the true mean) is 2 then you expect that your estimate might be off by about 2 in either direction.
In such a case when you see your estimate as "3" there is a reasonable chance it was "1" (as 3 is within a standard error of 1) and as high as "5" (as 3 is within a standard error of 5).
Comment: @ReneBt Thank you for the comment, but did you find something in my answer that suggested otherwise? I don't think I confused standard error and standard deviation in the answer.
Comment: Standard error and standard deviation are not the same, the former is the latter divided by the square root of N. Standard error is not how much on average we expect to be off. It is the range within which we reasonably expect to estimate the mean from a new random sampling keeping all experimental parameters constant.
Comment: If I make certain assumptions I can read it as standard error  correctly, but they are not explicitly made. It would be less ambiguous if you clarified it was the estimate based on averaging N repetitions. The main problem however is you description of it as the average amount your error will be out. The average error, by definition is 0.the mean absolute error will be closer to 0 than the standard error. I can't vote this answer up with something this wrong in it.
Comment: @ReneBt I think the problem you have mainly is the "average" word. Note that I didn't say "mean" there - because I wanted to use that word loosely. Which I felt sufficed for the simple question that was asked. I do agree with you that it might confuse somebody if they took it literally as "mean absolute difference from the true mean". Will see if I can change the wording to reinforce the point that it's only "speaking loosely".


Contents from all tabs is initially displayed

Question: I have the below code to display tabs. The tabs work when I click on them but not on page load (it shows the content of all tabs). I also need to be able to open all 1st/2nd or 3rd tabs on the page with a click of a button (multiple tab groups on the page)
<code>$("ul.tabs").each(function() {
    $(this).find('li:first').addClass("active");
    $(this).next('.tab_container').find('.tab_content:first').show();
});

$("ul.tabs li a").click(function() {
    $(".tab_content").hide();
    var cTab = $(this).closest('li');
    cTab.siblings('li').removeClass("active");
    cTab.addClass("active");
    cTab.closest('ul.tabs').nextAll('.tab_container:first').find('.tab_content').hide();

    var activeTab = $(this).attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
});
</code>

jsfiddle.
I'm also open to other tab solutions.
Answer: http://jsfiddle.net/agBgL/1/
You just need to hide tab content initially.
Comment: `` is in the place, so the `.next()` doesn't work. Here you go: http://jsfiddle.net/agBgL/2/
Answer: removing:
<code>.ui-tabs .ui-tabs-panel { display: block; }
</code>
Reference


How to Highlight the Item (Listview) of Next Activity After Clicking the Item(Listview) of Previous Activity?

Question: I have two Fragments. One Fragment Consist of Questions While OtherFragment  consist of Answers. For Example If one person click on Question(8) It means u can say that Item No 8, then it should go to next activity and highlight the Answer (8) of that Question. I am stuck. I shall be thank full to you.
Here is Some Code Which are sending Question No or list Item no to next Activity and next Activity code receiving this Question no and i saved it into Interger "a". Now what type of IF condition can work in the Next Activity?

First Activity

lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            int index = position + 1;
            Intent it = new Intent(this.getActivity(), NextActivity.class);
            it.putExtra("Qlist", index);
            startActivity(it);

        }

Next Activity

Intent it = getActivity().getIntent();

    int a = it.getIntExtra("Qlist", 0);

    String result=String.valueOf(a);

    Toast.makeText(getActivity(), ""+a, Toast.LENGTH_LONG).show();

ListView Adapter code of First Activity (using SQlite)

DatabaseAccess db=DatabaseAccess.getInstance(getActivity().getApplicationContext());

    List<String> lst;
    db.open();
    lst=db.getexamq();
    db.close();

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ExamQ.this.getActivity(), android.R.layout.simple_list_item_1, lst);
    lv.setAdapter(adapter);

ListView Adapter code of Next Activity (using SQlite)

DatabaseAccess db=DatabaseAccess.getInstance(getActivity().getApplicationContext());

    List<String> lst;
    db.open();
    lst=db.getexamq();
    db.close();

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ExamA.this.getActivity(), android.R.layout.simple_list_item_1, lst);
    lv.setAdapter(adapter);

Comment: Can you post some code?
Comment: What have you got already? I'd love to help but a little bit of work from your side is appreciated.
Comment: I am trying But The Point is that I actually Want to know that where to start. .. but let me think.....
Answer:
Use the intent Bundle to move the questionId or question No to the next activity
In the adapter of the Questions ListView, set a different background color for the question with a similar questionId. You can even set the background to have a fade animation or change to normal after a certain number of milliseconds or seconds.

ALL THE CODE REQUIRED IS A LOT Write something(some code), and we can help on the ListViewAdapter in case it doesn't work
EDIT: SAMPLE FAST CUSTOM ADAPTER CODE
    lv.setAdapter(new ArrayAdapter(ExamQ.this.getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, lst){
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View v = convertView;
            final String examQ = lst[position];

            if (v == null) {
                LayoutInflater vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(android.R.layout.simple_list_item_1, null);
            }

            TextView tv = (TextView) v.findViewById(android.R.id.text1);
            tv.setText(examQ);

            if( examQ.equals(result)) { // Unique identifier here
                v.setBackground(Color.RED); //Some other fancy color here
            }
            return v;
        }
    });

However, I just discovered you do not have a unique identifier for each question. So for the time being just use the question string and pass it to the next activity
Comment: I can move Question No to Next Activity. But can you tell me that If we use If Condition to match the Question no With Item No of Next activity and if they match then highlight it.is this posiible?
Comment: Yes, provide the adapter code, xml and activity code & I can help
Comment: Take a Look. As i Updated My Question with Code i have.
Comment: Provide the ListView Adapter Code
Comment: Take a look again.
Comment: Using My method, you would have to write a custom adapter. DO THIS, let me quickly add some code you will place there
Comment: ahan. I am waiting.
Comment: What Convert view for?
Comment: You mean that in if (exam question) condition, i should write a code which should pass it to the next activity?
Comment: Nope, this code goes in the second activity. In the first activity, pass the question in IntentBundle
Comment: Ok.. I will try .. Then i will let you know.. Thanks for all this help..
Answer: Suppose You have a textview for each answer in the listview of second fragment. Then you can compare the question id in the getView() of adapter of listview in second fragment. Now when you find your answer just call textview.setBackgroundColor().
Edit:
After lv.setAdapter (adapter); add
View v = lv.getViewAt(a);
if(v!=null)
    v.setBackgroundColor (Color.RED);

Comment: Can you explain me in some Code?? i mean do you have any code which can just tell me that how to check this Question No with Next activity??


Where and why use int a=new int?

Question: Just curious, what is the difference between:
int A = 100;

and
int A = new int();

I know new is used to allocate memory on the heap..but I really do not get the context here.
Comment: @eRaisedToX It is not an error to use new operator with a value type. https://stackoverflow.com/questions/5563774/dilemma-with-using-value-types-with-new-operator-in-c-sharp It basically does nothing observable. And the tag is for C# not C++.
Comment: To be simple enough...,    int A=100; is simply declaring an int var A and initialising it to 100..,
whereas int A= new int();  is an error   .,Although it could be..
 int *A = new int(); which means create space for an int on stack put 0 in it and return address of that int to integer pointer,i.e  A
Answer: static void Main()
{
    int A = new int();
    int B = default(int);
    int C = 100;
    Console.Read();
}

Is compiled to
.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] int32 A,
           [1] int32 B,
           [2] int32 C)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldc.i4.0
  IL_0004:  stloc.1
  IL_0005:  ldc.i4.s   100
  IL_0007:  stloc.2
  IL_0008:  call       int32 [mscorlib]System.Console::Read()
  IL_000d:  pop
  IL_000e:  ret
} // end of method Program::Main

As you can see first one just initialize it and second one is just the same and third one initialize and set to 100. As for the IL code generated, they both get initialized in a single line.
so
int A = new int();

Is the same as
int A = default(int);

Comment: is it also the same as 'int a;' ?
Answer: Difference?
the latter ends with A being 0, not 100.
When?
Pretty much never. Maybe in some generated code it is simpler to use the new TypeName() syntax, but default(TypeName) would be preferred even then.
And new does not "allocate memory on the heap". It initializes an instance; that is all.
Comment: @Miriah - there is meaning: it means we want to initialize a new object or value; it just doesn't strictly mean anything to do with heap or stack. Note that `new` has an alternative usage (as a keyword) in method hiding. Completely unrelated, but it exists.
Comment: SO there is no meaning in the new keyword?
Comment: Unless you want an instance of the object/structure and not just the default/null value.
Answer: I strongly recommend that you read this article from dotnet mob: http://codaffection.blogspot.in/2015/02/difference-between-declarations-int-i.html
int A = 100; //Initialises A to 100 manually

Suppose you declare an integer as
int A;

For further operations on A, you need to initialise A with an integer value, otherwise the compiler shows

use of unassigned local variable

To declare A as follows
int A = new int(); //A initialised to 0 (default value of int)

allows for further operations on A without a manual initialisation - I think you get my point now.

Now let's discuss using new ().
Use of new doesn't mean memory will be allocated on the heap; if A is a local variable (e.g. in a method) it will be allocated memory on the stack.
If A is a member of a class however, then memory will be allocated on the heap when an instance of the class is created.
Point to be remembered: if A is static, it will always be on stack memory!
Comment: I like this explanation, but what then is the difference between initializing a variable with "int x = 0" versus"int x = new()"?
Comment: @Stokely int x= 0 vs int x = new int();  no difference in both case x will initialised to zero.
Answer: int A=100;

Allocates an int on the stack and sets its value to 100.
int A=new int();

Allocates an int on the stack (yes, value types are always allocated on the stack, even with the new keyword) and sets its value to the default, that is, 0.
Comment: you said *always*... always is not "this precise case"
Comment: The "value types on the stack" is misleading. For example, in an array-of-structs, or as a field on a class. It also depends how you count a "unit on the stack then copy"
Comment: Always is incorrect, if the int is a local var, then it will be on the stack, but if it's an instance field then it will be on the heap.
Answer: I saw it from another link:
MSDN says "The new operator is also used to invoke the default constructor for value types."
Inside a method:

int x;: allocates an int on stack and does not initialize it.
int x=5;: allocates an int on stack and sets it to 5;
int x=new int();: allocates an int on stack and sets it to 0;
int x=new int(5);: does not compile.

http://msdn.microsoft.com/en-us/library/fa0ab757.aspx
Answer: myInt = new int();  // Invoke default constructor for int type.

This statement is equivalent to the following statement:
myInt = 0;         // Assign an initial value, 0 in this example.

Using the new operator calls the default constructor of the specific type and assigns the default value to the variable. The default value of an integer is 0 BTW.
The difference is that you can't initialize and set anything but the default value value using the new operator.
Comment: They are not the same. See my comments.
Comment: Initializing Value Types :
http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx
also in my reading, as 0 is the default value of an int, that's why myInt = default(int) and myInt = 0 are going to be the same.
Comment: Thanks for confirming my suspicions about using "new" and "default". Their use is pointless. It seems its much better to always instantiate a value type to a default value you choose, even if its 0, so its always available. You also avoid confusion as to what its custom default should be.
Answer: I don't think it is necessary to add new on int(because int has default memory size)..
new is used when we have a user-defined class of which we instantiate an object..
public static Main()
{
  Cat cat1=new Cat();
}

Public class Cat
{
  public bool Sex
  public string Name
}

Now compiler will allocate that much memory to cat1(memory size which is defined in class Cat)
Answer: "int" is a value type, so neither expression will allocate memory on the managed heap.  The first statement will initialize A to the literal you specify.  The second statement will leave A at a default value.
Answer: If you are using the int as a field in your class, you might even say simply int x; - since int is a value type it cannot be null and therefore gets its default value - i.e. 0.
Answer: I end up discovering my problem
I was modifying the values but not the Object
This is the proper way to do it :
 public ActionResult ChangeDefaultUserLockingSetting(int PasswordAttempts, int DefaultLockingTime)
        {
            var defaultAccountSettings = new DefaultAccountSettingsDataContext();

            var accountSettings = defaultAccountSettings.DefaultAccountSettings.First(u => u.id == 1);

            accountSettings.DefaultAccountLockoutTimeSpan = DefaultLockingTime;
            accountSettings.MaxFailedAccessAttemptsBeforeLockout = PasswordAttempts;

            defaultAccountSettings.SubmitChanges();
            return View("Index", loadAdministrationViewModel());
        }

Where and why use int a=new int?


How to show that $\hat{e}_m(k) = e^{−2πimk/N}$ for all $k$? How to show that $\hat{F}_m = e_m$?

Question: Let $\{e_0, e_1, \dots, e_{N-1} \}$ be the Euclidean basis for $l^2(Z_N)$, and let $\{F_0, F_1, \dots, F_{N−1} \}$ be the Fourier basis( where $F_m(n)= \frac{1}{N} e^{2 \pi i m n/N}$ and $\hat{z}(m) = \sum_{n=0}^{N-1} z(n) e^{-2 \pi i m n/N}$).

How to show that $\hat{e}_m(k) = e^{−2πimk/N}$ for all $k$? Notice that $\hat{e}_m$ is very nearly (up to a reflection and a normalization) an element of the Fourier basis.
How to show that $\hat{F}_m = e_m$?
Answer: These follow immediately from the definition of the Fourier transform. You may be confusing yourself with "e"s.
Comment: But how do they follow immediately from the definition of the Fourier transform? Could you explain a little bit, because I have got following, but I'm not satisfied with this solution of mine. $\hat{e}_m(k) = \sum_{n=0}^{N-1} e_m(k) e^{-2 \pi i m k/N} = e^{-2 \pi i m k/N}$ ii. How to show that $\hat{F}_m = e_m$? (my solution: $\hat{F}_m = \sum_{n=0}^{N-1} \frac{1}{N}e^{2 \pi i m n/N} e^{-2 \pi i m n/N} = \sum_{n=0}^{N-1} \frac{1}{N} = ? $ Any comments on my solutions.


I want to create a random sample of length n from a normal multivariate distribution

Question: I have a problem in understanding this question, especially this part:
"generate a random sample of length n from a normal multivariate"
This is what I have done using the R package mvtnorm:
my_function <- function(n=1,k){
mean = rep(0,k)
sigma = diag(length(mean))
rmvnorm(n, mean, sigma,method=c("eigen", "svd", "chol"), pre0.9_9994 = FALSE)}

my_function(3)
This way the output of my function is, in this example, a vector of three numbers which in my mind is A sample of length 3. Is this correct? Is there another way to do this?
I am asking this question because I have to do the same without using the library rmvnorm and with a normal bivariate.
I just managed to write the density function:
dbivnorm <- function(x,y,mux=0,muy=0,sigmax=1,sigmay=1,rho=0){
  (2*pi)^(-1) * ((1-rho^2)*sigmax^2*sigmay^2)^(-.5) *
    exp( -((x-mux)^2/(sigmax^2) -2*rho*((x-mux)/sigmax *(y-muy)/sigmay) +
             (y-muy)^2/(sigmay^2))/(2*(1-rho^2)) )
}

But now I am not sure how to proceed.
Comment: Its manual page explains how.  You will figure it out quickly enough by running `rmvnorm` a few times with different argument values.  Since (for some reason) you don't want to use `rmvnorm`, could you please be specific about what tools or techniques you *are* willing to employ?  If the reason for not using the solution available to you is educational, then please tag your post with [tag:self-study].
Comment: @whuber: sorry, I typed my answer while you were typing your comment!
Comment: This is a sample of length one (1) and dimension three (3).
Comment: Ok, how do I get a sample of length n, with let's say n = 3 using rmvnorm?
Answer: Usually, a good starting point to understand how to run an R function is to read the attached documentation:

which also contains an example as an illustration

where the entry n in rmvnorm(n,mean,sigma) is the number of elements in the random sample, while mean is the mean vector and sigma is the variance-covariance matrix.
Comment: In `R`, a matrix and an array of columns are identical concepts.
Comment: If $n=5$ and $k=5$, this is a correct outcome of $5$ realisations of a $5$-dimensional random vector.
Comment: Yes, I read that too but I have a doubt on my output: let's say I run rmvnorm(5,mean = rep(0,5), diag(length(mean))) This gives me a 5x5 matrix, but I just want the one random sample of length n, to me this seems 5 random samples of length 5. What am I not getting?
Answer: Are you allowed to use a package that provides you with independent normal distributed RVs? If not, the Box-Muller method (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform) could be used for that.
Given that you have n independent normal distributed random variables, using the cholesky decomposition $L^\top L = \Sigma$ (for the wanted covariance matrix $\Sigma$) and multiplying $L$ by the vector of independent normal RVs gives you a multivariate normal distributed random variable with covariance $\Sigma$.
Comment: Mmm, could you be a bit more specific on the first part of my questions? I mean, is what I did right for generating a random sample of length n from a normal multivariate? Because for that part I am allowed to use the package.
Comment: I'm very unsure what you are doing in your first part, especially the relation between 'my_function' and 'using_rmvnorm'. Normally, simply 'rmvnorm(rep(0,k),diag(k))' should work.
Comment: Yeah, I overcomplicated that, plus using_rmvnorm should just be my_function. Anyway, I have still another question. Given that I have the density function for the bivariate distribution, can't I just use rand() two times to get two values for x and y and then compute dbivnorm(x,y)?


Verificar se está autenticado

Question: Tenho a função autenticar que verifica se o e-mail e senha digitados conferem com os da tabela users.
O código está funcionando, porém após verificado que e-mail e senha conferem, eu faço um redirect para a view logado. Até aí tudo certo. Mas gostaria que essa view não fosse acessada diretamente. Eu gostaria de deixá-la acessível somente para quem está logado. Será que deu para entender?
Pois se eu acessar a url direta dessa view, ela acessa. Quero restringir isso.
<code>public function autenticar(Request $request)
{
    //Pego dados do formulário de login e armazeno na variavel $dados
    $dados = $request->except('_token');

    //Depois de armazenar na variavel dados, separo em $email e $password
    $email = $dados['email'];
    $password = $dados['password'];

    //Faz a consulta e verifica se email digitado é igual email do banco
    $query = $this->user->where('email', $email)->first();

    //Verifica se o email existe
    if (!$query)
    {
        return null;
    }

    //Verifica se a senha digitada é igual a senha hash do banco
    if (Hash::check($password, $query->password))
    {
        return redirect()->route('logado');
    }
    else
    {
        return null;
    }
</code>
Answer: Na sua view você pode fazer o seguinte:
<code>@if(Auth::check())
   //Conteúdo protegido
@endif

 @if(Auth::guest())
//Conteúdo para não logado(um form de login etc)
@endif
</code>
Enfim, existem outras maneiras de se fazer algo do tipo mas para fins de aprendizado, é um bom começo.
Dá uma olhada na documentação do laravel, é muito boa.
Comment: Deu certo! Mesmo assim vou ler com mais calma a documentação. Obrigado

Verificar se está autenticado


MariaDB installation fails with no package available

Question: I would like to install MariaDB version 5.5.56 on CENTOS 7(EC2 Instance). I tried using the command
sudo yum install MariaDB-server-5.5.56

But it says the package is unavailable. I need this specific version of MariaDB and I cant seem to find the solution.
If I run sudo yum install MariaDB-server, yum installs the 5.5.60 version.
Need guidance on this.
Answer: The most reliable way is to download the tarball from the official site and make it from source. It's more complicated than getting it through a package manager, but downgrading is not officially supported, and if you run into issues there's little help available from them.
To do that, you can use the instructions for setting up a proper build environment, found here. Once that's done, you can follow the instructions here to build the software.

If you still want to use yum, MariaDB does have an archive; it can be found here. Follow the instructions listed here to configure yum to only grab the specific minor release you want. Just from a quick look, this link is a good place to start.
I've pasted their example configuration below, with some alterations to show you a better idea of what it would look like.
[mariadb]
name = MariaDB-server-5.5.56
baseurl=http://archive.mariadb.org/mariadb-5.5.56/yum/centos7-amd64
gpgkey=http://archive.mariadb.org/mariadb-5.5.56/yum/centos7-amd64/rpms/MariaDB-5.5.56-centos7-x86_64-server.rpm
gpgcheck=1

Once done, you run
sudo yum clean metadata

and try to install as normal.
Comment: can we run it from the centos 7 using yum install?
Comment: @MadhuraMhatre I updated to include instructions for `yum install`.
Comment: I tried this but when I tried to start using systemctl start mariadb. It failed with below error-
Failed to start mariadb.service: Unit not found.
Comment: @MadhuraMhatre I can't remember which version had this issue, but for some older installs of MariaDB, the service name was still called `mysql`
Answer: if you get No package MariaDB-Galera-server available. Check file /etc/yum.conf, if my case there was a string: exclude=ansible1.9,mysql,mariadb,mariadb-,Percona-XtraDB-,Percona--55,Percona--56,Percona--51,Percona--50 Just comment this string and install goes well.


Symmetric functions for a subgroup of permutations

Question: It is a well-known theorem that the ring of polynomials $P \in \mathbb{C}[x_1 , \dots , x_n]$ that are invariant under all the permutations $\sigma \in \mathfrak{S}_n$ is in fact $\mathbb{C}[e_1 , \dots ,e_n]$ where the $e_i$ are the elementary symmetric polynomials, that can be seen as being generated by
$$(x-x_1)(x-x_2)\dots (x-x_n). $$
We write this as
$$ \mathbb{C}[x_1 , \dots , x_n]^{\mathfrak{S}_n} = \mathbb{C}[e_1 , \dots e_n]. $$
Consider a subgroup $G \subset \mathfrak{S}_n$.
Is there a similar description of the ring of polynomials that are invariant under $G$ ?
By similar, I mean the following: is it possible to find explicitly a minimal finite set of polynomials $f_1 , \dots , f_r \in \mathbb{C}[x_1 , \dots , x_n]$ such that
$$ \mathbb{C}[x_1 , \dots , x_n]^G = \mathbb{C}[f_1 , \dots , f_r] ? $$
It is known (see for instance here, theorem 1.2) that $r$ can be chosen smaller than $\frac{(g+n)!}{g!n!}$ where $g=|G|$.
Answer: I don't know what you mean by similar description. There is always a finite set of invariant polynomials such that all invariant polynomials are consequences of these being invariant. That is they are generated as ring by these.
However the invariants cannot be expected to be algebraically independent.
A necessary and sufficient condition for this to happen is the subgroup be generated by reflections: that is in the linear span of $x_i$'s the representation of this subgroup should be generated by (pseudo) reflections.
The sufficiency was proved by Chevalley, and necessity by Shepherd-Todd. See book by Humphreys, or Kane, or Kemper.
EDIT: for computational aspects see the books by Kemper & Derksen, or the book by Sturmfels (Algorithmic Invariant Theory)
Comment: I have edited the question to be more precise. I'm looking for a way to compute the $f_i$.


How do I access a numpy array using the memory index?

Question: I'm learning numpy and I came across an example that uses np.nditer:
a = np.arange(6).reshape(2, 3)
for i in np.nditer(a):
    print i,

This prints out:
0 1 2 3 4 5

Which is the memory index of each element. Given these indexes, how can I access each element in the numpy array? Just doing a[i] gives an error, as the array has more than 1 dimension.
Comment: "Which is the memory index of each element" - what the heck gave you that idea?
Comment: Iterating over `np.nditer(a)` gives you the (scalar) elements of `a`, not the "memory index" of each element.
Comment: @user2357112 umm....from the docs: https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#using-an-external-loop "Observe that with the default of keeping native memory order, the iterator is able to provide a single one-dimensional chunk, whereas when forcing Fortran order, it has to provide three chunks of two elements each". Some people are so rude :(. I clearly said in the question I'm learing numpy, so my terminology may be off.
Comment: Sam, you should get used to reading the content, not the tone of the advice you are given when learning programming. While @user2357112 is not being especially sensitive, he is not being particularly rude either. Notice that the point he is making is 100% factually accurate, so getting worked up over unfortunate phrasing only hurts you by letting emotion get in the way of your learning.
Comment: I am not saying that nothing should offend you, just to consider raising your tolerance a bit.
Comment: I mean, the answer gives little context so in addition to being rude, it's also not very helpful...
Comment: Actually, the second comment pretty much answers your question, although more succinctly than you may be accustomed to.
Answer: nditer returns elements of the array, as 0d arrays themselves.  You have to use extra parameters to get the (multi)index.
If I do your iteration, but display information about the i besides it's value, you'll see:
In [132]: a = np.arange(6).reshape(2,3)
In [134]: for i in np.nditer(a):
     ...:     print(i, type(i), i.shape, i.dtype)

0 <class 'numpy.ndarray'> () int32
1 <class 'numpy.ndarray'> () int32
2 <class 'numpy.ndarray'> () int32
3 <class 'numpy.ndarray'> () int32
4 <class 'numpy.ndarray'> () int32
5 <class 'numpy.ndarray'> () int32

Or equivalently, using the repr display:
In [135]: for i in np.nditer(a):
     ...:     print(repr(i))
     ...:
array(0)
array(1)
...

np.nditer isn't a very useful iteration mechanism, especially not at the beginning.  It is best seen as a stepping stone toward using it in advanced cython code.  In other words, study https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html, all the way to the end.

Looks like your example comes from this page.

The most basic task that can be done with the nditer is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.

There are more direct ways of iterating through an array:
In [136]: for i in a: print(repr(i))   # by rows
array([0, 1, 2])
array([3, 4, 5])

In [139]: for ij in np.ndenumerate(a):   # with value and 2d index
     ...:     print(ij)
((0, 0), 0)
((0, 1), 1)
((0, 2), 2)
((1, 0), 3)
((1, 1), 4)
((1, 2), 5)

The multi_index example on the nditer page provides similar information:
In [141]: it = np.nditer(a, flags=['multi_index'])
     ...: while not it.finished:
     ...:     print("%d <%s>" % (it[0], it.multi_index))
     ...:     it.iternext()
     ...:
0 <(0, 0)>
1 <(0, 1)>
2 <(0, 2)>
3 <(1, 0)>
4 <(1, 1)>
5 <(1, 2)>


Expiring App Store Provisioning Profile

Question: I have an application in iTunes store, for which the distribution certificate (in key chain access) is expiring tomorrow. It was generated a year ago and even though I have renewed my iPhone developer program recently, I have not renewed any certificates or signatures yet.
When I set my test device (iPod touch) date to a few days from now and try running the app on it, it shows "The application ** cannot be opened because the provisioning profile has expired".
Does it mean all people who purchased my application will get this message in a day? Or it's just me?
In other words, when a distribution certificate/profile is not updated and is set to expire, will an application which was purchased before this date also stop working on all user devices? I am very concerned about my users, who depend on this app. Will the application be removed from the store automatically in this case, or I have to pull it out and re-submit?
I am most concerned about the current users. Apple "program renewal" page does not mention that I should also update all my apps in the store. Confused.
Answer: Your application will still work for the users who downloaded it from the store, and it'll even work for you if you download it from the store.  This only effects users who put the application on the device using a provisioning profile (ie you built it and installed it on your device from xCode).  Users past, present, and future will not notice anything different.
Comment: Thanks Matt. I will sleep normally today.
Comment: @Matt S. does this also affect Enterprise Apps not distributed through the app store? They seem to expire silently and simply just not open again
Comment: If your certificate is "distribution profile" and you are using Ad-hoc the app it expires silently and it is not opening again.
Comment: Yes, thanks! (relieved!) Do I have to update the app ASAP for new users to buy it, or it will function for them too?
Comment: Yes I'm curious about Enterprise apps too @MattS.
Comment: Enterprise app store provisioning profiles that expire will cause your apps built with the enterprise distribution profile to stop running.  No warning.  You need to stay on top of it and distribute new versions built with the new profile to users, or use MDM of some other mechanism to distribute the new profile to devices.

Expiring App Store Provisioning Profile


Existe alguma forma no HTML de impedir que o usuário de um site utilize o zoom dos navegadores?

Question: Na tag audio do html eu posso configurar o tamanho do tocador?
NO Explorer fica muito grande!
Meu problema é esse: eu gostaria que o uso do zoom in e do zoom out dos navegadores não surtisse efeito sobre uma determinada página onde só há o login pra fazer. Eu coloquei uma imagem de fundo, mas se der zoom in ou zoom out o formulário, que tem fundo transparente, vai para outra parte da imagem. Eu queria manter sempre no mesmo lugar. O background está configurado para se adaptar a qualquer tamanho de tela.
Gostaria de saber se isso é possível.
Comment: Desculpe mas acho que você esta pensando errado. Você não pode limitar o usuário a não poder dar zoom, só porque o seu layout fica feio ou errado, você deve otimizar/corrigir o layout para que ele funcione bem em qualquer zoom, pois se for uma necessidade física do usuário ter que usar bastante zoom para poder ler? como fica?
Comment: Por favor descreva melhor o seu problema e coloque HTML.
Comment: Eu não ignoro estes fatos, mas o quadro é realmente grande.
Comment: juntei à pergunta texto do seu comentário, mas ainda acho que está pouco clara para podermos ajudar.
Comment: Concordo plenamente com o @Jader
Answer: Apesar de concordar com os colegas nos comentários, algo que talvez possa ajudar é colocar no css a propriedade background-attachment.
body {
    background-image: url('endereco-da-imagem.gif');
    background-repeat: no-repeat;
    background-attachment: fixed;
}

Essa propriedade pode ser fixed, scroll ou local.
Você também pode fazer um background que se repita, um padrão, separando esta imagem do restante dos sprites.
Quanto ao player de audio você pode determinar a largura e altura no embed:
<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  <source src="horse.ogg" type="audio/ogg">
  <embed height="50" width="100" src="horse.mp3">
</audio>

Novamente: os colegas estão corretos. Você não deve tirar do usuário o controle que ele tem de seu próprio navegador, mas tornar sua experiência agradável em qualquer dispostivo.


How to dispose a WPF application GUI?

Question: I have a WPF application with a GUI on the MainWindow. I want to dispose this window after a while based on some user actions. But I want the application continue to run in background. I know that Window can be set to hidden, but it still uses the memory.How to destroy the MainWindow without quitting the WPF application? Also I would like to know if it is possible to relaunch the  MainWindow after it was disposed.
Comment: Not familiar with WPF, but wouldn't it be simpler to put the background task in a console app and have the console app control the appearance/disappareance/dispose/etc of any UI you need?
Comment: Is it possible to launch a WPF window from a console app?
Comment: I don't know about a window itself, but you could launch a WPF app from the console to handle the GUI.
Comment: That sounds like a good suggestion. I have to get to know more about it.
Answer: <code>this.Close(); //Will close the window but keep the application running.

var mw = new MainWindow();
mw.Show(); //Will open a new MainWindow and show it.
mw.Close(); //Close this one too.
</code>
That said hiding it is the best choice, the amount of memory it uses should really be irrelevant. That's what memory is there for.
Comment: So this.close() will free the memory used for MainWindow?
Comment: Okay. But My GUI is a little heavy. I think close would be better.

How to dispose a WPF application GUI?


Custom datetime field is treated as a string in Views when filtering

Question: I have added a datetime field using BaseFieldDefinition::create() to my custom entity:
BaseFieldDefinition::create('datetime')
         ->setLabel(t('Target date'))
         ->setCardinality(1)
         ->setRequired(TRUE)
         ->setSetting('datetime_type', 'datetime')
         ->setDisplayConfigurable('form', FALSE)
         ->setDisplayOptions('form', [
           'type' => 'datetime_default',
           'weight' => 10,
         ])
         ->setDisplayConfigurable('view', TRUE);

When I create a view of my custom entity and add a filter on this Target date field, I expect to see the date filter options:

is equal to
is greater than
is greater than or equal to

Instead, I see the string filter options:

is equal to
contains any word
contains all words

I assume there's something I need to set to let Views know that my custom datetime should be treated as a datetime and not a string, but I can't it.
How do I get the date filter options instead of the string filter options?
Comment: May be wrong data type. Try with data type datetime_iso8601, created.
Comment: Or on your class extend  EntityViewsData, you have to define filter id of field is date.
Comment: @MrD For the data type, do you mean `::create('datetime')` should be `datetime_iso8601` (tried, invalid) or `created` (stores data as a UNIX timestamp instead of as a Drupal datetime string, which is not what I want because I need to save the timezone info as well).
Answer: Normally Drupal generates the views data for entities automatically, but not yet in this case. So the solution is to extend EntityViewsData and add it yourself until this issue is resolved Base fields miss out on Views data (datetime.module).
You find an example here: Provide a documentation on how to provide views integration for base fields


Why does a UIStackView with a single view, fill Proportionally, and Layout Margins causes ambiguous constraint error?

Question: The following code is an attempt to add a UIStackView to a view controller, pinned on all edges with a little margin, and add a label to it.
I want the StackView to use .fillProportionally as its distribution mode ready for when I add more views into it later on.
It seems that for a single arranged subview whenever the distribution mode is  .fillProportionally and layout margins are used then I get an ambiguous constrain error (below). What is the cause of this error?
override func viewDidLoad() {
    super.viewDidLoad()

    let label = UILabel(frame: .zero)
    label.text = "ABC"

    let stack = UIStackView(arrangedSubviews: [label])
    stack.translatesAutoresizingMaskIntoConstraints = false
    stack.distribution = .fillProportionally
    stack.isLayoutMarginsRelativeArrangement = true
    stack.layoutMargins = .init(top: 10, left: 10, bottom: 10, right: 10)
    view.addSubview(stack)

    NSLayoutConstraint.activate([
        stack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        stack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        stack.widthAnchor.constraint(equalTo: view.widthAnchor),
        stack.heightAnchor.constraint(equalTo: view.heightAnchor),
    ])
}

}
Abiguous constraint error (WTFAutoLayout):
(
    "<NSLayoutConstraint:0x600001a432f0 'UISV-canvas-connection' UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'.leading == UILabel:0x7ff470913280'ABC'.leading   (active)>",
    "<NSLayoutConstraint:0x600001a423f0 'UISV-canvas-connection' UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'.trailing == UILabel:0x7ff470913280'ABC'.trailing   (active)>",
    "<NSLayoutConstraint:0x600001a425d0 'UISV-fill-proportionally' UILabel:0x7ff470913280'ABC'.width == UIStackView:0x7ff46d510030.width   (active)>",
    "<NSLayoutConstraint:0x600001a77f70 'UIView-leftMargin-guide-constraint' H:|-(10)-[UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':UIStackView:0x7ff46d510030 )>",
    "<NSLayoutConstraint:0x600001a42940 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide']-(10)-|(LTR)   (active, names: '|':UIStackView:0x7ff46d510030 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600001a423f0 'UISV-canvas-connection' UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'.trailing == UILabel:0x7ff470913280'ABC'.trailing   (active)>

Comment: Did you ever find an approach to this?  Whilst I understand DonMag's excellent explanation below of why this is happening, I can't begin to think of how to fix it or workaround it.
Answer: Editing with clarification because my original answer was not entirely correct...
First, the .fillProportionally distribution property of a UIStackView is very often misunderstood.
Second, we get some oddities when a stack view's distribution is .fillProportionally and the stack view's .spacing is not 0, or when the stack view also has .layoutMargins set.
The problem you're hitting is the way auto-layout calculates the proportional sizing.
Based on experimentation, auto-layout calculates the proportional widths of the views and then applies the layout margins, subtracting from the width of the last view to accommodate the space.
This can be easily demonstrated as follows:

There are 6 horizontal stack views, each set to 200-pts wide, Distribution set to .fillProportionally, and filled with either one or two views. The Red views have an intrinsic width of 25, the Green views 75.
The first stack view, with a single view and no layout margins, fills the width as expected... the red view takes up 100% of the space.
The second stack view, with two views and no layout margins, also fills as expected... the red view is 50-pts wide (25%) and the green view is 150-pts wide (75%).
The third stack view, though, starts showing the problem. The single view is give a proportional width of 100%, or 200-pts... but then the layout margins are applied. This shifts the view 10-pts from the left, but because auto-layout doesn't subtract space from the first subview, it actually extends 10-pts past the edge of the stack view (so the red view is still 200-pts wide).
The fourth stack view looks like it's doing what we want... proportional fill with 10-pts margin on each side... the Red view is 50-pts wide (25% of 200) but the Green view is only 130-pts wide. So auto-layout gave the two views 50-pts (25%) and 150-pts (75%) but then it applied the margins and took the 20-pts away from the Green view.
Using layout margins of left: 100 right: 0 or left: 0 right: 100 for the bottom two stack views makes it much more obvious. Again, for each of those, Red gets 50-pts (25%) and Green gets 150-pts (75%), but then the margin of 100-pts gets stripped from Green.

So, to answer the original question about why we get ambiguous constraints when we have a single arranged subview and layout margins, look at stack view 3. Auto-layout could not manage to give Red 100% of the space and apply margins, so it throws the layout error.

Here's the code to run the above example. If you comment-out the third stack view, you won't get the error:
class ProportionalStackExampleViewController: UIViewController {

    let outerStackView: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .vertical
        v.spacing = 8
        return v
    }()

    let outerStackFrame: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.layer.borderWidth = 0.5
        v.layer.borderColor = UIColor.blue.cgColor
        return v
    }()

    let infoLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
        v.numberOfLines = 0
        v.textAlignment = .center
        v.text = "Red views have intrinsic width of 25\nGreen views have intrinsic width of 75\nAll horizontal stack views are 200-pts wide\nTap any view to see its width"
        return v
    }()

    let sizeLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.text = "(width)"
        return v
    }()

    let myGreen = UIColor(red: 0, green: 0.75, blue: 0, alpha: 1.0)

    override func viewDidLoad() {
        super.viewDidLoad()

        for _ in 1...6 {
            let lbl = UILabel()
            lbl.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
            lbl.numberOfLines = 0
            lbl.textAlignment = .center
            outerStackView.addArrangedSubview(lbl)
            let sv = UIStackView()
            sv.translatesAutoresizingMaskIntoConstraints = false
            sv.axis = .horizontal
            sv.distribution = .fillProportionally
            sv.spacing = 0
            outerStackView.addArrangedSubview(sv)
        }

        view.addSubview(infoLabel)
        view.addSubview(sizeLabel)
        view.addSubview(outerStackFrame)
        view.addSubview(outerStackView)

        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([

            infoLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            infoLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            infoLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),

            sizeLabel.topAnchor.constraint(equalTo: infoLabel.bottomAnchor, constant: 20.0),
            sizeLabel.centerXAnchor.constraint(equalTo: g.centerXAnchor),

            outerStackView.topAnchor.constraint(equalTo: sizeLabel.bottomAnchor, constant: 20.0),
            outerStackView.widthAnchor.constraint(equalToConstant: 200.0),
            outerStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),

            outerStackFrame.widthAnchor.constraint(equalTo: outerStackView.widthAnchor),
            outerStackFrame.heightAnchor.constraint(equalTo: outerStackView.heightAnchor),
            outerStackFrame.centerXAnchor.constraint(equalTo: outerStackView.centerXAnchor),
            outerStackFrame.centerYAnchor.constraint(equalTo: outerStackView.centerYAnchor),
        ])

        // StackView 1
        if let lbl = outerStackView.arrangedSubviews[0] as? UILabel,
            let sv = outerStackView.arrangedSubviews[1] as? UIStackView {

            lbl.text = "One view, no layoutMargins"

            var v = ProportionalView()
            v.w = 25.0
            v.backgroundColor = .red
            sv.addArrangedSubview(v)

            var tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)

        }

        // StackView 2
        if let lbl = outerStackView.arrangedSubviews[2] as? UILabel,
            let sv = outerStackView.arrangedSubviews[3] as? UIStackView {

            lbl.text = "Two views, no layoutMargins"

            var v = ProportionalView()
            v.w = 25.0
            v.backgroundColor = .red
            sv.addArrangedSubview(v)

            var tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)

            v = ProportionalView()
            v.w = 75.0
            v.backgroundColor = myGreen
            sv.addArrangedSubview(v)

            tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)
        }

        // comment out this block to see the auto-layout error goes away
        // StackView 3
        if let lbl = outerStackView.arrangedSubviews[4] as? UILabel,
            let sv = outerStackView.arrangedSubviews[5] as? UIStackView {

            lbl.text = "One view\nlayoutMargins left: 10 right: 10"

            var v = ProportionalView()
            v.w = 25.0
            v.backgroundColor = .red
            sv.addArrangedSubview(v)

            sv.isLayoutMarginsRelativeArrangement = true
            sv.layoutMargins = .init(top: 0, left: 10, bottom: 0, right: 10)

            var tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)

        }

        // StackView 4
        if let lbl = outerStackView.arrangedSubviews[6] as? UILabel,
            let sv = outerStackView.arrangedSubviews[7] as? UIStackView {

            lbl.text = "Two views\nlayoutMargins left: 10 right: 10"

            var v = ProportionalView()
            v.w = 25.0
            v.backgroundColor = .red
            sv.addArrangedSubview(v)

            var tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)

            v = ProportionalView()
            v.w = 75.0
            v.backgroundColor = myGreen
            sv.addArrangedSubview(v)

            sv.isLayoutMarginsRelativeArrangement = true
            sv.layoutMargins = .init(top: 0, left: 10, bottom: 0, right: 10)

            tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)
        }

        // StackView 5
        if let lbl = outerStackView.arrangedSubviews[8] as? UILabel,
            let sv = outerStackView.arrangedSubviews[9] as? UIStackView {

            lbl.text = "layoutMargins left: 100 right: 0"

            var v = ProportionalView()
            v.w = 25.0
            v.backgroundColor = .red
            sv.addArrangedSubview(v)

            var tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)

            v = ProportionalView()
            v.w = 75.0
            v.backgroundColor = myGreen
            sv.addArrangedSubview(v)

            sv.isLayoutMarginsRelativeArrangement = true
            sv.layoutMargins = .init(top: 0, left: 100, bottom: 0, right: 0)

            tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)
        }

        // StackView 6
        if let lbl = outerStackView.arrangedSubviews[10] as? UILabel,
            let sv = outerStackView.arrangedSubviews[11] as? UIStackView {

            lbl.text = "layoutMargins left: 0 right: 100"

            var v = ProportionalView()
            v.w = 25.0
            v.backgroundColor = .red
            sv.addArrangedSubview(v)

            var tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)

            v = ProportionalView()
            v.w = 75.0
            v.backgroundColor = myGreen
            sv.addArrangedSubview(v)

            sv.isLayoutMarginsRelativeArrangement = true
            sv.layoutMargins = .init(top: 0, left: 0, bottom: 0, right: 100)

            tg = UITapGestureRecognizer(target: self, action: #selector(showWidth(_:)))
            v.addGestureRecognizer(tg)
        }

    }

    @objc func showWidth(_ sender: UITapGestureRecognizer) -> Void {
        if let v = sender.view {
            sizeLabel.text = "Width: \(v.frame.width)"
            sizeLabel.textColor = v.backgroundColor
        }
    }

}

class ProportionalView: UIView {
    var w: CGFloat = 1.0

    override var intrinsicContentSize: CGSize {
        return CGSize(width: w, height: 40.0)
    }

}

Comment:  What an excellent answer. This is exactly the insight I was missing, thank you!
Comment: Great explanation.  I've been trying to understand this for days.  I have a similar scenario although it's with inner stack views that have multiple subviews but when embedded inside a scrollView and then added to a viewController as a childVC, the proportional constraints start breaking. Still have no idea how to fix but at least I understand why it's breaking
Comment: @Anthony - when you say *"the proportional constraints start breaking"* ... do you mean subview constraints proportional to each other? Or are you trying to use `Fill Proportionally` on stack views?
Comment: @DonMag - I've tried laying it out in different ways.  The best seems to work but gives me UISV-spacing constraint conflicts. Happy to share code, raise seperate question or DM
Comment: @Anthony - either post it as a new question or post the code somewhere (GitHub, pastebin, etc) and I'll take a look.
Comment: @DonMag - thanks.  Posted here: https://stackoverflow.com/questions/66646871/why-do-embedded-uistackviews-filled-proportionally-with-spacing-and-layout-ma
Comment: @DonMag - not sure if you saw but would really appreciate some help.  Thanks in advance.
Answer: First of all, set translatesAutoresizingMaskIntoConstraints of label to false.
label.translatesAutoresizingMaskIntoConstraints = false

Since you want to set all the layoutMargins to 10, the width and height of stack can not be equal to view's width and height.
You need to accommodate that difference of 20 (both sides) in width and height.
So the constraints should be,
NSLayoutConstraint.activate([
    stack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    stack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    stack.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1, constant: -20),
    stack.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1, constant: -20),
])

Also, the margin spacing is included within the constraints, there is no need to write the below code. So remove it.
stack.isLayoutMarginsRelativeArrangement = true
stack.layoutMargins = .init(top: 10, left: 10, bottom: 10, right: 10)

Comment: Thanks for your answer!
I'm particularly looking for a solution to the implications of Layout Margins and fillProportional rather than a way of working around it.
For example if I were trying to achieve the same layout by subclassing UIStackView instead of embedding it then I wouldn't want to touch the width and height constraint's constants


how to run bash inside python loop

Question: I have two files as below and I want to loop over the two files to create different combinations based on line in each file then input them as i and j to bash script in python:
file1
aaaa
tttt
cccc
gggg

file2
gggg
tttt
aaaa
cccc
ssss

I want to loop on the two files and then input them to a bash script. so every combination of i and j should be an input for bash script:
f1=[]
f2=[]
file1=open('file1.txt','r')
file2=open('file2.txt','r')

for i in file1:
    f1.append(i)

for j in file2:
    f2.append(j)

for i in f1:
    for j in f2:
        print(i)
        print(j)

bashscript i j

Comment: Use os.system() or subprocess.call() to execute
Answer: You can use subprocess.run() or subprocess.check_output()
depending whether you need to simply run the script, or if you want the output to be returned in Python.
Here a silly example
bash_example.sh is
echo 'Hello from Bash'

From within python:
from subprocess import check_output

check_output('bash bash_example.sh', shell=True)
b'Hello from Bash\n'

Comment: If you are explicitly running Bash anyway, `shell=True` is pretty silly (you are creating _three_ shells to execute _one_ `echo`).  Probably try `check_output(['bash', 'bash_example.sh'])` though of course if the Bash script is properly executable, you can just `check_output(['bash_example.sh'])`. What's probably more interesting to the OP is how to pass Python variables as arguments to the script, but this is obviously a common duplicate.
Comment: @tripleee You are right. I often use `shell=True` to avoid passing a list instead of a string to `check_output` and `run`.

how to run bash inside python loop


Does the sum of updated mixture weights in EM algorithm equal 1 in M step, why?

Question: I am usign EM algorithm to estimate my model's parameters. As you know, the mixture weight must be sum to one. $\sum \pi_n = 1$ where $n$ is the number of mixture component. In M step we can find the updated mixture weight for each iteration as follows: $\pi^{i+1} = mean(\tau)$ where $i$ is the number of iteration. My question here, how to prove that, the sum of updated mixture weight will also equal to one?
Any help please?
Answer: Let us say that we consider a mixture model of $K$ components and the inner density is $f(\dot;\Theta)$, i.e. a gaussian density if we consider GMMs and so on.
First of all the Q-function looks like
$$Q(\Theta, \Theta^{(\text{old})}) = \sum_{i=1}^n \sum_{k=1}^K T_{i,k}^{(\text{old})} \left[ \log \tau_k + \log f(x_i;\Theta)\right]$$
(see https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm for the GMM case with $k=2$ but it works just as fine with any other density $f(\dot;\Theta)$ and $K$ arbitrary).
It is easy to see that whenever you have two functions $F, G$ then
  $$ \text{argmax}_{\Theta} (F(\Theta) + G(\Theta)) = \text{argmax}_{\Theta} F(\Theta) + \text{argmax}_{\Theta} G(\Theta)$$
so that we can maximize the $\tau$ and the $\Theta$ individually. Now we want to get
$$\text{argmax}_{\tau} \sum_{k=1}^K \left(\underbrace{\sum_{i=1}^n T_{i,k}^{(\text{old})}}_{=: A_k} \right) \log(\tau_k)$$
under the condition that $\sum_{k=1}^K \tau_k = 1$ and $0 < \tau_k < 1$, i.e. the fact that $\sum_k \tau_k = 1$ does not pop out magically but rather we demand it and we maintain it throughout the execution of the EM algorithm and we have to work for it.
Put $f(\tau) = \sum_{k=1}^K A_k \log(\tau_k)$. Now, solving this problem is just the right application for the theorem of Lagrange (https://en.wikipedia.org/wiki/Lagrange_multiplier), i.e. we put
$$g(\tau) = (\sum_{k=1}^K \tau_k) - 1$$
and now we know that any maximal $\tau$ must be a 'critical' point of the so-called Lagrange function
$$L(\tau, \lambda) = f(\tau) - \lambda g(\tau)$$
i.e. we differentiate by each $\tau_k$ and by $\lambda$ and all these have to be zero. Differentiating by $\tau_k$ (and setting to zero) yields
$$0 = \partial_{\tau_k} L = \frac{A_k}{\tau_k} - \lambda$$
i.e.
$$\tau_k = -\frac{A_k}{\lambda}$$
differentiating by $\lambda$ and setting to zero yields the (original) restriction
$$0 = \partial_{\lambda} L = g(\tau) = (\sum_{k=1}^K \tau_k) - 1$$
so that
$$ 1 = \sum_{k=1}^K \tau_k = -\sum_{k=1}^K \frac{A_k}{\lambda} = \frac{-\sum_{k=1}^K A_k}{\lambda}$$
thus
$$\lambda = -\sum_{k=1}^K A_k$$
and
$$\tau_k = -\frac{A_k}{\lambda} = \frac{A_k}{\sum_{k'=1}^K A_{k'}}$$
Now it is easy to see that $\sum_{k} \tau_k = 1$ but this is not a suprise!!! We created the $\tau_k$ in a way that this equation must be satisfied.
Long answer cut short:
We do not prove it, we maintain this property throughout.
Regards,
FW
Comment: Just sum them up then you arrive at $\sum_{k} A_k / \sum_{k'} A_{k'}$ and then the denominator and the numerator are the same. Just replace k' by k...
Comment: Thank you for your very good answer. I was thinking about that today. However, if someone asked why "Now it is easy to see that $∑_{k}τ_{k}=1$"? is the answer because we take the mean of the $A_k$? sorry, if this is a silly question.


Laravel 4.1 eager relationship "with" ignoring constraint clause

Question: // class User
public function roles() {
    return $this->belongsToMany('Role', 'user_roles', 'uid', 'rid');
}

// class Role
public function users() {
    return $this->belongsToMany('User', 'user_roles', 'rid', 'uid');
}

// sql
-- user
id | name | other fields

-- user_role
id | name

-- user_roles, uid fk to user and rid fk to user_role
uid | rid

I am trying to load users with a certain role, i.e. load all editors, with the following code:
<?php
$roleName = 'editors';
return \User::with(array('roles' => function($query) use($roleName) {
    $query->where('name', '=', $roleName);
}))->get();

The above code returns every user, ignoring the $query->where. What's wrong?
Answer: Read the docs for with and whereHas . The latter is what you want here:
return \User::whereHas('roles', function($query) use($roleName) {
    $query->where('name', '=', $roleName);
})->get();

Comment: I was missing the difference between with and whereHas. Thanks!
Answer: another option that you can also try:
$role = new Role::find($role_id);
return $role->users->all();

This will return all users
or if you have some wheres:
$role = new Role::find($role_id);
return $role->users()->where('name','like','%foo%')->get();

this will return all users with like name of foo


how to complete arbitrary basis knowing 2 orthonormal vectors of Rd (d > 2)

Question: In a paper the following statement is used: "To construct the matrix B, complete the vectors (y, x) to an arbitrary basis of Rd and then apply the Gram-Schmidt orthonormalisation".
assume we know x and y.
Question:how to complete the 2 vectors to arbitrary basis in Rd?
(Rd is the dimensionality of the space)
Comment: Theoretically? Then it doesn't matter, completion exists. Practically? Choose random vectors. Anyway: Not suited here, better for math.SE.
Answer: As the question is migrated to math.SE, I turn my comment into an answer.
From the theoretical side, there is no problem, since there exists an extension. To see this, consider the orthogonal complement of the space spanned by $x$ and $y$. It is itself a vector space (of dimension $d-2$). This vector space has a basis, as any vector space has.
Practically, one could choose $d-2$ random vectors $x_1,\dots,x_{d-2}$ (e.g. be choosing each coordinate following a Gaussian distribution). This will give (together with $x$ and $y$) a basis of $\mathbf{R}^d$ with probability one: The vector $x_1$ will be in $\mathrm{span}(x,y)$ probability zero (since $\mathrm{span}(x,y)$ is a Null set for the chosen distribution) and the same is true for $x_2$ w.r.t. $\mathrm{span}(x,y,x_1)$, and so forth…