Brushable and zoomable timeline with d3

Question: I want to make a timeline where the user can choose between scrolling to zoom or select a region to zoom.
There are some examples of the first like:
https://bl.ocks.org/mbostock/4015254
Or zooming in on a area with brush:
https://bl.ocks.org/mbostock/f48fcdb929a620ed97877e4678ab15e6
But I cannot find an example that does both. How can I do both? Or are there any examples that I missed?
Comment: Did my comment below help at all?
Comment: No, I was not able to implement it. But at this moment I am focusing on my exams, so I don't have time to spend more than 1 day on it.
Answer: This is not the most straightforward thing to implement. As you will notice, the brush based zooming does not rely on d3.zoom but instead performs the zooming via listeners that fire on events to do whatever is needed to scale the axes and move the plot elements accordingly.
In comparison, all the scrolling based zoom examples typically rely on d3.zoom which utilizes a d3.zoom() behavior that keeps track of all the transforms performed on the plot while panning/zooming and is solely responsible for updating the various chart elements. The difficulty lies in the fact that the 2 approaches are quite different and if you manually change the chart view via brushing, you need to figure out a way to update the internal zoom transform that d3.zoom references so that it is aware of the changes made via the brush based zoom events.
This is not at all easy to do because d3.zoom was not designed to be fed information from elsewhere and the internal record of transforms that were performed are not meant to be updateable/mutable. You can update the transform via selection.call(zoom.transform, d3.zoomIdentity); but that unfortunately also fires a whole bunch of events related to the actual zoom behavior, which is not something you want since you already handled all the zoom behavior with your brush based zoom. An ugly, but effective workaround that I was able to use to reset the zoom transform was to mutate the actual .__zoom field of the DOM node that is bound to the d3.zoom behavior as follows:
// WARNING: Ugly mutation of __zoom property of pan/scroll-zoom rect to
// reset the transform without having to fire events associated with zoom
// d3.select(".zoom").node().__zoom = {k: 1, x: 0, y: 0}; <-- Fails since __zoom contains other hidden objects
scrollZoom.node().__zoom["k"] = 1;
scrollZoom.node().__zoom["x"] = 0;
scrollZoom.node().__zoom["y"] = 0;

So for example: If you want a 2D brush for rectangle zooming, but also d3.zoom based zooming for panning and mouse-scrolling, then anytime you use the 2D brush to zoom, you will want to reset the d3.zoom transform back to the identity transform as above. This prevents and ugly and jarring jitter in panning/scrolling response when chaining 2D brush based zooming actions with panning/mouse-scrolling actions due to the transform on record with d3.zoom not being in-sync with the view on display (due to the 2D brush based zoom changing the view without d3.zoom's knowledge).
Here is something else that is important to note:
d3.zoom has a limitation in that it currently only supports a common zoom scale for both X and Y axes (Source). This unfortunately means that there is no way to map a 2-D brush based zoom to a d3.zoom based approach since 2D brush based zooming produces different zoom scaling in X and Y. If you want to do things with minimal issues, using a consistent approach, I'd recommend looking into using d3.xyzoom. This is a fork of d3.zoom that implements support for different scales for X and Y axes. This would enable you to calculate the corresponding X and Y zoom scaling and translation values for any 2D brush selection, which you could then feed into d3.zoom, thus enabling you to perform all the zooming using a common approach (which also results in the least amount of code duplication).
That being said, if you are solely interested in a 1-D brush based zoom, you should be able to map that to a d3.zoom approach so that you don't have to deal with 2 different paths for handling the view and scaling of all the axes and other graphical elements in your chart. Here is a good example of this:
https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172
I apologize for the length of this post and if it is a bit rambling. I am working on putting together a block on my work in a couple of days and I'll try to circle back here and post a link when I get around to doing so. I only started learning D3 a week ago, so I'm learning along the way.

Brushable and zoomable timeline with d3


How to make high availability web page?

Question: When we need a high availability service (it doesn't meter what kind of service: it can be a database, a queue system, our application) we spread it info many machines to make sure when one machine is down rest of them can take this extra load.
Quite simple.
But how to spread load balancers into many machines?
A DNS record can point to 1 or few our servers. But when our server is down DNS and any client don't know that specific machine is not running. Clients will make request to it and they will get an info our web page is not working.
How to cluster load balancer layer?
Answer: First, consider the complexity you are willing to take on to bring availability above a single load balanancer box. Load is generally not a problem, a single host can hand off a very high number of connections.
Load balancers can be clustered like anything else, addressing hardware or other node failures. An open source example would be haproxy with VRRP based keepalived. Typical of several local HA designs it requires same layer 2. Which means alternate solutions on clouds that only give you layer 3.
Layer 2 doesn't help the Internet from getting to a healthy node, or if your data center goes offline. That implies being clever in DNS or IP routing.
DNS can return a different record based on an automatic health check or manually. However, clients can cache results for multiple hours, which is too long for many recovery objectives.
Directing the same IP on a different path is a routing problem. Announce a route to the working load balancer.
Answer: See HAPROXY or similar load/balance haproxy
ADD to response question:
Ok, yo need only one DNS record
client <-> HAPROXY  <-> server A
                    <-> server B
HAPROXY is on middle of client a servers.
HAPROXY config like
<code>bind *:80

        acl host_mysite hdr(host) -i mysite.com
        use_backend mysite if host_mysite

backend mysite
    mode http
    balance roundrobin
    option httpclose
    option forwardfor
    server  serverA ip:port check inter 2000
    server  serverB ip:port check inter 2000
</code>
Comment: I know about load balanced solutions. I'm wondering how does it work when you have 2 LB servers. How does it work with DNS records?
And how does it work when 1 one them is down? How to proxy the whole traffic to the second LB server?
Comment: Ok, yo need only one DNS record

client <-> HAPROXY

How to make high availability web page?


Authenticate user on every request - Spring MVC

Question: My application receives user creds with each request (header). I need to validate the user creds against database before doing any processing. REST based calls.
What is the best approach / standard practice here?
Plain Servlet Filters?
   Spring Interceptors?
   Or any other alternatives?
Note that I need to connect to the database at each request?
Appreciate your input!
Comment: Don't understand why a downvote here.
Answer: You can use spring-security.
You can find an example here.
Comment: No, but you asked for the "best approach".  I would consider Spring Security the "best approach" as it is highly configurable, annotation and/or config driven, and allows you to fairly easily expand and/or alter your security methods later down the road if you, for instance, decide to do SSO or store users in LDAP instead of a DB.  Plus its a Spring way of handling security, which fits nicely with Spring MVC.


von-Neumann regularity of $R/J(R)$

Question: Let $R$ be a ring with identity such that each (right) ideal of $R/J(R)$ is idempotent, where $J(R)$ is the Jacobson radical of $R$. Is $R/J(R)$  necessarily von-Neumann regular?
Certainly, the answer is "yes" in the commutative setting due to the fact that a commutative ring is von-Neumann regular if and only if each ideal of which is idempotent.
Thanks in advance!
Comment: you can ask the question more clearly as: «if $J(R)=0$ and all right ideals of $R$ are idempotent, is $R$ von Neumann regular?» by replacing $R$ by $R/J(R)$, which you can since $R$ plays no useful role in your question.
Answer: I was not previously aware of this paper, but searching for "all right ideals idempotent" drew me to it:

Lanski, Charles. "Idempotent ideals and Noetherian polynomial rings." Can. Math. Bull. 25.1 (1982): 48-53.

Theorem 4 says:

If $R$ is a ring with DCC on right annihilators, then the following are equivalent:

every ideal of $R$ satisfies (SI);
$R$ is a finite direct sum of simple rings with identity;
every right ideal of $R$ satisfies (SI)
every right ideal of $R$ is idempotent

Furthermore, each of 1-4 implies that every left ideal of $R$ is idempotent

(If you're curious about 1 and 3 and the (SI) condition, refer to the paper.)
At any rate, this gives us a lever to search for a candidate in the Database of Ring Theory.
At present, the hit you get is to a non-Artinian simple domain, which obviously satisfies the annihilator condition. By simplicity, $J(R)=\{0\}$. It can't be von Neumann regular, for a von Neumann regular domain must be a division ring.
Comment: @karparvar $J(R)\neq R$ in any ring with unity...
Comment: @karparvar You mean search via properties or just browse? There are links for both options on the front page, as well as in the nav menu. Also, you don't have to be logged in :) Logging in is useful if you want to suggest additions to the site, though.
Comment: Thanks a lot! Since the ring is simple, $J(R)=0$ or $J(R)=R$, and since it is a domain then $0$ is a maximal two-sided ideal. Why $J(R)=0$?
Comment: After logging in DRT, how and where could I search for a certain ring? Thanks!

von-Neumann regularity of $R/J(R)$


Apple Mach-O Linker Warning direct access in ... to global weak symbol

Question: I'm using xcode 4.2 with ios 5.0 sdk building iphone app.
Also, I import opencv library, and write some *.cpp codes with opencv functions.
However, I got a lots similar "apple mach-o linker waring"
For instance -

ld: warning: direct access in __ZN15CvBlobTrackerCCC2Ev to global weak symbol __ZTV9CvBlobSeq means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in __ZN18CvBlobTrackerAuto1C2EP23CvBlobTrackerAutoParam1
to global weak symbol __ZTV9CvBlobSeq means the weak symbol cannot be overridden at runtime.
This was likely caused by different translation units being compiled with different visibility settings.

How do I solve this?
Thanks!
edit:
just find out-
xcode with boost : linker(Id) Warning about visibility settings
Comment: possible duplicate of [xcode with boost : linker(Id) Warning about visibility settings](http://stackoverflow.com/questions/8685045/xcode-with-boost-linkerid-warning-about-visibility-settings)
Answer: Apple Mach-O Linker Warning comes in following cases
1.When the concerned file was not linked to target properly.
2.When the concerned file framework is not linked with code.
3.Replication of file so that compiler gets confusion
Please check your case against them.
If any one find any other reasons which I have not listed above please add it to the list.


Hausdorff measure of $f(A)$ where $f$ is a Holder continuous function.

Question: Let $f\colon \mathbb R^d\to \mathbb R^k$ be a $\beta-$ Holder continuous function ($\beta \in (0,1)$)  and $A\subset \mathbb R^d$. As for a Lipschitz function $g$ it holds that $H^s(g(A))\leq Lip(g)^s H^s(A)$, also for $f$ should hold a similar inequality. I want to know if what I've done is correct.
So, let $f$ be such that $|f(x)-f(y)|\leq L|x-y|^\beta$ for each $x,y$.
For each $\epsilon > 0$ there exists a covering $\{E_j\}_j$ of $A$ with $diam(E_j)\leq \delta$, such that $$\sum_j \alpha(\beta s)\Big(\frac{diam (E_j)}{2}\Big)^{\beta s}\leq H^{\beta s}_\delta(A)+\epsilon \quad (*). $$
Now $\{f(E_j)\}$ is a covering of $f(A)$ and $diam f(E_j)\leq L (diam(E_j))^\beta:=\delta'$, so $$H^s_{\delta'}(f(A))\leq \sum_j \alpha(s)\Big(\frac{diam f(E_j)}{2}\Big)^{s}\leq \sum_j \alpha(s) L^s \frac{(diam (E_j))^{\beta s}}{2^s}.$$
But $$\sum_j \alpha(s) L^s \frac{(diam (E_j))^{\beta s}}{2^s}=\frac{\alpha(s) L^s}{\alpha(\beta s) 2^{s-\beta s}}\sum_j \alpha(\beta s) \Big(\frac{(diam (E_j))}{2}\Big)^{\beta s}$$.
Now from $(*)$, we get that $$H^s_{\delta'}(f(A))\leq \frac{\alpha(s) L^s}{\alpha(\beta s) 2^{s-\beta s}} (H^{\beta s}_\delta(A)+\epsilon),$$ so $$H^s(f(A))\leq \frac{\alpha(s) L^s}{\alpha(\beta s) 2^{s-\beta s}} H^{\beta s}(A).$$
Is it correct? Can I get a better estimate?
Answer: Your argument is correct, and there is no way to improve the estimate. A simple example can be given in the context of abstract metric spaces: let $X $ be the metric space $ (A,d_\beta)$  where $d_\beta(x,y)=|x-y|^\beta$ is a metric. Let $f$ be the identity map from $A$ to $X$; it has the property $|f(x)-f(y)| = |x-y|^\beta$ for all $x,y$.
Unwinding the definition of $H^s$, one obtains
$$H^s(X) =  \frac{\alpha(s) }{\alpha(\beta s) 2^{s-\beta s}} H^{\beta s}(A)$$
which shows that equality holds in your estimate.

The abstract metric space $ (A,d_\beta)$ can be realized as a subset of a sufficiently high-dimensional Euclidean space (i.e., it's isometric to such a subset); this is a consequence of a theorem of Schoenberg on isometric embeddings into Euclidean spaces.


Selenium printing same information repeatedly

Question: Hello I am trying to scrape some data from a website that has data in its 'dl' tag here is how the website structure looks

Donald Duck

dl class="row">

Email

myemail.com

Mickey mouse

dl class="row">

Email

youremail.com

... data goes on but value differs

To scrape this i am using selenium:
my code for scraping
for element in driver.find_elements_by_class_name('ThatsThem-record-overview'): # here im scraping name
   #print(Style.RESET_ALL)
   print(Fore.RED + element.text + Style.RESET_ALL)
   #print(Style.RESET_ALL)
   time.sleep(1)
   dl= driver.find_element_by_tag_name('dl') # scraping data under dl tag
   print(dl.text)
   print('-----------------------')# seperator

So what is happening that whenever i execute the program it prints the dl stuff same for every name and data like this
donald duck
Email
myemail.com
-------------
mickey mouse
Email
myemail.com

I have already tried putting dl in for loop the same way i am doing to print name but it prints other things as well that i don't want
what can i do?
Comment: what is the extra data you are getting and what you don't want to print?
Answer: driver.find_element_by_tag_name('dl') will always return the first matching element. You need to use element to locate the
s
for element in driver.find_elements_by_class_name('ThatsThem-record-overview'):
    dl = element.find_element_by_tag_name('dl') # scraping data under dl tag
    print(dl.text)

Or just locate those elements directly
for element in driver.find_elements_by_css_selector('.ThatsThem-record-overview dl'):
    print(element.text)

Answer: Seems you were close. Using the class record-overview should have fetched you all the required data. However it would be better to target the individual name and email by traversing to the child tags. Additionally inducing WebDriverWait will optimize your program performance.
So, ideally you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following  Locator Strategies:

Using CSS_SELECTOR:
names[] = [my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.record-overview>h2>span")))]
emails[] = [my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.record-overview dl.row dd")))]
for name, email in zip(names, emails):
    print("{} Email is {}".format(name, email))

Using XPATH:
names[] = [my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[contains(@class, 'record-overview')]/h2/span")))]
emails[] = [my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[contains(@class, 'record-overview')]//dl[@class='row']//dd")))]
for name, email in zip(names, emails):
    print("{} Email is {}".format(name, email))

Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


To Mock a Mockingbird - Exclusive Club (logic puzzle)

Question: I'm reading To Mock a Mockingbird, by Raymond Smullyan, and I'm puzzled by the solution to one of the problems.
Chapter 3, Problem 5, The Exclusive Club, states:

There is [a] club known as the Exclusive Club. A person is a member of this club if and only if he doesn't shave anyone who shaves him. A certain barber named Cardano once boasted he had shaved every member of the Exclusive Club and no one else. Prove that his boast involves a logical impossibility.

The author argues that this is a logical impossibility because, if Cardano's statement is true, it leads to a contradiction. Firstly, he would not be a member of the Exclusive Club because he would have shaved himself (having shaved all members of the Club), which no member of the club can do. Neither has Cardano ever shaved himself.
Assuming his statement is still true, the author argues the contradiction occurs because someone from the Exclusive Club will then have shaved Cardano. This person cannot therefore be a member of the Exclusive Club, having shaved someone (Cardano) who has shaved everyone in the Club. Thus Cardano's claim is contradictory and false.
I fail to see how this argument holds up. I see at least two possible, logically valid, scenarios where Cardano's claim is true and not contradictory.

Cardano is not a member of the Exclusive Club. Cardano has shaved everyone in the Exclusive Club, but no one in the Exclusive Club has shaved him. Someone who is not in the Exclusive Club has shaved Cardano and Cardano has shaved that person as well.
No one has ever shaved Cardano.

Am I missing something?
Answer: Your first possibility doesn't work cause at the end you say someone who is not in the exclusive club has shaved Cardano and he shaved them back. This violates his claim that he has shaved everyone in the exclusive club and no one else.
Your second doesn't work since if no one has ever shaved Cardano, then he hasn't shaved anyone who has shaved him (since no one has shaved him). Thus by definition he is in the exclusive club. But this violates Smullyan's (I think valid) conclusion that he is not in the exclusive club: for if he were, by his claim, he must have shaved himself and thus violated the condition for membership in the exclusive club.


Can't see second azure sql database in SSMS object explorer

Question: I have created a second database on my existing Azure SQL server. The first database works fine and I can see it using SSMS.
I cannot see the second database in the object explorer. Autocomplete detects that it exists however.
Any suggestions?
Comment: What version of SSMS are you using?
Comment: @Sam 2014 - 12.0.4459.0
Comment: Have you resolved your issue yet?
Answer: So for me, it turned out that when I was connecting using SSMS, I had set the database to connect to as my first database by accident - meaning that was all I could see.
On connect, go to Options, then check the database you're connecting to. If you're using multiple users to connect to that server like I was, my admin user ended up also being forced to connect to a single database instead of < default >.
Comment: Ha thanks, your question turned up when I was having the same problem! Glad I could help :)
Comment: Thanks for your answer, that somehow solved the *urgent* issue I had too. But I recall you could see more than one DB, if your user had the right privileges, within the same connection. Now it seems I'm stuck with the one DB I select in Options tab. Has something changed?
Comment: If you leave the DB in the options tab to  you can see all the databases that user has permission to see. In my case, I had a user who could only see one DB and (as this user came up first in the list) when I changed user to the one with multiple connections, it didn't change the DB in the Options pane.
Comment: Ah, that makes sense. I have a few databases I like to be able to connect to quickly. I use the Registered Servers view window and add a New Server Registration for each specific database I need quick access to, specifying the database explicitly in the connection options.
Comment: Ding ding ding!!! That was it - been bothering me this whole time :)
Answer: SSMS does not automatically update the database list when new databases are added. You need to refresh the view manually.
In Object Explorer, highlight the Databases node. Hit F5 to refresh. The list of databases should refresh and your new database should appear.
Another method would be to disconnect SSMS from the server and reconnect.
Comment: that didn't work for me. I had to create a new connection despite refreshing about 5 times. I have the same version as @llessa. interestingly I now have TWO instances of the server in object explorer and the original only has one database and the one I just added has the newly added missing database
Comment: There's an aspect of SSMS 2016 behavior that I've found odd when connecting to Azure SQL Database. Assuming you have admin-level privileges, if you connect and open a query to the Azure SQL server without specifying a default database, you end up in the master database. You can use the database switcher dropdown once, and only once. After that, the switcher cannot be used. It's as though you were not limited to a single database, but after you make a choice, it limits you. I wonder if what you're experiencing is another side-effect of this.
Comment: Interesting, I  have a similar problem (using SSMS 13.0.16106.4) and I've tried both these methods and still can't see the other two databases - I can see them on the portal though
Answer: I solved the problem setting <default> in "Connect to database:", in the Connection Properties tab.


Azure bot from template with credentials doesn't work in emulator

Question: My bot just refuses to work with my appId & password on my dev emulator so tried to do the simplest version possible. This is what I tried:

Create a new blank project from the newly copied "Bot Application" template.
Update all the NuGet packages (except System.IdentityModel.Tokens.Jwt v5.1.4 as it isn't compatible with Microsoft.Bot.Builder 3.8.1).
Test it in the emulator with no AppId / Password and it works.
Update the AppId & Password in the web.config.
Run the emulator again and enter the AppId & Password into it.

So it's a brand new solution from the template with just with my credentials changed and this is the error that it gives:
POST 401 [conversationUpdate]
Error: The bot's MSA appId or password is incorrect.
Edit your bot's MSA info

The credentials are definitely correct as I've tested then with the cUrl command and received the token.
My dev machine is Windows Server 2008 R2.
Comment: There's a [Troubleshooting Bot Framework authentication](https://learn.microsoft.com/en-us/bot-framework/troubleshoot-authentication-problems) page
Comment: What about your BotId in your web config ? Remove BotId when you're testing with valid appId and password ;)
Comment: Thanks everyone. I'm just testing on the emulator without the appid & pwd and then putting it back for the deployment version.
Answer: You don't need the App ID and password when you are developing locally. You can also test your bot via the Bot Framework Developer Portal web chat once your bot is deployed & registered.
Scenario 1: If you are running your bot code on your local machine, don't use the app ID or password in the emulator.
Scenario 2: If your bot is deployed to Azure or other cloud service, then you will need to use the app ID/pwd to test in the emulator. On Azure, the recommended method is to add your MICROSOFT_APP_ID and MICROSOFT_APP_PASSWORD to your application settings as described in step 10 of the article Deploying Bot Framework to Azure on Linux.
Comment: I created another deployment target "local" with no values in those fields and then transformations on the debug & release config files to put in the values it needs when it gets deployed.


Fatal Error : Call to a member function bind_param()

Question: Esta me a aparecer este problema:

Fatal error: Call to a member function bind_param() on boolean in C:\xampp\htdocs\Myworld\Registo\cria_utilizador.php on line 32

Ao executar este codigo:
  $email = htmlspecialchars($_POST["email"]);
  $pw1 = $_POST["pw1"];
  $pw2 = $_POST["pw2"];
  $nome = $_POST["nome"];
  $sobrenome = $_POST["sobrenome"];
  $date = $_POST["dataN"];

  if($pw1 === $pw2){

    $hash = password_hash($pw1, PASSWORD_DEFAULT);
    $lig = new mysqli("localhost", "root", "", "myworld");
    if($lig->connect_error){
      die("
Serviço indisponível. Por favor tente mais tarde
");
    }
    $sql = "INSERT INTO utilizadores(email, password, nome, sobrenome, data_nascimento) VALUES(?, ?, ?, ?, ?,)";
    $inst = $lig->prepare($sql);
    $inst->bind_param("ssiss", $email, $hash, $nome, $sobrenome, $date);
    if($inst->execute() === TRUE){
      echo "
Bem vindo, " . $email . "
";
    }
    else{
      echo "
Registo não efetuado. Email indisponível
";
    }
    $lig->close();

  }
  else{
    echo "
As passwords não coincidem! Por favor repita o registo
";
  }

Answer: Esse erro é porque você tentou acessar o bind_param do objeto do mysqli ao invés do objeto gerado pelo prepare, faça sempre seguindo os exemplos da documentação:

http://php.net/manual/en/mysqli-stmt.bind-param.php

A documentação existe para isso mesmo e contém exemplos para a maioria dos casos, então o seu código deveria ser:
  $email = htmlspecialchars($_POST["email"]);
  $pw1 = $_POST["pw1"];
  $pw2 = $_POST["pw2"];
  $nome = $_POST["nome"];
  $sobrenome = $_POST["sobrenome"];
  $date = $_POST["dataN"];

  if($pw1 === $pw2){

    $hash = password_hash($pw1, PASSWORD_DEFAULT);
    $lig = new mysqli("localhost", "root", "", "myworld");
    if($lig->connect_error){
      die("
Serviço indisponível. Por favor tente mais tarde
");
    }
    $sql = "INSERT INTO utilizadores(email, password, nome, sobrenome, data_nascimento) VALUES(?, ?, ?, ?, ?,)";

    $stmt = $lig->prepare($sql);
    $stmt->bind_param("ssiss", $email, $hash, $nome, $sobrenome, $date);

    if($stmt->execute() === TRUE){
      echo "
Bem vindo, " . $email . "
";
    }
    else{
      echo "
Registo não efetuado. Email indisponível
";
    }
    $stmt->close();

  }
  else{
    echo "
As passwords não coincidem! Por favor repita o registo
";
  }

  $lig->close();

Comment: Já resolvi o problema, Obrigado.


On the splitting field over $\mathbb{Q}$ of $X^4 + 1$.

Question: My question can be stated very simply: why is the splitting field over $\mathbb{Q}$ of $X^4 + 1$ not the field $\mathbb{Q}[e^{i\pi/4}].$
After all, if one defines $\alpha = e^{i\pi/4}$, then
$$
X^4+1=(X - \alpha)(X- \alpha^3)(X-\alpha^{-1})(X-\alpha^{-3})
$$
I figure that the answer to my question will entail showing that what I'm calling "$\mathbb{Q}[e^{i\pi/4}]$" is essentially nonsense/invalid/ill-defined, etc., but I can't provide the argument myself.
BTW, I know (from my textbook) that the splitting field over $\mathbb{Q}$ of $X^4+1$ is $\mathbb{Q}[i,\sqrt{2}]$, but from this knowledge I'm not able to discern exactly where my reasoning above goes wrong.

Let me try to elaborate on my confusion here.
Suppose I treat $\alpha$ as an "opaque symbol".  All I know is that $\alpha^4 + 1 = 0$.  How do I determine that the degree of the extension $\mathbb{Q}[\alpha]$ is 4?
Answer: In fact there isn't a confusion, as we have that $\mathbb{Q}\left(e^{\frac{i\pi}{4}}\right) = \mathbb{Q}(i,\sqrt{2})$
The inclusion $\mathbb{Q}\left(e^{\frac{i\pi}{4}}\right) \subseteq \mathbb{Q}(i,\sqrt{2})$ is trivial, as $e^{\frac{i\pi}{4}} = \frac 1{\sqrt{2}}(1+i)$. On the other side we have that $i = \left(e^{\frac{i\pi}{4}}\right)^2 \in \mathbb{Q}\left(e^{\frac{i\pi}{4}}\right)$. From here trivially $\sqrt{2} \in \mathbb{Q}\left(e^{\frac{i\pi}{4}}\right)$ and so we can conclude that $\mathbb{Q}(i,\sqrt{2}) \subseteq \mathbb{Q}\left(e^{\frac{i\pi}{4}}\right)$
Comment: @kjo Note that you have two extensions of degree two. And indeed $[\mathbb{Q}(i,\sqrt{2}):\mathbb{Q}] = [\mathbb{Q}(i,\sqrt{2}):\mathbb{Q}(i)][\mathbb{Q}(i):\mathbb{Q}] = 2 \cdot 2 = 4$
Comment: @kjo To follow up on your second question we know that the degree of the extension is the degree of the minimal polynomial. So now we know that $\alpha$ is a root of $x^4 +1$. To prove that this is the minimal we need to prove that $x^4 + 1$ is irreducible in $\mathbb{Q}[x]$. Can you prove this?
Comment: Thanks.  I think I may have worded my question badly.  What's throwing me off is the expectation that the degree of an extension of the form $\mathbb{Q}(\alpha)$ would be 2, while in this case, with $\alpha = e^{i \pi/4}$, the degree is in fact 4...
Answer: Note that $\alpha^2=i$ so that $i$ is in the field you have defined.
Also $(\alpha+\alpha^{-1})^2=i+2+\frac 1i=2$ so that $\sqrt 2$ is in the field you have defined.
So your field contains $\mathbb Q (\sqrt 2, i)$, and you can just as easily show the inclusion the other way by writing $\alpha = (1+i)\frac {\sqrt 2}2$.
In fact $\alpha$ is a primitive element for the field $\mathbb Q(\sqrt 2, i)$, which is known to exist (by the primitive element theorem).
Fields differently specified can be the same without this being immediately obvious.
Comment: Thank you.  The fact that $\alpha^2$ is not in $\mathbb{Q}$ is the clue that the degree cannot be 2.
Comment: @kjo That's not quite right, but the fact that the minimal polynomial of $\alpha$ (x^4+1) has degree $4$ over $\mathbb Q$ will do it. To show degree higher than $2$ you have to show that $\alpha$ doesn't satisfy any quadratic equation with rational coefficients. The roots of $x^2+x+1=0$ are complex cube roots of $1$, and they do generate a quadratic extension.


Reconfiguring python

Question: I installed Python-2.7.3 with configure --enable-shared, make and install.
It so happens that now, I need to reconfigure to include the --with-pydebug option.
While running configure again, do I need to include all the flags I had before? (--enable-shared) or is it okay to configure again with just the additional flags?
Answer: configure configures the build from scratch (with minimal support for caching certain results). Therefore, you need to supply all the same flags as before.
When changing configure flags, it is also recommended to do a make distclean to ensure that everything is rebuilt. This is especially important with --with-pydebug since the basic PyObject layout will change.
Comment: And if interested, I think you can grep the original configure command out of `config.log`...
Comment: @mgilson: yes, this is very good advice especially if you've lost the original configure command. You can also find all of the environment settings in `config.log` in case you had to tweak e.g. the compiler path.
Comment: It seems to me that there was an easier way to get it, but I can't seem to remember what it was (or even if it actually exists) off the top of my head ...
Comment: Well, the command is usually near the top of `config.log`. So you don't usually need `grep`, just `less`.

Reconfiguring python


Is it possible to improve my pinky to such an extent?

Question: My pinky and ring finger are very close when playing some chords, as showed in Image 1. If I play the chord in Image 2, which is to hold B / F# / D / F# first and then hammer on E, my left hand will result in Image 3 and the E will be almost mute.
Is it possible to improve my pinky to the extent as Image 4?
If it is possible, how to achieve it?

In Image3 and Image4 my thumb anchors at the center of the neck.
Answer: Yes, I personally would recommend two things:

Dexterity Exercises
Stretching

There are many boring finger dexterity exercises out there, and though it may be tempting to just focus on your pinky, you would need to work all of the fingers; working to make all of them independent.
There is an old stretching trick a lot of instrumentalists use for different reasons.  You simply place your wrist in between the fingers you want to stretch.  At first, place your wrist sideways so you don't pull a muscle.  Over time, feel free to turn your wrist so it spreads your fingers wider.  I have known some to even wrap their wrist to make it even wider.
If you stretch every day and are diligent with dexterity (independence) exercises, your flexibility and finger strength will improve and you will be able to perform the chord.
For the time being, though I don't know the context, you could capo III.  Again, it may not be a practical solution.


A difficult problem on factorization algebra

Question: Factorize $(a+b+c)^7 - a^7-b^7-c^7$.
Comment: What if $a=-b?$
Answer: Hint. Note that $$(x^7-y^7)=(x-y)\left(\sum_{k=0}^6 x^ky^{6-k}\right)$$
which implies that $(a+b)$, $(b+c)$ and $(c+a)$ are factors.
Answer: When $a=-b$,
$$(a+b+c)^7-a^7-b^7-c^7=c^7-a^7-(-a)^7-c^7=0$$
By Factor Theorem, $a+b$ is a factor of $(a+b+c)^7-a^7-b^7-c^7$.
Similarly, $b+c$ and $c+a$ are also factors of $(a+b+c)^7-a^7-b^7-c^7$.
As $(a+b+c)^7-a^7-b^7-c^7$ is cyclic and symmetric,
$$(a+b+c)^7-a^7-b^7-c^7=(a+b)(b+c)(c+a)[p(a^4+b^4+c^4)+q(a^2b^2+b^2c^2+c^2a^2)+r(a^3b+a^3c+b^3a+b^3c+c^3a+c^3b)+sabc(a+b+c)]$$
for some constants $p$, $q$, $r$ and $s$.
Comparing the coefficients of $a^6b$, we have
$$7=p$$
Comparing the coefficients of $a^5b^2$, we have
$$\binom{7}{2}=p+r$$
Comparing the coefficients of $a^4b^3$, we have
$$\binom{7}{3}=q+r$$
Comparing the coefficients of $a^4b^2c$, we have
$$\binom{7}{4}\binom{3}{2}=p+q+3r+s$$
Therefore, $p=7$, $q=21$, $r=14$ and $s=35$.
$$(a+b+c)^7-a^7-b^7-c^7=7(a+b)(b+c)(c+a)[a^4+b^4+c^4+3(a^2b^2+b^2c^2+c^2a^2)+2(a^3b+a^3c+b^3a+b^3c+c^3a+c^3b)+5abc(a+b+c)]$$
It remains to show that
$$g(a,b,c)=a^4+b^4+c^4+3(a^2b^2+b^2c^2+c^2a^2)+2(a^3b+a^3c+b^3a+b^3c+c^3a+c^3b)+5abc(a+b+c)$$
is irreducible.
If $\alpha a+\beta b+\gamma c$ is a factor of $g(a,b,c)$, then so are $\alpha a+\beta c+\gamma a$, $\alpha b+\beta a+\gamma c$, $\alpha b+\beta c+\gamma a$, $\alpha c+\beta a+\gamma b$ and  $\alpha c+\beta b+\gamma a$.
If $\alpha,\beta,\gamma$ are mutually distinct, then the product of these factors has degree $6$.
So at least two of $\alpha,\beta,\gamma$ are equal, say $\beta=\gamma$. But then
$$[\alpha a+\beta (b+c)][\alpha b+\beta (c+a)][\alpha c+\beta (a+b)]$$
is a factor of degree $3$ of $g(a,b,c)$ and thus there is one more cyclic and symmetric linear factor left. This factor should be $a+b+c$.
However, when $a=-b-c$,
$$(a+b+c)^7-a^7-b^7-c^7=(b+c)^7-b^7-c^7\ne0$$
and hence $a+b+c$ cannot be a factor of $g(a,b,c)$.
Therefore, $g(a,b,c)$ has no linear factors.
$g(a,b,c)$ either has no factors or only has cyclic and symmetric quadratic factors, i.e.
$$g(a,b,c)=[a^2+b^2+c^2+m(ab+bc+ca)][a^2+b^2+c^2+n(ab+bc+ca)]$$
Comparing the coefficients of $a^3b$,
$$2=m+n$$
Comparing the coefficients of $a^2bc$,
$$5=m+n$$
Such pair of $m$ and $n$ does not exist.
$g(a,b,c)$ is irreducible.


What should the AUROC be on the test set when no positive example is present?

Question: Assume we have a probabilistic, binary classifier. We compute the AUROC on a test set in which no positive example is present (i.e. the ground truth is always 0). What should the AUROC be?
Comment: I agree. It seems that the $TPR$ coordinate is undefinited when you vary the threshold on probabilities. On the other hand, the $FPR$ coordinate should vary from 1 to 0 varying the threshold on probabilities from low values to high values. However, why do you need this?
Comment: @Simone Thanks. Just to know how to deal with these special case in a program. I am doing multi-label classification, and sometimes one label is always negative in the test set.
Comment: @FranckDernoncourt I find it odd to monkeypatch such situations by saying AUROC is undefined (this is a symptom, not the problem). What do you do after concluding AUROC is undefined? Penalize this somehow? Instead, you should fix the true problem, i.e. ensure that your test set always has all labels (e.g. through stratified cross-validation).
Comment: @MarcClaesen I am using the same code on different data set. In one data set, one label is absent from the train and sets, but is present in the test set. I'm not allowed to use the test set to train. If the AUROC was defined, it could be used when computing the AUROC over all labels. If undefined, I simply ignore it. Ideas welcome!
Answer:
The true positive rate (TPR), aka. sensitivity, hit rate, and recall, is defined as $ \frac{TP}{TP+FN}$.
The false positive rate (FPR), aka. fall-out,  is defined as $ \frac{FP}{FP+TN}$.
The ROC plots the TPR against the FPR.

Since the test set contains no positive example, then TP = FN = 0. This means that the TPR is undefined (division by zero), which means that the ROC cannot the plotted, which means that AUROC is undefined.


Is it secure to use a DLL for the main logic of your .NET application?

Question: If a user knows almost anything about coding in .net, and they see a .dll, they have the unfortunate ability to call your public functions and subroutines. I know you could try a "key" system, where it will check for a certain "key" as an argument, and only run the code if the "key" is valid, but I just ran some code and a .dll that I made, and when the .dll threw an unhandled exception, it showed me the contents of the file.
How can you protect your .dlls? Should you only put code in that you are willing to risk?
Comment: Something else to keep in mind: I don't think you are able to "see the code" for a DLL on an unhandled exception, if the DLL is built in release mode and a PDB file is not present.
Comment: @Mark Rushakoff: a .NET assembly can be decompiled using reflector...
Comment: @Mitch Wheat: Agreed, but the .NET framework shouldn't give much detail when there's an unhandled exception if the DLL was built in the above manner.
Answer: Nevermind calling existing methods etc. Reflector will decompile the code!
Obfuscation will get you so far, but to protect critical IP you need to host it on a secure server that you control.
Answer: Be aware that there is no difference between a .NET DLL and an EXE file when it comes to ability to decompile or re-use in other applications.
Your question implies that putting all of your code in an executable is somehow safer, this is a big misconception.
Both are assemblies, so it is equally simple to instantiate and use publicly visible types in an executable, as it is with a DLL assembly.  (As an example. in Visual Studio go to: Add Reference, Browse, and then notice that 'exe' is a valid component to reference.)
So the question is really more general: is it safe to deploy .NET assemblies of any type to your customers?  As another answer says, the only guaranteed safe approach is to not deploy at all, but keep the assemblies on your own server (eg develop a web application).
Obfuscation will not stop someone from accessing your code, just make it harder (for a while) for them to understand it.
Answer: I'm going to sidestep the actual question you asked in order to more quickly point you in the direction you need to go.
You need to look into .Net code obfuscation.  Here's a good post from someone else asking essentially the same question, but in different terms:
.NET obfuscation tools/strategy
Edit - added
Here's a good article on the issue you're asking about.
https://web.archive.org/web/20210802164229/https://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/080404-1.aspx
And @Mitch Wheat is right.  Obfuscation will only get you so far.  But it's a start.  If you're going to be redistributing your dll's, you'll need to get used to the idea that someone persistent enough is going to crack them.
Comment: Will that also obfuscate the functions and subroutines?
Comment: I'm going to have to advise you to read the article at the second link rather than answer that.  The article covers the topic much more clearly than I can in a few posts or an answer here, and it sounds like you need to look at the basics of the topic.  (no offense).
Answer: A small question
Is you application a web application or a C# (windows forms/command prompt) application.
If it is a web application, you can put the logic which you want to hide in a web service hosted on some other URL not accessible to public.
Also if it is a windows application, you can still obfuscate the dll. But remember, you can make the hackers difficult to decompile but not impossible. I also had a similar question in the link below.
How to preventing decompilation of any C# application
You have to weigh the benefits of decompilation over the business returns of hiding/leaving the code as it is.
Hope this  helps.


Problems with Outlier Detection

Question: In a blog post Andrew Gelman writes:

Stepwise regression is one of these things, like outlier detection and
  pie charts, which appear to be popular among non-statisticians but are
  considered by statisticians to be a bit of a joke.

I understand the reference to pie charts, but why is outlier detection looked down upon by statisticians according to Gelman?  Is it just that it might cause people to over-prune their data?
Comment: If you look at the comments on that same page you linked to, you'll find an answer from Andrew himself, as well as further discussion. See for example this comment: http://andrewgelman.com/2014/06/02/hate-stepwise-regression/#comment-168922
Comment: The detail here on statisticians versus non-statisticians is unfortunate. Look through e.g. Barnett and Lewis' treatise on outliers and you will see test after test suggested mostly by statisticians focusing on implausible situations. It's true that (e.g.) in physics people often still follow ancient rules proposed by Peirce and Chauvenet  but much of the dopeyness here is associated with statisticians too. Disclosure: I am not a statistician, and I tend to believe that outliers are often genuine and that finding the right scale on which to work makes almost all tractable.
Comment: @NickCox: I think Gelman may have been referring to different statistician vs non-statistician conversations. For example, when looking malicious behavior on networks, lots of non-statisticians are fired about outlier detection; "of course I want to know about unusual behavior!!". Reading through the statistical literature, many statisticians start and end their papers "well, this *can* be done and here's how **but**..."
Comment: ...or alternatively, biologists are often okay with dropping outliers, because they believe these outliers are due to procedural errors rather than an unusual result from a properly executed experiment. So to them, a procedure that automatically drops procedural errors sounds great, but a statistician is not so happy with what actually happens in practice.
Answer: @Jerome Baum's comment is spot on. To bring the Gelman quote here:

Outlier detection can be a good thing. The problem is that
  non-statisticians seem to like to latch on to the word "outlier"
  without trying to think at all about the process that creates the
  outlier, also some textbooks have rules that look stupid to
  statisticians such as myself, rules such as labeling something as an
  outlier if it more than some number of sd's from the median, or
  whatever. The concept of an outlier is useful but I think it requires
  context—if you label something as an outlier, you want to try to get
  some sense of why you think that.

To add a little bit more, how about we first define outlier. Try to do so rigorously without referring to anything visual like "looks like it's far away from other points". It's actually quite hard.
I'd say that an outlier is a point that is highly unlikely given a model of how points are generated. In most situations, people don't actually have a model of how the points are generated, or if they do it is so over-simplified as to be wrong much of the time. So, as Andrew says, people will do things like assume that some kind of Gaussian process is generating points and so if a point is more than a certain number of SD's from the mean, it's an outlier. Mathematically convenient, not so principled.
And we haven't even gotten into what people do with outliers once they are identified. Most people want to throw these inconvenient points away, for example. In many cases, it's the outliers that lead to breakthroughs and discoveries, not the non-outliers!
There's a lot of ad-hoc'ery in outlier detection, as practiced by non-statisticians, and Andrew is uncomfortable with that.
Answer: This demonstrates the classic tug of war between the two types of objectives for statistical analyses such as regression: descriptive vs. predictive. (Pardon the generalizations in my comments below.)
From the statistician's point of view, description usually matters more than prediction. Hence, they are inherently "biased" towards explanation. Why is there an outlier? Is it really an error in data-entry (extra zeros at the end of a value) or is it a valid data point which just happens to be extreme? These are important questions for a statistician.
OTOH, the data scientists are more interested in prediction rather than description. Their objective is to develop a strong model that does a great job of predicting a future outcome (e.g., purchase, attrition). If there's an extreme value in one of the fields, a data scientist would happily cap that value (to the 98th percentile value, for instance) if that helps improve the predictive accuracy of the model.
I don't have a general inclination towards either one of these two approaches. However, whether the methods/approaches such as stepwise-regression and outlier-treatment are "a bit of a joke" or not depends on which side of the fence you are standing.

Problems with Outlier Detection


Idempotents in $\mathbb{Z}[i] \otimes_{\mathbb{Z}} \mathbb{Z}[i]$

Question:
Letting $\mathbb{Z}[i]=\left\{a+bi:a,b \in \mathbb{Z} \right\}$ be the ring of Gaussian integers, how many idempotents are there in $\mathbb{Z}[i] \otimes_{\mathbb{Z}} \mathbb{Z}[i]$?

I came across this in my reading, and I'm a little unsure of how to approach this. Any help would be appreciated!
Answer: Geometrically, the spectrum of $\mathbb Z[i]\otimes_\mathbb Z\mathbb Z[i]$ is two copies of the spectrum of $\mathbb Z[i]$ meeting each other above the point $2\mathbb Z$ of $\mathrm{Spec}\mathbb Z$. So it is connected, which means there is no idempotent different from $0$ and $1$.
Comment: It might be nice to note what goes wrong with the "obvious proof" that the tensor product $\mathbb{Z}[i]\otimes\mathbb{Z}[i]$ has four idempotents. Namely, this ring is isomorphic to $\mathbb{Z}[i][x]/(x^2+1)$. Now $x^2+1=(x+i)(x-i)$, and so we can CRT this to get the product of two integral domains, so four idempotents, right? Wrong. The issue is that while $x-i$ and $x+i$ are coprime, since $\mathbb{Z}[i][x]$ is not a PID (it has dimension 2) this does not imply that $(x-i)$ and $(x+i)$ are comaximal! In fact, they jointly generate $(2)$ which is consistent with Cantlog's geometric picture.
Comment: See [this post](http://math.stackexchange.com/questions/160853/connectedness-of-the-spectrum-of-a-tensor-product) for the general case of tensor product of rings of integers.
Answer: We have $$\mathbb{Z}[i] \otimes_{\mathbb{Z}} \mathbb{Z}[i]\cong\Bbb Z[i][X]/(X^2+1).$$ Every element of the ring $\Bbb Z[i][X]/(X^2+1)$ can be uniquely written as $a+bx$, with $x^2=-1$. If $(a+bx)^2=a+bx$, then $a^2-b^2=a$ and $2ab=b$. Now we have two cases: $b=0$ and $a=0,1$ or $b\ne 0$ and then $a=1/2\notin\Bbb Z$. It follows that $0,1$ are the only idempotents.


How to discard a DHCP request's old IP address (and provide a new one)?

Question: I switched from a 192.168.0.0/24 network to 10.10.10.0/24. The addresses are provided by dnsmasq-dhcp.
The switch went fine for all devices but one - a printer (called PRINTER). This printer was assigned a fixed IP based on its name defined in /etc/hosts (via dhcp-host=PRINTER) and still does with the new ranges.
When it requests an IP address, the DHCP server states in its logs that
dnsmasq-dhcp:  not giving name PRINTER to the DHCP lease of 192.168.0.20 because the name exists in /etc/hosts with address 10.10.10.20

I do not understand this message: the name indeed exists in /etc/hosts, with now the new 10.10.10.20 address. While I guess that the DHCP query from the printer hints about the old IP address it used to have, why doesn't dnsmasq just ignore that and provide the new IP address?
Answer: Check if your printer name for old ip is here:
/var/lib/misc/dnsmasq.leases
and edit that file, you must stop dnsmask first
check the Lease times you setup when you configured dhcp, if you assigned too much time then it will take a while to "fix "itself
Answer: First off, I will assume that your printer is properly implementing DHCP and DDNS updates, but this is not always true.  I am also assuming that the original lease it obtained has not expired yet.  If you are getting this message after expiration, then you might be dealing with an improper DHCP implementation.
Your printer obtained a lease of 192.168.0.20, and was told that it would be valid for X number of days.  Some time before that, you changed the range to 10.10.10.0/24.  The printer still has an address lease that is technically valid, although undesirable.
During a lease, it is common for a device to request a lease renewal and/or a DDNS update.  The lease renewal is obviously declined, since the original address is no longer valid for new leases, but that doesn't mean the printer will stop using it.  It might not request a new address until the original lease has fully expired.  This is not a bug.
The name update seems to be what is triggering the error, though.  Depending on your configuration, it could be the printer requesting the name renewal, or the DHCP server requesting the renewal on behalf of the printer.  The name renewal is being rejected since the address it's tied to is no longer a valid address on the server.  The server parts are smart enough to know this, but the device will hang on until the bitter end before trying again, and probably succeeding.
The renewal process is basically the client or its agent asking if it may please continue using this name on that address.  The server gets to answer "Yes," or "no," but does not get to say "No, but use this one instead."
The shortcut is to get your printer to release its lease and get a new one.  You can usually do this through the web interface, or sometimes a power cycle.


Klein 4 group ismorphic to D4?

Question: Klein 4-group is a symmetry group of rectangle (or rombus).
And as far as I understand it is not isomorphic to Dihedral group of order 4.
Because Dihedral group of order 4 is a group of rotations of square.
If this is true then why Wiki says that they are isomorphic:

The Klein four-group is the smallest non-cyclic group. It is however an >abelian group, and isomorphic to the dihedral group of order (cardinality) 4

What am I missing here?
Answer: You are confusing 'the dihedral group with 4 elements' with 'the dihedral group that is the symmetry group of the square'. The dihedral group with 4 elements is the set of symmetries of a bigon (i.e. a 'polygon' with 2 vertices, which can be thought of as two curved lines joined together) or of a rectangle (thanks to Akiva Weinberger).
The dihedral group that is the symmetry group of a square is of order 8 and usually is denoted $D_4$.
Comment: It's best to imagine the 2-gon as having two curved sides, here, so that it has an "area". Thus, the symmetries are the identity, rotating, flipping horizontally, and flipping vertically. (There are only two symmetries of an actual line segment, I believe — identity and rotating.)
Comment: Thank you, guys, I got it now!

Klein 4 group ismorphic to D4?


How to display version number instantly

Question: I want to have the app version number displayed in my settings when the settings page is opened. My issue is that I learned that has to be done asynchronously. How do I get the version number and display it in a Text once it gets it?
My code that returns a future:
Future<String> getVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();

    return packageInfo.version;
  }

I want to display the version here:
ListTile(
     title: Text("Version"),
     subtitle: Text("1.0.0"), //replace with getVersion()
),

Answer: Use package_info to get the version of the app.
make state variable with dummy initialization and in initState make a function call to get the version value and update the state variable which is initialized with the dummy value
My working code here
//initialize dummy value
PackageInfo _packageInfo = new PackageInfo(
  appName: 'Unknown',
  packageName: 'Unknown',
  version: 'Unknown',
  buildNumber: 'Unknown',
);

@override
void initState() {
  super.initState();
  //get package details
  _initPackageInfo();
}

Future<Null> _initPackageInfo() async {
  final PackageInfo info = await PackageInfo.fromPlatform();
  setState(() {
    _packageInfo = info;
  });
}

Render list tile view as
new ListTile(
  title: new Text('${_packageInfo.version}'),
  leading: const Icon(
    FontAwesomeIcons.codeBranch,
    size: 20.0,
  ),
),

you view will show somthing like icon 1.0.0 which is specified as version in your package.
Hope it helps you. let me know if not
Comment: Good solution. Thanks!

How to display version number instantly


Trumpet low range in a big band

Question: A common voicing technique in big band music is to have the 4th trumpet play an octave below the lead trumpet. Is there a limit to how low this can go and still be effective, other than the hard limit of the 4th trumpet's lowest note?
Answer: Low range limit of the trumpet is pretty much the limit, but you'll want to listen to the pitches of the 3rd and 2nd above it if it's a closed voicing. It shouldn't be too muddy, even in a closed voicing, but a cluster chord at the trumpet's low range can sound a little...flubby.
If you're coming up against that low-end limit, consider doubling lead, trying a different voicing type (if you're doing Drop 2+4 or quartal, try 4-way close), or just use lead trumpet as a melodic lead, and leave the harmonic voicings to saxes and bones using a sort of tutti spread rather than 4- or 5-part soli.
"The lead range, related balance considerations, and the need for variety in spacing (close versus open) should help you determine which voicings to choose and for how long." - Modern Jazz Voicings, Ted Pease & Ken Pullig
Comment: There's so much great arranging advice in this answer!
Answer: I wouldn't go below written A.  And if you find yourself in this area too much, consider another voicing strategy.

Trumpet low range in a big band


useState - Array renderiza sempre vazio na primeira vez

Question: Estou tentando fazer uma validação da variável prods com o .length, porém percebo que toda vez que este useEffect roda, ele retorna vazio antes da atualização da variável. Logo, qualquer tipo de validação com length se torna dispensável pois sempre cai neste primeiro vazio antes de atualizar os dados da váriavel.
const [prods, setProds] = useState([]);
const [prodsByCprod, setProdsByCprod] = useState([]);

useEffect(() => {
  async function loadProdsByCprod() {
    const response = await api.get('/produtoByFk_Nfe');
    setProds(response.data);
  }

  loadProdsByCprod()
}, []);

useEffect(() => {
  async function verificationCProd() {
    if (prods.length < 1) {
      alert("Você não tem produtos");
      history.push('/consulta');
    }
  }

  verificationCProd();
}, [prods]);

Mesmo o prods tendo dados, ele entra nesse if.
Eu conseguiria fazer esta validação de alguma outra forma? Visto que preciso que ela carregue para ver se a variável prods é alimentada e o usuário tem produtos, caso ao contrário, irei redirecioná-lo para outra página.
Answer: O useEffect é um hook que executa após primeira renderização do componente e após as renderizações subsequentes sempre que qualquer uma das dependências passadas for alterada. O que está acontecendo no seu caso é que, na primeira renderização do componente, o vetor prods está, de fato, vazio, então ele acaba sempre entrando nessa condição do if.
Para corrigir esse problema, use uma ref que armazene a informação de primeira renderização, como no código abaixo.
const firstRenderRef = useRef(true);

useEffect(() => {
  if (firstRenderRef.current) {
    firstRenderRef.current = false;
    return;
  }

  if (prods.length < 1) {
    alert("Você não tem produtos");
    history.push('/consulta');
  }
}, [prods]);

Se situações como essa acabarem ficando muito comuns, considere criar um hook personalizado para isso.
function useStateUpdate(handler, deps) {
  const firstRenderRef = useRef(true);

  useEffect(() => {
    if (firstRenderRef.current) {
      firstRenderRef.current = false;
      return;
    }

    return handler();
  }, deps);
}

Dessa forma, o seu código final ficaria com essa cara
useStateUpdate(() => {
  if (prods.length < 1) {
    alert("Você não tem produtos");
    history.push('/consulta');
  }
}, [prods]);

Comment: Funcionou perfeitamente, obrigado pela explicação.


Question related to Hibernate Transaction code

Question: While I am working on spring boot with hibernate I got some confusion on transaction management code. Can any one clarify my doubt?
public class HibernateConfig {

    @Value("${db.driver-class-name}")
    private String DB_DRIVER;
    @Value("${db.password}")
    private String DB_PASSWORD;
    @Value("${db.url}")
    private String DB_URL;
    @Value("${db.username}")
    private String DB_USERNAME;
    @Value("${hibernate.dialect}")
    private String DB_DIALECT;
    @Value("${hibernate.show_sql}")
    private String DB_SHOW_SQL;
    @Value("${entitymanager.packagesToScan}")
    private String DB_PACAKAGESTOSCAN;

    public DataSource dataSource() {
        DriverManagerDataSource datasources = new DriverManagerDataSource();
        datasources.setDriverClassName(DB_DRIVER);
        datasources.setUrl(DB_URL);
        datasources.setUsername(DB_USERNAME);
        datasources.setPassword(DB_PASSWORD);
        return datasources;
    }

    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionfactory = new LocalSessionFactoryBean();
        sessionfactory.setDataSource(dataSource());
        sessionfactory.setPackagesToScan(DB_PACAKAGESTOSCAN);
        Properties hb_properties = new Properties();
        hb_properties.put("hibernate.dialect", DB_DIALECT);
        hb_properties.put("hibernate.show_sql", DB_SHOW_SQL);
        return sessionfactory;

    }

@Bean
public HibernateTransactionManager transactionManager() {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactory().getObject());
    return transactionManager;

    }

}

Well in the above code the last method transaction manager why we need to write? In this method what is happening internally can anyone explain me?
Answer: Because hibernate needs transactions in order to perform its operations. Example would be @OneToMany relationship. Once an entity is loaded you actualy need an active transaction in order to fetch its Lazy relationships. Only within an active transaction the entity is in managed state.
Make the following experiment. Try to load an entity with Lazy relationships without active transaction, the load will succeed but then try to access one of the relationships.
Without an active transaction you will not be able to perform a simple save operation.
Answer: Just based on the docs:

Binds a Hibernate Session from the specified factory to the thread,
  potentially allowing for one thread-bound Session per factory.

Basically thanks to a transaction manager you are able to perform various CRUD operations and conform to the ACID database rules.
On top of that it:

Supports custom isolation levels, and timeouts

Then if certain operations are only fetching data, then you can set the transaction as readOnly increasing the performance.


Interpreting almost sure convergence

Question: I'm reading: https://en.wikipedia.org/wiki/Convergence_of_random_variables#Almost_sure_convergence and here it says that

Given a probability space $(\Omega,\mathcal{F},P)$ and a random variable $X:\Omega \rightarrow \mathbb{R}$ almost sure convergence stands for $$P\left(\omega \in \Omega: \lim_{n \rightarrow \infty} X_n(\omega)=X\right)=1.$$ [...] almost sure convergence can also be defined as follows: $$P\left(\limsup_{n \rightarrow \infty} \left\{\omega \in \Omega: |X_n(\omega) - X(\omega)| > \varepsilon\right\}\right)=0, \quad \forall \; \varepsilon>0.$$

My question is, what is the intuition behind this equivalence? I understand the first definition, but why do we use $\limsup$ in the second one to make the equivalence work? Thanks
Answer: I don't really see intuition here, the equivalence just follows from using the definition of convergence. For a sequence of sets $(A_n)$ the set $\lim \sup(A_n)=\{A_n\ \ i.o\}$ is the set of elements which belong to infinitely many of the sets $A_n$. The formal definition of this set is $\cap_{n=1}^\infty \cup_{k=n}^\infty A_k$.
Assume $X_n\to X$ almost surely by the first definition and let any constant $\epsilon>0$. Define the sequence $A_{n,\epsilon}:=\{\omega: |X_n(\omega)-X(\omega)|>\epsilon\}$. Note that if $\omega\in\lim\sup A_{n,\epsilon}$ then it means that $|X_n(\omega)-X(\omega)|>\epsilon$ for infinitely many values of $n$, and hence $X_n(\omega)$ obviously does not converge to $X(\omega)$. So $\lim\sup A_{n,\epsilon}\subseteq \{\omega: X_n(\omega)\nrightarrow X(\omega)\}$, and by monotonicity of probability:
$\mathbb{P}(\lim\sup A_{n,\epsilon})\leq \mathbb{P}(\{\omega: X_n(\omega)\nrightarrow X(\omega)\})=0$
Second direction: Now assume $X_n\to X$ by the second definition. For each $k\in\mathbb{N}$ define $B_k=\lim\sup A_{n,\frac{1}{k}}$ where the sets $A_{n,\epsilon}$ are defined like before. Then by assumption $\mathbb{P}(B_k)=0$ for all $k$, and hence $\mathbb{P}(\cup_{k=1}^\infty B_k)=0$. Now suppose we have $X_n(\omega)\nrightarrow X(\omega)$ for some $\omega$. This implies that there must be some $m\in\mathbb{N}$ such that $|X_n(\omega)-X(\omega)|>\frac{1}{m}$ for infinitely many natural numbers $n$, and thus $\omega\in B_m\subseteq\cup_{k=1}^\infty B_k$.
In other words, we have the inclusion $\{\omega: X_n(\omega)\nrightarrow X(\omega)\}\subseteq\cup_{k=1}^\infty B_k$, and so $\mathbb{P}(\{\omega: X_n(\omega)\nrightarrow X(\omega)\})=0$.
Comment: Thank you so much
Answer: Intuition
There is not much intuition to be gleaned here. The second definition comes from "massaging" the definition of the [non-random] limit of real numbers (since for a fixed $\omega$, the limit $\lim_{n \to \infty} X_n(\omega)$ is just a non-random limit).
The utility of the second definition is that it is easier to verify because it involves relatively simple sets $\{|X_n(\omega) - X(\omega)| > \epsilon\}$ (fixed $\epsilon$, fixed $n$). You only need to deal with one $n$ at a time to understand this set, and under certain circumstances, bounding the probability of this set for each $n$ can be enough to bound probability of the $\limsup$. By contrast, the set $\{\lim_{n \to \infty} X_n(\omega) = X(\omega)\}$ is difficult to deal with because of the limit inside the event.

Notation
Let $A_{n, \epsilon} = \{|X_n(\omega) - X(\omega)| > \epsilon\}$.
Note that
$$\limsup_{n \to \infty} A_{n, \epsilon} := \bigcap_n \bigcup_{k \ge n} A_{k,\epsilon}$$
by definition.

(1) $\implies$ (2)
Fix $\epsilon > 0$.
If $\omega \in \bigcap_n \bigcup_{k \ge n} A_{k, \epsilon}$, then $|X_n(\omega) - X(\omega)| > \epsilon$ for infinitely many $n$, so $\lim_n X_n(\omega) \ne X(\omega)$. Thus
$$P(\limsup_n A_{n, \epsilon}) \le P(\lim_n X_n(\omega) \ne X(\omega))$$
for each $\epsilon$.
So if almost sure convergence holds in the sense of the first definition, then it holds in the sense of the second definition.

(2) $\implies$ (1)
Conversely, suppose $\omega$ is such that $\lim_n X_n(\omega) \ne X(\omega)$. If you write out the definition of a limit, this means there exists some $\epsilon$ such that $|X_n(\omega) - X(\omega)| > \epsilon$ for infinitely many $n$. That is, there exists $\epsilon$ such that $\omega \in \bigcap_n \bigcup_{k \ge n} A_{k, \epsilon}$. Then
$$P(\limsup_n A_{n, \epsilon}) \ge P(\lim_n X_n(\omega) \ne X(\omega))$$
for this particular $\epsilon$. So if almost sure convergence holds in the sense of the second definition, it also holds in the sense of the first definition.

Interpreting almost sure convergence


SQL select, only return results where a rate or figure changes in a date and time order sequence

Question: I am trying to return rates in a SQL database that are seperated by timebands, I only need to return the results where a rate changes from the intial timeband, for example; BH(Bank Holiday), WD(Weekday), WE(Weekend) for reference...
ClientType  Column2     Column 3
Private     BH 06:00    £22.00
Private     BH 09:00    £25.00
Private     BH 17:00    £25.00
Private     WD 06:00    £12.00
Private     WD 09:00    £14.00
Private     WD 17:00    £14.00
Private     WE 06:00    £16.00
Private     WE 09:00    £16.00
Private     WE 17:00    £16.00
Family      BH 06:00    £28.00
Family      BH 09:00    £28.00
Family      BH 17:00    £28.00
Family      WD 06:00    £12.00
Family      WD 09:00    £12.00
Family      WD 17:00    £12.00
Family      WE 06:00    £15.00
Family      WE 09:00    £15.00
Family      WE 17:00    £15.00

So trying to get the above data returned as,
ClientType  Column2     Column 3
Private     BH 06:00    £22.00
Private     BH 09:00    £25.00
Private     WD 06:00    £12.00
Private     WD 09:00    £14.00
Private     WE 06:00    £16.00
Family      BH 06:00    £28.00
Family      WD 06:00    £12.00
Family      WE 06:00    £15.00

Only the results are returned where the rate changes across the timeband sequence.
Further to that if the results only return one of each timeband for example the Family type client, then it will rename the timenband to just BH, WD & WE. For example
ClientType  Column2     Column 3
Private     BH 06:00    £22.00
Private     BH 09:00    £25.00
Private     WD 06:00    £12.00
Private     WD 09:00    £14.00
Private     WE          £16.00
Family      BH          £28.00
Family      WD          £12.00
Family      WE          £15.00

Thank you
Comment: Your data seems to assume an ordering to the data, but SQL tables represent *unordered* sets.  How is the data ordered?  Also tag with the database you are using.
Comment: It is ordered by ClientType first, then Column 2 which is the timeband names, BH, WD then WE naturally fall into order then adding a time to each 'BH 06:00, BH 09:00 further orders these. Sorry I should have mentioned that. Thanks
Answer: I think you can do what you want with lag():
select clienttype, column2, column3
from (select t.*,
             lag(column3) over (partition by clienttype, left(column2, 2) order by column2) as prev_column3
      from t
     ) t
where prev_column3 is null or prev_column3 <> column3;

Comment: Thank you this has gotten the ball rolling nicely. With some tweaks this is giving the results I need. Thank you


MySQL PHP Updating DateTime only when specific column is updated

Question: I've made a very simple PHP script that increments 1 to my dishwasher_count row in my members table. It works as it's supposed to when it looks like this:
PHP:
include "admin/vars.php";

//connect to the database
$db = mysql_connect($db_host,$db_user,$db_pass);
      mysql_select_db($db_name);

//Runs when user sends GET
if(isset($_GET['name'])) {
$name = $_GET['name'];
// Increment the dishwasher_count by 1 and update the dishwasher_latest field value of the requested name.
$update = mysql_query("UPDATE members SET dishwasher_count = dishwasher_count + 1 WHERE name='$name';

}

$result = mysql_query("SELECT name, dishwasher_count, dishwasher_latest FROM members ORDER BY dishwasher_count DESC");
while($row = mysql_fetch_assoc($result)){
      echo "
" . $row["name"].
      "

Urplockningar: "
      . $row["dishwasher_count"]. "

      Senaste: " . $row["dishwasher_latest"] . "
";
}

mysql_close($db);

The problem is that i want it to also show when the latest increment was, I got it working by using "TIMESTAMP" and "on update CURRENT_TIMESTAMP" in MySQL. But the problem is that it will update the TIMESTAMP when any rows are updated, and I only want it to update the dishwasher_latest to the current time when the dishwasher_count updates.
I've tried doing this, but it seems to brake the SQL:
$update = mysql_query("UPDATE members SET dishwasher_count = dishwasher_count + 1 WHERE name='$name'; UPDATE members SET dishwasher_latest=now()");

I've been working with this problem for a while now, but can't get it to work. How would I get this to work?
Comment: you have syntax errors above
Comment: *"I've tried doing this, but it seems to brake the SQL:"* - Yep, and here's what you need to do, visit http://php.net/manual/en/function.mysql-error.php and apply that to your query.
Comment: I guess you need a trigger... on update
Answer: If you want to record when a specific column was changed, then you cannot use timestamp column, that is for recording when any fields within the record changes.
Your idea to update a datetime field to current time is a good one, just you need to work on the implementation. mysql_query() does not support executing multiple statements in 1 call. You should not be even using mysql_*() functions at all, they are deprecated.
Solutions:

Combine the 2 updates in a single query: update table set field1=..., field2=... where field3=...
Use mysqli or pdo insted of mysql module and execute the 2 statements with them. Just make sure that the 2nd one aldo has a where criterion, otherwise the whole table will be updated.
Have 2 separate mysql_query() calls with the 2 statements. Again, watch out for the where.
You could use a trigger as well, but that would be an overkill.
Comment: This ***"answers/explains"*** the OP's immediate issue.
Answer: Are you looking for something like this?
UPDATE members SET dishwasher_count = dishwasher_count + 1,dishwasher_latest=now() WHERE name="$name";

This will only update the row affected with a new timestamp
Comment: Thank you! that worked just like I wanted it to. You are a real life saver, and time saver.
Comment: haven given an explanation in regards to the OP's code failing, would be beneficial for all, including future visitors to the question. Plus, who knows; might even yield more points ;-)


Simplifying $(6a-b)(36a^2+6ab+b^2)+(3a+b)^3$

Question: I would really appreciate some help with simplifying this algebraic problem.

$(6a-b)(36a^2+6ab+b^2)+(3a+b)^3$

This part seems a bit tricky: $(36a^2+6ab+b^2)$
Shouldn't it be $12ab$ in the middle? That way, it would be possible to solve it using $(a+b)^2$
Any suggestions?
Comment: Hint:

$$x^{3} - y^{3} = (x-y)(x^{2} + xy + y^{2})$$
Answer: Simplify:$(6a-b)(36a^2+6ab+b^2)=(6a)^3-b^3$
Comment: My final answer, using this was $3a(11a^2+9ab+3b^2)$
Is this right, then?
Comment: The final answer should be: $3a(81a^2+9ab+3b^2)$.
Comment: $6a^3 - b^3 + (3a+b)^3$
$6a^3 -b^3 + (27a^3 + b^3 + 27a^b + 9ab^2)$
$6a^3 - b^3 + 27a^3 + b^3 + 27a^2b + 9ab^2$
$33a^3 + 27a^b + 9ab^2$
$= 3a(11a^3 + 9ab + 3b^2)$
Comment: I cannot find a way to add linebreaks, so please excuse the formatting.
Comment: It's: ($6a)^3-b^3+(3a+b)^3=216a^3-b^3+27a^3+27a^2b+9ab^2+b^3$. Eventually this is equal to: $243a^3+27a^2b+9ab^2$
Comment: I'm sorry, I realized my mistake. Utterly stupid of me. Thank you so much!
Answer: Hint:
$$(6a-b)(36a^2+6ab+b^2)=(6a)^3-(b)^3$$

so:
$$
(6a-b)(36a^2+6ab+b^2)+(3a+b)^3=(6a)^3-b^3+3^3a^3+3\cdot3^2a^2b+3\cdot3ab^2+b^3=
$$
$$
=2^3\cdot3^3a^3+3^3a^3+3\cdot3^2a^2b+3\cdot3ab^2=3^3a^3(8+1)+3\cdot3^2a^2b+3\cdot3ab^2=
$$
$$
=3^5a^3+3^3a^2b+3^2ab^2=3^2a(3^3a^2+3ab+b^2)
$$
Comment: Using this, final answer I got was $3a(11a^2+9ab+3b^2)$
Is this right?
Comment: Sorry. I had a stupid mistake...I edit.
Comment: Its fine :) But if you could check my answer, that would be great!
Comment: Your $11 a^2$ is wrong. See the comment of Paulo.
Comment: @AmanBhargava See my answer how to test your calculation, without the help of others.
Comment: @DietrichBurde Why did you take $a=1$ and $b=0$?
Answer: Here is an easy way to check your calculation. You got $f(a,b)=3a(11a^2+9ab+3b^2)$.
Hence $f(1,0)=33$. Now check in your given formula for $a=1$ and $b=0$. Then you' ll obtain $f(1,0)=243$, a contradiction. So your calculation cannot be correct. Indeed, we have
$$
f(a,b)=9a(27a^2 + 3ab + b^2).
$$


Can't process weather json in Android correctly using Jackson

Question: I have this method inside an AsyncTask<Object,Void,GenericResults>, with GenericResults being the class where I store a bunch of different results from my application, such as the latitude, longitude and pressure of the current location. I pass the GenericResults object I create in the params of the AsyncTask, and have it add the aforementioned values, then return the modified object (all of this in doInBackground).
The weather API I'm using is weatherunderground's, located here.
The problems I'm having are twofold: just iterating through the json, if I tell it to stop at JsonToken.END_OBJECT it'll only go until the first } in the JSON, so it never gets to where I want it to stop. On top of that, if I use any fieldName.equals() inside this method I keep getting null pointer exceptions. What is the correct way to obtain the contents of the pressure_mb field?
private void getWebPressure(String longitude, String latitude) {
    HttpURLConnection conn;
    try {
        URL weatherUrl = new URL("http://api.wunderground.com/api/"+API_KEY+"/conditions/q/"+latitude+","+longitude+".json");
        conn = (HttpURLConnection) weatherUrl.openConnection();
        InputStream in = new BufferedInputStream(conn.getInputStream());
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(in);
        boolean done = false;
        while (!done) {
            parser.nextToken();
            String fieldName = parser.getCurrentName();
            parser.nextToken();
            Log.v(LOG_TAG, fieldName + " " + parser.getValueAsString());
            if (fieldName.equals("pressure_mb")) {
                done = true;
                result.setPressure(parser.getValueAsString());
            }
        }
        conn.disconnect();
    }
    catch(IOException e){
        Log.e(LOG_TAG,e.toString());
    }
}

Answer: Had to switch around the parser logic a bit and make sure the value was not null before trying to do any .equals()
while (parser.nextToken() != null && !done) {
            parser.nextToken();
            String name = parser.getCurrentName();
            if (name!=null){
                if (name.equals("pressure_mb")) {
                    parser.nextToken();
                    String value = parser.getText();
                    Log.v(LOG_TAG,value);
                    result.setPressure(value);
                    break;
                }
            }
        }


#states visible

Question: The states visible seems to work correct in D7. In D8 I want to test make a field visable if one OR another field have a value. And also when two fields  have a value. What I have below works if both fields have a value.
<code>use Drupal\Core\Form\FormStateInterface;
use \Drupal\Core\State\StateInterface;

function mymodule_form_alter(&$form, FormStateInterface     &$form_state, $form_id) {
  if ($form_id == 'node_page_form') {
    $form['field_format']['#states'] = array(
      'visible' => array(
          ':input[name="field_item_type"]' => array('value' => 'tv_show'),
          'or',
          ':input[name="field_extra"]' => array('value' => 'bike'),
      ),
    );
  }
}
</code>
Comment: Fix like that : 'visible' => array(
          array( ':input[name="field_item_type"]' => array('value' => 'tv_show') ),
          'or',
          array( ':input[name="field_extra"]' => array('value' => 'bike') ),
      ),
Answer: Try the below code .It works .
<code>$form['field_item_type'] = [
  '#type' => 'select',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#options' => ['tv_show'=> 'Tv show','serials' => 'Serials']
];
$form['field_extra'] = [
  '#type' => 'select',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#options' => ['movie' => 'movie','chair'=>'Chair'],
];
$form['field_format'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#required' => TRUE,
];
$form['field_format']['#states'] = [
  'visible' => [
    [
      [':input[name="field_item_type"]' => ['value' => 'tv_show']],
      'or',
      [':input[name="field_extra"]' => ['value' => 'movie']],
    ],
  ],
];
</code>
Comment: Thanks. Helped a lot :)

#states visible


How we send registration data along with WebServices in Android

Question: I have one android application to be made.
In the Registration process i have to fill in two fields

Phone number
Name

Along with these two fields i have to also send my deviceid, current time and OS version dynamically.
How can i do so?
My Web Service is
http://frapp.badoniya.com/webservices/register.php?username=Vijay%20&deviceid=12345&mobile=98XXXXXXXX&platform=Android&os_version=4.0
Please give me a step wise solution.
Because i am very new in programming.
Answer: you have to use an AsyncTask and inside the async task you can use HTTPPost or HTTPGet requests to call a webservice using parameters
Answer: Use an AsyncTask to achieve what you are looking for. Here are few examples on how to use an AsyncTask, Send a GET request and Sending a POST request. For this scenario you must send a GET request.
GET Request
Example 1
Example 2
POST Request
Example 1
AsyncTask
Example 1


Can't sync site config from git, entities exist of type x

Question: For whatever reason I seem unable to find a good resource to explain syncing the actual structure of a site (like blocks and configs).
I'm using git currently and am doing local development using lando. I have just been using the same folder this whole time but recently had to do some things and needed to clone my repo.
I've got the site running but it's back to the "defualt" state and made me install drupal and such.
I have the config/sync folder but cannot use drush cim or sync via the UI.
The configuration cannot be imported because it failed validation for the following reasons:
Entities exist of type Taxonomy term and Vocabulary Blog Categories. These entities need to be deleted before importing.
Entities exist of type Shortcut link and Shortcut set Default. These entities need to be deleted before importing.
Entities exist of type Paragraph and Paragraph type Webform + Content. These entities need to be deleted before importing.
Entities exist of type Paragraph and Paragraph type Standard Content. These entities need to be deleted before importing.
Entities exist of type Content and Content type Page. These entities need to be deleted before importing.
Entities exist of type Content and Content type Homepage. These entities need to be deleted before importing.
Unable to install the Commerce Store module since it requires the Path alias module.
Unable to install the Commerce Number Pattern module since it requires the Path alias module.
Unable to install the Commerce Order module since it requires the Path alias module.
Unable to install the Commerce Product module since it requires the Path alias module.
Unable to install the Commerce Cart module since it requires the Path alias module.
Unable to install the Commerce Checkout module since it requires the Path alias module.
Unable to uninstall the Path alias module since the Path module is installed.
Unable to uninstall the Path alias module since the Pathauto module is installed.

This is spat out by the UI.
I had tried to do something with the uuid but it obviously didn't work. I'll say that's because, again, I can't seem to find a good explanation of how this actually works.
Comment: "For whatever reason I seem unable to find a good resource to explain syncing the actual structure of a site (like blocks and configs)."

The reason is that the Drupal documentation is horrendous, and the structure of a Drupal site is a tangle of bizarre, misguided, and self-defeating ideas.
Answer: Two things are happening:

In your active configuration in the database, some module(s) is/are installed, that isn't/aren't installed in the configuration you are trying to import. The problem is that you have content for the thing(s) being uninstalled, so if you were to import the configuration, you'd have ghosts in your database. These ghosts are listed in the errors that begin with 'Entities exist of of type X'.
To resolve this you'll need to either enable the missing item(s) in the configuration you're trying to import, or you'll need to delete the items from the database before you import your configuration.
The configuration you are trying to import has enabled modules, but the codebase for those modules does not exist in the Drupal installation you are trying to import the configuration into. These modules are listed at the end of the errors that begin with 'Unable to install the X module' (ex - you are missing the Path Alias code base).
To resolve this, you'll either need to add the code for the required modules to your codebase.
Comment: Right so those make enough sense on their own. But I can't get it to work. It won't install the commerce because it needs path alias but path alias won't install because of the other path modules.
Is there no way to force this import? How did this actually happen in the first place?
Comment: You'll need to fix them in the order that they appear in the list. So first fix number 1 that I gave above, then number 2.
Comment: Can't answer as to why it happened at the first place, it will have come from whatever you have done.
Comment: managed to get all the errors gone, then it broke the whole site saying that it can't delete the default language.
Comment: If my answer was what helped you get the errors fixed can you please mark this as the correct answer? You can open a new issue for the new problem that has arisen.


IIS7 & IE8 - Pages rendering differently on same versions of IE8?

Question: I have an ASP.NET (framework 2.0) web app running under IIS7.
When I run the app on the server, using IE8, localhost the app runs the way it is supposed to.
When I run the app in Visual Studio 2008 (framework 2.0) it runs the way it is supposed to.
But when I try to run the app from another computer it renders incorrectly.
Same versions of IE8.
What would cause the serving of an ASP.NET application to render correctly on the server, but incorrectly when serving to another computer, when the Internet Explorer versions are the same?
Can anyone help?
Comment: Do you have compatability mode switched on on one of the computers? There is a little torn page icon next to the address bar, if it is clicked then it renders the page differently.
Comment: Compatibility mode of IE perhaps?
Comment: Looks like this : https://www.goarmyed.com/images/browserSettings/IE8/compatability_mode.jpg
Comment: Use fiddler (HTTP Proxy) to compare headers on both request. You can also run SMSNIFF on the server to look at the traffic for both.
http://www.nirsoft.net/utils/smsniff.html
smsniff needs admin permission to run but it doesn't need to be installed.
Comment: SLC, no the page appears to be compatible.  Not 'incompatibility' icon shown.
Comment: Okay, just noticed something...
On the server, IE8 (localhost) has the compatibility icon showing.
when I click the torn page, the rendered page looks incorrect.
Does that mean that the page that looks good is incompatible?
Comment: Is there a setting in IIS7 to serve page with compatibility mode turned off?
Answer: You can force IE to work in a specific compatability mode with one of the following meta tags in the head:
<code><meta http-equiv="X-UA-Compatible" content="IE=4">   <!-- IE5 mode -->
<meta http-equiv="X-UA-Compatible" content="IE=7.5" > <!-- IE7 mode -->
<meta http-equiv="X-UA-Compatible" content="IE=100" > <!-- IE8 mode -->
<meta http-equiv="X-UA-Compatible" content="IE=a" >   <!-- IE5 mode -->
</code>
Here is a link to more information regarding the compatibility meta tag:
http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
One other thing you could try is to save the output source on each system and then compare to see if they are the same.  If they are identical then it comes down to the rending on the client which is a compatibility setting.
Comment: Another strange thing is that the browser on my desktop (IE8) does not have the 'compatibility mode' button.  When I right click the toolbar, the 'Compatiblility View Button' is checked, however it does not show up.
Comment: I was able to fix this issue by adding an entry into the HTTP Response Headers section of IIS7.  I added:
Name:  X-UA-Compatible
Value:  IE=100
So far, the site seems to be working correctly now.


c# creating reference between 2 forms

Question: My question may sound weird,but I have no idea on how to create a reference between 2 windows forms(for example to create a referrence and call it TheMainForm1).I'm fighting with this since 2 days(yes I know...) What I'm trying to do is to hide the Form1,but until now the only method I found is:
this.Hide();
        Form2 form2 = new Form2();
        form2.Show();

But the above code creates a new Form1...
Please guide me on how to create a reference,I'm trying to learn c#.
HUGE thanks for any replay!
Comment: Specify _reference between two windows_. What are you trying to achieve?
Comment: Tried [this solution](http://stackoverflow.com/questions/11184665/need-to-access-the-other-winform-in-c-sharp/11184761#11184761)? Just suggesting
Comment: I don't see any method create new instance of Form1. So what exactly does you want?
Comment: I'm trying to acheav this: http://stackoverflow.com/questions/11526902/c-sharp-winforms-application-showing-many-tray-icons/11526946#11526946
Answer: Why don't you just pass it in in the constructor for Form1 and store it in a member variable?
public Form1(Form2 form2)
{
  // store in member
  _form2 = form2;
}

Answer: You can try this solution:
There should be a Program.cs which contains a Program class. Add two static properties (or fields) and use them.
static class Program
{
    internal static Form1 form1;
    internal static Form2 form2;

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        form1 = new Form1();
        form2 = new Form2();
        Application.Run(form1);
    }
}

And if you want to switch from Form1 to Form2, you can use this:
this.Hide();
Program.form2.Show();

c# creating reference between 2 forms


Obter links externos com cURL PHP

Question: Tenho este código que me retorna a página do Google.
<?php

$request = curl_init();
curl_setopt_array($request, [
    CURLOPT_URL             => 'https://www.google.com.br',
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_SSL_VERIFYPEER  => false,
]);
$response = curl_exec($request);
curl_close($request);

echo $response;

Porém, ele não me trás os links externos como imagem entre outros. Repare que, ao em vez dele me trazer google.com/... ele trás o nome do meu vHOST viperfollowdev.com, veja a imagem a baixo para entender.
Existe alguma maneira de corrigir isso?

Meu segundo exemplo foi:
<?php

$request = curl_init();

curl_setopt_array($request, array(
    CURLOPT_URL                         => 'https://www.instagram.com',
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_FOLLOWLOCATION  => true,
    CURLOPT_SSL_VERIFYPEER  => false,
));

$response = curl_exec($request);
curl_close($request);

$response = str_replace('/static/bundles/', 'https://www.instagram.com/static/bundles/', $response);
$response = str_replace('/static/images/', 'https://www.instagram.com/static/images/', $response);
$response = str_replace('/data/manifest.json', 'https://www.instagram.com/data/manifest.json', $response);

echo $response;

Está pegando porém não mostra ainda na minha página. Passei a url inteira mas não funciona.
Answer: Sobre o erro
Isso ocorre pois a Google não utiliza o link completo dos arquivos nos atributos src, srcset etc. Ao invés disso, ela utiliza apenas o path do arquivo: Ex: /path/to/image.png
Com isso o navegador sempre vai procurar essas imagens no site acessado, no seu caso, http://viperfollowdev.com.
Soluções
Para corrigir isso, basta adicionar o código abaixo ao imprimir a variável $response.
echo '<base href="https://www.google.com.br/" />';

Porém essa solução não funcionará em todos os casos. Quando você já tem definido a url base (como no código acima) em seu html, o navegador ignorará a nova "url de base".
Nesse caso, resta apenas utilizar a regex para solucionar seu caso (ou ao menos parte dele).
Regex
(src=|href=|srcset=|url)('|"|\()(\/.*?)('|"|\))

A regex acima irá capturar todos os valores dos atributos src, srcset, href e url. Esse último para css.
Agora basta utilizar a função preg_replace para substituir os valores.
Exemplo:
<!DOCTYPE hml>

        <title>Title of the document</title>
        <base href="https://www.bing.com.br/" />

        <?php

            $url = "https://www.google.com.br";

            $request = curl_init($url);

            curl_setopt_array($request, [
                CURLOPT_RETURNTRANSFER  => true,
                CURLOPT_AUTOREFERER  => true,
                CURLOPT_SSL_VERIFYPEER  => false,
            ]);
            $response = curl_exec($request);
            curl_close($request);

            echo preg_replace("/(src=|href=|srcset=|url)('|\"|\()(\/.*?)('|\"|\))/", "$1$2{$url}$3$4", $response);

        ?>

A regex pode variar de site para site. A depender do que você queira alterar, é necessário customizar a regex e deixa-lo mais completo, porém o principio é o mesmo.
Comment: Obrigado, funcionou, olha meu segundo exemplo na minha pergunta quase parecido, só que o seu mais organizado.
Answer: No primeiro caso o que acontece é que você obteve o código html do request e os recursos são declarados para caminhos virtuais que não existem na sua aplicação. Algo que já você deve ter percebido por fazer o replace em sua segunda tentantiva. Mas existem outras validações e procedimentos que são executadas no host e impedem você de apresentar o conteúdo deles. (Sessões, Tokens, Headers e etc.)
Aconselho que se você quer consumir ou exibir o conteúdo de outros sites e serviços, deve se restringir à suas APIs, regras e termo de uso.
Dê uma olhada em Google API e Instagram API, talvez o que você busca fazer é até suportado pelas duas plataformas.
Comment: Concordo, "deve se restringir à suas APIs, regras e termo de uso.", é pra estudos veja que, na primeira tentativa foi com o google.

Obter links externos com cURL PHP


Failed to consume input event.Android

Question: This is the error i often see in my application.Can anyone know ,any idea ,what is the reason for this error.
the error has two lines :
     consumer ~ Error -1 pinning ashmem fd 69
' ~ Failed to consume input event.  status=-2147483648

Answer: I recently fixed similar bug in app I work on. The problem was in buggy native code that was closing file descriptors twice,- it means it first was closing it in Close method and later invoking Close again in destructor with no checking if file descriptor was already closed.
Native open function returns as file descriptor, a first free lowest number. So from time to time above bug was closing descriptor that got reused between one Close and the second invocation of it. It mostly happend that this descriptor was used by parcel.
While searching for solution to this bug, I found that this errors happen in two cases:

when there are too many file descriptors being open, which might suggest that there is a leak
when code is closing file descriptors twice

debugging this is not easy, its hard to reproduce, also if you dont use native code then its even harder to understand the problem.
If you have no native code, then this bug might occur when trying to communicate with window that was closed. Like you have not closed some dialog but closed activity owning it. I never experienced such case but, I am adding it as a hint.

Failed to consume input event.Android


Determine all ways the integer $2015$ can be written as a sum of consecutive positive integers.

Question:
Q) Determine all ways the integer $2015$ can be written as a sum of
  (more than one) consecutive positive integers. Prove that you have
  found all possible combinations.

I was thinking of using Gauss' formula where
Sum=$\frac{n(n+1)}{2}$ Since we want the sum to be $2015$ then $2015=\frac{n(n+1)}{2}$ and then we are left with $4030=n(n+1)=n^2+n$
but then I got stuck. Any ideas?
Comment: Rewrite it as $n^2+n-4030=0$ and solve this as a quadratic equation in the variable $n$. Actually  you should aslo try sum of consecutive integers from some $a$ to $b$.
Comment: See http://math.stackexchange.com/a/139852/589.
Comment: Well, you don't necessarily have to start from 1 , so $2015= \frac{n(n+1)}{2}$ is not very helpful. Instead , try smaller cases, especially the numbers with odd factors ,and you might spot  something helpful.
Answer: Hint:  Your thought is a good one, but Gauss' formula presumes you start adding from $1$.  If you add from $m$ through $n$, the sum is $\frac {n(n+1)}2-\frac{(m-1)m}2$  because you subtract the sum from $1$ through $m-1$.  You should be able to factor this.
Answer: The sum of an arithmetic progression is the number of terms times the average element.
IF the number of terms is odd, then the average element is an integer, so you should look to write 2015 as as a product where the first factor is odd (which is not much of a demand since there can't be an even factor of 2015).
If the number of terms is even (and the step size is 1), then the average element is a half-integer, so you should look to write 4030 as a product where the first factor is even and the second is odd.
In each of these cases find out which factorizations lead to the first element of the progression being positive.
Comment: If the number of terms are odd then would I be allowed to start at 1 since 1 is a factor.
Comment: @swandilaon: It is the number of terms times the _average term_, not the number of terms times the _first_ term. Starting at 1 is "allowed" as far as it goes, though it won't give you a sum of 2015.