Does $f\otimes_A 1_{A/m}:M\otimes A/m\to N\otimes A/m$ injective for all maximal $m$ imply $f$ is an isomorphism?

Question:
Let $A$ be a commutative ring. Suppose $f\colon M\to N$ is a morphism of free $A$-modules of equal, finite rank. If $f\otimes_A 1_{A/m}$ is injective for all maximal ideals of $A$, does this imply $f$ is an isomorphism?

I suspect it is true, since it seems similar to statements about localizing at maximal ideals in commutative algebra.
Fixing bases of $M$ and $N$, let $D$ be the determinant of $f$ with respect to these bases. Towards a contradiction, suppose $D$ is not a unit, so that $f$ is not invertible. Then $D$ is contained in some maximal ideal $m$. By hypothesis,
$$
f\otimes_A 1_{A/m}\colon M\otimes_A A/m\to N\otimes_A A/m
$$
is injective, and these are now $A/m$-vector spaces of equal, finite dimension, so $f\otimes 1_{A/m}$ is an isomorphism.
As a scalar, $D$ is now $0$ since it's in $m$, is there a contradiction to be found using $f\otimes 1_{A/m}$?
Comment: If $D=0$ modulo the maximal ideal, it says that the map of vector spaces over $A/m$ of the same rank can not be an isomorphism
Comment: For a map $f:V\to V$ of finite dimensional vector spaces over a field, $f$ is an isomorphism if and only if $\det f\neq 0$.
Comment: @Mohan Sorry, why exactly? That's what I'm having a hard time seeing.
Comment: Related: http://math.stackexchange.com/questions/611900/lemma-1-3-4b-in-bruns-and-herzog/612188#612188.
Answer: Suppose first that $A$ is local with maximal ideal $\mathfrak m$. Then you want to show that if $\hat f:M/\mathfrak mM\to N/\mathfrak mN$ is injective $f$ is an isomorphism. Since this is an injective map of $k=A/\mathfrak m$ vector spaces of equal dimension it is also onto, and this means that $f$ itself is onto (use Nakayama). It suffices you show that an onto map $f:M\to N$ with $M,N$ free of equal rank must be an isomorphism. There is a lovely argument by Vasconcelos: $M=A^n$ is an $A[X]$ module by $Xm=f(m)$ and the hypothesis is that $\mathfrak aM=M$ for the ideal $(X)$ of $A[X]$. By Nakayama there is an element $u=X p(X)\in \mathfrak a$ such that $(1-Xp(X))M=0$. It follows that if $f(m)=Xm=0$ then $m=0$, so $f$ is a monomorphism. Note this works when $f:M\to M$ is an endomorphism with $M$ finitely generated.
This proves the claim for local rings. Can you try to prove the general case now?
Comment: Thanks Pedro, is the idea to localize at any maximal ideal, and then use the isomorphism  $A/m\cong A_m/m_m$? Then $f\otimes 1_{A/m}$ injective implies $f\otimes 1_{A_m/m_m}$ is injective, and since $A_m$ is local, using the case you've shown here, $f$ is an isomorphism?
Comment: There is no need to invoke Vasconcelos' result in this case: if $A^n\to A^n$ is onto then it's iso by using an elementary matrix argument.
Comment: @user26857 Sure, just thought it was something worth mentioning.
Comment: What is a quick way of getting $f$ is onto when the ring is not local? Somehow one would want $N=f(M)+JM$, where $J$ is the jacobson radical.
Comment: Looks like one can finish the general case by localization, and not as what i wanted like above.
Comment: @user114539 Yes, thats the idea.
Answer: A homomorphism $f$ of free modules of the same rank, say $n$, corresponds to an $n\times n$ matrix, say $M$.
Notice that $f$ is an isomorphism iff $M$ is invertible.
Since $f$ modulo every maximal ideal is injective, hence bijective, we have that $M$ is invertible modulo every maximal ideal, that is, $\det M\ne0$ for every maximal ideal. This shows that $\det M$ is an invertible element of $A$, hence $M$ is invertible.
Comment: This answer is an expanded version of Mohan's comments.


Error Using Phusion Passenger - Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)

Question: I have finally got RoR set up on my server using Phusion Passenger and the default RoR applicatioon page shows, however when I click 'About your application's environment' I get an error saying 'Ruby (Rack) application could not be started' and under the Error Message bit 'Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)'.
If I do 'bundle install' at the command line I get a list of 'Using x (y)' style messages including this:
Using sqlite3-ruby (1.2.5)
(I had to downgrade to 1.2.5 due to an issue with the latest one)
I really dont understand why I am getting the error above as sqlite3-ruby is obviously there.
Stack Trace On Error Page:
0   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    87  in `materialize'
1   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `map!'
2   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `materialize'
3   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  90  in `specs'
4   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  135     in `specs_for'
5   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  124     in `requested_specs'
6   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/environment.rb     23  in `requested_specs'
7   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb     11  in `setup'
8   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler.rb     107     in `setup'
9   /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  326     in `prepare_app_process'
10  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   155     in `initialize_server'
11  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  572     in `report_app_init_status'
12  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   153     in `initialize_server'
13  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    204     in `start_synchronously'
14  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    180     in `start'
15  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   128     in `start'
16  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  253     in `spawn_rack_application'
17  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     132     in `lookup_or_add'
18  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  246     in `spawn_rack_application'
19  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     82  in `synchronize'
20  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     79  in `synchronize'
21  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  244     in `spawn_rack_application'
22  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  137     in `spawn_application'
23  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  275     in `handle_spawn_application'
24  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `__send__'
25  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `server_main_loop'
26  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    206     in `start_synchronously'
27  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/helper-scripts/passenger-spawn-server   99

Edit:
This is my passenger.conf file.
LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/ext/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6
PassengerRuby /opt/ruby-enterprise-1.8.7-2011.03/bin/ruby
PassengerMaxPoolSize 2

Answer: You seems to have two versions(ruby-enterprise-1.8.7 and 1.9.1) of ruby runtimes installed. Make sure you install the sqlite3-ruby gem (and passenger) on the same runtime.
You have installed the passenger gem in 1.9.1 ruby runtime however you are setting the PassengerRuby to 1.8. I think you shouldn't do that. Set it to 1.9.1. And make sure you run bundle install (inside your rails project folder) with ruby 1.9.1, so that it installed all needed gems to the 1.9.1 runtime.
PassengerRuby /path/to/1.9.1/here/bin/ruby

If you want to manage different versions of ruby runtimes with ease i suggest looking at RVM
Comment: This means that Passenger wont run using enterprise? This is the one I want to run with.
Comment: I am assuming it shouldn't be using both. How can I make sure it only uses the enterprise version?
Comment: Just another thought, - Is it actually using both versions or just accessing the passenger files?
Comment: I just edited my question. Hopefully this answers your questions.
Comment: If you want to use ree runtime, install the passenger gem to 1.8.7 runtime (so the PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6 will look something like PassengerRoot /usr/local/lib/ruby/gems/1.8.7/gems/passenger-3.0.6) The important thing is to use one runtime for passenger and your rails app.
Answer: Your Passenger configuration seems wrong.. you supply the PassengerRoot of a passenger gem in your 1.9.1 universe, but point to PassengerRuby in the 1.8.7 universe.
I would advise recompiling the passenger apache module from Ruby 1.9 using passenger-install-apache2-module and change your configuration according to the instructions given by the installer.
Also, if you're using Rails I suggest you upgrade to 1.9.2 or stick with 1.8.7. Rails does not play nice with Ruby 1.9.1.


Write icon to disk in VB.NET

Question: I have an icon. Is there a way to save it somewhere on the disk?
I am dealing with a function:
Private Function ReturnIcon(ByVal Path As String, ByVal Index As Integer, Optional ByVal small As Boolean = False) As Icon

Is there a way to save this to an ICO file (file extension .ico)?
Comment: Sharing your research helps everyone. Tell us what you found and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer:) Good Luck!
Answer: Have you even tried searching with Google, or on SO?
Icon.Save()
Edit 1: Disregard this. I noticed you wish to save it as an ico.
Edit 2: If you wish to preserve the icon format, then you're going to end up with a low quality output (See this comment).
I you are extracting the icon from an executable file, I recommend using something like this to extract and save the icon resource.
Comment: Downvoting is a great way to let me know which areas of my answer need improvement and that the other answers addressed the problem better than I did. Oh wait...
Comment: I'll get you back to zero. [We're all trying to share the love this summer](http://blog.stackoverflow.com/2012/07/kicking-off-the-summer-of-love/?cb=1). I didn't downvote but I'm guessing its more the tone...

Write icon to disk in VB.NET


Determining roman numeral notation

Question: I am just starting to learn music theory so if I'm making an obvious mistake, forgive me.
Given the chord progression D major B♭ major F major C major, I have assumed that it is in the key of F major and is some form of the familiar chord progression vi IV I V. The only difference is that the D is major instead of minor.
I looked into secondary dominant chords to write the D major in the form "function/key" but I couldn't figure out how to write it since D is not the dominant of any chord in the progression.
Would it be correct to simply write it as VI IV I V with "VI" capitalized or am I missing something?
Answer: You are correct: in F major, VI capitalized means D major, whereas vi in lower-case means d minor.
By the way, your A# major should be written as Bb major.
Answer: Generally speaking, capitalized roman numerals (VI) represent major chords and lower-case (vi) represent minor.
However, you should never arbitrarily substitute chord qualities! Most of the time, a non-diatonic chord has some kind of secondary function and this must be notated in your analysis. Labeling a D major in the key of C as a II instead of a V/V will most likely cost you points on an academic assignment!
Now, there are a few ways to analyze D major in the key of F:
First, VI is a chromatic submediant of I and is perfectly viable...if it comes from or goes to a I. So I-VI and VI-I are just fine, but, unfortunately, VI-IV is not, so that's out.
Next, in a minor key, major V is often used instead of minor v as the dominant function, so V-i is perfectly acceptable. Because of this, we can use the V of any minor degree as a secondary dominant. In this case, we would use V/ii (D->Gm). But this would mean we have to resolve to ii in order to establish the dominant relationship and make it functional, so let's try again!
Clearly, context matters! So, finally, let's look at what comes next: Bb, or IV. Now that we know where we are going, let's assume we need to find some kind of secondary function to Bb. Since D major is a chromatic mediant of Bb, III-I is perfectly valid (just like VI-I above). But this is a secondary function, so in the key of F it becomes III/IV, a secondary chromatic mediant.

Determining roman numeral notation


Where to add DNS for my domain i.e. ns1.mydomain.com (Any disadvantages?)

Question: My VPS hosting provider has agreed that I can use their DNS servers to present a more professional look by giving out vanity nameservers to my clients.
For example, they have said I need a DNS records directing ns1.MyDomain.com to the IP of ns1.VPSProvider.com.
Therefore any DNS queries sent to ns1.MyDomain.com will then be sent to the IP for ns1.VPSProvider.com instead and they will respond
The domain is registered with 123-reg. Therefore, how/where do I add a dns record for ns1.MyDomain.com would it be with 123-reg's help? Is it just a CNAME record of ns1?
Secondly, are their any disadvantages by having a vanity nameserver like this e.g. spam, google, rdns etc
Comment: After a little research may it may require creating 2 A records for ns1 and ns2 for MyDomain.com pointing to VPSProvider.com nameserver IP Addresses.
And then creating 2 NS records for ns1.MyDomain.com and ns2.MyDomain.com
Would that be correct, could someone please confirm?
Comment: Vanity domain names, I understand. But vanity name servers? Very few people look at the address bar, or know what a domain name is. But how many people fetch the NS records of a domain to see if you are "professional"?
Comment: If you have clients that you sell hosting too to go along with any website you have developed; would it not be far more professional to tell them to point their domain nameservers to ns1.MyDomain.com rather than ns1.SomeOtherHostingCompany.com?
Comment: It is not professionnal, it is deceiving, since you do not really manage the name server.
Comment: If people are knowledgeable enough to use dig to fetch the NS records, they can certainly use whois to find "who you are hosting with"...
Comment: Maybe so, but I am not intentionally out to deceive anyone for malicious reasons. I am simply just trying to present a professional image and lessen the confusion; when taking over the hosting of a customers website, with regards to nameserver changes. Further, possibly except for the very high level hosting providers how many resellers etc do the same thing? But this question I asked wasn't to debate these type of semantics.
Answer: You cannot use CNAME records since the right-hand side of a NS record cannot be an alias (RFC 1035, section 3.6.2).You have to use A and AAAA records and keep them in synch with VPSProvider.com. Not easy because they can change suddenly.
Frankly, if you do not know the DNS at all, it is better to not use "vanity name servers", specially for paying customers...
Answer: You need to create two A records pointing ns1.mydomain.com to the ip address of ns1.vpsprovider.com, and ns2.mydomain.com to the ip address of ns2.vpsprovider.com.  CNAME entries add extra dns lookups, and should be avoided when creating nameservers (and infact break RFCs).
If you're using these vanity nameservers for your own domain and not just for other people's domains, then you'll also need to set the ns records for your domain to your own nameservers and the ip addresses of the nameservers provided.  You'll want to do all this on your vps provider's nameservers rather than 123-reg's because you'll no longer be using 123-reg for anything other than domain registration.
There are no disadvantages in having a nameserver setup like this other than the fact that you then have to use the control panel of the vps provider to change your dns rather than the 123-reg control panel (though that may actually be an advantage).
I don't recall if 123-reg provide .uk nameservers or not.  If they do, and your domain is a .uk domain, then there will be a small theoretical loss of speed by switching to a .com nameserver.  However this won't be noticable.
Comment: @Kaerast - so I was on the correct path with my first comment? So whatever the nameserver entries are on 123-reg's side for MyDomain.com would be ignored once I have added the NS entries to the control panel of my VPSProvider.com?
Comment: You'll need to set the nameservers and ip addresses of those nameservers in the 123-reg control panel. Once you have done that, the rest of the dns configuration is done at your vps provider.
Comment: Thanks, 1 final thing so suppose the reason my change at 123-reg ("This is not a valid nameserver") is because the changes made to MyDomain.com have not propagated through.
Comment: You need to add both the ip address and the name of the nameserver when using a nameserver on the same domain.  You also need to make sure that the nameserver at the vps provider is ready to respond (try dig yourdomain.com @ns1.vpsprovider.com). Finally 123-reg sometimes just doesn't like you changing nameservers, so contact support if it's all otherwise working.


Dynamically grow menu based on terms in vocabulary?

Question: As terms are added to a vocabulary, I need these terms to be incorporated into a menu with a custom URL structure.  For example, I might have the Restaurant Taxonomy which has the following terms:

McDonalds
Taco Bell
Wendys

I need to have a menu generated that matches a particular pattern with the term names plugged in - this pattern can be arbitrary.  For example, I have the pattern /restaurants/<term-name> would generate a menu with the following links:

/restaurants/mcdonalds
/restaurants/taco-bell
/restaurants/wendys

As terms are added, this menu needs to grow dynamically.  How can this be accomplished?
Answer: The Taxonomy Menu module will be able to handle that...

Transform any of your taxonomy vocabularies into existing menus easily!
Features

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules

The module page also links to a tutorial called How to add a block menu of tags (or other taxonomy terms) on a Drupal site in conjunction with the Menu Block module in case you need that functionality.


bind won't start neither showing the error

Question: I have been using debian, so things are different in CentOS 7.
I was trying to setup bind however it fails to start. and doesn't show exact error.
Error :
systemctl status -l named.service
named.service - Berkeley Internet Name Domain (DNS)
   Loaded: loaded (/usr/lib/systemd/system/named.service; enabled; vendor     preset: disabled)
   Active: failed (Result: exit-code) since Mon 2016-08-08 20:20:25 UTC; 8s ago
  Process: 8822 ExecStartPre=/bin/bash -c if [ ! "$DISABLE_ZONE_CHECKING" ==     "yes" ]; then /usr/sbin/named-checkconf -z /etc/named.conf; else echo "Checking     of zone files is disabled"; fi (code=exited, status=1/FAILURE)

Aug 08 20:20:25 asdfs bash[8822]: zone IP.in-addr.arpa/IN: loaded     serial 2016082802
Aug 08 20:20:25 asdfs bash[8822]: zone localhost.localdomain/IN: loaded     serial 0
Aug 08 20:20:25 asdfs bash[8822]: zone localhost/IN: loaded serial 0
Aug 08 20:20:25 asdfs bash[8822]: zone     18.104.22.168.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa/IN:     loaded serial 0
Aug 08 20:20:25 asdfs bash[8822]: zone 184.108.40.206.in-addr.arpa/IN: loaded serial 0
Aug 08 20:20:25 asdfs bash[8822]: zone 0.in-addr.arpa/IN: loaded serial 0
Aug 08 20:20:25 asdfs systemd[1]: named.service: control process exited, code=exited status=1
Aug 08 20:20:25 asdfs systemd[1]: Failed to start Berkeley Internet Name Domain (DNS).
Aug 08 20:20:25 asdfs systemd[1]: Unit named.service entered failed state.
Aug 08 20:20:25 asdfs systemd[1]: named.service failed.

My reverse File:
$TTL 1d ;
$ORIGIN IP.IN-ADDR.ARPA.
@       IN      SOA     ns1.domain1.org.   info.domain1.org. (
                                   2016082802
                                   7200
                                   120
                                   2419200
                                   604800
)
    IN      NS      ns1.domain1.org.
    IN      NS      ns2.domain1.org.
1       IN      PTR     ns1.domain1.org.
2       IN      PTR     ns2.domain1.org.

@       IN      SOA     ns1.domain2.org.   info.domain2.org. (
                                   2016080931
                                   7200
                                   120
                                   2419200
                                   604800
)
    IN      NS      ns1.domain2.org.
    IN      NS      ns2.domain2.org.
1       IN      PTR     ns1.domain2.org.
2       IN      PTR     ns2.domain2.org.

My named.conf:
//
// named.conf
//
// Provided by Red Hat bind package to configure the ISC BIND named(8) DNS
// server as a caching only nameserver (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//

options {
#       listen-on port 53 { 127.0.0.1; };
#       listen-on-v6 port 53 { ::1; };
    directory       "/var/named";
    dump-file       "/var/named/data/cache_dump.db";
    statistics-file "/var/named/data/named_stats.txt";
    memstatistics-file "/var/named/data/named_mem_stats.txt";
    allow-query     { localhost;MY.SERVER.IP.ADDRESS; };

    /*
     - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
     - If you are building a RECURSIVE (caching) DNS server, you need to enable
       recursion.
     - If your recursive DNS server has a public IP address, you MUST enable access
       control to limit queries to your legitimate users. Failing to do so will
       cause your server to become part of large scale DNS amplification
       attacks. Implementing BCP38 within your network would greatly
       reduce such attack surface
    */
    recursion yes;

    dnssec-enable yes;
    dnssec-validation yes;
    dnssec-lookaside auto;

    /* Path to ISC DLV key */
    bindkeys-file "/etc/named.iscdlv.key";

    managed-keys-directory "/var/named/dynamic";

    pid-file "/run/named/named.pid";
    session-keyfile "/run/named/session.key";
};

logging {
    channel default_debug {
            file "data/named.run";
            severity dynamic;
    };
};

zone "." IN {
    type hint;
    file "named.ca";
};

zone "domain2.org" IN {
    type master;
    file "/etc/named/domains/domain2.db";
    allow-update { none; };
};

zone "domain1.org" IN {
    type master;
    file "/etc/named/domains/domain1.org.db";
    allow-update { none; };
};

zone "IP.in-addr.arpa" IN {
    type master;
    file "/etc/named/domains/reversefile.rev";
    allow-update { none; };
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

Any help?
Comment: Have you looked at your syslog logs for named errors?  Most likely /var/log/messages...
Answer: I guess it's the DISABLE_ZONE_CHECKING environment variable. I bet you have it set somewhere, in the /etc/sysconfig/named as a wild guess.
Comment: Nope, its commented. and after struggling with it, it starts successfully, however my domain isn't up. if I ping in my server e.g `ping ns1.domain.com` or `ping domain.com` I receive good response. I have also added the domain and server IP to my `/etc/hosts/` as `IP domain.com`. named-checkzone gives me a good response. `named-checkzone domain.com domain.com.db
zone domain.com/IN: loaded serial 2016080931
OK`. I have configured the name server in the domain, but domain remains down.
Comment: I believe that my named is privately setup. I mean my domain is only working on the server. e.g if I `wget` a file from my domain on server, it successfully downloads. However, publicly its down.
Answer: Finally I figured it out. Actually in my named.conf file I had used allow-query { localhost; my.ip; }; and I wasn't using allow-transfer So i just swapped. In short I added following to my named.conf
allow-query { any; };
allow-transfer { localhost; server.ip; };

So its working now. Thank @yoonix for suggesting me about /var/log/messages


Qual o melhor tipo para armazenar área, volume e perímetro?

Question: Decimal, Numeric ou Float, qual a melhor opção para armazenar área ou volume?
Eu usaria o Decimal, mas gostaria de ver a opinião de outros também.
Parece que não, mas o tipo certo ou o mais próximo disso faz toda a diferença, até porque apanhei com um banco com tipos REAL e não quero perder tempo com tipos errados. Usei c# pois nela irei mapear os tipos do banco pelo C#.
Answer: De forma geral o decimal é o mais correto. Mesmo que não precise da exatidão dele se interagir com outras unidades que precisam, a ruim contamina a boa e tudo fica errado.
De forma geral eu vejo zero vantagens em usar um tipo de ponto flutuante binário. Sim, pode ter mais performance e deve ocupar menos memória, mas o risco é muito grande, principalmente na mão de programadores que não são muito afiados em desenvolvimento de software e façam tudo com muita minúcia, com profundo entendimento de todas as consequências. E tudo seja absurdamente bem documentado, o que nunca acontece.
Veja mais em Qual a forma correta de usar os tipos float, double e decimal?.
Coloquei no GitHub para referência futura.
Answer: É pouco difundido mas existe os tipos espaciais no C#. Claro que é possível trabalhar com qualquer tipo de dado com ponto flutuante, mas além de armazenar certamente você vai querer fazer cálculos com estes pontos.
Já precisei para um trabalho acadêmico e foi uma mão na roda.
https://docs.microsoft.com/pt-br/ef/core/modeling/spatial


MySQL ODBC error "server has gone away"

Question: Occasionally we're seeing an error from ASP pages:
Microsoft OLE DB Provider for ODBC Drivers error '80004005'

[MySQL][MyODBC 5.00.11][MySQL] 2006 MySQL server has gone away

We're handling it the best way we can in ASP but it still crops up. I think it's more to do with the MySQL ODBC driver than the ASP code. We never see this with PHP code we also have running under the same IIS server, however PHP re-connects each time it is ran, whereas I believe the ODBC driver connects once and stays connected.
I've checked the settings in the driver but there doesn't seem to be anything I can change to help mitigate the problem.
Can anyone explain why this is happening and how to reduce the number of times it happens?
Answer: The problem is that the connection is timing out. This is not a setting that you can change at the ODBC level. I got round it by polling the connection every 10 seconds with a simple query. That keeps the connection alive.
Answer: Not sure about ASP, but in Java/Tomcat/DBCP we have ability to stick a simple test statement (such as SELECT 1) in connection pools before actually getting the connection. Maybe there is something similar in ASP, too?

MySQL ODBC error "server has gone away"


Could not resolve host after removing KDE packages

Question: When the server was deployed, KDE was installed, it was not needed and I removed it.
Now when executing queries with any utilities (including apt) I get Could not resolve host.
What could I delete by mistake and how to make it work?
My server is Debian 9.2 (stretch)
Comment: what´ s in /etc/resolv.conf? As to what package, I think you need the dnsutils (https://packages.debian.org/stretch/dnsutils)
Comment: Great thanks! You saved my day! After I googled anout dns utils, I found that I also need bind_9 and now It's work!
Comment: On Linux the DNS is just managed with `/etc/resolv.conf` setting a DNS server like `188.8.131.52` there is enough to get name resolution to work. The DNS config file (`/etc/resolv.conf`) is the basis, every system/disto/config use an additional application to manage the DNS like: Resolvconf, Dnsmasq, NetworkManager (KDE), Rdnssd, Netconfig, Resolved, Bind, etc. All those DNS's applications does edit/update `/etc/resolv.conf` with the currently used DNS, on the other hand all network applications (client) does read the config file through `libc` to know what DNS to use to resolve internet's domains.
Answer: Thanks to natxo asenjo, I was need in dnsutils and bind_9


Integrating $\int_{0}^{4} \frac{x}{\sqrt{1+2x}} dx$

Question: I was doing questions in my textbook and I was not able to integrate the following/got it wrong and I couldn't figure out why after several attempts.
$$\int_{0}^{4} \frac{x}{\sqrt{1+2x}} dx$$
The solutions manual started by doing the following:
$$x = \frac{u-1}{2}$$
$$u=1+2x$$
The $u$ part I understand but where are they getting $x = \frac{u-1}{2}$?
Subsequently they proceeded by:
$$\frac{1}{2}\int_{0}^{4} \frac{\frac{u-1}{2}}{u^{.5}} dx$$
Again I am totally fine with everything except for that $\frac{u-1}{2}$ in the numerator.
Comment: Also, the integral they provide in terms of $u$ is WRONG. It needs a change of limits, namely it should be $$\int_1^9 {blah \space du} $$
Comment: Well, you have an $x$ in the numerator; how do you turn it into $u$? Answer: The first equation you wrote.
Comment: Isn't is simply equivalent to $u=1+2x$?
Comment: Simply $u=2x+1\to 2x=u-1\to x =\frac {u-1}{2}$. Also, avoiding writing non-$\Bbb Z$ powers using decimal notation, instead it's much more helpful to use fractions/radicals (e.g. $u^{\frac 12}$ instead of $u^{0.5}$)
Answer: Try this
Given $$\int_0^4\dfrac{x}{\sqrt{1+2x}}\ dx$$
Applying u-substitution $u=\sqrt{1+2x}$
First compute the integral without bounds$$\implies\int\dfrac{u^2-1}{2}\ du=\dfrac12\int u^2-1\ du=\dfrac12\left(\dfrac{u^3}{3}-u\right)$$
Now substituting back $u=\sqrt{1+2x}$
$$\dfrac12\left(\dfrac{u^3}{3}-u\right)=\dfrac12\left(\dfrac{(\sqrt{1+2x})^3}{3}-\sqrt{1+2x}\right)=\dfrac13(x-1)\sqrt{2x+1}$$
Now applying the boundaries$$\left[\dfrac13(x-1)\sqrt{2x+1}\right]_0^4=3-\left(-\dfrac13\right)=\dfrac{10}{3}$$
Answer: To get $x = \frac{u-1}{2}$ from the $u$-substitution $u = 1+2x$, you just solve for $x$ from the substitution. This trick can be convenient sometimes depending on the integral, and is completely valid.
However keep in mind that the actual $u$-substitution also includes a component of $du = (u')dx$ where $u'$ is the derivative of $u$ with respect to $x$, so the $dx$ in the second integral needs to be a $du$. (You can also solve for $dx$ - and often do - through an abuse of notation, and then substitute that into the integral.)
It just so happens that $du = 2dx$ here - and thus $dx = \frac{1}{2}du$, which also explains the presence of the $1/2$ in front of the integral after.
Comment: Ahhh I did not know that trick. That's interesting. Thank you!
Comment: $du\ne dx$ here.  That's where that $\frac12$ should have come from.  That $dx$ should be a $du$.
Comment: My bad, I got too hasty in writing the post. I'll rewrite it.
Answer: Hint: $$\int\frac{\frac{u-1}2}{u^{1/2}}du=\frac12\int\frac{u-1}{u^{1/2}}du=\frac12\int u^{1/2}du-\frac12\int\frac{du}{u^{1/2}}$$
Answer: You may avoid substitution by partial integration while noting that

$(\sqrt{1+2x})' = \frac{1}{\sqrt{1+2x}}$

$$\int_{0}^{4} \frac{x}{\sqrt{1+2x}} dx = \int_{0}^{4} \underbrace{x}_{u} \cdot \underbrace{\frac{1}{\sqrt{1+2x}}}_{v'} dx = \left[ x \sqrt{1+2x} \right]_0^4 - \int_{0}^{4} \underbrace{1}_{u'} \cdot \underbrace{\sqrt{1+2x}}_{v} \;dx$$
$$= 12 - \left[ \frac{1}{3}(1+2x)^{\frac{3}{2}}\right]_0^4 = 12 - \frac{1}{3}(27-1)  = \frac{10}{3}$$
Comment: A hater seems to be downvoting valid answers. Sad person though.


How to forward https subdomain using Godaddy

Question: I am trying to forward https subdomains using DNS records
For http subdomain I succeeded using the following CNAME and A records on GoDaddy
CNAME   gc1 alias.redirect.name.
TXT _redirect.gc1   Redirects to https://gifffted.com/pages/augmented-reality

But that doesn't forward in case I try to open https://gc1.gifffted.com
How can I fix that
The site is hosted on Shopify
Answer: You may be unclear on what a subdomain is.
Take this example URL:
http://www.example.com

In this URL, "example.com" is your root domain, and the subdomain is "www". Its the piece of the url separated from the root domain by a . .
HTTP and HTTPS are not subdomains, they are protocols, separated from the subdomain/domain usually by ://. In the above example the protocol is http.
Broadly speaking, A domain (with or without a subdomain) tells the browser where to look for a website, but protocols like HTTP and HTTPS determine how it communicates with the website. Protocol is not decided by DNS, but by the browser and your website.
DNS A records associate domain names (like "example.com")  to IP addresses (like 126.96.36.199).
If you also want your website to have a subdomain, like foobar (foobar.example.com), you require a CNAME entry, which defines foobar.example.com as an alias, in other words, it says "foobar.example.com" should go to the same website as "example.com".
More on that in this article.
Once you can do this much, you should be able to access example.com and foobar.example.com over http, and https, as long as your hosting supports both. This is because the protocol portion of the URL tells your browser how to speak to the website, not where to look for it (so it's looking in the same place for http and https).
P.S. I'm not 100% sure if this answers your question, as I'm not 100% sure I understand your question. If you are instead wondering how to redirect from http to https, you can do that separately via HTTP redirects, so long as your hosting supports it. The hoster might possibly also just offer a "force HTTPS" option, but I'm not sure.


Fetch discount start date and end date

Question: I have a discount 'women's day'. I have set start and end date as 8March 8AM to 8 March 8PM for this discount. In my coupon validation function, I want to check if the current time is in between 'women's day' discount start and end time or not. So I basically need a start and end time of discount.
Answer: I don't understand why do you need that..
From your question I can assume you have both the discount module and coupons module..
If using discount in general, you don't need to apply a coupon, and the discount will be applied with rules only on the dates that you put in on the default discount creation form.
The same goes for coupon creation, when creating a coupon, you can set coupon criteria as date range and that will also be applied by default in coupon validation.
Answer: You should be able to load the discount by using:
$discount = entity_load('commerce_discount', YOUR_DISCOUNT_ID);

To see what's available to you, install Devel and use the dpm() function:
$discount = entity_load('commerce_discount', YOUR_DISCOUNT_ID);
dpm($discount);

You can run this from the /devel/php page.
Comment: You're welcome. If this solved your problem, mark this post as the "Answer" for others with the same question.
Answer: I think you don't want to allow a coupons for specific time period, if discount is activated for specific period

Add a rule with event Redeem a coupon
Add a condition Data comparison to check site:current-date > start date (value)
Add a condition Data comparison to check site:current-date < end date (value)
Add an action to remove all the coupon
5 Add an action to show msg on site
Comment: thanks Shrikant Nakade, resolving with this method is what agreed by others.

Fetch discount start date and end date


Interpret cross random effect

Question: I am new to mixed models and have some trouble interpreting my model output.
I am investigating realisations of the vowel in words such as NURSE. For this I measured Formant values (F1/F2). In this case I am interested in F2. Without going into too much detail, I coded three contexts <Er, Ir, Vr> and want to see how the speakers F2 values vary in each context. I created a model (below) with a cross random predictor (phoneme|individual). the F2 values were normalised (zscores).
lmer <- lmer(F2 ~ (phoneme|individual) + (1|word) + age + frequency + (1|zduration), data = nurse_female).

Linear mixed model fit by REML ['lmerMod']
Formula: F2 ~ (phoneme | individual) + age
   Data: nurse_female

REML criterion at convergence: 686.3

Scaled residuals:
    Min      1Q  Median      3Q     Max
-5.4834 -0.3934  0.0302  0.4440  3.3055

Random effects:
 Groups     Name        Variance Std.Dev. Corr
 individual (Intercept) 0.4461   0.6679
            phonemeIr   0.8407   0.9169   -0.86
            phonemeVr   1.9711   1.4040   -0.95  0.93
 Residual               0.3388   0.5821
Number of obs: 334, groups:  individual, 23

Fixed effects:
             Estimate Std. Error t value
(Intercept)  1.395335   0.263929   5.287
age         -0.016893   0.004959  -3.406

Correlation of Fixed Effects:
    (Intr)
age -0.969
> plot(nurse_female_F2.lmer8)
> summary(nurse_female_F2.lmer8)
Linear mixed model fit by REML ['lmerMod']
Formula:
F2 ~ (phoneme | individual) + (1 | word) + age + frequency +
    (1 | zduration)
   Data: nurse_female

REML criterion at convergence: 654.4

Scaled residuals:
     Min       1Q   Median       3Q      Max
-2.09203 -0.20332  0.03263  0.25273  1.37056

Random effects:
 Groups     Name        Variance Std.Dev. Corr
 zduration  (Intercept) 0.27779  0.5271
 word       (Intercept) 0.04488  0.2118
 individual (Intercept) 0.34181  0.5846
            phonemeIr   0.54227  0.7364   -0.82
            phonemeVr   1.52090  1.2332   -0.93  0.91
 Residual               0.06326  0.2515
Number of obs: 334, groups:
zduration, 280; word, 116; individual, 23

Fixed effects:
                   Estimate Std. Error t value
(Intercept)         1.79167    0.32138   5.575
age                -0.01596    0.00508  -3.142
frequencylow       -0.37587    0.18560  -2.025
frequencymid       -1.18901    0.27738  -4.286
frequencyvery high -0.68365    0.26564  -2.574

Correlation of Fixed Effects:
            (Intr) age    frqncyl frqncym
age         -0.811
frequencylw -0.531 -0.013
frequencymd -0.333 -0.006  0.589
frqncyvryhg -0.356  0.000  0.627   0.389

I checked model fit with a residual plot, checked that each effect is significant using anova tests. I also created a random effects plot for the crossed random effect.

My question is now, how to I interpret the variance? Is it right to say that for Vr all speakers vary in their F2 between 0 and 1.97? And would be correct to say speaker 50 realises a mean F2 value of about 1,75 but has a max and min F2 of ca -3  and -.5?
Comment: First this is not crossed random effects. You have random intercepts for individuals and random slopes for phoneme. However you have not fitted fixed effects for phoneme which is probably a mistake. Normally you fit fixed effects and if you have reason to think they vary by participant you can add random slopes.
Comment: I've seen the three similar posts over the past day. Maybe some back and forth discussion would be helpful? If you'd like, you can contact me, information can be found through my profile?
Answer: Robert is right, these are not crossed random effects, but I think I understand the data enough that I can answer the other parts of your question. If you are interested in how phoneme changes across the different contexts, you need to have it has a fixed effect.
Something like this:
fit <- lmer(F2 ~ (phoneme|individual) + (1|word) + phoneme + age + frequency + (1|zduration), data = nurse_female)

As for the last question You have plotted the different individuals for each phoneme. So the (Intercept) category corresponds to the phoneme . The model above will allow you to plot the difference between the different F2 values of the three phonemes taking into account the differences between participants and that participants may not all produce the phonemes with equal differences between the three levels. You can then plot the fixed effects to see the differences of the "average" participant. For example, the code below would plot all fixed effects using the effects package.
library(effects)
plot(allEffects(fit))

Comment: Thank you so much! That already helped massively!
Comment: Glad I could help!

Interpret cross random effect


Measure of Image of Linear Map between Different Dimensional Space

Question: If $L \in {\mathbb R}^{m \times n}$ ($m < n$) is a linear map from ${\mathbb R}^n$ onto ${\mathbb R}^m$ (onto means $L$ has full row rank). Given a compact set ${\mathcal A} \subset {\mathbb R}^n$ (compact set in Euclidean space is Lebesgue measurable), how to calculate the measure $\mu_{m}(L({\mathcal A}))$, where $\mu_{m}(\cdot)$ is the Lebesgue measure in ${\mathbb R}^m$?
Answer: When $m=n$ the answer is, of course, $\mu_m(L(\mathcal{A})) = |\det(L)| \mu_n(\mathcal{A})$.  So it's natural to ask what the analog of this formula is when $m<n$.  There is no simple formula, but we can at least understand the geometry of the problem by considering the SVD (Singular Value Decomposition) $L = U \Sigma V^T$.  Here $U$ and $V$ are orthogonal matrices (in $m$- and $n$-d, respectively, with $\det(V) > 0$, w.l.o.g.), and $\Sigma = \Sigma^{m \times m}[I^{m \times m} \,|\, 0^{m \times d}]$, where $\Sigma^{m \times m}$ is a diagonal matrix with positive diagonal elements (the singular values of $L^{m\times n}$), and $0^{m \times d}$ comprises $d = n-m$ columns of zeroes.
Now consider the effect of $U \Sigma V^T$ on $\mathcal{A}$.  The matrix $V^T$ simply rotates $\mathcal{A}$ into a special alignment with the axes of $\mathbb{R}^n$. The matrix $P = [I^{m \times m} \,|\, 0^{m \times d}]$ projects $V^T\mathcal{A}$ onto the first $m$ dimensions of $\mathbb{R}^n$.  The orthogonally projected image $\mathcal{A}_m =PV^T\mathcal{A}$ is the key to determining $\mu_m(L(\mathcal{A}))$.  If we can determine $\mu_m(\mathcal{A}_m)$, then the rest is easy.  The remaining matrices are $\Sigma^{m \times m}$, whose determinant is the product of the singular values, and $U$, whose determinant is $\pm 1$.  Thus we arrive at the formula
$$\mu_m(L(\mathcal{A})) = \det(\Sigma^{m \times m}) \mu_m(\mathcal{A}_m).$$
Unfortunately, there is no simple way to determine $\mu_m(\mathcal{A}_m)$ in general.  In particular, we cannot obtain it directly from $\mu_n(\mathcal{A})$.  If we try, what we find instead is that
$$
\mu_n(\mathcal{A}) = \mu^*_m(\mathcal{A}_m),
$$
where $\mu^*_m$ is a measure on $\mathbb{R}^m$ weighted by the "amount of $\mathcal{A}$" that was mapped to $x$, i.e.,
$$
\frac{d \mu^*_m}{d\mu_m}(x) = \mu_d(P^{-1}x \cap \mathcal{A}).
$$
For example, if $n=3$ and $m=1$, then $\mu^*_m(x)$ would be the area of a cross-section of $\mathcal{A}$ (in a plane containing $x$).  In the case $m = n$, $\mu^*_m$ reduces to $\mu_m$, but otherwise the fact different cross-sections of $\mathcal{A}$ have different areas makes it difficult to compute $\mu_m(\mathcal{A}_m)$ and $\mu_m(L(\mathcal{A}))$.
Comment: I fear I buried a simple idea in notation.  Suppose $n=3$, and $\mathcal{A}$ is some 3-d set (a solid bunny, say). If $m=2$, then $\mathcal{A}_m$ is some orthgonal projection of the bunny onto the plane whereas $\mu^*_m$ is a weighted measure on that plane.  The weight at any point (i.e., the Radon-Nikodym derivative $d\mu^*_m/d\mu_m$) is simply the 1-d measure of the amount of bunny on line perpendicular to that point.
Comment: Yet, my concern is: why do we need such a weighted measure? The area of the projection (of that bunny) is not weighted (I mean the Lebesgue measure).
Comment: Thanks very much for your help. [+1] So, the key point is how $V^T {\mathcal A}$ is projected under $P$. If we got the measure $\mu_m (PV^T {\mathcal A}) =: \mu_m ({\mathcal A}_m)$, the rest parts of calculating $\mu_m(L({\mathcal A}))$ are simply scaling and rotating ${\mathcal A}_m$. Yet, the result seems to be $\mu_m(L({\cal A})) = \det(\Sigma^{m\times m}) \mu_m ({\mathcal A}_m)$. Sorry, I didn't understand the meaning of $\mu_m^*({\mathcal A}_m)$.
Comment: I agree with you that it is not an easy thing to derive the image ${\mathcal A}_m$ (e.g., ${\mathcal A} \subset {\mathbb R}^2$ is a triangle, and ${\mathcal A}_m \subset {\mathbb R}$ is determined by how one places this triangle).
Comment: Thanks a lot! [+1] Could I say $\mu_d(P^{-1}(x))$ (the weight on $x \in {\cal A}_m$) is the 1-d measure corresponding to the preimage $P^{-1}(x)$ in the bunny case, and $\mu_m^*({\cal A}_m)$ is the weighted measure on ${\cal A}_m$. I am not sure if my above understanding is correct.
Comment: Yes:  $\mu_d(P^{-1}(x))$ is simply the 1-d measure of the pre-image $P^{-1}(x)$ in the bunny case.
Comment: Oh!  Yes, the answer was all messed up.  The weighted measure shouldn't have been in the formula. [+1]
Comment: Thanks so much! [Accepted]


Where is the desktop background stored in a Server 2008 R2 roaming profile?

Question: I'm not sure why this has been so hard for me to find but where, oh where, is the desktop background stored in a roaming profile on Windows Server 2008 R2?
Answer: Do you have Application Data redirected? Try %appdata%\Microsoft\Windows\Themes\TranscodedWallpaper.jpg
Comment: Somehow I was not finding this. Sheesh.


Angular 2 - Getting object id from array and displaying data

Question: I currently have a service that gets an array of json objects from a json file which displays a list of leads. Each lead has an id and when a lead within this list is clicked it takes the user to a view that has this id in the url ie ( /lead/156af71250a941ccbdd65f73e5af2e67 )
I've been trying to get this object by id through my leads service but just cant get it working. Where am I going wrong?
Also, i'm using two way binding in my html.
SERVICE
  leads;

  constructor(private http: HttpClient) { }

  getAllLeads() {
    return this.http.get('../../assets/leads.json').map((response) => response);
  }

  getLead(id: any) {
    const leads = this.getAllLeads();
    const lead = this.leads.find(order => order.id === id);
    return lead;
  }

COMPONENT
  lead = {};

  constructor(
    private leadService: LeadService,
    private route: ActivatedRoute) {

      const id = this.route.snapshot.paramMap.get('id');
      if (id) { this.leadService.getLead(id).take(1).subscribe(lead => this.lead = lead); }

   }

JSON
[
  {
    "LeadId": "156af71250a941ccbdd65f73e5af2e66",
    "LeadTime": "2016-03-04T10:53:05+00:00",
    "SourceUserName": "Fred Dibnah",
    "LeadNumber": "1603041053",
  },
  {
    "LeadId": "156af71250a999ccbdd65f73e5af2e67",
    "LeadTime": "2016-03-04T10:53:05+00:00",
    "SourceUserName": "Harry Dibnah",
    "LeadNumber": "1603021053",
  },
  {
    "LeadId": "156af71250a999ccbdd65f73e5af2e68",
    "LeadTime": "2016-03-04T10:53:05+00:00",
    "SourceUserName": "John Doe",
    "LeadNumber": "1603021053",
  }
]

Answer: You didn't used the newly created leads array (const leads is not this.leads), so do this:
getLead(id: any) {
    return this.getAllLeads().find(order => order.LeadId === id);
}

And change your map to flatMap, because from the server you get an array, but you have to transform it to a stream of its items:
getAllLeads() {
    return this.http.get('../../assets/leads.json').flatMap(data => data);
}

Don't forget to import it if you have to: import 'rxjs/add/operator/flatMap';
Comment: That worked. Thanks so much for taking the time to help - its much appreciated. Also learnt something new - mergeMap!
Comment: I'm getting the error Property 'find' does not exist on type 'Observable'
Comment: @DBoi You have to import `find`: `import 'rxjs/add/operator/find';`
Comment: Thanks Roland. i'm now getting this error on the first 'id' - Property 'id' does not exist on type 'Object' even though my ILead model has an id:string;
Comment: @DBoi Even if your `ILead` model has `id`, are you sure that the object has? In your JSON file you have `LeadId`. Try this: `order.LeadId === id`. If this is not the issue, try to log your object to check what's the problem with it.
Comment: Unfortunately i'm still getting the same error using LeadId. Have I mapped it correctly in the getAllLeads function? Its logging the array in the console if I do .map((response) => console.log(response));
Comment: I think, I know the problem now: in your `getAllLeads` method change `map` to `flatMap` (with the same parameter). It should work. I update my answer too.
Comment: thanks Roland, just in case you need to update your answer... I had to import 'rxjs/add/operator/mergeMap';
Comment: Getting the following error: Argument of type '(data: Object) => Object' is not assignable to parameter of type '(value: Object, index: number) => ObservableInput<{}>'.
  Type 'Object' is not assignable to type 'ObservableInput<{}>'.
    The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
      Type 'Object' is not assignable to type 'ArrayLike<{}>'.
        The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
          Property 'length' is missing in type 'Object'.
Comment: You should play with `console.log` in your `getAllLeads()` too to check the issue. Maybe try something like this: `.flatMap((data: any[]) => data)`.
Answer: You can have getLead in your component level itself since you are not making any api to get the information. In your component,
this.lead = this.leads.find(order => order.id === id);

or to make the above service work, just do leads instead of this.leads
 const lead = leads.find(order => order.id === id);

Comment: im getting the error Property 'find' does not exist on type 'Observable'
Comment: in my getAllLeads function?
Comment: are you referring to my JSON set up?


Construct disjoint sequence of infinite subsets of $\mathbb{N}$ whose union is not $\mathbb{N}$

Question:
Possible to construct a disjoint sequence of infinite subsets of $\mathbb{N}$ whose union is not $\mathbb{N}$?

I am thinking this must be possible.
I've considered trying to define each sequence as the range of some function. I have to find a way to hop over natural numbers in some way to leave infinitely many left for each subsequent subset of $\mathbb{N}$. Thinking about just leaving out $1$ so then the union isn't $\mathbb{N}$. I haven't tried to do anything like this before. Any possible hints on how this can be done and I can think a little more to see if I can come up with something? If not I may just ask for an answer heh.
Thanks much for your time and input I appreciate it very much.
Answer: Consider $A_n = \{ p_n^k : k \geq 1 \}$ where $p_n$ is the $n$th prime number.
Answer: Sure. For $k\in\Bbb N$ let $A_k=\{(4k+1)2^n:n\in\Bbb N\}$. It's easy to check that the sets $A_k$ are infinite and pairwise disjoint, and their union contains no number of the form $(4k+3)2^n$.
Or let $\{A_k:k\in\Bbb N\}$ be any partition of $\Bbb N$ into infinite sets. For $k\in\Bbb N$ let $B_k=\{2n:n\in A_k\}$. Then $\{B_k:k\in\Bbb N\}$ is a partition of the set of non-negative even integers into infinite sets, whose union therefore contains none of the odd integers.
Answer: An all-too-easy answer: choose your favorite way of mapping $\mathbb{N}$ to a subset of $\mathbb{N}$ (say, the even numbers).  Now, take a partition of $\mathbb{N}$ into disjoint infinite subsets (e.g., via the inverse of the pairing function), and apply that map to each of the subsets.
Answer: You can just do arithmetic progressions:
Choose distinct $x,y \in \mathbb{N}$
Define $$b: |x-y|+1 $$
$$
O = \bigcup_{x \in \mathbb{N}, x \ne 1} \{x,x+2b,x+3b,\ldots\}
$$
Now just ensure that you omit at least one progression from your collection, (by the $x\ne 1$ condition), and their disjoint, infinite union will not be $\mathbb{N}$.


How to make the JBoss 5.0 shared library available?

Question: I want to share a jar file for two war in the same instance.
For test, I make the jboss folder and war file like this.
1)JBoss Folder
server/default
-- deploy/
 -- myApp.war

-- lib/
 -- test_1.2.jar(only one method to output "1.2")

2)WAR
myApp.war
-- META-INF/
-- WEB-INF/
 -- class/

    -- myservlet(reference class test to output the version)

 -- lib/

    -- test_1.1.jar(only one method to output "1.1")

I hope the shared library could override the jar file in WAR,
but i still get the version "1.1".
it means that the jar file in WAR worked, but not the jar in the "server/default/lib".
Comment: I Know,
I need to set   to change the ClassLoader.
Answer: Have you considered packing both WARs into an EAR and moving to JAR to the lib/ folder in the EAR? This makes it portable and will also work on JBoss AS 7 and later.


Redirect with ? in URL - Drupal 7

Question: I have Domain Access instaled, but not very sure if that is the problem: I have several domains under the same installation. It all works perfectly, but when I try to enter www.example.com/?q=user, it only works for some of the domains, for others it redirects to the home, and this causes other problems.
I have revised .htaccess (even installed a fresh copy), I have seen in the database, and cannot trace the problem, which is completely consistent. When using the same config in localhost (home PC), the problem is not found, so there is some incompatibility that came accros the project.
Any suggestion? I have Clean URLs switched on, but because it depends on any domain config, I cannot be sure because don't know where it stores the data, apparently it does work perfectly (don't understand ? in a content node, for example).
Comment: Are all of your domains active/enabled?
Comment: Yes, and working perfectly. The only problem was with the thumbnails of images created, which were broken, and only are activated when visited with other domain. Curiously, with those domains which do not show the problem above. It is very strange. I have download the exact data from the host and trying to reproduce locally with the same data, because all attempts have been a failure. The problem is consistent, and I discovered were related (not creating image thumbnail, which uses ? in the URL as a process, and  redirection when trying to enter the user login in the old fashion with ?q=user
Answer: I have discovered the problem. It is a malfunction of module or submodule Domain Locale. If you have a domain whose list of languages does not contain your default language (main site), then it doesn't work. All the project to the trash, months of development ruined.

Redirect with ? in URL - Drupal 7


Char array pointer in C

Question: I want to run this code but i can not. i have yet started to learn pointer in C. I am trying to get the addresses of letters. Problem is printf("in adress: %p\n",p[i]);` Thanks
#include <stdio.h>

int main(void){
    char letter;
    int c=0;
    int i;
    char pattern[7];
    char *p;
    printf("Enter a letter: ");
    scanf("%c",&letter);
    printf("Enter a pattern: ");
    scanf("%s",pattern);
    p=pattern;
    for(i=0;i<7;i++)
    {
        if(letter==pattern[i])
        {
            c++;
            printf("Letter < %c > is found in pattern %s\n",letter,pattern);
            printf("in adress: %p\n",p[i]);
            printf("index:%d\n",i);
        }

    }
    if(c==0)
        printf("The pattern does not include any letter");

  return 0;
}

Comment: `p[i]` is not the address of the i'th element of p - it's the *value*.
Answer: This line of code has some potential problem that can easily happen
scanf("%s",&pattern);

you can make it a little bit safer like this
scanf("%6s",&pattern);

it's a 6 because you need one extra byte '\0' at the end of the string, which takes us to the next problem
for(i=0;i<7;i++)

here you are assuming that all bytes are non-nul which would be ok except that you are reading a string with scanf() and unless you create the array one byte bigger than the number of characters you want to store in it, scanf() will overflow the array i.e. write a byte beyond it's bounds.
Adding the "%6s" length specifier to the format string solves this, but you can only store 6 non-nul bytes in the array, and for the other problem
for (i = 0 ; pattern[i] != '\0' ; i++)

would be better, because you don't need to know the length of the string in advance and you don't risk reading past the end of the array.
Try this:
#include <stdio.h>

int main(void)
{
    char  letter;
    char  c;
    int   i;
    char  pattern[7];
    printf("Enter a letter: ");
    if (scanf(" %c",&letter) != 1)
     {
        printf("error: invalid input.\n");
        return -1;
     }
    printf("Enter a pattern: ");
    if (fgets(pattern, sizeof(pattern), stdin) == NULL)
     {
        printf("error: end of file.\n");
        return -1;
     }
    for (i = 0 ; pattern[i] != 0 ; ++i)
    {
        if (letter == pattern[i])
        {
            c++;
            printf("Letter < %c > is found in pattern %s\n", letter, pattern);
            printf("in adress: %p\n", pattern + i);
            printf("index    :%d\n", i);
        }

    }
    if (c == 0)
        printf("The pattern does not include any letter");
    return 0;
}

You also was printg the address wrong, because in pointer[i] the subscript operator dereferences the pointer, it's equivalent to *(poitner + i).
Comment: q1.c: In function 'main':
q1.c:12:2: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[7]' [-Wformat=]
  scanf("%6s",&pattern);
  ^
q1.c:20:4: warning: format '%p' expects argument of type 'void *', but argument 2 has type 'int' [-Wformat=]
    printf("in adress: %p\n",p[i]);
I have these mistakes now
Comment: The problem is `&pattern`, it's good that you are using warnings, a good way to learn is to try and interpret the warnings and errors and think about why it couldn't work the way you wrote it. Use `fgets()` instead, as the code I posted

Char array pointer in C


Existence of Distribution with Given Multivariate Marginals

Question: Consider discrete random variables $X_1,\cdots, X_n$, and let $D$ be their joint distribution. For each subset $S\subseteq[n]$ let $D_S$ be the marginal distribution $(X_i)_{i\in S}$.
Fix $k<n$. Suppose you are given, for every $S$ of size $k$, a distribution $D_S$. Under what conditions do the distributions $\{D_S\}_{S\subseteq[n],|S|=k}$ correspond to marginals of some distribution joint $D$?
In the case $k=1$, the solution is trivial: every set of distributions $(D_{\{i\}})_{i\in[n]}$ is the set of marginal distributions of the product distribution $D_{\{1\}}\times\cdots\times D_{\{n\}}$.
For $k>1$, a necessary condition is that the $D_S$ are consistent: for any two sets $S_0,S_1$ of size $k$, let $T=S_0\cap S_1$. Then we require that the marginal distribution of $D_{S_0}$ restricted to $T$ is identical to the marginal distribution of $D_{S_1}$ restricted to $T$.
Is consistency sufficient for the extistence of a joint distribution $D$? If not, are there any simple conditions under which we can conclude that a joint distribution $D$ exists? Note that I only care about existence, and do not care if the joint distribution is unique or how to actually compute the joint distribution.
Comment: This has a similar flavor to the [Kolmogorov Extension Theorem](https://en.wikipedia.org/wiki/Kolmogorov_extension_theorem).
Answer: It turns out that consistency is not sufficient, even in the case $k=2$. Suppose the domain is just $\{0,1\}$. Consider the case where are the pairwise marginal distributions are uniform over pairs of distinct elements, that is uniform over $\{01,10\}$. Then all the variables $X_i$ are just uniform, giving consistency. However, any joint distribution $D$ with the given marginals would have to have all the $X_i$ be distinct. This is clearly impossible for $n\geq 3$.


Tipo Double e tipo Decimal, qual adequado para valor monetário?

Question: Achei aqui no SO uma pergunta com uma resposta até bem aceita pela comunidade Que tipo de dados (double, float ou decimal) eu deveria usar para representar moeda em .NET com C#?
Só que eu nunca tive problemas com o double para cálculos monetários, tive sim com float esse ai já me deixou de cabelo em pé, então a partir desta resposta afirmando que o Decimal é o correto, ou isso é apenas p/ quem usa C# e nada a haver com MySQL, comecei a testa-lo, e me deixou um pouco inseguro, por exemplo dizer que vou armazenar sempre 2 dígitos de ponto flutuante, tem casos onde o usuário vai "necessitar" (exceção) fazer o registro do valor com 4 dígitos no banco que por sua vez irá gravar apenas os dois primeiros, por este motivo me sinto mais seguro com double.
Pergunta - existe um exemplo código fonte que me mostre esse "erro" de arredondamento do Double para eu ver para crer, ou uma fonte de referencia livro, site confiável que sinalize essa recomendação do uso Decimal para registrar valores monetários em MySQL?
Obs 1 - Os tipos de dados me refiro são do MySQL pois também vi uma citação do MSDN https://msdn.microsoft.com/pt-br/library/364x0z75.aspx só que é referencia de C# e me perdoem aos adeptos a MS preciso de uma fonte mais "segura" quando digo site confiável ( pois estou falando de MySQL, não SQL Server, .Net, C# etc.)
Obs 2 - Tem um link do próprio MySQL http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html meu inglês não é muito bom, vejam se estou equivocado, diz:

maximum number of digits for DECIMAL is 65

Numero máximo de digitos para DECIMAL É 65
E na sequência diz

Before MySQL 5.0.3, the maximum range of DECIMAL values is the same as for DOUBLE

Ou seja o maior DECIMAL é igual ao DOUBLE.
Continuando o texto do site

but the actual range for a given DECIMAL column can be constrained by the precision or scale for a given column

Essa parte pelo que entendi é o DECIMAL que fica limitado pela precisão ou estou enganado ?
Vou colocar aqui um teste, espero que alguém me demonstre esse "erro" da mesma maneira (semelhantemente)
CREATE TABLE `teste` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numero` double NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `test`.`teste` (`numero`) VALUES ('0.1');
INSERT INTO `test`.`teste` (`numero`) VALUES ('99.9');

SELECT sum(numero) FROM teste;

mysql>     SELECT sum(numero) FROM teste;
+-------------+
| sum(numero) |
+-------------+
|         100 |
+-------------+
1 row in set (0.00 sec)

Comment: fiquei na dúvida pois achei um link onde um "moderador" diz que o Mysql 5.x depreciou o tipo Decimal http://www.scriptbrasil.com.br/forum/topic/76609-double-decimal-ou-float/
Comment: Olha o erro do float, bem claramente. E o double tem o mesmo problema: http://sqlfiddle.com/#!9/6d5af/2
Answer: Eu duvido que você nunca teve problemas. Eu acho que você nunca percebeu o problema. A maioria dos casos vai errando por 1 centavo. Claro que erros de 1 centavo podem se transformar em milhares de reais quando multiplicado.
O motivo de tanta gente usar errado é justamente porque o erro não costuma ser tão evidente e nos casos onde ele se torna um problema enorme a pessoa não sabe validar.
Em contabilidade, 1 centavo de erro destrói o trabalho. Em outras atividades pode só dar prejuízo, muitas vezes pequeno, ou pode dar processo vindos de parceiros comerciais ou governo. Não vou entrar em detalhes porque não sou advogado.
Tem um site confiável onde diz isto e ele é o Stack Overflow. Tem várias referências nele.
Nessa minha resposta eu organizo vários links para outras perguntas/respostas sobre o assunto. Se você seguir todos os links lá terá todas as informações que precisa. Poderá aprender que o problema ocorre por causa da representação binária dos números que impede de representar todos os números com precisão.
Uma referência na documentação do MySQL. Teste executando no SQLFiddle.
Coloquei no GitHub para referência futura.
Imagino que todo mundo que participa destas respostas, mesmo que apenas através de votos, concordam que o tipo DECIMAL deveria ser usado. Acho que já seriam várias fontes e a variedade obtida em um local onde o que se posta é validado por seus pares, dá uma boa confiabilidade.
No link postado no comentário, uma pessoa diz que os tipos DECIMAL e NUMERIC estão obsoletos. Peça para ele citar a fonte. Provavelmente ele não entendeu a pergunta ou não sabe do que está falando. Ser moderador não significa que ela entenda do assunto que trata o site. Para saber mais sobre estes tipos tem uma pergunta aqui no site.
Alguns exemplos de imprecisão podem ser obtidos no artigo da Wikipedia.
Um simples 0.1 já é problemático. Vou mostrar em C# porque é a linguagem que trabalho melhor entre as mainstream mas o "erro" é do processador, e não da linguagem, isto vale para PHP, JS, SQL, etc. Somar 0.1 em um double 100 vezes, deveria dar 100, correto? Porque então dá 99.9999999999986?
using static System.Console;

public class Program {
    public static void Main() {
        double x = 0.0d;
        for (var i = 0; i < 1000; i++) x += 0.1d;
        WriteLine(x);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
$x = 0.0;
for ($i = 0; $i < 1000; $i++) $x += 0.1;
echo $x;

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Algumas coisas foram sendo adicionadas depois à pergunta.
Se você acha que o site da Microsoft tem alguma informação que não é confiável, cabe a você provar que tem algo errado. Se ninguém mais reclamou, deve estar certo. Se o problema é porque o site é da Microsoft e ela é uma empresa toda errada, aí eu não vou conseguir te convencer de nada porque você acredita em Saci Pererê também.
As citações da documentação do MySQL não tem nenhuma relação com o problema. Mas pelo menos nela mostra que os tipos citados anteriormente não estão obsoletos. O tipo DECIMAL não tem nenhuma imprecisão, o número que você coloca nele, é o número que será usado, ao contrário de DOUBLE que usa um número aproximado ao que você tentou armazenar nele. Claro que o DECIMAL terá quantas casas decimais que você determinar. É óbvio que meio centavo não poderá ser armazenado em um DECIMAL com apenas duas casas decimais. Mas é decisão do programador resolver isso de acordo com o cenário. O DOUBLE muda o valor e isto ocorre independente da vontade do programador.
Entenda o problema lendo tudo o que eu passei e você perceberá que a afirmação "Ou seja o maior DECIMAL é igual ao DOUBLE" é completamente falsa. Como eu disse, as citações não falam do "problema do arredondamento" por causa da representação binária.
O tipo DOUBLE pode até esconder um pouco melhor o erro do FLOAT mas em algum momento ele aparecerá e não é tão difícil.
Pode ser útil: Qual a forma correta de usar os tipos float, double e decimal?
Comment: Não. Ela é uma referência para o seu caso, ela pode não ser a melhor mas ela é. Você acha que não é porque você ainda não entende o porquê deste erro ocorrer. Quando você ler tudo e entender, verá que não faz diferença que tecnologia você está usando ou de que empresa. Todos os produtos são dependentes de como o processador funciona. De qualquer forma tem aí uma referência oficial um exemplo executando mostrando que o problema ocorre facilmente. O seu exemplo só não foi suficiente para apresentar o erro, mas outros são. Você não pode pegar um exemplo que funciona e achar que todos funcionam.
Comment: eu vou ler e seguir os links e material que você já indicou, pelo mesmo motivo que acredito na sua resposta, não é porque algum Moderador ou usuário com boa reputação falou que seja verdade, vou procurar me aprofundar, procurar um código que exemplifique esse "problema" que possa ser colocado num ambiente de teste e "provar" esse erro.
Comment: esse problema de somar 0.1(acho que com 99.1 isso?) nao ocorre problemas no mysql da 100 redondinho
Comment: Não sei como você está testando.
Comment: editei a pergunta com um exemplo de código, li suas referências cai na questão do C# e .net que não é o caso, aqui minha dúvida é se isso também se aplica ao MySql
Comment: bigown me desculpe se lhe ofendi falando sobre confiança na MS, só explanei que ela não é referencia para o meu caso (MySql) e deixei isso bem claro na pergunta, ref. ao Saci Perere, creio que você deveria dar alguma credibilidade ao site do próprio MySql uma vez que de lá que vem o programa em discussão aqui.
Comment: E para quem deu negativo, por favor me informe onde está o erro para eu corrigir. EU odeio postar coisa errada.
Comment: pois é, eu usei o seu exemplo, por isso fiz a pergunta, EU nunca encontrei o erro, por isso que a pergunta foi feita, alguém como você é a pessoa certa ( acredito ) para demonstrar, eu estou quase convencido que o Decimal seja o mais apropriado, só não achei a "falha" no Double que esta citando.
Comment: @bigown Desculpe estar voltando nesta pergunta tão antiga, mas por quê esse problema com o float e double ocorre? Tentei ler o wikipedia que você deixou mas não entendi muito bem.
Comment: @Francisco veja se alguma ajuda https://pt.stackoverflow.com/questions/tagged/valor-monet%c3%a1rio?sort=votes&pageSize=50.


Puppet revokes OpenSSL certificates

Question: I'm experiencing some certification revokations in the puppet master and this behavior seems to be random.
I just checked one of the CA certificates and I found this:
<code># openssl crl -text -in /var/lib/puppet/ssl/ca/ca_crl.pem

Certificate Revocation List (CRL):
        Version 2 (0x1)
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: /CN=Puppet CA: puppet.master
        Last Update: Dec 16 11:55:15 2015 GMT
        Next Update: Dec 14 11:55:16 2020 GMT
        CRL extensions:
            X509v3 Authority Key Identifier:
                keyid:FF:9D:F6:0B:4A:17:27:A6:7D:DF:3A:8A:FC:D1:99:73:24:CA:87:08

            X509v3 CRL Number:
                83
Revoked Certificates:
    Serial Number: 02
        Revocation Date: Nov 18 10:55:38 2015 GMT
        CRL entry extensions:
            X509v3 CRL Reason Code:
                Key Compromise
</code>
...... (the output continues with several Revoked Certificates)
What does cause the OpenSSL "Key Compromise" error? No FQDN changes were made to the agent nor any system related file. Also I checked that the OpenSSL versions of the servers that has the certificates revoked are the same than other which certificate is valid: OpenSSL 1.0.1e-30
Thank you all!
Answer: Could you have run into this?

Masterzen's Blog, 2010-11-14, Puppet SSL Explained (Archived here.)

If for any reason you need to fully re-install a given node without changing its fqdn, either use the previous certificate or clean this node certificate (which will automatically revoke the certificate for your own security)

(Emphasis mine.)

Puppet revokes OpenSSL certificates


Use p-values to weight correlations before combining them

Question: I have a correlation between two dimensions $A$ and $B$, each dimension has 1 variable $i$ with $j$ samples. $A_i$ and $B_i$ (Let's call it $r_{Di}$). I also have a correlation of $A_i$ with another variable $C_i$ (Let's say $r_{Ei}$). For each correlation I calculate the $p$-value. For these 2 correlations, I do the correlation between ($r_D$) and ($r_E$) for all the $i$ variables. As I have the $p$-values of each correlation of $A$ with $B$ and each correlation of $A$ with $C$, can I use these $p$-values to do a weighted correlation for the correlation between $r_D$ and $r_E$? If I can use the $p$-values for this correlation how do I combine them?
I could find a question (When combining p-values, why not just averaging?) which seems to imply that there are further uses of $p$-values. But the aim of such methods seems to combine different independent studies and not from the same study.
To calculate those $p$-values are calculated with this function in r package WGCNA, whose descriptions says "Calculates Student asymptotic p-value for given correlations":
<code>function (cor, nSamples) {
    T = sqrt(nSamples - 2) * cor/sqrt(1 - cor^2)
    2 * pt(abs(T), nSamples - 2, lower.tail = FALSE)
}
</code>
Comment: What for? How exactly do you want to weight correlation by p-value?
Comment: see http://stats.stackexchange.com/questions/164181/family-wise-error-boundary-does-re-using-data-sets-on-different-studies-of-inde/164232#164232
Comment: @Tim Because the p-values indicates how much I trust a value, so for further correlations I hope that this information can be incorporated somehow. In R the package corr: `w.cor(AB, AC, w = ?)`
Comment: @Llopis there is no such package on CRAN so I'm not sure what do you refer to. I *guess* that you mean [weighted correlation](http://stats.stackexchange.com/questions/221246/such-thing-as-a-weighted-correlation) but if so, then the weights are per *observation*, not per variable, and certainly nor per pairs of variables.
Comment: Oh, I mixed names it is from the boot package. Yes, I mean weighted correlation.So I can't do the correlation between ABi ABj with ACi ACj  using for each pair?, The corr function of the boot package expect this weight for each pair
Comment: Can you look at your question again and clarify it in the light of the comments by editing it? At the moment it does not seem clear to us whether you want to combine the p-values or combine the correlations in some way.
Comment: I want to use the p-values combined to do a weighted correlation on previous correlations.
Comment: Could you explain what you mean by the "correlation between $(A-B)$ and $(A-C)$"?  Are you actually subtracting values or are you trying to refer to something else?  It certainly reads like subtraction but I can't quite believe you mean that, since there doesn't seem to be any reason to suppose the correlations of the differences have any mathematical connection with the original correlations.
Comment: I think I have clarified it, I am using the correlation between A and B to correlate it with the result of the correlation between A and C. So like nested correlations. See edit
Comment: What does the index "$i$" refer to, then?  Although have included it, your description indicates there is exactly *one* correlation between $A$ and $B$ and exactly *one* correlation between $A$ and $C$.  You cannot correlate two numbers!
Comment: That's what I was editing now :D, I hope it is clearer now.
Comment: Yes it is, thank you.  Now that we see you are correlating two sets of statistics (namely, the correlation coefficients) it makes sense to follow up with the next question: exactly what hypotheses do these p-values correspond to and exactly how were they calculated?  In general you cannot do anything at all relevant with those p-values, but if you could supply this information it might be possible to back-calculate the *standard errors* of the correlation coefficients and then you would have something to work with.
Comment: I could manage to calculate the standard error. I am using R so I added the function I use to calculate the p-value. The null hypotheses is that there is a normal distribution, if I understood correctly the vignette.
Answer: No, you can't do that.  The flaw is that p-values do not "indicate how much I trust a value".  Rather, p-values can be considered a measure of evidence against the null value.  Those aren't the same thing (although they do sound similar to people at first).  The confidence interval could be considered a measure of how much your trust the (point) value of your correlation, but I would not use it in the way you are thinking.
I wouldn't bother trying to use a weighted correlation at all in your circumstance.  Moreover, knowing the correlations between A and B, and between A and C, does very little to constrain the possible correlation value between B and C (see: If A and B are correlated with C, why are A and B not necessarily correlated?).
Comment: I'm not sure I follow this, @Llopis. You've computed $r_{AB}$ & $r_{AC}$, & now you want to compute $r_{(A-B)(A-C)}$? That doesn't make sense. (1) you don't do that--that's a spurious correlation; & (2) the p-values wouldn't be relevant for that even if it did make any sense. Why do you want to do that? What is your real goal here? It might help if you provided more information about your situation, your study, your data, & what you ultimately want to know.
Comment: I am doing the correlation between $A_i$ and $B_i$ (let's call it $r_{Di}$) and between $A_i$ and $C_i$ (let's call it $r_{Ei}$) and I want to use the p-values of those correlations to the correlation between $r_E$ and $r_D$. In this sense the evidence against the null value wouldn't be useful?


First-order Discrete Markov Chain with time lag

Question: I want to estimate the first-order transition matrix of a sequence in discrete time, e.g.
$$ s = 1,0,1,0,1,1,0,1,0,0, \dots$$
but states are not evenly spaced in time. So that even if $s_{t=1} = 1$ and $s_{t = 2} = 0$, and $s_{t=3} = 1$ and $s_{t = 4} = 0$, the time lag between $t_{1}$ and $t_{2}$ is one day, whereas the time lag between $t_{3}$ and $t_{4}$ is one week.
How can I estimate the correct transition matrix accounting for the time lag between states? References are well accepted.
Comment: If the time intervals are generally of one unit (day) and sometimes
a multiple of the unit (e.g. 2 days, 7 days), then just replace the
transition matrix, say $\mathbf{P}$, by a suitable power of it (e.g.
 $\mathbf{P}^2$, $\mathbf{P}^7$). It the time design is more complex
with no clear unit, then use a Continuous Time Markov Chain model.
Answer: Taking "one day" as your time unit, consider the complete sequence $x_1,\dots,x_n$ and sum over the "missing data" days for which you don't have an observation.
More specifically, if you have only information about $k$ days $I=\{i_i,\dots,i_k\}\subset\{1,\dots,n\}$, then, defining $I^c=\{1,\dots,n\}\setminus\{i_i,\dots,i_k\}$, and using the marginal
$$
  p(x_{i_1},\dots,x_{i_k}) = \sum_{i\in I^c}\sum_{x_i\in\{0,1\}}\left(p(x_1)\prod_{j=1}^n p(x_j\mid x_{j-1})\right),
$$
you have the likelihood of the transition matrix elements based only on the observed days. Maximization of this (in general intractable) likelihood looks like a job for the EM algorithm.


Acces viewController's properties from the TabBarController

Question: I have a UITabBarController (embedded in a UINavigationController) which have some "child" UIViewControllers.
When the user arrives on the TabBarController, the first ViewController is shown. I'm handling the datas in my TabBarController, and then I'm using it in the different viewControllers. So it's not a problem to access the TabBarController's properties from the children ViewControllers.
Now, what I'm trying to do is to access the children ViewControllers' properties, inside my TabBarController.
I know that something like this is possible to loop through the controllers :
for (UIViewController *v in self.viewControllers)
{
    if ([v isKindOfClass:[MyViewController class]])
    {
        // Do something here
    }
}

This code works, I correctly find MyViewController, but now I don't know how to access its properties. Could someone give me a tip on how do this please ?
Thanks !
Answer: for (UIViewController *v in self.viewControllers)
{
    if ([v isKindOfClass:[MyViewController class]])
    {
       MyViewController *myViewControllerObj = (MyViewController *)v;

        // you can access all the properies here
        // example: myViewControllerObj.yourPropery;
    }
}

Comment: This is exactly what I tried first but this seems to don't work. When I try to NSLog a UILabel's text, it show me `(null)`.
Comment: What exactly is (null)? The UILabel or its text property?
If null is shown then it is probabyl really null at that point in time.
Comment: u may creating an new object for MyViewController after assigned value to UILabel. It may be in UITabBarController or any where else. please cross check the  MyViewController allocations. Else it will work fine. also cross check the myViewControllerObj object values. it will give good idea to u
Answer: cast tye to your secific ViewController and access properties. Dont foget to include your header file in .m file.
Header:
#import "MyViewController.h"

type casting:
MyViewController *vc = (MyViewController*) v;
v.myProperty = myValue;


can you return implicit type from a method?

Question: Can you do something like this in C#
var GetSomething()
{
    var x = new { a = "b", i = 1 };
    return x;
}

Or maybe is there any alternative that I can do? About having a type for the return yes, I know about that. I was looking for something more generic :D
Comment: Perhaps you should explain why you want to do such a thing as likely you will get better advice.
Answer: var is syntactic sugar - it is not a lack of type. The type is determined in compile time.
It can only be used inside methods.
Perhaps you are looking to use dynamic instead.

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time.

Also see Using Type dynamic.
dynamic GetSomething()
{
    dynamic x = new { a = "b", i = 1 };
    return x;
}

Answer: var a = GetSomething();

static   Object  GetSomething()
{
    var x = new { a = "b", i = 1 };
    return (Object)x;
}

Anonymous types can be returned from methods but must be cast to object, which defeats the purpose of strong typing.
Comment: Would probably be useful to add how (or if) the member fields of the original anonymous type can be recovered by casting back?
Answer: I managed to return anonymous type. I returned it as an object and then cast it. Thanks for anyone who answered :D
object GetSomething()
{
    var x = new { a = "b", i = 1 };
    return x;
}


Binded ComboBox lose Item names after clear and add objects to collection

Question: I have an observableCollection property in C# code and a ComboBox binded to this observable collection:
<ComboBox x:Name="CameraInstances" Margin="10,0,0,0" Width="250" StaysOpenOnEdit="True" VerticalAlignment="Center" VerticalContentAlignment="Center"
                                   ItemsSource="{Binding Path=CameraSettingsManager.Observable, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                                   SelectedIndex="{Binding Path=CameraSettingsManager.EditingCameraIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                   SelectionChanged="CameraInstances_OnSelectionChanged" DisplayMemberPath="Name"
                                   IsSynchronizedWithCurrentItem="True"
                                   Height="30"/>

Also I have another ComboBox which works as filter for this and on SelectionChanged event I clear observable collection and ad new items according to selected filter:
public void Load(ObservableCollection<Object> objects, CameraBehavior behavior)
{
    try
    {
        objects.Clear();

        if (behavior == CameraBehavior.Undefined)
        {
            if (firstPersonCameraContainer.Count > 0)
            {
                 foreach (KeyValuePair<string, FirstPersonCamera> camera in firstPersonCameraContainer)
                 {
                     objects.Add(camera);
                 }
             }

             if (thirdPersonCameraContainer.Count > 0)
             {
                 foreach (KeyValuePair<string, ThirdPersonCamera> camera in thirdPersonCameraContainer)
                 {
                     objects.Add(camera);
                 }
             }

             if (flightCameraContainer.Count > 0)
             {
                 foreach (KeyValuePair<string, FlightCamera> camera in flightCameraContainer)
                 {
                     objects.Add(camera);
                 }
             }
         }
         else if (behavior == CameraBehavior.FirstPerson)
         {
             if (firstPersonCameraContainer.Count > 0)
             {
                 foreach (KeyValuePair<string, FirstPersonCamera> camera in firstPersonCameraContainer)
                 {
                     objects.Add(camera);
                 }
             }
         }
         else if (behavior == CameraBehavior.ThirdPerson)
         {
             if (thirdPersonCameraContainer.Count > 0)
             {
                 foreach (KeyValuePair<string, ThirdPersonCamera> camera in thirdPersonCameraContainer)
                 {
                     objects.Add(camera);
                 }
             }
         }
         else
             if (behavior == CameraBehavior.Flight)
             {
                 if (flightCameraContainer.Count > 0)
                 {
                     foreach (KeyValuePair<string, FlightCamera> camera in flightCameraContainer)
                     {
                         objects.Add(camera);
                     }
                 }
             }
         }

         catch (Exception e)
         {
             MessageBox.Show(e.Message + e.StackTrace + e.TargetSite);
         }
     }
}

But actually after collection is updated in ComboBox It seems that ComboBox losing ItemsSource. Does someone know why?
Answer: Sorry, problem was solved by myself. It was actually because I add to collection wrong type (Dictionary instead of concrete type).


How to prove that a strong solution of the homogeneous Dirichlet boundary problem really exists?

Question: For homogeneous Dirichlet boundary problem
$$
\left\{\!\!
\begin{aligned}
&-\Delta u+c(x)u=f(x),~\text{in}~\Omega,~~~~~~~~~~~~~~(I)\\
&u=0,~\text{on}~ \partial\Omega
\end{aligned}
\right.
$$
I know that the strong (classical) solution is defined as the function $u\in C^2(\bar{\Omega})$ satisfying
the problem (I) above in the usual sense.   On the other hand, the weak solution is the function $u\in H^1_0(\Omega)$ satisfying the following:
$$
\int_\Omega\left(\sum_{i=1}^n\frac{\partial u}{\partial x_i}
\frac{\partial v}{\partial x_i}+c(x)uv\right)\,dx=\int_\Omega fv\,dx~~~~~~~(II)
$$
for every $v\in H_0^1(\Omega)$.
My question are the following:
(a) How do I prove/show that such a strong solution $u\in C^2(\Omega)$ really exists? In other words, how do I solve for this $u$?
(b) If I want to obtain a weak solution, do I have to solve (II) explicitly to obtain $u$?   How is it easily solved?  Any reference, guide?
Answer: This is a question of regularity i.e. you know that a weak solution $u \in H^1_0(\Omega)$ exists so now you must prove that any weak solution of (I) is actually an element of $ C^2(\Omega) \cap  C(\overline{\Omega})$. (Note: you didn't mention it but for $u$ to be a classical solution you also need $u \in C(\overline{\Omega})$ for the boundary condition to make sense).
Your PDE is elliptic and the regularity theory of elliptic PDE is very well understood. A classical reference is Partial Differential Equations by Lawrence C. Evans (see Chapter 6) or a more in depth reference is Elliptic Partial Differential Equations of Second Order by Gilbarg and Trudinger. In fact, just googling 'regularity theory elliptic PDE' will likely return hundreds of references.
To answer your second question about 'explicitly solving' (II) it is practically impossible. To put it into perspective if $u$ satisfies (II) with $c=0$, $f \in C^\infty(\Omega)$ and $\Omega$ with $C^\infty$ boundary then standard regularity theory implies that $u \in C^\infty(\overline{\Omega})$. Hence, $u$ satisfies $-\Delta u =f $ in $\Omega$ and $u=0$ on $\partial \Omega$. We know then that we can write $u$ in terms of a Green's function, but only in very very specific cases of $\Omega$ can we actually work out that Green's function. If $c \neq 0$ there are still 'Green's functions' but these are even more challenging to calculate than before! This is why mathematicians gave up on trying to 'solve' PDE a long time ago - it is much easier (and often more useful) to understand the underlying theory.


Angular 4 - fetch file from /src folder during development

Question: In /src folder I have file abc.json. On development machine I should get it with url http://localhost:3000/abc.json. On production machine this file is generated on-fly.
I used Angular 2 - project was generated by CLI 1.0.0-beta.26. And after command
npm start

I could fetch abc.json.
The start command is:
"start": "ng serve --port=3000"

Then I generated new project using CLI 1.2.6 (Angular 4.3.2 - the latest at the moment of writing). And now the response from this URL is:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Error</title>

Cannot GET /sessionInformation.json

What should I change to allow to download abc.json?
Answer: The development server is not able to access the src dir.
You will need configure this file as an asset.
// .angular-cli.json
"assets": [
  "assets",
  "favicon.ico",
  "abc.json"
]

You can read more here in the docs


How to connect IRQ output of XPS INTC to Microblaze Interrupt input

Question: I have written a custom PLB core for my design, and added interrupt functionality during custom core generation. Interrupt generation logic is designed in custom peripheral. For interrupt control, I added XPS interrupt controller (v2.01a) to the system and connected my custom core's interrupt ports to INTC via master bus. However, as I need to connect IRQ output of INTC to Interrupt input of Microblaze (v8.40), I cannot connect those two ports using Ports tab of System Assembly View, there is no connection option except external port and core's itself. I tried to do it manually on .MHS file, but still I cannot see IRQ and Interrupt ports connected in Graphical Design View. Besides, in Bus Interfaces tab of Assembly View, I can see INTERRUPT port of Microblaze but again, no change can be made.
Answer: Use AXI_INTC insteed of XPS_INTC and it should work.
There you will find two bus :

AXI BUS
INTERRUPT BUS.

You will be able to connect the interrupt bus to your MicroBlaze component


How do I keep multiple copies of Outlook in sync when using RPC over HTTP?

Question: I use Outlook 2007 at work with our Exchange 2003 server.  I just setup my home system with Outlook 2007 so that I could use the RPC over HTTP to access Exchange without having to use a VPN.
It works fine.  I can get mail, send mail, etc.  What it doesn't seem to be doing is staying in sync.  For example, I read a few messages at home, moved them into different folders from the Inbox, etc.  That all seemed fine.  When I login to my work machine and look at the copy of Outlook there, the mail is still unread and nothing has been moved.
Am I missing something simple here?  I would have to assume that my home machine should be telling Exchange where these messages belong and that they've been read.
Both machines are running Windows 7, if that matters.
Ideas?
Comment: OK, it appears that it has to do with the cached mode checkbox in the account settings.  When I turn that off it does keep them in sync.  Unfortunately, with that off things on my home system run MUCH slower too.  Does anybody know what the default settings for the caching are and would it eventually have "caught up"?
Comment: Mixing work e-mail with home software seems like a bad idea, and will probably lead to a question like this posted some day: http://serverfault.com/questions/146324/should-i-keep-my-ex-employers-data
Answer: Check your send and receive settings. If you aren't connecting back to the exchange server frequently then the changes you are doing locally at home won't be reflected until the next time it connects.
Also make sure you have installed the latest Office 2007 Service Pack SP 2 Currently as that had a number of improvements for Outlook as per Outlook 2007 improvements in the 2007 Office suite Service Pack 2 and also the post Office 2007 SP2 Update for Outlook - Outlook 2007 hotfix package (Outlook.msp): June 30, 2009 which mentions further performance improvements for Windows 7 RC.


Why is the sum of any ten consecutive Fibonacci numbers always divisible by $11$?

Question: I was wondering if anyone has any insights regarding the fact that the sum of any $a_1, \dots, a_{10}$ consecutive Fibonacci numbers is divisible by $11$ (and furthermore equals to $a_7*11$). What can this tell us about the series as a whole (its structure etc)?
Comment: See Andre's answer [here](http://math.stackexchange.com/questions/60049/fibonacci-and-lucas-identity).
Comment: Can you try with https://proofwiki.org/wiki/Euler-Binet_Formula ?
Answer: Just write every term in the sum in terms of $a_1$ and $a_2$ (keeping in mind that $a_{n+2}=a_n+a_{n+1}$):
$$a_1+a_2+(a_1+a_2)+(a_1 + 2a_2)+(2a_1+3a_2)+(3a_1+5a_2)+(5a_1+8a_2)+(8a_1+13a_2)+(13a_1+21a_2)+(21a_1+34a_2). $$
Then the sum is clearly equal to $55a_1+88a_2 = 11(5a_1+8a_2)$, which is $11$ times the seventh term of the sum.
Comment: Yes, this shows us why its is divisible by 11 but not the meaning of it. what does it say about the structure etc. of the Fibonacci series?
Comment: @NSChotzen I guess I answered the question as I read it in the title.  I'm not sure this property can give us some powerful insight on this (otherwise very well studied) sequence.  Perhaps questions of the form "What can X tell us about Y?" are slightly too vague, and in some cases the answer may very well be "Nothing much, really".
Comment: it seems to me that each set of a1,...,a10 acts like a telescopic expansion of the initial series: when (and I think only when) you accumulate 10 consecutive members, the whole group is the exact expansion of the 7th member. when a7=5a1+8a2    which in their turn of course, are comprised of 3a1+5a2 + 2a1+3a2 and in the new set it's 55a1+88a2 (which are comprised of 33a1+55a2 + 22a1 + 33a2). and it only happens in a set of 10. Right?


Erro de socket em C recv(), send() // SERVER [ENCERRADA]

Question: Sou novato em c e na área de redes, fui criar um código em c para colocar em prática a teoria, contudo, após bindar e criar o socket do connect, qualquer função como recv() ou send() me retorna -1 [erro]. Por vezes também, só de colocar um printf() ou alterar qualquer pequena coisa no código eu recebo um erro de conexão no lado cliente. Para simular um cliente estou utilizando o netcat 7.8. Se houver possibilidade de alguém me explicar o porque deste erro serei grato. Se houver sugestões de melhorias no código e tudo mais por favor, não hesitem em falar! Grato.
Eis o código:
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>

int main()
{
    printf("\niniciando ...\n");
    int server, conecta, client,x;
    struct sockaddr_in endereco_servidor;
    struct sockaddr_in endereco_cliente;

    server = socket(AF_INET, SOCK_STREAM, 0);

    endereco_servidor.sin_family = AF_INET;
    endereco_servidor.sin_port = htons(30000);
    endereco_servidor.sin_addr.s_addr = inet_addr("10.0.0.176");

    bind(server, (struct sockaddr *)&endereco_servidor, sizeof endereco_servidor);
    x = listen(server, 1);
    while(1==1)
    {
        printf("\nENtROU WHILE\n");
        client = accept(server, (struct sockaddr *)&endereco_cliente, sizeof endereco_cliente);
        x = send(client, "Ola", 100, 0);
        printf("%i", x);
    }
    return 0;
}

Answer: O principal problema é o seguinte:
Na chamada a accept você está passando o terceiro argumento incorretamente.
Esse terceiro argumento deverá ser o endereço de memória da variável que guardará o tamanho da struct relativa ao cliente.
Isso é devido ao fato desta função poder modificá-la.
Logo, você pode declarar uma nova variável para isso antes:
int size_endereco_cliente = sizeof(endereco_cliente);

E na chamada a accept passar o seu ponteiro, desta forma:
client = accept(server, (struct sockaddr *) &endereco_cliente, &size_endereco_cliente);

No mais, se você não tiver interesse em saber as informações do cliente, é possível simplesmente passar NULL como segundo e terceiros argumentos:
client = accept(server, NULL, NULL);

É uma alternativa.
Melhorias:
Há um defeito no envio do "Ola" para o cliente. Executando do jeito que está você vai perceber que o cliente receberá uns caracteres estranhos logo depois da mensagem. Isso é porque há uma necessidade de ajustar o terceiro argumento de send para o tamanho correto da mensagem que está no segundo argumento. E, neste caso, esse tamanho não é 100.
Recomendo usar uma variável para guardar a mensagem e medi-la com strlen() no momento do envio.
Dica: Você está usando o IP do computador na LAN como endereço para o servidor, talvez ele não seja estático. Nesse caso, recomendo usar 127.0.0.1 para fazer os testes se forem apenas no seu computador.
Referências:
https://www.geeksforgeeks.org/accept-system-call
http://man7.org/linux/man-pages/man2/accept.2.html
https://linux.die.net/man/2/send
Comment: Na parte em que utilizo (struct sockaddr *)&endereco_cliente, o que este ponteiro significa? Ah, e obrigado pela resposta e dicas bem claras, foram de grande ajuda!