Hartshorne chapter 2 exercise $2.17$

Question:
Let $f: X \to Y$ be a morphism of schemes, and suppose that $Y$ can be covered
by open subsets $U_i$, such that for each $i$, the induced map $f^{-1}(U_i) \to U_i$ is an
isomorphism. Then $f$ is an isomorphism.

I can show that $f$ is injective and surjective as follows. Suppose $f(x) = f(y)$, then  as $U_i$'s cover $Y$, there exists $U_i$ such that $f(x),f(y) \in U_i$ and since $f^{-1}(U_i) \to U_i$ is injective $x=y$.
Also $f$ is surjective since for any $y \in Y$ there is an $U_i$ such that $f^{-1}(U_i)$ contains $x$ that maps to $y$.
I think I still need to show that $f$ is continuous, has a continuous inverse and that the map $f^\sharp$ on sheaves is also a ring isomorhpism. How can I proceed with this?

I think I have a proof for this. Let $g_i : U_i \to f^{-1}(U_i)$ be the inverses of the given isomorphisms. Now if we can show that $g_i$ and $g_j$ agree on $U_i \cap U_j$ we can glue them to form an inverse for $f$.
Now this follows since $f |_{f^{-1}(U_i) \cap f^{-1}(U_j)} \circ g_i|_{U_i \cap U_j} = f |_{f^{-1}(U_i) \cap f^{-1}(U_j)} \circ g_j|_{U_i \cap U_j}$ as both give the identity.
Comment: Hint: for $f^\#$, think stalks.
Comment: I think this can be done without considering stalks? @TabesBridges
Answer: You have to check two things:

the map of topological spaces given by $f$ is a homeomorphism
after the first item, you need to verify that the map of sheaves $\mathcal{O}_Y\to f_*\mathcal{O}_X$ is an isomorphism.

For the first item, try proving the following more general lemma:

Given a map of topological spaces $f:X\to Y$ and an open cover $\{U_i\}_{i\in I}$ of $Y$ such that $f|_{f^{-1}(U_i)}: f^{-1}(U_i)\to U_i$ is a homeomorphism for each $i\in I$, $f$ is a homeomorphism.

A few hints about this: use the hypotheses to verify that $f$ is a bijection. Therefore, it has a well-defined inverse map $f^{-1}$ (no gluing needed). You can verify continuity of $f^{-1}$ by observing that continuity can be checked locally, and the open cover condition tells you that $f^{-1}$ is continuous on an open cover.
For the second item, note that given a morphism of sheaves $\psi:\mathcal{F}\to \mathcal{G}$ on a space $Y$, the property of $\psi$ being an isomorphism can be checked on an open cover. Given the setup, we know that there exists an open cover $\{U_i\}$ of $Y$ such that $f|_{f^{-1}(U_i)}:f^{-1}(U_i)\to U_i$ is an isomorphism of schemes. In particular, the induced morphism $f^{\#}|_{U_i}: \mathcal{O}_{U_i}\to f_*\mathcal{O}_{f^{-1}(U_i)}$ is an isomorphism of sheaves. Item 2. follows.

Hartshorne chapter 2 exercise $2.17$


Ring localization and ideals

Question: I'm trying to solve a couple of problems involving ring localization and I'm not sure if my solutions are right or if I understand the idea of localization correctly.

Let $A$ be a commutative ring, $S$ a set closed under multiplication with $1 \in S \subset A - \{0\}$, $J$ an ideal in $A$ and $i : A \rightarrow A_S$ with $i(a)=\frac{a}{1}$. Prove that
$$ \langle i(a) : a \in J\rangle  = \{ \tfrac{a}{s} \in A_S : a\in J \}$$

I'll start by proving $\subset$. Let $p \in \langle i(a) : a \in J\rangle$, then $ p = \sum _{j \in I} s_j i(a_j)$ with $s_j \in A_S$ and $a_j \in J$.
Then, $p = \sum _{j \in I} \frac{\alpha_j}{\beta_j} \frac{a_j}{1} $ with $\alpha_j \in A$, $a_j \in J$ and $\beta_j \in S$. Since $J$ is an ideal $\alpha_j a_j = a'_j \in J$. Working through the sum then:
$$p = \frac{\sum_j a'_j ( \prod_{k \not= j} \beta_k)}{\prod_{j\in I} \beta_j} = \frac{a''}{s'} \, \text{for some} \, a'' \in J, \, s' \in S $$
Now I need to prove the other inclusion.
If $p \in \{ \frac{a}{s} \in A_S : a\in J \}$ then obviously $p = \frac{a}{s}$ for some $a\in A$ and $s \in S$ so $p = \frac{1}{s} i(a)$ and it's done.
I understand that the elements of $A_S$ are classes of the form $(a,s)$ with $a\in A$ and $s\in S$ but, is $\frac{1}{s}$ always an element of $A_S$ even if there's no $a \in A$ so that $i(a)$ is in the same class as $\frac{1}{s}$?
I don't think it's necessarily true that there's an $a \in A$ so that there's a $t \in S$ with $t(as - 1) = 0$ for all $s \in S$ so that would lead me to think no.
Comment: Some MathJax advice:

`<` and `>` mean "less than" and "greater than", and produce spacing correct for that meaning only; to make angle brackets, use `\langle` and `\rangle`.
Comment: The set of all elements of $A_S$ of the form $i(a)$ comprise a representation of $A$ in $A_S$. You have, for instance, $\mathbb Z$ in $\mathbb Q$, and of course $\mathbb Q$ has many non-integers. (The example is misleading in that $i$ is injective in that case, which is not always true).
Comment: @ZevChonoles Thanks, I'll keep that in mind.
Comment: @KarlKronenfeld Right, I think I see what you mean. I do have all the pairs $(a,s)$ in $A_S$ but $i(A)$ is not $A_S$ so there's no problem. Sounds pretty obvious now that I read it aloud :/ Thanks
Answer: First prove that
$$
J^e=\left\{\frac{a}{s}:a\in J, s\in S\right\}
$$
is an ideal of $S^{-1}A$ (I prefer this notation over $A_S$). This poses no problem, but just to sketch the proof:

$0/1\in J^e$, because $0\in J$
if $a,b\in J$ and $s,t\in S$, then
$$
 \frac{a}{s}+\frac{b}{t}=\frac{at+bs}{st}\in J^e
 $$
because $at+bs\in J$ and $st\in S$
if $a\in J$, $b\in A$ and $s,t\in S$, then
$$
 \frac{a}{s}\frac{b}{t}=\frac{ab}{st}\in J^e
 $$
because $ab\in J$ and $st\in S$

Then the inclusion $\subset$ follows by observing that, for $a\in J$, $i(a)=\frac{a}{1}\in J^e$, because $1\in S$, and from the fact that $J^e$ is an ideal.
For the converse, an element $a/s$ with $a\in J$ can be written as
$$
\frac{a}{s}=\frac{a}{1}\frac{1}{s}=i(a)\frac{1}{s}
$$
so it belongs to the ideal of $S^{-1}$ generated by $i(a)$, which is obviously contained in $\langle i(a):a\in J\rangle$.

Ring localization and ideals


rails ActiveRecord find in console

Question: When I'm in the Rails 3.2 console, I can do this just fine:
p = Person.last
p.last_name

and it prints the last name.
But when I try to find it by the id, it's able to locate the single
record and store it in my variable p, but I can't print the last_name
column. For example:
p = Person.where(id: 34).limit(1)

printing p here shows all the columns but p.last_name says this
NoMethodError: undefined method `last_name' for
#<ActiveRecord::Relation:0x000000055f8840>

any help would be appreciated.
Answer: A where query will return an ActiveRecord::Relation, which sort of acts like an array, even if you limit the number of returned records.
If you instead change your query to:
p = Person.where(id: 34).first

it will work as you want, and arel knows to automatically limit the query to a single result, so you don't have to explicitly specify limit(1).
You could also change to either
p = Person.find(34) # Throws an ActiveRecord::RecordNotFound exception if Person with id 34 does not exist

or
p = Person.find_by_id(34) # Returns nil if Person with id 34 does not exist. Does *not* throw an exception.

and it will return a single record as expected.
EDIT: A where query returns an ActiveRecord::Relation, as @mu is too short mentioned in comments.
Comment: Yes, true, but I didn't want to confuse the situation further.
Comment: p = Person.find_by_id(34) for the win. Thanks.
Answer: This returns a collection of active record objects:
p = Person.where(id: 34).limit(1)

But there's only one with id = 34, so it's a collection of 1.
The way to do this is:
p = Person.where(id: 34).limit(1).first

or, better:
p = Person.where(id: 34).first

or, even better:
p = Person.find(34)

Answer: What you are probably actually looking for is
@person = Person.find(34)
@person.last_name

Answer: In your case Person is a class and it is inherited from ApplicationRecord
p = Person.where(id:10).limit(1)

It returns just the result of the query not the object.
You can check it by using
p.class # => It reurns Nilclass which means its not at all a class

So you cannot use p.last_name or p.first_name on p.

rails ActiveRecord find in console


extract 7z archive on linux web hosting

Question: Would anyone know how to extract 7z archive on linux web hosting.
I am currently using the code below to unzip .zip files, but this does not work for .7z
<code>// Unzip File

$zip = new ZipArchive;
if ($zip->open($userPath . 'import.7z') === TRUE) {
$zip->extractTo($userPath);
$zip->close();

} else {
echo 'failed';
}
</code>
Answer: The 7z file format can use various compression algorithms, so you might be able to decompress the archive with one of the existing utilities for bzip2 or deflate.
You will likely need to use a library such as this one though. Here is the latest version.
Comment: how do i use this file on the server? do you have any example commands?
Comment: You will need to include the file with require_once or include etc, and then just look through the file in your editor, its comments are pretty documenting they explain how to use it.
Comment: The link for this is dead. I've been looking for this for ages now but none of the links work! Please reupload!

extract 7z archive on linux web hosting


How can we use carbon diffforhumans with array

Question: I am using my user controller to return his liked documents and it is returning in array rather than object so i want to use carbon diffforhumans with my date field how can we use it .Here is my controllers code
public function myfavourites()
{
    // echo "This is myfavourites";
    $user_id = Auth::user()->id;
    // $liked_post =  Like::all()->where('user_id', $user_id);

    return view('user.myfavourites')->with('likes', Like::where('user_id', $user_id)->orderBy('created_at', 'DESC')->paginate(12));
}

and here is my blade code

Published {{ $like->document['created_at']->diffForHumans() }}

here h6 is in foreach loop where i am looping throw the all liked documents by the user.
i have relation with my like model to with my document model
here is my relationship function
public function document()
    {
        return $this->belongsTo('App\Document');
    }

whats the solution of this problem either i have to return likes in object form if yes then how?
Answer: You need to use Carbon class to use diffForHumans(),

Published {{ \Carbon\Carbon::parse($like->document['created_at'])->diffForHumans() }}

if its an array you'll either need to loop through each item in the array or use a key for single item
@foreach($like->document as $key => $value)

Published {{ \Carbon\Carbon::parse($value['created_at'])->diffForHumans() }}

@endforeach

or through single key

Published {{ \Carbon\Carbon::parse($like->document[0]['created_at'])->diffForHumans() }}

Comment: @AdnanAli you're welcome, sorry i was in impression that there were multiple documents, but since you figured it out, its all good,
Comment: Thanks Aditya Thakur this works when i delete [0] and it became like this
Published {{ \Carbon\Carbon::parse($like->document['created_at'])->diffForHumans() }}


Inference for a distribution with different number of samples due to censoring

Question: I have the following problem in case someone has an idea about how to solve this.
Assume three experiments that refer to the same population for a random variable $X$.
In the first experiment, I observe samples in $x=\{1,2,3\}$ (frequencies $n_i^1$, $i=\{1,2,3\}$) but no higher values due to (right) censoring. In the second experiment, I observe samples in $x=\{1,2,3,4,5\}$ (frequencies $n_i^2$), and, finally, in the third one I observe samples in $x=\{1,\ldots,10\}$ (frequencies $n_i^3$).
I would like to obtain the empirical distribution function of the population in $\{1,\ldots, 10\}$ by making use of all the information. What would be a good way of combining the frequencies from all the experiments?
Comment: Closely related questions whose answers can be applied to address this one include http://stats.stackexchange.com/questions/23860, http://stats.stackexchange.com/questions/60256, and http://stats.stackexchange.com/questions/34882.
Comment: Can you tell e.g. between '3' & '3 or more' in the first experiment? Or are all values of '3' equivalent to 'more than 2'?
Comment: Thank you. I do have a frequency which is  '>3' as well in the first one, '>5' in the second one and '>10' in the third one and actually these frequencies are much larger than what I have in 1...10 so I would like to focus in the range [1,10]
Comment: Maximum likelihood is easy to apply also in the censored case!
Comment: Thank you @kjetilbhalvorsen. I am not a statistician and quite new in the field. Could you give me some references (maybe some R package to play with) for non-parametric density estimation under right-censoring using ML? Is the fact that most of my data is censored affecting the estimation?
Comment: I will try to write an answer, wait a little  bit ...
Comment: Thank you @whuber , I am still trying to understand the connection, probably need to think harder
Comment: I did not understand the connections either ...
Comment: @Kjetil These are aggregated ("binned") data.  The links I provide give detailed methods to estimate distributions (or equivalently, any of their properties or parameters) from such data. Your answer here is a specific application of the methods described in each of those other threads.
Answer: If I have understood this correctly, you are sampling on three occasions from the same population, defined by a distribution on the naturals, a count distribution. Let that distribution be defined by $P(X=i)=\pi_i, i=0,0,2,\dots$.
The counts n the first occasion are $N_{1j}, j=1,2,3$, where $N_{11}$ is the number of ones observed, and son on, while the last count $N_{13}$ counts three or larger. In the same way define the counts on the second and third occasion, where the last count inclueds "... or larger".  The we can write the loglikelihood function as
$$
\ell = (N_{11}+N_{21}+N_{31}) \log \pi_1 + (N_{12}+N_{22}+N_{32}) \log \pi_2 + (N_{23}+N_{33}) \log \pi_3 + \dots + N_{13} \log(1-\pi_1-\pi_2) +
N_{25} \log(1-\pi_1-\pi_2-\pi_3-\pi_4) + N_{3,10}\log(1-\pi_1-\dots -\pi_9)
$$
And then this loglikelihoodfunction should be maximized in the unknown parameters. This can be done non-parametrically as written above, or with some parametric model for the $\pi_i$'s.  Continuing with the non-parametric case, first we find the partial derivative with respect to $\pi_1$, which is
$$
\frac{\partial \ell}{\partial \pi_1} =\frac{N_{11}+N_{21}+N_{31}}{\pi_1} - \frac{N_{13}}{1-\pi_1-\pi_2} - \frac{N_{25}}{1-\pi_1-\dots -\pi_4} -
\frac{N_{3,10}}{1-\pi_1-\dots -\pi_9}
$$
then other partial derivatives can be calculated in like manner, and the equations solved. I leave that step as an exercise.
Answer: This is exactly the case that the Kaplan Meier curves are created from: in fact, they are a generalization of the Empirical Distribution Function that allows right censoring.
If you are familiar with R, they can be fit using the survfit function in the survival package.


What do the referees write during the matches?

Question: It is easy to see the referees write on small notebooks during football matches. It happened on some episodes: goals, substitutions, cards.
Especially in the case of yellow/red cards, how can they write about the reasons on such small notebooks? I do not remember ever seeing referees turn the page, so I guess there is only a single side to write on.
Comment: Once I start refereeing in the upcoming season, I will be more than happy to scan and upload a page out of my book and add it to my answer. However, be warned - my handwriting is quite poor!
Answer: As mentioned, referees will record goals, substitutions and cautions and send-offs in their books throughout the match. Referees will also keep track of injuries, number switches between players (e.g. defender switching shirt with goalkeeper), team official misconduct, any further misconduct by sent-off players and any extraordinary circumstances that need reporting to the competition administrator such as:

players revealing non-approved slogans, logos or advertising during the match, as mandated by the final paragraph of Law 4.4,
any circumstances leading to the abandonment of a match, so that the competition organisers can make a decision under Law 7.5,
any outside interference during the match that may have led to a significant suspension of play under Law 5.3, such as poor weather, spectator interference, flood light failure, damage to the goals or pitch - this is especially important in social and recreational matches where added time is not played and such a suspension could influence the final result.

Every referee will use a different system for recording information - this may also change depending on the competition rules and reporting requirements.

I will now provide some examples of how I record information in matches that I referee.
The first step I undertake is splitting the sheet into my book into two columns. On the left, I write the home team and their predominant colour, and on the right the away team and their predominant colour. Down the bottom of the sheet, I will write the date of the match and the competition name. If other information isn't generally available online after the match, such as the ground and the round number, I will record that as well. When performing the coin toss, I will record each captain's name and number in case I need to communicate with them during the match. I will keep note of who has the first kick off in my book, and which goal they are attacking in the first half (relative to me facing the technical area). At half time, I will rule a horizontal line under all recorded information, record who has the second kick-off, and being recording information again.

#3 Goal 21'

This means that number three scored a goal in the 21st minute of the half.

#1 -> #3
#3 -> #20 GK 16'

In the sixteenth minute of the half, #1 put on the #3 shirt, and #3 put on the #20 shirt as part of a goalkeeper change.
In matches that don't use return substitutes (as mentioned in Law 3.2):

#5 OFF
#7 ON SUB 44'

In the forty-fourth minute of the half, a substitution was made in which #5 came off, and #7 came on. I also have the numbers 1 2 3 written at the bottom of the team's column which are crossed out as subs are used to ensure that a team does not exceed the maximum number of substitutions permitted (usually 3).
In all competitions that I've refereed, cautions are not appealable, therefore only the caution offence needs to be recorded. I simply record cautions under the following system in my book:

Y1 - unsporting behaviour;
Y2 - dissent by word or action;
Y3 - persistent infringement;
Y4 - delaying the restart of play
Y5 - failure to respect the required distance;
Y6 - entering or re-entering the field of play without permission;
Y7 - deliberately leaving the field of play without the referee's permission

NB These codes may change next season, as entering/re-entering without permission and leaving without permission have been merged into one offence; furthermore, the ordering of these offences in the Laws of the Game has been modified (alphabetically ordered).

along with the player's number, and the time that the offence occurred, under the team's column in my book.
Similar to as in Nij's answer, I end up with a row like this:

#7 Y5 27'

This means that number 7 was cautioned in the 27th minute of the half, for failure to respect the required distance. Note that in contrast to Nij's example, only the offence is recorded, not the specific details. In the competitions that I referee, it is irrelevant as to whether the offence occurred at a corner kick, free kick or throw-in.
The minute is only recorded in case the player is sent-off for receiving a second cautionable offence in the same match. When preparing the send-off report, for completeness, as well as listing the two cautionable offences, I will also state the minute in which each occurred.
For send-offs (other than second cautionable offence), I will also record on the reverse side of the page some information about the offence to help prepare the send-off report after the match e.g.

for offensive, insulting and abusive language I will record the words used and who they were directed to,
for violent conduct I will record how far the player ran to get involved, their dememeanour, whether it was retaliatory, unprovoked, or in self-defence,
for denial of an obvious goalscoring opportunity, I may draw a picture using Xs and Os of where defenders were located and where the offence occurred.

When the match is completed, I will also add the player's name from the team sheet to the reverse side of the page.
Send-offs are recorded using the following scheme in my book:

R1 - serious foul play;
R2 - violent conduct;
R3 - spitting;
R4 - denial of an obvious goalscoring opportunity by deliberate handling;
R5 - denial of an obvious goalscoring opportunity by free kick offence other than deliberate handling;
R6 - offensive, insulting and/or abusive language/gestures
R7 - second cautionable offence.

NB As with the caution codes, these may change next season, as the ordering of sending-off offences in the Laws of the Game has also been modified (there is no meaningful order to these).

A couple of examples follow:

#3 R1 30'

This means that number 3 was sent-off for serious foul play in the 30th minute of the half. On the reverse side (or in another page), I will have some notes like this. This is not what I would write in the send-off report after the match - just some notes.

#3 R1 Anklehackers FC (Home)
Sprinted towards stationary opponent on touchline in front of
  technical area. Jumped from two metres away with both feet 10 - 15cm
  off the ground at the ball. Made contact with the ball. Left leg made
  no contact with opponent, right leg contact with left knee of
  opponent. Opponent was seriously injured and took no further part in
  the game.

At the conclusion of the match, this would be updated to:

#3 R1 Anklehackers FC (Home) John Smith
Sprinted towards stationary opponent on touchline in front of
  technical area. Jumped from two metres away with both feet 10 - 15cm
  off the ground at the ball. Made contact with the ball. Left leg made
  no contact with opponent, right leg contact with left knee of
  opponent. Opponent was seriously injured and took no further part in
  the game.

in order to be able to complete the send-off report.
The final example:

#4 Y1 30'
...

...
#4 Y2 15'
#4 R7 15'

As there is a horizontal rule, this means halftime occurred between the two cautions. So in the 30th minute of the first half, number 4 was cautioned for unsporting behaviour. In the 15th minute of the second half (the 60th minute if we're playing 45-minute halves in the competition), number 4 was cautioned for dissent, and subsequently sent-off for receiving a second caution in the same match.
After the match, I will write the following on the reverse side of the sheet:

#4 R7 15' Anklehackers FC (Home) Tom Jones

in order to be able to complete the send-off report. When completing send-off reports for a second caution, if either or both of the cautions are for unsporting behaviour, as a courtesy, I will also provide the form of unsporting behaviour from Law 12.3 under the Cautions for unsporting behaviour section - e.g. recklessly kicked an opponent, carelessly tripped an opponent to interfere with or stop a promising attack - if I can remember it (I never have forgotten in ten years of refereeing, as it would be extremely unlikely for there to be more than one, or at most two send-offs in a match). However, this is strictly not required in the leagues I referee in.

Finally, I will provide an example of the team sheets and sending-off reports that are used in competitions I referee in. No matter what scheme the referee uses to record information, they must have at least enough information to complete the sheet. Note that in the following team sheets, the referee completes the section that is highlighted in blue (the team managers complete the sections that are highlighted in yellow).
Any injuries, or other pertinent information are recorded in the Referees (sic) Remarks section on the reverse side of the sheet.
Team sheet front:

Team sheet reverse:

NB the goalscorer and minutes of goals are not recorded in these competitions. However, I am always in the habit of recording this information, as occasionally I do referee competitions where this information is required.
For each send-off that occurs within the match, a separate send-off report must be completed. Information such as the location and round can usually be obtained via the competition website, but it is important to ensure that the player's name is copied from the team sheet, as the team sheet remains with the home team at the conclusion of the match.
Comment: What a fabulous and comprehensive answer! I don't get why it's not accepted.
Answer: A caution can only be given for one of six reasons, and a suspension for one of seven reasons. That reduces the amount required to remember; an offence is in one of just thirteen categories.
Systems exist to shorten the writing needed. For example, in one possible system

a caution is given late in the first half for failing to respect distance at an indirect free kick

The referee would write "#7 38 C4 @ IFK" to indicate who received the caution, why the caution was given and when, under what justification in the laws.
Various systems are used by different organisations to make it easy to note the reason for a card, and remind the referee what occurred when they write a match report afterward.
Beyond that, referees develop an experience that helps them remember offences long enough to get through the match. They also have two assistants recording everything as well, so if anything is not recalled, the three can confirm details of the event.
Comment: This good answer seems right, if you can add any link to confirm that I can accept it
Comment: They'll probably add the players jersey number to help them remember. Unless the 38 is the number, but I've taken it as the minute it happened in. Possibly one of the most important things when giving a yellow card so in case of a second yellow you can verify.
Comment: @Don_Biglia Seems like `#7` is the jersey number.
Comment: Yeah, now it's there yes.
Comment: Nice answer - brief and to the point.


Why isn't IIS serving my static CSS / JS files?

Question: I added an ASP.NET MVC3 site to ISS (which was working fine in the debugger). When viewing the site in a browser, everything appeared to be working fine except that all of the CSS and JS files were returning a 404.
Here is the site in IIS Manager:

Other details:

OS: Windows Vista Home Premium 32-bit (with SP2)
IIS: 7.0.6000.16386
Visual Studio 2010 Express with SP1
Answer: It sounds like a permissions error. Did you remember to add the IIS User IIS_IUSRS to the list of users that can access the files?
Comment: How to set it up in IIS Express? and how come there is no IIS_IUSRS in my computer?
Comment: Woops... I gave `IIS_IUSRS` full access to the folder and it's working now.
Comment: Like @Blaise I'd like to know how to manage IIS users with IIS Express.


Show $S^2$ is not homeomorphic to the closed unit disk.

Question: How to show unit closed disk is not homeomorphic to sphere $S^2$?
Answer: The fundamental group of the closed disk is trivial since it is contractible.  But if there were a homeomorphism, remove the center of the unit disk and this changes the fundamental group to $\mathbb{Z}$ while $S^2$ with a point removed is contractible.
Answer: There are more topological invariants than the fundamental group. For example, the Euler characteristic of the disk is $1$ and the Euler characteristic of the 2-sphere is $2$. Another example, $\pi_2(D^2) = 0$ and $\pi_2(S^2) \cong\mathbb{Z}$.
You can think of a topology sequence as, in part, the building of a repertoire of invariants which you can use to check whether spaces are not homeomorphic (or not homotopy equivalent).
Answer: Also, you can consider arbitrary four distinct points a,b,c,d (in order) on the boundary of the unit disk and their images on S^2. Lets say f is a homeomorphism from unit disk to S^2. Geometrically, we can find two paths from f(a) to f(c) and from f(b) to f(d) on S^2 so that these paths do not intersect. However, If we take the inverse images of those two paths, we can say that they are paths one of which is from a to c and the other is from b to d. Such paths must have at least one intersection point. Lets call this as x in unit disk. Now, f(x) is in the intersection of those two paths, but the images of those paths were taken to be non-intersecting. Hence, we get that there can be no homemorphism between unit disk and S^2.
Answer: I don't know if it is too much to invoke Jordan Separation Theorem to show this. $S¹$ doesn't separate the disk but it's homeomorphic image (if a homeomorphism exists) separates the sphere.


How do I fix the Drush error "SQLSTATE[HY000] [2002] No such file or directory"?

Question: I just updated my macos' php version using homebrew. This worked, the php version I'm currently running is 8.0.2
But doing this my Drush stopped working. When running drush cr I get the following error:
In Connection.php line 189:
SQLSTATE[HY000] [2002] No such file or directory

I tried several suggestions mentioned here:
I've got `PDOException: SQLSTATE[HY000] [2002] No such file or directory` when using drush
The highest voted answer:
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Gives me the following feedback:
mkdir: /var/mysql: File exists
ln: /var/mysql/mysql.sock: File exists

When I then run mysql_config --socket I get /Applications/MAMP/tmp/mysql/mysql.sock  as return.
I also tried changing the .zprofile on my computer. I added:
export PATH=/Applications/MAMP/bin/php/php8.0.2/bin:$PATH

and
export DRUSH_PHP="/Applications/MAMP/bin/php/php8.0.2/bin/php"

But, as you might see, I don't really know what I'm doing and why. Can someone help me get Drush working again? I'm working on Drupal 9 websites using Drush 11 (drush -v is working).
Comment: I was on MAMP for years. Switched to DDEV. Never looked back.
Comment: "drush stopped working"-- what doesn't work? drush can't be found?  drush can't connect to your site?  which commands work and which don't?
Comment: Sorry, I thought I mentioned that...I updated my question
Comment: Also, if you don't understand what you're doing, you should carefully keep notes of any changes that you make to your system, because you are likely to change things that don't need to be changed, causing even more problems down the line.  If a change doesn't fix the problem, it should be undone immediately.
Comment: Are you certain MySQL is running?
Comment: Yes MYSQL is running, my sites are running smoothly.
Answer: Use 127.0.0.1 instead of localhost in the database connection configuration.


what is wrong with 'this.setState'

Question: Please i have this problem with my react class,i'm trying to update my state but i'm get this error "Cannot read property 'setState' of undefined" ..I have tried every solution online,but no luck
here is the code
export default class PageBackground extends Component{
    constructor(props) {
            super(props);

            this.state={
                lat         :'nothing',
                longi       :''
            };
            this.getLocation=this.getLocation.bind(this);
            }

        componentWillMount() {
            this.getLocation();
        }
        getLocation () {

            fetch('http://freegeoip.net/json/')
             .then((res)=>res.json())
             .then(function (objec){this.setState({lat:objec.latitude,longi:objec.longitude});})
             .catch((err)=>console.log("didn't connect to App",err))
             console.log(this.state.lat)
        }

        render(){
            return(

{this.state.lat}

                )
            }
        }

Comment: Do you get the console logs?
Comment: I think `this` is in the context of the function. maybe you should try `that=this` and `that.setState`
Comment: There is litterally a million duplicates of this very error. I'm surprised you haven't been able to find any of them.
Answer: The function () { ... } syntax won't maintain the this reference from the context. Use an arrow function instead:
then(() => {
    this.setState({lat: objec.latitude, longi: objec.longitude})
})

Another option is to add .bind(this) after function () { }.
Or, just save this to a local variable and use it inside the function:
var self = this;
fetch('http://freegeoip.net/json/')
         .then((res)=>res.json())
         .then(function (objec){self.setState({lat:objec.latitude,longi:objec.longitude});})
         .catch((err)=>console.log("didn't connect to App",err))
         console.log(this.state.lat)

However, arrow functions were introduced exactly for this kind of problems.
Comment: @JohnAnisere The answer to the first question is that arrow functions capture `this` from the surrounding code, therefore you don't have to bind `this` to them manually. They work in the way you would expect. The other question is more complicated. You are talking about the problem when class methods are used as "loose" (first class) functions. The methods are not bound automatically to their instance and must be bound manually.
Comment: thank you very much.This worked but i want to know why? i read the arrow function doesn't work well with 'this' why is this situation different?
Comment: and why do we even have to bind all methods in we create in es6 class in our constructor?
Answer: Try this out:
   getLocation () {
            var self = this;
            fetch('http://freegeoip.net/json/')
             .then(function (objec) {
               console.log(objec);
               self.setState({lat: objec.latitude, longi: objec.longitude})
             })
            .catch(function (error) {
               console.log(error);
            });
        }

Answer: The problem here is, you are trying to accesss this in a different scope.
Whenever we pass a function() {} as a callback it creates it's own scope.
Use arrow function's instead.
() => { 'your code here'; }

Arrow functions share the scope of its parent.
getLocation = () => {
    fetch('https://freegeoip.net/json/')
        .then(res => res.json())
        .then((objec) => {
            this.setState({ lat: objec.latitude, longi: objec.longitude });
        })
        .catch(err => console.log("didn't connect to App", err));
    console.log(this.state.lat);
}

what is wrong with 'this.setState'


lme4 formula to test levels under an independent variable

Question: I am running a linear mixed effects model in R using (lme4). I have two independent variables: word types (five levels) and lexicality (two levels), and one dependent variable; reaction time. I used the following formula to look at the overall interaction between the dependent variables.
mydata.mod1=lmer(RT~lexicality*wordType*(1|Item)+(1|Subject), mydata)
summary(mydata.mod1)

My question now is about the possibility of looking at each level under word types separately and compare it to lexicality based on reaction time.  For example, I want to take Type Two (under word types) and compare it to lexicality. What terms should I include to run this type of analysis. I have tried the following formula, but it did not show what I needed:
mydata.mod2=lmer(RT~wordType*(1+lexicality|Subject)+(1|Item),mydata)

Is there something I missed?
Answer: I cannot add this as a comment, because it is too long. It should be slightly helpful to get started at least.
You have missed quite a lot =) Terms in brackets are the random effects. (1+...|...) means that you make a random slope model together with random intercept as opposed to just a random intercept model (1|...). Use the ranef() command to see the difference.
Here are couple of useful references you should read before doing the analysis (unless you have done so already):

Winter, lme4 tutorial
Baayen et al. 2008
Barr et al. 2013

All of them are written in a language understandable for non-statisticians. See especially the difference of ANOVA and mixed model equations from Barr et al. 2013.


Autenticação Vraptor + AngularJs

Question: Estou tentando fazer autenticação de usuários em meu sistema, porém estou um tanto perdido. Como faço pra retornar o usuário logado do servidor pro front-end ?
Atualmente eu consigo verificar se o usuário existe em meu banco de dados da seguinte forma:
@Post
@Path(value = "/auth")
@Consumes(value = "application/json", options = WithoutRoot.class)
private void autenticar(Usuario usuario){
    if(usuarioDAO.autenticar(usuario.getCodigo(), usuario.getSenha()) != null){
        //Se o usúario existir retorna OK, como retornar o usuário logado caso exista?
        result.use(Results.status()).ok();
    }else{
        //Retorna um erro
    }

}

Front-end:
Service:
angular.module("oraculo").factory("usuarioAPI", function ($http, config) {

    var _getUsuario = function(usuario){
        return $http.post(config.baseURL + "/Oraculo/usuario/usuario", usuario);
    };

    return {
        getUsuario: _getUsuario

    };
});

Controller:
angular.module("oraculo").controller("loginCtrl", function($scope, $routeParams, usuarioAPI){

    $scope.autenticar = function(usuario){
        console.log("usuario" +usuario)
        usuarioAPI.getUsuario(usuario).success(function(data) {
            sessionStorage.setItem('userLogado', data) //objeto de usuário.
            var user = sessionStorage.getItem("userLogado");
            console.log("usuario:" +user.login)
        })
        .error(function(response, status) {
            console.log("erro " + status);

        });

    }

});

Answer: EDIT 1
Faça o seguinte:
@Inject
private Result result;

@Inject
private UsuarioDAO usuarioDAO;

@Path(value = "/auth")
@Consumes(value = "application/json", options = WithoutRoot.class)
private void autenticar(Usuario usuario){
    Usuario usuario = usuarioDAO.autenticar(usuario.getCodigo(), usuario.getSenha());
    boolean usuarioValido = usuario != null;

    if(usuarioValido){
        result.use(json()).from(usuario).serialize();
        result.use(Results.status()).ok();
    }else{
        //Retorna um erro
    }
}

EDIT 2
Para criar uma variável global no angular você pode usar um service que armazena o usuário em cache:
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
  var usuarioLogado;
  if(usuarioLogado)
     return usuarioLogado;
  else{
      /* aqui roda tua consulta para o back-end e com o retorno popula a variável usuario logado */
      return usuarioLogado;
  }

});

no controller:
function MyCtrl($scope, UserService) {
   console.log(UserService.usuarioLogado);
}

Outra alternativa é usar o $rootScope:
function MyCtrl($scope, $rootScope) {
   $rootScope.usuarioLogago = /* aqui passa o teu usuario retornado pelo back-end*/
}

O $rootScope é uma váriavel global compartilhada por todos os controllers do angular. Em outras palavras, o que você definir dele ficará visível para os demais controllers.
EDIT 3
Exemplo completo:
angular.module("oraculo").factory("$servicoGenerico", function($http, $q, $injector) {
    function ajax(url, parametros, metodo) {
        var requisicao = $http({
            method: metodo,
            url: url,
            data:parametros
        });

        var promessa = requisicao.then(function(resposta) {
                return(resposta.data);
            },
            function(resposta) {
                return($q.reject("Something went wrong"));
            }
        );
        return promessa;
    }
    return({
        ajax:ajax
    });
});

angular.module("oraculo").factory("$usuario", function($servicoGenerico, config) {
    return {
        logar : function(usuario) {
            var promessa = $servicoGenerico.ajax(config.baseURL + "/Oraculo/usuario/usuario", usuario, "POST");
            return promessa;
        }
    };
});

angular.module("oraculo").controller("loginCtrl", function($scope, $usuario, $rootScope){
    $scope.autenticar = function(usuario){
        console.log("usuario" +usuario);
        return $usuario.logar(usuario);
    };

    $scope.getUsuarioCorrente = function(){
        if($rootScope.usuarioLogado)
            return $rootScope.usuarioLogado;

        $scope.autenticar("<passa aqui o usuario>").then(function(usuarioLogado){
            $rootScope.usuarioLogado = usuarioLogado;
            return usuarioLogado;
        });
    };
});

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/29729/discussion-on-answer-by-emir-marques-autenticacao-vraptor-angularjs)

Autenticação Vraptor + AngularJs


Add child category to multiple parent category in Magento

Question: I want to assign a specific child category to multiple parent categories .
For e.g, If there are 2 parent categories ,say, Dell Laptop and  Sony Laptop and a child category named as Laptop accessories. I want to include the "Laptop Accessories" category in both "Dell Laptop" and "Sony Laptop" .
By default,this functionality is not in Magento, I need to create 2 child categories named as "Laptop accessories" and then assign it to parent categories.
How can I solve this issue? Does any have worked on it?
Thanks in advance!
Answer: Category Parent Child relationships in Magento are one to many (one parent category has many children, each child has exactly one parent).  The database schema does not allow what you want to do.
If your issue is creating the multiple "Laptop" categories quickly, consider creating your categories as a CSV and using a tool like Unirgy's RapidFlow to import them, or alternatively writing a setup script.
Comment: hi Jim, but this is not happening!! I mean Magento is such a huge platform and might having some ways to achieve this
Comment: Magento is a huge platform.  But I reviewed the database schema before I answered the question, and it's not technically possible.  If a third party extension were to try and provide this capability, it would need to rewrite/override some very core aspects of the system, and I'm not sure I'd be comfortable with that.
Comment: Additionally your issue may be one of information architecture.  If the laptop accessories in your example relate to both brands of laptops, then it probably belongs as a standalone category at the same level in your category hierarchy as the two laptop categories.  If the products in in the Sony > Laptop Accessories are different to the products in Dell > Laptop accessories, then you really do have two separate categories (they just happen to have the same name).


Store token replacement values in the database rather than tokens themselves

Question: Is there a way to store the token replacement values of tokens put in a form field in the database rather than the tokens themselves?
I have a text field in a custom content type that has a token as default value (using Token Filter), [current-user:uid], so on node creation the replacement value is inserted into the node. In the database, it's stored as '[current-user:uid]', rather than as the replacement value. What is one way of storing the replacement value rather than the token string in that table?
Comment: Your question is so generic that I can only answer it with an equally generic: "Yes, there is a way to do that".
Comment: If there is a way to do that, would you mind giving me a hint what that way is?
Answer: The gist of it is to execute token_replace in a suitable location. Here's an example.
<code>hook_node_presave($node) {
  if ($node->type == 'page') {
    $replaced_text =  token_replace($node->field_with_replacements['und'][0]['value']);
    $node->field_with_replacements['und'][0]['value'] = $replaced_text;
  }
}
</code>
Comment: hook_node_presave plus token_replace worked like a charm on various fields, all but the Serial module field (which has a different sort of array, Serial also has problems with Pathauto). Many thanks.
Comment: Yes, serialized data would need to be un-serialized before tokens could be replaced. If you consider this answer "right", you should accept it as the right one.


Show that $|PQ|=|P'Q'|$

Question: Let $P, P', Q, Q'$ be four different points in the euclidean plane, such that $PP'$ and $QQ'$ have different midpoints and the line $g$ passes through these midpoints and is perpendicular to $PP'$ and $QQ'$.
(a) Show that $|PQ|=|P'Q'|$.
(b) Let $P=(r,s)$ and let $g: \ ax+by+c=0$. Calculate $P'$.
$$$$
So that the line $g$ passes through the two midpoints and is perpendicular to $PP'$ and $QQ'$, the $PP'$ and $QQ'$ must be parallel, or not?
Does this mean then that $|PQ|=|P'Q'|$ ?
Answer: So line $g$ is perpendicular to lines $PP'$ and $QQ'$ hence these lines are parallel. Moreover, $g$ is perpendicular bisector for both $PP'$ and $QQ'$ which means all points on the line $g$ are equidistant from $P$ and $P'$ and from $Q$ and $Q'$. From this we can conclude that $|PQ|=|P'Q'|$ (if $M$ is midpoint of $QQ'$, $\triangle PMQ \cong \triangle P'MQ'$).
Regarding b):
Let $P'(p,q)$ then we have that $\frac{q-s}{p-r}=\frac{b}{a}$  or $aq-bp=as-br$
We also know that midpoint belongs to line $g$ so $a\frac{r+p}{2}+b\frac{s+q}{2}+c=0$ or $ap+bq=-2c-ar-bs$. Solving the system yields: $$q=\frac{a^2s-2abr-2bc-b^2s}{a^2+b^2}$$ $$p=\frac{b^2r-2abs-2ac-a^2r}{a^2+b^2}$$
Comment: We need angles $\angle PMQ$ and $\angle P'MQ'$ which are alternate interior to $\angle MPP'$ and $\angle MP'P$ and we have that $\triangle MPP'$ is isosceles.
Comment: @MaryStar: Your approach will work, you can remove absolute value bars. I also posted my solution for b).
Comment: To show that that the triangles $\triangle PMQ$ and $\triangle P'MQ'$ are congruent we have: $|MP|=|MP'|$, $|MQ|=|MQ'|$ and is the last condition that the angles $\angle PQM$ and $\angle P'Q'M$ are right?
Comment: I see!! Could you give me a hint for question (b) ? Do we use that the distance of $P$ and $P'$ from $g$ is the same?
Comment: Let $(r', s')$ be the coordinates of $P'$. Then $PP'$ is a line of the form $y-s=\frac{s'-s}{r'-r}(x-r)$ and this line must be perpendicular to $g:y=-\frac{a}{b}x-\frac{c}{b}$, so $\frac{s'-s}{r'-r}(x-r)\cdot \left (-\frac{a}{b}\right )=-1$.And the second condition is $d(P,g)=d(P',g)$, or not?
Comment: From the last equation we have \begin{align*}d(P,g)=d(P',g) \Rightarrow \frac{|ar+bs+c|}{\sqrt{a^2+b^2}}=\frac{|ar'+bs'+c|}{\sqrt{a^2+b^2}}\Rightarrow |ar+bs+c|=|ar'+bs'+c|\end{align*} Do we have to take cases about the absolute values?
Comment: Thank you very much!! :-)

Show that $|PQ|=|P'Q'|$


Many dependent variables, few samples: is this an example of "large $p$, small $n$" problem?

Question: "Large $p$, small $n$" typically refers to "many independent variables, few samples".
In my case, I have $1$ independent variable, $300$ dependent variables, and $n < 20$ samples.
Thus, my case is not the typical "large $p$, small $n$" scenario (even though I do have many regression coefficients to estimate -- it's just that they are not due to the independent variables, but due to the number of dependent variables).
How is my situation classified?  Does it fit into the "large $p$, small $n$" scenario, albeit I have actually less independent variables than samples?

Note: I would like to do a multivariate regression or MANOVA on my data, but have a "multicollinearity" problem.  But it is not really multicollinearity because I only have one independent variable.  What's going on here?
Comment: Can you clarify your situation? Do you simply want to test if there is change across your IV? Do you want to predict values for all DVs for future observations? Are you trying to run Fisher's linear discriminant analysis?
Comment: How do you know you have a multicollinearity problem? Do you have high correlation in your dependent variables? Also, you sure as heck can have multicollinearity in your dependent variables. "Multicollinearity" just means "at least one variable is (approximately) linearly dependent on another variable."
Comment: @ssdecontrol I know I have a multicollinearity problem because trying to fit a multivariate regression or do a MANOVA test fails due to multicollinearity/singularity (says Matlab)
Answer: There are several combinations on the size of $n$ and $p$: small $n$ - large $p$, small $p$ - large $n$, large $n$ - large $p$ ... See Johnstone & Titterington, 2009, Statistical challenges of high-dimensional data for an overview.
In your case, it appears that you have a small $p=1$ and relatively small $n$, with high dimension of the dependent variable. It is likely that your independent variable may not contain enough information to properly model $300$ responses.
The justification of this claim is as follows. If you use a GLM for your data, then you have $20$ samples to estimate $300+$ parameters in the covariance matrix of the errors. This may induce over-fitting, and the precision of the estimators will be unnecessarily vague (in the sense that confidence intervals for these parameters might be too wide) and inaccurate (far from the true value). However, if you restrict the structure of the covariance matrix, then it may be possible to estimate the parameters more accurately (How to restrict the structure of the covariance matrix? That's a big question which depends on the context). Moreover, the fewer covariates you use, the more "responsibility" the residual errors carry to explain the unobserved variability. This may, for instance, inflate the variances or induce the need for more flexible distributions than normal for modelling the residual errors.

Additional references of possible interest:

West, 2003, Bayesian Factor Regression Models in the "Large p, Small n" Paradigm

CV question: Summary of "Large p, Small n" results
Comment: (+1) Welcome to our site!  Your mastery of the $\TeX$ markup, clear restatement of the question, pithy answer, and ability to find and cite references show you are already expert at contributing to forums like this.  I hope you will continue to participate!
Comment: Aha! This important assumption appears to be missing from the question--or maybe it is understood but not stated?  I had taken the model to be of the form $y_i = \alpha_i + \beta_i x + \varepsilon_i$ for each dependent variable as indexed by $i$, requiring estimating $300$ parameters $\{\alpha_i, \beta_i\}$. An example would be a collection of about $20$ time series (such as daily measurements of $20$ experimental subjects) with a covariate $x$ available with each time series (such as a characteristic of each subject).
Comment: (I misread the question, too.) Why, though, do you suggest there might not be enough information? There's enough data to estimate the entire covariance matrix, after all. I admit the estimates will be pretty uncertain, but no individual component of that matrix will be any more uncertain than if the problem involved only two dependent variables. Would you continue to maintain there would not even be enough information here if $300$ were changed to $2$? Sure, there are multiple testing problems, but the situation is better than if one had to perform $300$ separate ordinary regressions.
Comment: (-1) After the misunderstanding was cleared, I feel that this answer does not address the actual question that was asked. As I read it, the question is primarily about terminology.
Comment: How is the model of this type? The question says that the response ${\bf y}$ is of dimension $n \times 300$ while there is only $1$ predictor.
Comment: @JuhoKokkala You just made me doubt about my reading skills ... I think you are right, and I have modified my answer.
Comment: @whuber I have added some discussion on your points. Thanks for the feedback.
Comment: Thanks.  I am not sure what exactly you mean by "inflate the variances": that phrase has an ambiguous referent. Regardless, what's holding up my understanding is the thought that one could just run 300 separate regressions. By giving up all information about correlations among the dependent variables, you would lose information about correlations among the 600 parameter estimates: but it seems the residuals shouldn't be drastically affected by that procedure. If anything, they ought to be slightly reduced overall, thereby *decreasing* estimated residual variances and parameter standard errors.
Comment: @whuber But if you run 300 separate regressions, you will end up with 300 estimators of the (single) regression coefficient.The claim about the variances is rather empirical. For example, if the sample contain outliers, the estimation of the variance is typically "inflated" by these.
Answer: [As I read it, the question is primarily about terminology, and @East's answer (good as it is) does not explicitly address it.]
Sometimes the distinction between dependent and independent variables is not so clear. As you are referring to MANOVA, you probably have $300$ variables measured for two groups. Technically, you are right, it is $300$ dependent variables, but imagine that you want to predict the group membership by looking at the variables (after all, the purpose of running MANOVA is to test if the groups are different or not). Now group identity suddenly becomes a dependent variable, and you have $300$ independent variables to make the prediction.
So I think the distinction between dependent and independent variables is not very important here, and your situation can be safely described as "large $p$, small $n$".
In practice, people definitely do refer to classification problems, e.g. linear discriminant analysis, with number of features $p\gg n$ as "large $p$, small $n$" (see e.g. The Elements of Statistical Learning 18.2). But linear discriminant analysis is almost the same thing as MANOVA, see here: How is MANOVA related to LDA? So I would advocate to go ahead and to call it "large $p$, small $n$" in MANOVA context as well.


Configuring a basic multisite development environment in Linux

Question: While installing Multisite devlopment i followed below instructions    https://www.drupal.org/node/823990#comment-10184088
When i trying to call http://testsite.localhost/install.php throwing error Forrbidden Access to Page and in apache2/errorlog its showing AH01276: Cannot serve directory /var/www/html/drupal/sites/testsite.localhost/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive, referer:
Answer: If you followed the exact instructions and you did not change any paths, then you have a typo: /var/www/html/drupal/sites/testsite.localhost/ See the extra 'html' directory? Make sure the paths in the apache config (step#3) match the actual paths in your file system.


Convergence of $\sum^\infty_{n=1} \frac {e^{2ni}}{n\sqrt n}$

Question: Does $$\sum^\infty_{n=1} \frac {e^{2ni}}{n\sqrt n}$$
Converge?
What test would you use to study the convergence of this series?
Answer: Note that $\vert e^{in \theta} \vert = 1$. Hence, we have
$$\left \vert \sum_{n=1}^{\infty} \dfrac{e^{in\theta}}{n\sqrt{n}}\right \vert \leq \sum_{n=1}^{\infty} \dfrac{\left \vert e^{in\theta}\right \vert}{n\sqrt{n}} =  \sum_{n=1}^{\infty} \dfrac1{n\sqrt{n}} = \zeta(3/2)$$
Comment: I was trying to help. Your answer answers both questions only implicitly.
Comment: the comparison test is for positive summands. Surely you mean the Weierstrass M-test?
Comment: Since part of the question asks which test to use, shouldn't you state it?
Comment: This uses the comparison test.
Comment: @Tim Whatever name you call it.


why is my nslookup not always returning an IP?

Question: I wrote an nslookup code but in some cases, it does not print the IP, it prints some domain.
I wrote a DNS packet that the dst IP is 188.8.131.52.
for example the domain "stackoverflow.com" will work but for this one "s.ytimg.com" it wont work and the answer will be "b'ytstatic.l.google.com.'"
# Creates DNS request
fullmsg = IP(dst = DST_IP)/UDP()/DNS(rd = 1,qd = DNSQR(qname = "s.ytimg.com"))
ans = sr1(fullmsg, verbose = 0)
print(ans[DNS].summary())# output: DNS Ans "b'ytstatic.l.google.com.'" expected: "22.214.171.124"

I expected that it will print the IP but like I said it does not print IP for every entered domain.
Answer: You are getting a CNAME as the answer. You need to further resolve it. I.e.: check if the answer is a valid IP address. If it isn't try to resolve the answer.
https://en.wikipedia.org/wiki/CNAME_record


angularJS $http.get(localhost/teste) não funciona no Chrome

Question: No meu controller possuo um  $http.get(http://www.testesitelocal.com:18888/teste_json) que me retorna os valores do JSON teste. Faço essa requisição na minha maquina local. No Webview que fiz em JavaFX isso funciona normal, mas no Chrome não funciona (no Firefox e no IE ocorre a requisição normal).
Retorno do erro:

XMLHttpRequest cannot load http://www.testesitelocal.com:18888/teste_json . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.testesitelocal.com:8000 <http://www.testesitelocal.com/>' is therefore not allowed access.
Answer: Consegui achar a resposta! Olhem:
Definição de domínios explícita: (1, 2, 3 e 4)
Configuração do JavaScript:
Com jQuery/Zepto:
function verificaCodigoTurma(codigo, retorno) {
  try {
    $.support.cors = true;
    $.ajax({
      cache: false,
      timeout: 5000,
      //async: false,
      type: 'POST',
      //crossDomain: true,
      url: 'http://TESTESTE/VERIFICA',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      data: '{"sch_code":"' + codigo + '", "app_id":1}',
      //JSON.stringify(teste),
      success: function (data) {
        retorno(data);
      }
    });
  }
  //Exceção geral da sincronização
  catch (err) {}
}

Sem jQuery / Vanilla-JS:
function verificaCodigoTurma2(codigo, retorno) {
  var xmlhttp = new XMLHttpRequest();

  var params = '{"sch_code":"' + codigo + '", "app_id":1}';

  xmlhttp.open("POST", "http://www.ETESTEr.com.br/Services/TESTE.svc/TESTE", false);
  xmlhttp.setRequestHeader("Content-type", "application/json");
  xmlhttp.setRequestHeader("Content-length", params.length);
  xmlhttp.setRequestHeader("Connection", "close");
  //Para funcionar, além da configuração abaixo é necessário colocar o seguinte header no servidor:
  //Access-Control-Allow-Credentials: true
  xmlhttp.withCredentials = true;
  xmlhttp.send(params);
  var jsonResponse = JSON.parse(xmlhttp.responseText);
  retorno(jsonResponse);
}

Você ainda pode usar JSONP, no caso de requisições GET.
Para que o CORS funcione você deve também configurar o servidor:
IIS:
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
  <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>

Apache:
Header add Access-Control-Allow-Origin "*"

Lembrando que essas configurações acima permitem que qualquer website acessem dados do seu, retirando a segurança dele. Por isso procure restringir os domínios cobertos pela Access-Control-Allow-Origin.
Crédidos: Airton Barbosa que conseguiu e foi atrás da resposta correta e ainda ofereceu mais de uma solução
Comment: Propus uma edição, mas não mudei o código, só passei ele no [jsbeautifier](http://jsbeautifier.org/). Se alguém tiver um código mais limpo por favor edite.
Comment: O *menino que vive morrendo* editou o post e não sei onde a minha proposta de edição foi parar: eu tinha reescrito os códigos. Depois edito novamente.
Comment: Deixando de lado a desorganização, algo que alguém irá arrumar, vale lembrar que *é melhor arrumar a aplicação para funcionar com CORS do que desativar a segurança do Google Chrome*.
Comment: Só agora parei pra ver que quem respondeu foi o autor da pergunta.
Comment: hehehehe É que achei a resposta e postei rápido....me desculpe.
Comment: Tranquilo! Depois dou uma passada no seu servidor de minecraft ;) abs


String ReplaceAll() method is not giving proper results

Question: "This is the snippet of my code"
public class Test {
    public static void main(String[] args) {
        String s = "sourav /*the patameter*/ /*the patameter*/ /*the patameter*/";
        if (true) {
            s = s.replaceAll("\\/*the patameter\\*/", "111");
            System.out.println(s);
        }
    }
}

"As replaceAll() method takes a regex i gave the escape sequence ,Still it is not getting escaped."
"The response i am getting is sourav /*111 /*111 /*111"
"Expected response is sourav 111 111 111".
"I know this can be done with simple replace() method .But can i do it with replaceAll().Please Let me know"
Comment: Yes, `\\/*` matches "0 or more occurrences of /". It doesn't match the `*`. Perhaps you meant `\\/\\*` at the start of the pattern? (It's not clear to me that you even need to escape the forward slash.) As another hint: when something doesn't give you the results you expect, it's always best to *start* with the assumption that you're doing something wrong rather than that the standard library of a very widely-used platform is broken. If your title had "is not giving the results I expect" that would be better than "is not giving proper results"
Comment: Try [`\/\*the patameter\*\/`](https://regex101.com/r/PBUOIT/1), you have to escape the `*`
Comment: I suggest you use an online regex helper and play a bit with it.
Comment: s = s.replaceAll("\\/\\*the patameter\\*\\/", "111"); Try this
Comment: \\/\\*the patameter\\*\\/  with this it is working.
Answer: Try:
s.replaceAll("/\\*the patameter\\*/", "111");

Or even better:
s.replace("/*the patameter*/", "111");

Comment: Yes as I mentioned in my question , it can be done with Simple replace() , but wanted to do  with ReplaceAll().
Answer: Try using the \Q and \E switches.  It's the way to declare a string literal (escape) within the regex pattern.
s = s.replaceAll("\\Q/*the patameter\\*/\\E", "111");


Using AND instruction with 32-bit operand in 64-bit

Question: I have a question on the AND instruction in 64-bit mode. I have this manual telling me that the AND 32-bit immediate is to be sign-extended to 64-bit. But I can't do this
and rax,0x80000000

Which is ridiculous I think because 0x800000 is a perfect DWORD operand. The highest I can go with it is
and rax,0x7fffffff

So what's happening here? I can't use MSb=1 to sign-extend an operand? If so, then how's sign-extension is supposed to work against an operand without being able to use it as in 0x80000000?
Thanks for you replies.
Comment: There is nothing wrong with `0x80000000` in the machine code but that means `0xffffffff80000000` due to sign extension. To avoid the possible confusion of writing `x` but getting `y` the assemblers don't allow that. As I said, you **can** get that output if you write `-2147483648`.
Comment: @royalfinest - `and rax,-0x80000000` should also work.
Comment: You can't encode `0x80000000` as that would be sign extended to `0xffffffff80000000`. You can however use `and eax, 0x80000000` to achieve the required effect given that 32 bit operations zero the top bits.
Comment: It's exactly the same thing. Of course `movsx` does not take an immediate so you can't really compare. The point is `0x80000000` as an operand is sign extended to `0xffffffff80000000` which makes it no longer equal to `0x000000080000000` that you have written hence most assemblers don't allow it. If you write it as `-2147483648` that will be encoded as `0x80000000`.
Comment: I don't get it. It's a 64-bit operation anyway. Why can't 0xffffffff80000000 work?
Comment: That **does** work but that's obviously not `0x80000000`.
Comment: So in a way of saying it, I can only use +positive immediate operand?
Comment: Since it's sign extended you can use negative too but you need to specify them as negative. Depends somewhat on your assembler.
Comment: Thanks jester. I am not actually questioning your replies. I am more concern about the misleading information from the manual. By not allowing sign-extension to work properly against an operand, then the manual shouldn't simply say "sign-extend the 32-bit operand to 64-bit" because from what I know, that's not how sign-extension work. If "sign-extension" in AND entry implies different meaning that what is written in MOVSXD/MOXSX "sign-extension" entry definition, then ... I don't know what to say. LOL.
Comment: Jester, have you looked into the AND 0x7ffffffff encoding? If you look at it then you'll know that there's nothing wrong with AND 0x80000000 either. There's no wrap-around no nothing that should limit it to just positive operand. It's a perfect 6-bytes 64-bit encoding with REX and stuff. I don't know, I could be missing something obvious here. Too much chemicals.
Comment: Not quite a duplicate of [addq with 64bit immediates?](https://stackoverflow.com/q/23762332) since this question realizes that the immediate is only a dword, but not realizing it needs to be a value such that `i == (int32_t)i`, i.e. one that can fit in a *sign-extended* 32-bit immediate.  Assemblers work with values, not encodings, that's why we use them.  (Some assemblers do truncate and warn, like NASM would I think stuff that `0x80000000` into the sign-extended dword immediate, encoding `and rax, 0xffffffff80000000`.)
Answer: "by preventing people from doing something stupid, you might prevent them from doing something clever": an attitude born of respect and humility; you don't know all the answers, so don't impose random stupidity like Jester pointed out in the comments.
fwiw, gcc / gnu as understands:
and $0x80000000, %rax

clang, religiously infused, insisted upon:
and $0xffffffff80000000, %rax

now, quick, are there enough f's there?  Does this help readability?  If you don't understand sign extension, how much assembly are you going to understand anyways?
Comment: GAS (GNU assembler (GNU Binutils) 2.36.1) correctly rejects `and $0x80000000, %rax` with `Error: operand type mismatch for 'and'`.  So does GAS 2.25.1.  What version are you using?


Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

Question: I've looked around on this one and I thought I had done everything I needed to so as to fix this issue. Apparently not though.
Basically I have a country, region, destination. Every region must belong to a country. Every destination must belong to a country. A destination MAY belong to a region.
Country > region > destination
or
Country > destination
When my code first thing creates the database I get the infamous:
Introducing FOREIGN KEY constraint 'FK_Destinations_DestinationRegions_DestinationRegionID' on table 'Destinations' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
This is all done using EF Code First.
I have a Country class:
public class DestinationCountry
{
    public int ID { get; set; }
    public bool Active { get; set; }
    [Required(ErrorMessage=" ")]
    [DisplayName("Country")]
    public string Name { get; set; }
}

And a map:
public class DestinationCountryMap : EntityTypeConfiguration<DestinationCountry>
{
    public DestinationCountryMap()
    {
        // Primary Key
        this.HasKey(t => t.ID);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(256);

        this.ToTable("DestinationCountry");
        this.Property(t => t.ID).HasColumnName("ID");
    }
}

I have a region class:
public class DestinationRegion
{

    public int ID { get; set; }
    [Required(ErrorMessage = " ")]
    [DisplayName("Country")]
    public int DestinationCountryID { get; set; }
    public string Name { get; set; }
    public virtual DestinationCountry DestinationCountry { get; set; }
}

And a map:
public class DestinationRegionMap : EntityTypeConfiguration<DestinationRegion>
{
    public DestinationRegionMap()
    {
        // Primary Key
        this.HasKey(t => t.ID);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(256);

        this.ToTable("DestinationRegion");
        this.Property(t => t.ID).HasColumnName("ID");
        this.Property(t => t.DestinationCountryID).HasColumnName("DestinationCountryID");

        // Relationships
        this.HasRequired(t => t.DestinationCountry)
            .WithRequiredPrincipal()
            .WillCascadeOnDelete(false);

    }
}

I have a destination class:
public class Destination
{

    public int ID { get; set; }
    [Required(ErrorMessage = " ")]
    [DisplayName("Country")]
    public int DestinationCountryID { get; set; }
    public int DestinationRegionID { get; set; }
    public string Name { get; set; }
    public virtual DestinationCountry DestinationCountry { get; set; }
    public virtual DestinationRegion DestinationRegion { get; set; }
}

And a map:
public class DestinationMap : EntityTypeConfiguration<Destination>
{
    public DestinationMap()
    {
        // Primary Key
        this.HasKey(t => t.ID);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(256);

        this.ToTable("Destination");
        this.Property(t => t.ID).HasColumnName("ID");
        this.Property(t => t.DestinationCountryID).HasColumnName("DestinationCountryID");
        this.Property(t => t.DestinationRegionID).HasColumnName("DestinationRegionID");
        this.Property(t => t.Name).HasColumnName("Name");

        // Relationships
        this.HasRequired(t => t.DestinationCountry)
            .WithRequiredPrincipal()
            .WillCascadeOnDelete(false);

        this.HasOptional(t => t.DestinationRegion)
            .WithOptionalPrincipal()
            .WillCascadeOnDelete(false);
    }
}

Could someone please tell me how I am doing this wrong.
Comment: It seems this does work. What's important is to remember to add the maps (whoops):

 modelBuilder.Configurations.Add(new DestinationMap());
 modelBuilder.Configurations.Add(new DestinationCountryMap());
 modelBuilder.Configurations.Add(new DestinationRegionMap());

I also changed "WithRequiredPrincipal" to "WithRequiredDependent".
Answer: SQL Server has a very simple model for cascading deletes. It can't cope with what you've specified here: If a Country is deleted, a Destination may be deleted either directly, or via intermediate Regions (hence the reference to multiple cascade paths).
If you can, you should consider re-organizing such that every Country has at least one Region (even if it's a dummy Region), and every Destination only belongs to a Region (and has no direct link to the Country). Then, all deletes can follow a single path (Country -> Region -> Destination).
Comment: Is that to say "WillCascadeOnDelete(false)" is just a lie?

I understand what you're saying except I am doing this for a CMS that I will not have control of. As in I won't be entering the data. And on top of that the navigation will be built using this model so where a country has no regions it just shows the destinations.

Is there really no way of doing this?
Answer: It seemed what I have does work with just the minor change of "WithRequiredPrincipal" to "WithRequiredDependent". Most importantly though, I needed to include my mapping class in the modelBuilder.Configuration.


With probability one, the function $t \mapsto B_t$ is nowhere differentiable.

Question: The context is that we have a theorem about Brownian motion which says that with probability one, the function $t \mapsto B_t$ is nowhere differentiable.
I am confused about what it means by a function $t \mapsto B_t$. It seems like it refers to the Brownian motion $B_t$, but to me it also seems like a function that sends $t$ to a function space, i.e. $$f: \mathbb R \to \text{a function space}$$. Am I right?
How is the open set defined in this function space? $L^p$ norm? Could you help to explain that with a concrete example?
Comment: Let $P$ be the Wiener measure on $C[0,\infty)$. Then $P(f \text{ is somewhere differentiable})=0$
Answer: Brownian motion $(B_t)_{t\geq 0}$ can be thought of as a collection of normal random variables $B_t\sim \mathcal{N}(0,t)$ in a probability space $(\Omega, \mathcal{F}, \mathbb{P})$ satisfying certain conditions like independent and stationary increments and almost surely continuous trajectories.
What do that last condition - and the event you asked about - mean?
Let
$$A=\{\omega : t\mapsto B_t(\omega) \text{ is nowhere differentiable.} \}$$
be the event in question.
For every fixed $\omega$, $t\mapsto B_t(\omega)$ defines a trajectory, a function $B_{\bullet}(\omega):[0,\infty)\to \mathbb{R}$ like usual. For this function, it can be tested whether the claim is true or not.
Then the set of $\omega$ with non-differentiable trajectories will be an event for which we will be able to compute its probabiltiy, and it will turn out to be $1$.
As further intuition, when people graph Brownian motion they are graphing for a fixed $\omega$ one of said trajectories, which defines a curve on the line (or on space if it is a $d$-dimensional Brownian motion). The following is an example graph of a Brownian trajectory $t\mapsto B_t(\omega)$, where the $x$ axis is time $t$ and the $y$ axis is the position on the line:

The same tratment that event $A$ got applies for other events, which could provide other concrete examples as well - a first one is
$$C=\{\omega : t\mapsto B_t(\omega) \text{ is continuous.}\}.$$
For a last concrete examples we may look at processes indexed in discrete time instead. If $(X_n)_n$ is a Markov process with state space $\mathbb{N}_0$ measuring a pile of coins' height, with transition probability $P$ with $P_{i,i+1}=\frac{1}{i+1}$ and $P_{i,0}=1-\frac{1}{i+1}$ for $i\in \mathbb{N}_0$ and initial state $0$, the event
$$\{\omega : n\mapsto X_n(\omega) \text{is increasing}\}$$
can be thought of in a similar manner as well.
Comment: Thank you for adding information about $\omega$, which makes the definition clearer to me now. Could you provide a real life example where we have different values of $\omega$? Maybe a stock example? What is the sample space?
Comment: When we say that $t \mapsto B_t(\omega)$ is continuous, do we mean that $B_t(\omega)$ is continuous? Then, to prove $B_t(\omega)$ is continuous, we need to show $B_t(\omega)^{-1}(Y) \in \Sigma$ for every $Y \in \mathcal B$.
Comment: The sample space is something we *suppose* exists when we model situations in real life by using these processes. We would say that the concrete things we are seeing are the result of one fixed $\omega$ from all possible in $\Omega$. $\Omega$ the state space is usually thought of as all possible outcomes that make sense for a certain experiment, activity or process - however, for the mathematics we usually mostly care about the probability measure and not any concrete choice of $\Omega$, because we don't really know it.
Comment: We do care about $\Omega$ to show formal existance of a process or random variable. Sometimes it could also make our understanding esier to work with a concrete version of $\Omega$. For example, a more concrete version of $\Omega$ for the discrete example could be $$\Omega=\{(x_n)_n \subseteq \mathbb{N}_0 : x_{n+1}=x_n + 1 \text{ or } x_{n+1}=0\},$$ but $$\Omega_2 = \mathbb{N}_{0}^{\mathbb{N}}$$ could also be used if we define the associated probability measures accordingly.
Comment: Yes! For Brownian motion it is required that with probability one the trajectories are continuous, so there would be nothing to prove if you already know your process has that law. But if one were to want to prove that a process is a Brownian motion then showing that $B_{\bullet}(\omega)^{-1}(U)$ is open for all $U$ open could be a way to do it. You could look at the Kolmogorov continuity theorem if you want to see more https://en.wikipedia.org/wiki/Kolmogorov_continuity_theorem?wprov=sfla1.
Answer: I found the following explanation helpful in helping me to understand the definition of Brownian motion.

There are two ways to think of $\omega$ in the definition of brownian motion $B_\omega(t)$. One is to think of $\omega$ as the Brownian motion path. A random experiment is performed, and its outcome is the path of the Brownian motion. Then $B_\omega(t)$ is the value of this
path at time $t$, and this value of course depends on which path resulted from the random experiment. Alternatively, one can think of $\omega$ as something more primitive than the path itself, akin to the outcome of a sequence of coin tosses, although now the coin is being tossed "infinitely fast." Once the sequence of coin tosses has been performed and the result $\omega$ obtained, then the path of the Brownian motion can be drawn. If the tossing is done again and a different $\omega$ is obtained, then a different path will be drawn. (Steve Shreve, Stochastic Calculus for Finance II)

In the Original text, $B_\omega(t)$ is written as $W(t)$. For clearity, I changed $W(t)$ to $B_\omega(t)$.


Groovy: Dynamically addings methods with a specific signature

Question: So, I need to dynamically create (or inject) methods into an object that have a specific return type and method signature, because a Java tool we're using will be finding this methods via Reflection and checks for void type. Method names will be determined at runtime.
Using metaClass. = { ... } however adds a closure which doesn't show up as a regular method (even if it can be used as one) and also has a return type.
I can't modify the method finding code, and it it not Groovy-aware.
I can't use methodMissing() or invokeMethod() because the method needs to actually exist. If I could overload class.getMethods() I think it would be possible, but I can't figure out how.
Is there any way to do this in Groovy?
Comment: Can you be a little more specific? i.e., give some example code.
Answer: You could use AST Transformations to add the code at compile time, but it wont work on classes that you don't compile, so I'm guessing that probably wont work.
You could probably replace the object with a CGLIB based proxy. If you can be more specific about the code in question...
EDIT: A little more info. Groovy metaClass magic is not available in Java unless the Java code were to explicitly call groovyClass.invokeMethod("someMethod",args);. So there isn't a way to do what you're asking with MetaClasses. CGLIB maybe.


OS X Crash Log Symbolication

Question: I cannot symbolicate OS X (not iOS) crash logs from testers and users using XCode 4.6 . The crash logs cannot be dragged into the organizer, and the organizer does not show any crash logs from ~/Library/Logs/DiagnosticReports/, though some logs are in that directory.
Didier Malenfant commented on a previous thread  XCode not importing OS X crash log that

The bottom line is quite simple. As of now (Xcode 4.6), OS X crash logs cannot be imported into Xcode. Only iOS ones.

Is this the current state of affairs?  It's hard to imagine that organizations are able to support new OS X software without effective ways to intepret crash reports.
Comment: see http://stackoverflow.com/questions/6085734/how-do-i-symbolicate-a-crash-report-of-a-mac-os-x-app-that-a-user-emailed-to-me
Comment: Thanks. But the answer you cite is more than a year older than the answer I cited above, which contradicts it.  Are you routinely symbolicating user-submitted logsin xcode 4.6.?
Answer: If you have a stack trace; for example:
0   com.your_app        0x00000001016191e0 0x1015fb000 + 123360
1   com.your_app        0x000000010161509d 0x1015fb000 + 106653
2   com.your_app        0x00000001016147b9 0x1015fb000 + 104377
3   com.your_app        0x000000010161df81 0x1015fb000 + 143233`

Try the following:
atos -o YOUR_APP.app.dSYM/Contents/Resources/DWARF/YOUR_APP -l 0x1015fb000 0x00000001016191e0 0x000000010161509d 0x00000001016147b9 0x000000010161df81`

Answer: You can use GDB for Symbolication, Put your release build and your .dSYM file in the same directory
open terminal
$ cd directory
$ gdb MyApp.app
(gdb) info line *0x00085f3c

or you can use atos as suggested by trojanfoe
$cd directory
$atos -o MyApp.app/Contents/MacOS/MyApp
info 0x00085f3c

or
$ cd directory
$ lldb MyApp.app
(lldb) image lookup -v --address 0x1ec4

Comment: Or `lldb` :)   `image lookup -v --address 0x1ec4`
Comment: Or `atos`: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/atos.1.html
Answer: We had the same problem with our app and I was symbolicating the crash reports manually line by line with atos.
I now tweaked Apple's symbolicate script such that it works with Mac apps and crash reports from PLCrashReporter.
https://github.com/lksnmnn/Symbolicate-CrashReports
How to use it:
Make sure you have all of the following files on your computer:

The crash report: report.crash
The dSYM file of your app: MyApp.dSYM
The executable / app folder of your app: MyApp.app
The improved symbolicate script: symbolicatecrash

Now go in the command line (Terminal) and do the following:
# set the developer directory
export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"

# Now run the script
/Path/To/symbolicatecrash /Path/To/report.crash > /Path/To/readable_report.crash

# Use -v for verbose logging.

The script will find your dSYM and your executable and symbolicates as much as it cans. You will now find your symbolicated report in the stated output file readable_report.crash
Build settings:
For proper reports and symbols, set your build settings to this:
Strip Debug Symbols During Copy: Yes
Strip Style: All Symbols
Strip Linked Product: Yes

Answer: I've used MacSymbolicator and Xsymbolicate in cases where I had a dsym and crash report file. They did the job for simply needs, though Xcode's built in crash reporting support has also gotten better, at least for apps sold in the App Store.

OS X Crash Log Symbolication


Only show an element when another input element is set - Adaptive Cards

Question: I am currently learning about Adaptive cards for using it in Power Automate to send them to Microsoft teams.
As an exercise I needed to build this card: Candidate FeedBack form
I built the card in the Microsoft Adaptive card designer and I got this card payload:
<code>{
"type": "AdaptiveCard",
"body": [
    {
        "type": "TextBlock",
        "size": "Medium",
        "weight": "Bolder",
        "text": "CANDIDATE FEEDBACK FORM"
    },
    {
        "type": "ColumnSet",
        "columns": [
            {
                "type": "Column",
                "width": "auto",
                "items": [
                    {
                        "type": "Image",
                        "url": "{CandidateUrl}",
                        "altText": "ProfilePicture",
                        "horizontalAlignment": "Left",
                        "style": "Person"
                    }
                ],
                "horizontalAlignment": "Center",
                "verticalContentAlignment": "Center"
            },
            {
                "type": "Column",
                "width": "auto",
                "horizontalAlignment": "Center",
                "verticalContentAlignment": "Center",
                "style": "emphasis",
                "items": [
                    {
                        "type": "TextBlock",
                        "text": "{Candidate Name}",
                        "wrap": true,
                        "color": "Dark"
                    }
                ]
            }
        ]
    },
    {
        "type": "Container",
        "backgroundImage": {
            "url": "https://www.solidbackgrounds.com/images/950x350/950x350-light-gray-solid-color-background.jpg"
        },
        "items": [
            {
                "type": "Input.Text",
                "placeholder": "Input candidate comments",
                "id": "CandidateComments",
                "isMultiline": true,
                "isRequired": true,
                "label": "Comments",
                "errorMessage": "You must set the candidate comments"
            },
            {
                "type": "Input.ChoiceSet",
                "choices": [
                    {
                        "title": "Hire",
                        "value": "Hire"
                    },
                    {
                        "title": "No Hire",
                        "value": "No Hire"
                    }
                ],
                "placeholder": "Placeholder text",
                "isRequired": true,
                "style": "expanded",
                "id": "Decision",
                "label": "Decision",
                "errorMessage": "You must select the decision"
            },
            {
                "type": "Input.ChoiceSet",
                "choices": [
                    {
                        "title": "Past experience in the topic area",
                        "value": "Experience"
                    },
                    {
                        "title": "Inclusive behaviors and work ethics",
                        "value": "Inclusivity"
                    },
                    {
                        "title": "Ability to work without supervision",
                        "value": "Independent"
                    }
                ],
                "placeholder": "Placeholder text",
                "isMultiSelect": true,
                "style": "expanded",
                "label": "Suggest follow-up discussion regarding:",
                "id": "Suggestion"
            }
        ]
    }
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0",
"actions": [
    {
        "type": "Action.Submit",
        "title": "Submit"
    }
]
}
</code>
The card is working ok but I got an idea and I have not been able to do it. The thing is that I would like that the Suggestion Choice element only appears if the user selects the "Hire" decision, because it does not have much sense to have a follow-up discussion with someone that you decided not to hire.
I noticed that the ChoiceSet has a property called "Only show when" but I only have been able to make it work using the sample data editor. For example when I add this data to the sample data editor:
<code>{
    "Test":"Testing"
}
</code>
And this expression in "Only show when": ${$root.Test == "Testing"}, It works but I don't need it to do it with sample data but when the id "Decision" is equal to "Hire". So that is the question, how can I achieve that the ChoiceSet is only shown when the id "Decision" is equal to "Hire".
PS: Other thing that I saw is that I can unmark the ChoiceSet as "Initially Visible" and there is an action "ToggleVisibility" which can make it visible, but I don't know how to trigger that action only when the Hire decision is chosen.
Thank you in advance!
Answer: You can't do it directly from the UI itself.  You can update the card when user submits it, but right now there is no such action available that can execute some event on checkbox check and uncheck.
Comment: Thank you. I had to use containers with the action toggle visibility as a workaround. Another thing that can work is using show card actions with the two decisions


Send Commands to socket using netcat

Question: I am sending text commands to a custom protocol TCP server. In the example below I send 2 commands and receive a response written back. It works as expected in telnet and netcat:
$ nc 192.168.1.186 9760
command1
command2
theresponse

not working when i tried in batch:
@echo off
cd..
cd C:\nc
nc 192.168.1.186 9760
00LI002LE99
end

Please help me on this.
Comment: Please elaborate what "not working" means.  What do you see happen, and what do you expect to happen?  Put your commands in a file called "commands.txt" and then run `nc 192.168.1.186 9760 < "commands.txt"`
Answer: When you run nc interactively, it takes input from standard input (your terminal), so you can interact with it and send your commands.
When you run it in your batch script, you need to feed the commands into the standard input stream of nc - just putting the commands on the following lines won't do that; it will try to run those as entirely separate batch commands.
You need to put your commands into a file, then redirect the file into nc:
nc 192.168.1.186 9760 < commands.txt

On Linux, you can use a "here document" to embed the commands in the script.
nc 192.168.1.186 9760 <<END
command1
command2
END

but I haven't found an equivalent for windows batch scripts. It's a bit ugly, but you could echo the commands to a temp file, then redirect that to nc:
echo command1^

command2 > commands.txt

nc 192.168.1.186 9760 < commands.txt

The ^ escape character enables you to put a literal newline into the script. Another way to get newlines into an echo command (from this question):
echo command1 & echo.command2 > commands.txt

Ideally we'd just pipe straight to nc (this isn't quite working for me, but I can't actually try it with nc at the moment):
echo command1 & echo.command2 | nc 192.168.1.186 9760

Comment: You may be able to use something like an echo tool with newlines on Windows to pipe a short multiline list into netcat.  It's also possible the destination system would accept the particular commands being used all on one line if separated with semicolons.
Comment: Have added a suggestion using a temp file - would be nice to do this with a pipe though. Good idea about semicolons.
Comment: I'd assumed so, but it's not working correctly for me (using `sort` command instead of `nc`, as I don't have `nc` installed on Windows), but will edit answer anyway...
Comment: Yes... windows seems to be broken (surprise!)  Sorry about that.

Send Commands to socket using netcat


Chrome trava com loop correto de JavaScript

Question: Estou tentando rodar o seguinte código, só que não consigo! É como se o navegador parasse de funcionar.
var scores = [60, 50, 60, 58, 54, 54,
58, 50, 52, 54, 48, 69,
34, 55, 51, 52, 44, 51,
69, 64, 66, 55, 52, 61,
46, 31, 57, 52, 44, 18,
41, 53, 55, 61, 51, 44];

for (var i=0; i < scores.length; i = i++) {
    console.log("Buble Solution #" + i + " Score: " + scores[i]);
}

Porém quando eu tento executar o sinônimo com o i = i + 1, dá certo!
Answer: Quando usas i++ acontecem duas coisas:

o i sobe de valor (soma +1)
essa ação retorna o i inicial

Pois, retorna o i inicial (antes de ser somado mais 1).
Experimenta:
var i = 0;
alert(i++); // 0
alert(i); // 1

Ou seja, no teu loop estás fazer o i tomar o valor do retorno de i++, ou seja: i = i++, o que é o mesmo que dizer i = 0... eternamente.
Daí o problema.
Quando usas i = i + 1 já não tem problema, e quando usas somente i++ (sem usar i =) também já não tem problema.
Comment: Muito bom! Obrigado! Me ajudou muito!
Comment: ou `++i` que incrementa a variável e depois retorna o novo valor. Ainda acredito que na sua situação, utilizar `forEach` seria mais performático..


Javadoc de JSF não localizado no Netbeans

Question: Uso o Netbeans 7.2.1 e queria saber porque somente o Javadoc de objetos do Java (java.lang, java.io, etc) são mostrados. Todos os outros (javax.*) mostra algo do tipo:

javax.faces.context
public abstract class FacesContext extends Object
O Javadoc não foi localizado. A documentação do Javadoc não existe para este item ou você não adicionou o Javadoc especificado no
  Gerenciador de Plataformas Java ou no Gerenciador de Bibliotecas.

Já tentei incluir a URL http://download.oracle.com/javase/7/docs/api no gerenciador de plataforma Java Ferramentas > Plataforma java > Javadoc mas não funcionou.
Answer: Você fez o correto para adicionar o Javadoc para a JDK, mas não para bibliotecas e componentes  que estão fora da JDK , como por exemplo o JSF, referenciado na sua pergunta.
Para adicionar o Javadoc desses componentes no NetBeans, você primeiro deve baixar esse Javadoc no site oficial da biblioteca ou usar o Javadoc online da própria biblioteca. Depois, crie seu projeto no NetBeans. Com o projeto criado:

Clique com o botão direito no projeto e selecione Propriedades;
Selecione no menu a esquerda Bibliotecas;
Na aba Compilar, selecione a biblioteca que você quer adicionar o Javadoc;
Clique no botão Editar;
Clique na aba Javadoc;
Adicione o arquivo baixado ou a URL do Javadoc;
Fim;
Comment: Em propriedades do projeto não existe o menu Bibliotecas. No item Compilar eu só tenho como selecionar ou gerenciar a plataforma (JDK)


Exposing sort breaks order

Question: In my view I am exposing two sort options in the following order:
Date > Newest First
Title > A-Z
When both sort options are exposed it will correctly display the nodes sorted by date but will randomly sort the nodes by title. So for example titles starting with a R will appear for nodes which have titles starting with a D. When I turn off exposing the Title sort it will display correctly. First sorted by date and correctly sorted from A to Z. But I do need to expose the Title sort. So what am I missing? Or is it just a bug?
My Views settings

Sort settings date field

Sort settings title field
Answer: It's not a bug. Node creation date is stored with hours, minutes and seconds. If you are sorting by creation time, only nodes created in the very same second will ever use secondary sort criteria - Unless you will set granularity:
Comment: Thanks, but the date field I'm using is not the Node creation date. It's a custom (date) field which offers no 'Granularity' when configuring the sort criterion. Your solution also doesn't explain why the sort is correct when I turn off exposing the title field.
Comment: @rroose So please post screenshots of how you configured fields and filters in question. Without them all I could do was to assume defaults.
Comment: I've added screenshots.

Exposing sort breaks order


7zip string/stream compression PHP/C? No file name / date store in .7z archive, every byte count

Question: I want compress 1 small file/data, only file size matter.
No need file information store, like filename, size, date, etc...
If I use rar/7zip/zip as CLI, file information added to archive. It's not good for me.
I finding the BEST compression solution for file size.
In PHP I can use gzdeflate() or bzcompress() to compress string then save to file as compressed. I finding a same or CLI solution.
Environment: Linux, 32/64 bit.
I want to use 7zip/7za as same for string/stream compression.
If I using a binary version of 7z, for example: 7za a -mx9 output.7z input.dat
But this time in .7z found file/date/size information and file size is bigger.
How can I use 7zip or other better compressor like as bzcompress or gzdeflate to compress data stream only, without file informations?
Maybe I cannot use 7zip actually in PHP because not supported yet.
Someone can recommend/create a small C/C++ CLI application/source or in other language what can usable in Linux CLI to compress 1 file and output to 1 file?
For example I want shell exec:
7zcpp input.dat output.7z
or
7zcpp -mx9 input.dat output.7z
Summary: Compression speed not important, only better, smaller file size. I want compress only 1 file (string/stream), every byte count, no need filename/date information inside the archive. I can use any better compressor than 7zip, but I think this is one of best actually. Any ideas, recommendations?
Thanks
Comment: File that contains what? How big is it?
Comment: Various files, like text files or images. Maybe from 7zip/LZMA2 SDK can be create this small application?
Comment: Strange, why no "experts" here about this topic. I'm surprised.
Comment: You don't seem to know about how data compression works, and you're asking us to write code for you. I'm not surprised.
Comment: Netcoder: NO, I just finding any program to do that what I described. Like a small program with 7zip or same algorithm WITHOUT file management, only compress data string/stream.
Comment: I'm surprised. No more info...
Answer: 7Zip memory compression functions - You could check out their SDK and try to look through the functions, - In (C, C++, Java and C#, too bad no php, unless you create your own php extension to bring 7z functionality into your app). In the LZMA SDK, go through the path C\Util\Lzma, find the LzmaUtil.c, it's a perfect example to help you . But I've personally used zlib, lzma compresses to 8% of data set size, compared to zlib's 12%, even though zlib is much faster. But since you don't give a shit about speed, lzma is best for you then
Comment: Any pre-compiled executables for my function to just compress without file information, no filename no date, etc?


Firebase.js: Authentication doesn't work as expected

Question: I'm trying to print Success on the console whenever the user enters the right email/password. I have entered a false info and it works, but with a correct user the console nor logs the success or appends to the errors div
 document.getElementById("login").addEventListener("click", function(){
            var email = $('#email').val();
            var password = $('#password').val();
            app.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
          // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;

            if (error) {
                console.log(error.message)
                  $("#errors").append('

'+ error.message + '

');

            }
              $("#errors").append('

Login Success, Welcome

');
              console.log("success")

         });
 });

Could anyone point out what i'm doing wrong?
Answer: This is because you try to detect a success in the catch() method.
Since the signInWithEmailAndPassword() method returns a Promise you should use the then() method as follows:
 document.getElementById("login").addEventListener("click", function(){
            var email = $('#email').val();
            var password = $('#password').val();
            app.auth().signInWithEmailAndPassword(email, password)
             .then(function(userCredential) {
                    console.log(userCredential.user);
                    $("#errors").append('

Login Success, Welcome

');
                    console.log("success")
             })
             .catch(function(error) {
             // Handle Errors here.
               var errorCode = error.code;
               var errorMessage = error.message;

               // if (error) { // Not needed anymore
                   console.log(error.message)
                    $("#errors").append('

'+ error.message + '

');

         });
 });

Comment: Awesome, Thank you <3
Comment: @excitedmicrobe Thanks! :-)