Redirect www to non-www

Question: I have my nginx config like::
# HTTP - redirect all requests to HTTPS:
server {
        listen 80;
        listen [::]:80 default_server ipv6only=on;
        return 301 https://$host$request_uri;
}

# HTTPS - proxy requests on to local Node.js app:
server {
        listen 443;
        server_name example.com;

        ssl on;
        # Use certificate and key provided by Let's Encrypt:
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

        # Pass requests for / to localhost:3000:
        location / {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://localhost:3000/;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_cache_bypass $http_upgrade;
                proxy_redirect off;
        }
}

Currently with the config above:
http://example.com get redirected to https://example.com.
And when I type http://www.example.com that gets redirected to https://www.example.com.
I would like the www requests to redirected to non-www
So if someone types http://www.example.com or https://www.example.com I would like it to be redirected to https://example.com. How would would I accomplish this?
Comment: Possible duplicate of [nginx rewrite from www to non-www](http://serverfault.com/questions/826463/nginx-rewrite-from-www-to-non-www)
Comment: You need another server block listening explicitly for the domains you want to forward. Please read a tutorial, or any of the answer on this site that would answer your question. I have a tutorial here https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-pt1-introduction-configuration-downloads/
Comment: @Tim, there is no need for a separate `server` block.
Comment: @TeroKilkanen, I guess using default server works if it's the only site Nginx is running, but it's not how I do it. Also, if you want to forward https://www to https:// I think the only way is another server block. I'll provide an answer that illustrates, but I really think this is too trivial, it's been asked and answered 100 times.
Answer: You need to replace
# HTTP - redirect all requests to HTTPS:
server {
    listen 80;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://$host$request_uri;
}

with:
# HTTP - redirect all requests to HTTPS:
server {
    listen 80;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://example.com$request_uri;
}

This way nginx does not use the Host header in the client request for determining the host for redirection.
Answer: Here's the standard Nginx site setup to forward to non-www https website
# Main website, https non-www
server {
  server_name example.com;
  listen 443 ssl http2; # http2 is optional
  # locations, ssl configuration, etc
}

# forward https www to non-www
server {
  server_name www.example.com;
  listen 443 ssl;
  return 301 https://example.com$request_uri;
}

# Forward http to https
server {
    listen       80;
    server_name  example.com www.example.com;
    access_log  /var/log/nginx/access.log main buffer=128k flush=1m if=$log_ua;
    return       301 https://example.com$request_uri;
}

Redirect www to non-www


Prevent users from accessing admin area

Question: Good Day,
am Facing a code error with my Admin control panel PHP page.
I want to prevent any other user from accessign this page unless his job_title= admin.
it works but even the admin himslef redirects back to login page again !!
here is the code
<?php
include('db.php');
?>
<?php
// Inialize session
@session_start();
ob_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['name']) || ($_SESSION['job_title'] != "admin")) {
header('Location: index.php');
}
ob_flush();
?>
>?

?>

Any help ?
Comment: If you remove `@` before `@session_start();` is any error reported?
Comment: @mschr yes but they are alot :D
Comment: @PLB always reports " session start error function"
Comment: Are you sure that the values in $_SESSION are being set correctly on the login page? What is in there if you print them out at the top of your validation code?
Comment: @MinaWilson Session does not start, maybe it's already started. can you let me see reported error completely?
Answer: Try this, if still problems, let me know.
$_SESSION['name'] = 'dennis';
$_SESSION['job_title'] = 'admin';
if (!isset($_SESSION['name']) || (!isset($_SESSION['job_title']) ? false: ($_SESSION['job_title'] !== 'admin'))) {
    echo 'Redirecting';
} else {
    echo 'You\'re good! Not redirecting!';
}

This may be an easier way to understand, just put into a function.
$_SESSION['name'] = 'dennis';
$_SESSION['job_title'] = 'admin';

if (!isset($_SESSION['name']) || !isBoss()) {
    echo 'Redirecting';
} else {
    echo 'You\'re good! Not redirecting!';
}

function isBoss() {
    if (isset($_SESSION['job_title']))
        if ($_SESSION['job_title'] === 'admin')
            return true;
    return false;
}

Comment: `$_SESSION['name']` is always defined and function `isBoss()` always returns true using this script. By the way, that function could be more readable and only one line: `return (isset($_SESSION['job_title'] && $_SESSION['job_title'] === 'admin') ? true : false;`
Comment: I broke it down so he could understand what is going on in the first example. isBoss() won't always be true because if the session['job_title'] is not defined or is not admin it will return false. I declared the session name and job title for my testing only.
Comment: Session is started, you define `$_SESSION['job_title'] before you call your function and session is never destroyed.
Comment: Please see my edited post. I stated they are only there for testing purposes.
Answer: I think your problem is a fubar newline :) Have added login page reference, which is unsetting the session variables you check for if logins fail.
Be very careful with where you put your <?php ?> tags - and in .inc files, such as db.php include - you may leave out the closing ?> tag on last line to avoid accidental ENTER, then CTRL + S failures, sneaking in an unwanted newline char in your output buffer (ob). IF ob_start is activated, nothing is written from server before you choose or script ends. ELSE if its not, default is that every \n will flush output and start the Content part of the payload.
login.php:
<?php
session_start(); // put this on top-most line in your script
$ok = check($_POST['user'], $_POST['pass']);
if($ok) {
 $user = db_get_user_creds($_POST['user']);
 $_SESSION['name'] = $user['name'];
 $_SESSION['job_title'] = $user['job_title'];
} else {
 // session_unset();
 unset($_SESSION['name']);
 unset($_SESSION['job_title']);
}
?>

admin.php
<?php
session_start(); // put this on top-most line in your script
// or, use ob_start at the very first line
// (with no widespace what so ever written out before it)

include('db.php');
?> I am writing out a newline here, session / header section is going to become unstable
<?php
// Inialize session
// @session_start(); moved up top
ob_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['name']) || ($_SESSION['job_title'] != "admin")) {
header('Location: index.php');
}
ob_flush();
?>

See the 'I am writing out newline here' bit
A little deeper down rabbithole goes; the communication flow is like this:
1) HEADERS such as
Connection: keep-alive\r\n
Content-Type: text/html\r\n    (etc)
2) DOUBLE NEWLINE (one newline with no previous chars on that line)
\r\n
3) CONTENTS
Body
Of Page

Prevent users from accessing admin area


Simple regex pattern in C#

Question: I've been trying to do this for some time now, but my Regex skills are pretty bad.
I have this text

    One

    Two

And I want to get the value of "Two". I've tried multiple things like
\n(.*)\n
\nOne\n	\n\n(.*)\n

And this is my C# source
foreach (Match m in Regex.Matches(src, pattern, RegexOptions.IgnorePatternWhitespace))
{
    MessageBox.Show(m.Groups[1].Value);
}

I tried changing the RegexOptions with no luck. If anyone could help me it'd be greatly appreciated.
Thank you
Comment: Use XElement class, it is much easier.
Comment: use `HTML agility pack` it would be much simpler rather then now
Comment: XElement.Parse(").Elements("td").Last().Value
Answer: Why not simply :
string expression = @"\[\s]*[A-Za-z]*[\s]*\";

And if you want to name your group
string expression = @"\[\s]*(?<groupName>([A-Za-z]*))[\s]*\";

Answer: Use the s (DotAll) modifier forcing the dot . to match newline sequences as well.
foreach (Match m in Regex.Matches(src, @"(?s)\s*(.*?)\s*	"))
         MessageBox.Show(m.Groups[1].Value);

Note: Follow .* with ? for a non-greedy match here.
Answer: Enable dotall(s) modifier to make . to match a newline character.
(?<=)\s*(\w*)\s*(?=<\/td>)

DEMO
And your code would be,
Regex rgx = new Regex(@"(?s)(?<=)\s*(\w*)\s*(?=<\/td>)");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[1].Value);

Simple regex pattern in C#


starting an activity crashes

Question: I have a service and a listener to locations notifications.
When a location notification is received, I want to start an activity.
The call to startActivity, crashes every time, and I do not understand why?
How can I do this?
my Service:
public class MyService extends Service {
    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
          super(looper);
        }
        @Override
        public void handleMessage(Message msg)
        {
          synchronized (this)
          {
            Bundle data = msg.getData();
            handleRequest(data);
          }
        }
}

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("OpenAppThread");
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
...

My location notifier
public class LocationNotifier implements
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener,
    LocationListener {

    private MyService mContext;

public void onLocationChanged(Location locationHere)
{
    Intent intent = new Intent(mContext, AnotherActivity.class);
    mContext.startActivity(intent);  // This Crashes !!!

Comment: Likely because mContext = null. Do you ever pass your context to your LocationNotifier class?
Comment: you forgot to post the most important part: the logcat output
Comment: @zgc7009 is probably right. If so, you should be receiving a NPE in your method.
Answer: 1.- Check if your context is different to null.
2.- Check if your activity is registered in the manifest.
3.- Check if the onLocationChanged is a infinite bucle.
If you can copy and paste the logcat, that is a information useful to we can help you.

starting an activity crashes


Over/under pitch note

Question: I know there is a quarter tone notation, but is there a symbol for music score that will simply say over/under pitch? I think quarter tone notation might be too strict/rigid in music arrangement that is not quarter tone at all, just some solo parts requires this specific intonation.
I'm transcribing the vocal part of the song. She sings some notes deliberately over/under pitch, and I have no idea how to smuggle this subtlety into violin part. Should I care about such subtle things at all? Or leave it "dry" and rather rely on the performer's interpretation?
Comment: Yeah, Bartók used up- and down-arrows in his Violin Concerto no. 2, which is somewhat related to this proposal, and about the right level of detail for your notation problem.
Comment: If I couldn't find anyone who has done it before, I would invent a symbol for slightly sharp and another for slightly flat and put a key at the top of the score.
Answer: There is a notation form I have come across called Sagittal notation.  It seems pretty comprehensive for microtonic notation.

The Sagittal notation system is a comprehensive system for notating musical pitch in all possible scales and tunings - a universal set of microtonal accidentals, equally suited to extended just intonation, equal divisions of the octave (or of any other interval), or any of the non-just non-equal "middle path" tunings or temperaments. It is called Sagittal because, you guessed it, it uses various arrow-like symbols, pointing up or down to indicate raising or lowering of pitch.

It is described in detail here:

http://www.sagittal.org/sagittal.pdf

Over/under pitch note


Poweredge 2650 RAC Card setup

Question: I have a Poweredge 2650 with RAC 3.37 installed.  Recently acquired the server and I have found some difficulty in setting up the RAC.  On booting normally you can setup the IP, Gateway, Netmask and DNS in a regular boot up "Press Control + D to setup Remote Access" screen.
There is no where on this menu that allows you to set a RAC password!
So i set the system/setp passwords in the F2 setup bios page.
no luck here either.
Throughout the trial I can ALWAYS get to the RAC login page.
"root"/"calvin"&systempassword do nothing for me.
Any thoughts guys/gals(i have to assume there atleast a few female geeks out there...)
Bios Rev of 2650 is A21.
Answer: A few quick searches suggest that if root/calvin isn't working when you use the racadm tool, your best bet may be to disconnect the battery on the RAC and let it drain to see if it resets to factory defaults.
All of the references to the racadm tool, whether going in via telnet or serial require that you authenticate yourself (specifically have the ConfigureDracIII permission bit).  I assume the problem here is that you're working with a system that you have physical but not root access to.
I did find this musing about using the on-board jumpers to do the same thing:
http://newsgroups.derkeiler.com/Archive/Alt/alt.sys.pc-clone.dell/2006-04/msg00949.html
but it was speculation on the part of the original poster.
Comment: Absolutely correct, i do have physical access.  I will unplug the battery when I get home and give it 10 mins to discharge.
Comment: Hmmm, it doesnt look like there is a battery on the RAC for the 2650.  Any other thoughts?
Answer: I'd start here, with the Dell manuals: http://support.dell.com/support/edocs/software/smdrac3/RAC/en/is/index.htm
Answer: The answer was to sell the server and buy a new one.  Never found reliable information to resolve this.

Poweredge 2650 RAC Card setup


Free algebra (Boolean algebra)

Question: Could someone give me a simple explanation of Free Algebra on $\kappa$. How to construct free($\omega$).
here is it says
http://en.wikipedia.org/wiki/Free_Boolean_algebra
free($\omega$) is equal to the collection of all clopen of cantor space. How ?
Answer: This is my understanding of free boolean algebras, or equivalently free boolean rings:
The free commutative ring on a set $S$ is the polynomial ring $\mathbb{Z}[\{X_i\}_{i \in S}]$. In order to make it boolean, we have to ensure $2=0$ and $X_i^2=X_i$. That is, we take $B(S): =\mathbb{F}_2[\{X_i\}_{i \in S}]/(X_i^2-X_i)_{i \in S}$. This is easily seen to be a boolean ring. In fact, it is the free boolean ring on $S$, i.e. $S \mapsto B(S)$ is left adjoint to the forgetful functor from boolean rings to sets.
Observe that $B(S) = \bigotimes_{i \in S} \mathbb{F}_2[X_i]/(X_i^2-X_i)$ (tensor product of $\mathbb{F}_2$-algebras), and the Chinese Remainder Theorem implies $\mathbb{F}_2[X_i]/(X_i^2-X_i) \cong \mathbb{F}_2 \times \mathbb{F}_2$. In particular, we have $\dim_{\mathbb{F}_2} B(S) = 2^{|S|}$ when $S$ is finite;  more precisely we have $B(S) \cong \mathbb{F}_2^{2^{|S|}}$ (using that tensor products commute with finite products).
For general $S$, we have that $B(S)$ is the colimit of the $B(T)$, where $T$ runs through the finite subsets of $S$. It follows that $\mathrm{Spec} B(S)$ (the corresponding Stone space) is the limit of the discrete spaces $\mathrm{Spec} B(T) \cong  \{0,1\}^T$, i.e. that $\mathrm{Spec} B(S) = \{0,1\}^S$. For countable infinite $S$ this is the Cantor space, and corresponds to the colimit of the boolean rings $\mathbb{F}_2^{2^n}$ with transition maps $A \mapsto (A,A)$, which may be denoted as $\mathbb{F}_2^{2^{\infty}}$. This is analoguous to the Bratteli diagram of the AF-algebra corresponding to the Cantor space, which is basically the same with $\mathbb{F}_2$ replaced by $\mathbb{C}$.
Comment: Thanks dear Martin for this info. This is from Categorical & Ring Theory  point of view. it is little bit hard for me but at least I got some ideas. Let's wait for another volunteer to give some simpler explanation and from Boolean algebra or topological or measure point of view.

Free algebra (Boolean algebra)


Failure in artifact upload in Apache ACE

Question: I have seen in the documentations of ACE that one of the reasons for failure during upload of new artifacts is when type of artifact is not recognized. But what are the other reasons? For example why this error occurs even after uploading a jar file?
Answer:
Out of the box, ACE comes with support for bundles and configuration
  files that follow the Auto Configuration specification. However, it is
  possible to extend ACE with support for new types of artifacts. Doing
  so requires you to do three things:

Write a resource processor, according to the Deployment Admin
  specification.
Write an ArtifactHelper service implementation.
Write an ArtifactRecognizer service implementation.

https://ace.apache.org/dev-doc/adding-custom-artifact-types.html
This means that you can only upload .jars that are bundles (OSGi compliant) and configurations. Regular jars will not work unless you follow the steps described in the manual.
Hope that helps.


Net compactness and relative compactness

Question: I'm trying to understand the relation between the following conditions. I will assume that $X$ is a Hausdorff topological space and $A \subset X$.

$\overline{A}$ is compact;
Every net $\{x_{\lambda}\}_{\lambda \in \mathbb{L}} \subset A$ has a subnet converging to some point;

It is clear to me that $1 \Rightarrow 2$. I read that $2 \Rightarrow 1$ if $X$ is regular, but I am not able to find a proof. I would like to have a proof and, if possible, an explicit example in which the implication $2 \Rightarrow 1$ is false.
Comment: Well I was also asking for an example in the non regular case. Your answer was quite helpful honestly. Can you write it back? Also the comment on the non regularity of the space: I was trying to understand it and everything disappeared! If you want also to provide a proof for he regular case, you are welcome!
Comment: I have added a second proof to my answer which you may be interested in, and which I would consider the "right" way to think about regularity in this context.
Answer: I find these things easier to think about in the language of filters.  Using the usual correspondence between nets and filters, (2) is equivalent to saying that every filter on $X$ containing $A$ has an accumulation point in $X$.
So, suppose $\overline{A}$ is not compact, and we will find a filter containing $A$ with no accumulation point in $X$.  Since $\overline{A}$ is not compact and is closed in $X$, there is a filter $F$ containing $\overline{A}$ with no accumulation point in $X$.  Let $G$ be the filter generated by all open elements of $F$ together with $A$.
First, I claim $G$ is a proper filter.  Indeed, suppose $U\in F$ is open.  Then $U\cap \overline{A}\in F$ since $\overline{A}\in F$.  Since $U$ is open and $A$ is dense in $\overline{A}$, this means $U\cap A$ is nonempty.  Since every element of $G$ contains a set of the form $U\cap A$, this means $G$ is a proper filter.
Second, I claim $G$ has no accumulation point in $X$, and is thus our desired filter since $A\in G$.  Indeed, let $x\in X$ be any point.  Since $x$ is not an accumulation point of $F$, there is an open neighborhood $U$ of $x$ such that $X\setminus U\in F$.  By regularity, there are disjoint open sets $V$ and $W$ such that $x\in V$ and $X\setminus U\subseteq W$.  Then $W\in G$, and hence $X\setminus V\in G$, and hence $x$ is not an accumulation point of $G$.

Here is another proof which is a bit more complicated at first glance but which nicely conceptualizes the role of regularity.
Recall that if $X$ is a set, then the set $\beta X$ of ultrafilters on $X$ has a natural compact Hausdorff topology, which has as a basis the sets $U_A=\{F\in\beta X:A\in F\}$ for each $A\subseteq X$. If $X$ is a Hausdorff space, we will write $C_X\subseteq\beta X$ for the set of ultrafilters that converge in $X$ and $L:C_X\to X$ for the map taking an ultrafilter to its limit.  We then have the following remarkable characterization of regularity.

Theorem: Let $X$ be a Hausdorff space.  Then $X$ is regular iff $L:C_X\to X$ is continuous.
Proof:  Suppose $X$ is regular.  Let $F\in C_X$, write $x=L(F)$, and suppose $U$ is a neighborhood of $x$.  By regularity, let $A$ be a closed neighborhood of $x$ contained in $U$.  Then $A\in F$ since $A$ is a neighborhood of $x$, and if $G\in C_X$ and $A\in G$ then $L(G)\in A$ since $A$ is closed.  Thus $U_A\cap C_X$ is a neighborhood of $F$ in $C_X$ whose image under $L$ is contained in $U$, as desired.
Conversely, suppose $X$ is not regular; let $x\in X$ with a neighborhood $U$ which contains no closed neighborhood of $x$.  For each neighborhood $V$ of $x$, its closure is not contained in $U$, so we can pick an ultrafilter $F_V$ which contains $V$ and converges to a point $L(F_V)\not\in U$.  Consider these $(F_V)$ as a net in $\beta X$, indexed by the directed set of neighborhoods of $x$ ordered by reverse inclusion.  By compactness of $\beta X$, this net has a subnet converging to an ultrafilter $F$.  Since $V\in F_V$ for all $V$, this limit $F$ must contain every neighborhood of $x$; that is, $L(F)=x$.  However, the net $(L(F_V))$ is entirely outside the neighborhood $U$ of $x$, so no subnet can converge to $x$.  Thus $L$ fails to preserve the convergence of this subnet and is not continuous.

Using this theorem, proving $2\Rightarrow 1$ for regular spaces is quite natural.  In terms of ultrafilters, (2) says that every ultrafilter containing $A$ has a limit in $X$.  Now suppose this is true and let $(x_i)$ be a net in $\overline{A}$.  For each $i$, we can pick an ultrafilter $F_i$ containing $A$ which converges to $x_i$.  By compactness of $\beta X$, there is a subnet of $(F_i)$ that converges to some ultrafilter $F$, which will still contain $A$.  By (2), $F$ converges to some $x\in\overline{A}$.  Since $X$ is regular, the theorem says that the corresponding subnet of $(x_i)$ converges to $x$.  Thus $(x_i)$ has a convergent subnet.  Since $(x_i)$ was an arbitrary net in $\overline{A}$, this means $\overline{A}$ is compact.

Finally, here is an example of how $2\Rightarrow 1$ can be false if $X$ is not regular.  Let $X$ be the closed unit disk and let $A\subseteq X$ be the open unit disk, and say a subset $C\subseteq X$ is closed if it contains the closure of $C\cap A$ with respect to the usual topology.  This defines a topology in $X$ (another way to describe it is you take the usual topology and then enlarge it by declaring that every subset of the unit circle $X\setminus A$ is closed, and take the topology that generates; so a closed set in $X$ is just a union of a closed set in the usual topology and an arbitrary subset of $X\setminus A$).
Now $\overline{A}=X$ is not compact, since $X\setminus A$ is closed in $X$ but is not compact since it is infinite and discrete.  However, every net in $A$ has a limit in $X$.  Indeed, every net in $A$ has a subnet converging to some point of $X$ with respect to the usual topology by compactness, and the same is true of the topology of $X$ since nets in $A$ which converge with respect to the usual topology still converge with respect to the topology of $X$.
Comment: @Jakobian I don't know of any result along those lines.  One obstacle is that if $X$ is finite then $C_X$ is discrete so any map out of it is continuous, even though $X$ may not be regular.
Comment: @Jakobian: Though, I guess one reformulation you can give for non-Hausdorff spaces is: $X$ is regular iff whenever $(F_i)$ is a net of ultrafilters converging to an ultrafilter $F$, if $F_i$ converges to $x_i$ and $F$ converges to $x$, then $(x_i)$ converges to $x$.  (Note in particular that taking $F_i=F$ for all $i$, this implies that if an ultrafilter has two different limits in $X$ those limits must be topologically indistinguishable, so that the $T_0$ quotient of $X$ is Hausdorff, so this theorem is easily reduced to the Hausdorff case.)
Comment: Thank you very much for your answer. I still have to understand all the details. Is this topology regular?
Comment: No; in fact it's a fairly well-known example of a Hausdorff space that is not regular.  For instance, if you pick a point $p\in X\setminus A$ and a small open ball $B$ around $p$, then $\{p\}\cup(B\cap A)$ is open but does not contain any closed neighborhood of $p$ (any closed neighborhood would have to contain points near $p$ in $X\setminus A$).
Comment: Thank you very much for having posted it again. I see, it is a very nice example! Do you know how to conclude the proof in the regular case i.e. how to prove that $p$ is a cluster point for the original net?
Comment: I have added a proof in the regular case.
Comment: Thank you very much for both proofs! I am not very familiar with filters, but I will try to understand everything. However, I'm still trying to use nets but maybe it's not possible in this particular case..
Comment: Thank you for sharing this theorem! The reason why we are assuming that $X$ is Hausdorff, is for the function $L$ to be well-defined. However, is it possible even if $X$ isn't Hausdorff, to define $L:C_X\to Y$, where $Y = 2^X$ is the hyperspace of non-empty subsets of $X$ with appropiate topology? Perhaps the Vietoris topology? So that the continuity of $L$ tells us something about the underlying space $X$.
Comment: The reason this formulation doesn't easily translate into a continuity condition is that the $F_i$ and $F$ may not be distinct even if the $x_i$ and $x$ are so there is not a well-defined function whose continuity you are talking about.  To get a continuity statement you have to replace the domain $C_X$ with a larger domain that distinguishes all the $F_i$ and $F$.  (This is essentially what I did in my answer to your question, with the $F_i$ becoming the points in $S$ and $F$ becoming the point $\infty$.)
Answer: IIRC the proof is along these lines:
If we have a net $x_i, i \in I$ that is defined on $\overline{A}$, we need to proof it has a convergent subnet (or cluster point) in $\overline{A}$. For each $i \in I$ we find some net $a_j, j \in N_i$ on $A$ that converges to $x_i$ (as $x_i \in \overline{A}$ this is possible). Then using a Kelly-like diagonal construction we combine these nets in a "super-net" on $A$ and then using the given we have some cluster point on $p \in \overline{A}$ of this super-net, and using closed neighbourhoods of $p$ we can find a subnet of the original net $(x_i)_{i \in I}$ that converges to $p$ too.
Comment: Thank you. Can you please expand the last part? It is exactly where I have troubles, to show that p is a cluster point for the original net.
Comment: Hi professor Brandsma, could I ask your assistance [here](https://math.stackexchange.com/questions/3682336/vq-le-sum-i-1k-vq-i-where-q-1-q-k-are-rectangles-that-cover-the-r/3682377#comment7567159_3682377)?


Retornar resultados do banco de dados

Question: Bom dia pessoal sou novo na programação estou criando um sistema de consulta e cadastro de usuários, porém não estou conseguindo retornar os itens já cadastrados
include_once("ConexaoBigData.php");

$nome = $_POST['Nome'];
$email = $_POST['Email'];

$sql = "insert into Funcionarios (Nome,Email) values ($nome, $email)";

 $salvar = mysqli_query($conexao,$sql);

 $linha = mysqli_affected_rows($conexao);

mysqli_close($conexao);

Comment: Não entendi, você não consegue retornar, isso é papo pra select, e porque você posta um Insert?
Comment: Acabei confundindo, nesse cado seria Select * from e o nome da tabela Obrigado !
Comment: Edite sua pergunta colocando o código pertinente a dificuladade
Comment: Usa qual versão do PHP? Talvez seja interessante usar PDO também https://www.php.net/manual/pt_BR/book.pdo.php
Answer: Você está fazendo apenas o insert. Tente assim:
include_once("ConexaoBigData.php");

$nome = $_POST['Nome'];
$email = $_POST['Email'];

$sql = "insert into Funcionarios (Nome,Email) values ($nome, $email)";

 $salvar = mysqli_query($conexao,$sql);

 $linha = mysqli_affected_rows($conexao);

$funcionarios = mysqli_query($conexao, "select * from Funcionarios");

mysqli_close($conexao);

Com isso você terá populado a variável funcionarios com os registros existentes na tabela e poderá utilizar ela onde você quiser no seu código.

Retornar resultados do banco de dados


Custom action bar for each fragment - not menu

Question: Let me explain first: my application is planed to use 3 activities with swipe navigation. I am using different sherlock action bar for each one of them.
But since it is not possible to swipe between activities, the only solution is to work with fragments. I implemented that, but I came across a problem: is it possible to customize action bar for each fragment? Because now I'm stuck only with one. I've Googled and every solution is based on a menu, but is it possible to apply custom styles to menus and in fragments?
Sorry if this was already answered, I haven't found any solution online.
Is it possible to use this kind of approach?
public class ControlActivity extends SherlockFragmentActivity {
<code>ActionBar actionBar;
View actionBarView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewpager_layout);
    ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    actionBar = getSupportActionBar();
    actionBarView= getLayoutInflater().inflate(
            R.layout.friend_list_ab_layout, null);
    actionBar.setCustomView(actionBarView);

}
private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public SherlockFragment getItem(int pos) {
        switch(pos) {

            case 0:
                actionBarView= getLayoutInflater().inflate(
                        R.layout.friend_list_ab_layout, null);
                actionBar.setCustomView(actionBarView);
                return MainActivity.newInstance();
            case 1:
                actionBarView= getLayoutInflater().inflate(
                        R.layout.news_feed_ab_layout, null);
                actionBar.setCustomView(actionBarView);
                return NewsFeed.newInstance();
            default:
                actionBarView= getLayoutInflater().inflate(
                        R.layout.friend_list_ab_layout, null);
                actionBar.setCustomView(actionBarView);
                return MainActivity.newInstance();
        }
    }
    @Override
    public int getCount() {
        return 2;
    }
}
</code>
}
Answer: well you can build your own action bar, what i mean to say is that you should create a dynamic  fragment and use it at an action bar and give it styling a as action bar, use frame layout as a plcaeholder for the fragment and when you swipe the fragment replace the actionbar fragment with new one
Comment: Your solution seems to be reasonable, but is it possible to use approach like i am suggesting in edited first post?


C : error while writing file using UDP socket

Question: I have to send over UDP 1024 byte of a file (in this example a txt file) to a server and write this bytes in an output file. I receive this error:
write(): bad address
I need to pass bytes through a data structure, so created a struct named "pkt" with a void *buf where i can write bytes.
This is my example program.
Client side:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define SERV_PORT           5197
#define MAX_BLOCK_SIZE      1024

struct pkt {
    void *buf;
    int num;
};

int main(int argc, char *argv[]) {

    if (argc != 3) {
        fprintf(stderr, "Usage: %s <IP SERVER> <file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd;
    struct sockaddr_in addr;
    int fd;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        perror("socket()");
        exit(EXIT_FAILURE);
    }

    memset((void*)&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(SERV_PORT);

    if (inet_pton(AF_INET, argv[1], &addr.sin_addr) <= 0)
    {
        perror("inet_pton()");
        exit(EXIT_FAILURE);
    }

    fd = open(argv[2], O_RDONLY);
    if(fd == -1)
    {
        perror("open()");
        exit(EXIT_FAILURE);
    }
    //READ FILE
    ssize_t n;
    void *buf;

    buf = alloca(MAX_BLOCK_SIZE);
    n = read(fd, buf, MAX_BLOCK_SIZE);
    if(n != MAX_BLOCK_SIZE)
    {
        perror("read()");
        exit(EXIT_FAILURE);
    }

    struct pkt packet;
    packet.buf = buf;
    packet.num = 0;

    if(sendto(sockfd, &packet, sizeof(struct pkt), 0, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        perror("sendto()");
        exit(EXIT_FAILURE);
    }

    close(fd);

    return EXIT_SUCCESS;

}

server side:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define SERV_PORT           5197
#define MAX_BLOCK_SIZE      1024

struct pkt {
    void *buf;
    int num;
};

int main() {
    int sockfd;
    struct sockaddr_in addr;
    socklen_t len;
    int output;

    output = open("test.txt", O_WRONLY|O_CREAT, 0664);
    if(output == -1)
    {
        perror("open()");
        exit(EXIT_FAILURE);
    }

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        perror("socket()");
        exit(EXIT_FAILURE);
    }

    memset((void*)&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(SERV_PORT);

    if(bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        perror("bind()");
        exit(EXIT_FAILURE);
    }

    while (1) {
        len = sizeof(addr);
        ssize_t n;

        struct pkt packet;
        n = recvfrom(sockfd, &packet, sizeof(struct pkt), 0, (struct sockaddr*)&addr, &len);
        if( n < 0)
        {
            perror("recvfrom()");
            exit(EXIT_FAILURE);
        }

        printf("Packet number %d\n", packet.num);

        void *buf = (packet.buf);

        if (write(output, buf, MAX_BLOCK_SIZE) == -1) {
            perror("write()");
            exit(EXIT_FAILURE);

        }
    }

    return 0;
}

Comment: What do you expect `sizeof(struct pkt)` to return?
Comment: The size of my `pkt` data structure
Comment: Do you expect your 'packet.buf' to mean anything upon receipt?
Comment: @Simon And what do you think the size of that struct is??? Why not just use raw buffers to read the data into?
Comment: The " packet.buf " must contain the bytes I want to write. It is filled by the client.
Comment: Ohwait, it gets worse, 'alloca' on client side, so data is well and truly gone when server gets the pointer to it that is invalid anyways..
Comment: @Simon - OK, but the client is not sending that data!
Comment: @MartinJames Why the client is not sending my packet? I have passed an address in sendto()
Comment: @mathematician1975 Maybe the size is 1024 + sizeof(int)
Comment: @Simon - it is, but the data pointer within will not be valid at the other end.  In fact, by the time the datagram is received, the pointer will not be valid at either end.
Comment: @MartinJames But in case i have to pass an array of integer, i have to equally pass the pointer of this array...
Answer: this line:
packet.buf = buf;

is the main problem with the code.
All this line does is copy a pointer to buf.
so when the sendto() is executed, the pointer is sent, not the contents of buf.
suggest :
replace:
struct pkt {
    void *buf;
    int num;
};

with
struct pkt {
    char buf[1024];
    int num;
};

and replace this:
packet.buf = buf;

with
memcpy( packet.buf, buf, sizeof( packet.buf ) );

Comment: Thanks, it works. But if i need to send a jpg, or pdf, or another file...i can send it using a "char" buffer?


Does subtracting a positive semi-definite diagonal matrix from a Hurwitz matrix keep it Hurwitz?

Question: I am having a linear algebra problem here. I will be grateful if someone can help me.

Let $A\in \mathbb{R}^{n\times n}$ be Hurwitz and diagonizable, and let $B$ be a diagonal matrix whose diagonal elements are non-negative. Is $A-B$ still Hurwitz?

I know that if $B=cI$, where $c$ is a positive scalar, $A-B$ is a Hurwitz matrix. However, I am not sure whether $A-B$ is still a Hurwitz matrix when some diagonal elements in $B$ are zero and the others are positive. Are there any general results on the similar topic?
Thanks in advance!
Comment: Yes. Sorry about the unclear statement. I mean that all the eigenvalues of $A$ have negative real part.
Answer: No. Random counterexample:
$$
A=\pmatrix{-4&3\\ -2&1},\ B=\pmatrix{3&0\\ 0&0},\ A-B=\pmatrix{-7&3\\ -2&1}
$$
The eigenvalues of $A$ are $-2$ and $-1$; hence $A$ is Hurwitz and diagonalisable over $\mathbb R$. However, $A-B$ is a $2\times2$ real matrix with negative determinant, so it has exactly one positive eigenvalue and one negative eigenvalue.
Comment: Thanks for your help!  For your example, if $B=\left[\begin{array}{cc}0& 0\\0 & b\end{array}\right]$, where $b>-0.5$,  $A-B$ will always be Hurwitz stable. I suppose for other cases there exist similar conditions to ensure Hurwitz. It seems that even if no general condition exists but a relaxed version of the statement under study can be explored case by case.
Answer: If $A$ is not only Hurwitz, but also symmetric, then it is negative definite and, thus, $-A$ is positive definite. Let
$$D := \mbox{diag} (d_1, d_2, \dots, d_n)$$
where $d_i \geq 0$, be a positive semidefinite diagonal matrix. Hence, $-(A-D) = -A + D \succ 0$ and, thus, $A - D \prec 0$. As $A-D$ is negative definite, it is also Hurwitz. We conclude that Hurwitz-ness is preserved when $A$ is symmetric.
Comment: Thanks! This also gives a good perspective of the problem. Another interesting problem is to find conditions to make $A+D\prec 0$. Let $\overline{\delta}$ be the supremum of the eigenvalues of $A$, and $\overline{d}$ be the supremum of all the elements of $D$, then if $\overline{\delta}+\overline{d}<0$, the statement holds.


Use entity reference to target revisions of an an entity

Question: I'm building a custom entity document which supports revisions. Revisions are seen as versions of the document (v1.1, v1.2, ...), the title field is revisionable as well.
Then there is a custom entity customer, which needs to accept documents. On creation of a customer, I need to point out which revision of the document is suitable for this customer.
I have an entity reference field on the customer to target a document. However, I'm not achieving to target revisions of a document.
I tried entity reference display in views (with a view that supports revisions) but I'm not able to select it in the field settings (no eligible view found). Probably because I can only select 'Document' as target type and not 'Document revisions'.
I tried entity reference revisions module but gave me the same results. This module just keeps track of changes in parent vs child revisions (I guess).

I would expect document revisions being available in the settings above!

Any suggestions on how to do this properly, am I missing something? I want to make use of core as much as possible for this one.
Update: I ended up creating a custom field plugin to get the required solution.
Comment: By concept this cannot work with core and an entity reference field, as it only allows to store a `target_id`. You'll need ERR as @M.Anagnostopoulos pointed out, this field type stores a `target_id` and a `target_revision_id`
Comment: I'm not sure ERR works in this context. It was developed for the very close 1:1 relationship of paragraphs with their parent, which keep track of changes parent vs child as the OP has mentioned.
Comment: have you tried the [Entity Reference Revisions](https://www.drupal.org/project/entity_reference_revisions) module?
Comment: Yes, I did but didn't work. I'll update this in my question as well.
Comment: Maybe it would be best if we focused on the EER module for the time being while trying to tackle this issue, how exactly did it not work? could you edit your question with details on how you used/configured it. There might be a catch in it which you missed.
Comment: I updated question with screenshots. As 4K4 points out, ERR is not doing the trick here.
Answer: Revisions are stored in a separate db table from content. Views module makes you choose the base table for the query to the database when you're creating a new View (it's commonly called Views type: Content, User, Media, Taxonomy terms).
The easiest way to allow an Entity Reference Field to choose a particular Revision of a Content item is to build the list of Content Revisions items, and not a list of Content items.
Create a new Views entirely but this time choose Content revisions under Show, and not Content (you can't change that from within your existing Content type Views).
Your aim it to have a separate revision in each Views row, because when you're using that list within an ER Field each Views row becomes one checkbox/radio button to select when you're creating a new node.
Revisions can be grouped by their original content ID, Title or something else in common, but I'm not sure if the Entity Reference Views Display type supports that, I expect it doesn't and it won't affect it, you'll still get a plain list of all Revisions and you need to make sure yourself what to output and how to style it to make the options clear. There are probably ways on how to improve the ER Display output in Field widgets but that is out of scope of this question.

I haven't tries this, but usually when listing content referenced through ERs you need to add a Relationship to get any other info than an ID of the referenced entity. You'd need a Relationship to get that info. In your case if you start with Content Views type I expect you'd have to make sure to have each Revision is in a separate row (after you make them appear in results by adding a Relationship, and you'd probably need to list only the Revision info to make them appear in separate rows). I know it's possible to create the reverse ER Views through the forward list Views this way, but haven't tried it with Revisons, maybe the same logic applies.
Anyway, go with the Content Revisions Views type as explained above ;)
Comment: Hi prkos, the view you see in attachment is of type document revision. It lists all revisions correctly. But my ER field doesn't pick up the view (no eligible view found)
Comment: :facepalm: I'll get back to you after a reboot.


Colocando itens em um array com Reactjs

Question:
Estou tentando colocar itens em um array ao clicar no botão, mas o mesmo esta iniciando vazio.Perceba que eu cliquei 3 vezes mas ele me mostra que o array tem 2 posições.
Eu tenho uma div que é o display essa div recebe o estado da constante operation que é um array. Ao clicar em em um botão é disparada um função chamada addOperation(2) com o valor 2, que coloca esse numero dentro do array.Estou utilizando setOperation([...operation, value]) para empurrar o numero no array.
O problema é que ao clicar no botão o programa coloca o numero na segunda posição do array, e a primeira fica vazia, vocês sabem o que pode estar acontecendo?
Comment: A atualização de state é uma operação assíncrona. Uma das formas de pegar o valor atualizado é utilizar o useEffect. Aqui tem alguns exemplos: https://reactjs.org/docs/hooks-effect.html
Comment: Uma coisa importante, não coloque a imagem, só em determinados caso, nesse por exemplo que é código, coloque sempre o código.
Comment: Uma coisa se a minha resposta foi a solução do seu problema aceite como resposta e dê uma olhada no [tour](https://pt.stackoverflow.com/tour) para que tenha noção de como funciona.
Answer: O que está acontecendo é que o seu array está sendo atualizado certo com as 3 posições criadas, mas, não mostra isso no console.log porque o ReactJs não atualizou seu componente, para que isso aconteça precisa utilizar o useEffect que no momento da atualização da variável o valor do novo array é mostrado, exemplo:

function App() {
  const [operation, setOperation] = React.useState([]);
  React.useEffect(() => {
    console.log(operation);
  }, [operation]);
  function addOperation(value) {
      setOperation([...operation, value]);
  }
  return (

      <button onClick={e => addOperation(2)}>Add</button>

        {operation.map((o,i)=>(
{o}
))}

  )
}
ReactDOM.render( <App/> , document.getElementById('root'));

o useEffect nesse caso fica observando as alterações na variável e com isso mostra o valor correto das posições conforme a atualização do componente porque o estado sempre é assíncrona.
Comment: show deu certo.

Colocando itens em um array com Reactjs


Is there a paging version of `watch`?

Question: Under a UNIX shell, how can I get a similar effect to the watch command, but with paging so that I can scroll around in the output if it takes up more than one screen?
In other words, I want a program that is to watch what less is to cat.
As an example, lets say I wanted to watch the output of qstat, I could use
watch qstat

to watch the output of qstat, but this can only shows the first screenful.
With a paging version of watch, I would be able to move around in the output as it is still continuously updated by watch. Is there any way to do this at the moment with existing utilities?
Comment: because my screen is already full? why use `less` when you can just use `cat` and a bigger window?
Comment: This probably belongs on SuperUser or maybe ServerFault.
Comment: You are probably right, how can I move it?
Comment: Three people have voted to move it so far; if two more people (or a moderator) vote to move it, then it will happen automatically.
Comment: Why not just open a bigger window and go away with paging altogether?
Answer: Rather than modifying the 'watch' command, use screen!
For example, let's say that you need to be able to see 300 lines of height and 100 characters of width and move around that. After starting screen, force the size thus:
C-a :height -w 300
C-a :width -w 100

Now start your watch command. You can then use C-a <ESC> to page around the display.
Unfortunately, the display doesn't refresh while in copy mode. But if you want to adjust which section of the window you're viewing, the easiest way may be to rerun the height/width commands as by default your terminal shows the lower-right of the virtual window.
Comment: the only issue then is how to continually repeat the command, while blanking the screen between each go
Comment: Oops, I meant run the watch command inside screen. Fixed.
Comment: yartls - yet another reason to love screen :)
Comment: note that `C-` is aka `ctrl-`
Comment: What is the `tmux` version of this?
Answer: You can try this:
$ while vmstat; do sleep 1; done | less

replace vmstat with qstat and adjust the sleep to your needs.
Comment: Yes, but you can scroll back. You can't have both at once.

Pressing shift f, that is capital 'F' will work like tail.
Comment: Append `+F` to "pre-press" F and automatically follow: `while vmstat; do sleep 1; done | less +F`
Comment: all this does is keep repeating the command into `less`, which means that you need to keep scrolling to see the latest output.
Answer: Multitail: http://www.vanheusden.com/multitail/
Example:
 vmstat 1 |multitail -j

Scroll back by press 'b' and page/arrow up/down.
Comment: Ok, this is for `vmstat` - but how would it work for `watch`? if I try `watch -n1 ls -la | multitail -j`, I get just an empty screen? EDIT: I can do something like `multitail -R 1 -l "ls -la"` (that would be `watch -n1` - but I cannot scroll in that window? Ah, https://www.networkworld.com/article/3445228/using-multitail-on-linux.html - for scrolling you need to press `b`, but then the window that gets shown there, gets deleted on next 1 sec refresh, so its useless for that)
Answer: OK, I've had a little go at a watchless function. It's a bit rough, and it doesn't yet appear to completely work, but here goes:
#!/bin/bash -u
out=$(mktemp)
(while [ 1 ]; do
    "$@" > $out;
    sleep 2;
done) &
less $out
kill $!

You have to manually use the R key in less to get the display to update.
It appears to work for watchless date but not for watchless qstat or watchless pstree, which both show blank. Any ideas?
Comment: You should use a second file to write the output of the next run of the command and then `mv` this second file to the file read by `less` as `mv` is atomic. Otherwise `less` could think that the file has disappeared if a refresh is requested at the same time as the file is being written to with `"$@" > $out`. You should also write to the output file once before starting the loop.
Answer: I implement a simple python script to satisfy this request, named "watchall"
get it by:
pip install watchall
replace watch with watchall and enjoy scrollable screen.
now it only supports -n and -d flags.
Comment: The link to it is here: https://github.com/mfatemipour/watchall . But is seems you removed the python version ? Was it not working at all ?
Answer: I don't see how this could be implemented as the row contents change, and watch would reset back to first line every 2 seconds even if you could scroll down.
Some workarounds are:
watch 'qstat | tail -n40' to show output of qstat beginning from 40th line from bottom
watch 'qstat | grep jsmith' to grep the output so the lines you are interested in are always in the first screen.
Note that you need to put the commands around the pipe in single quotes - otherwise you will be piping the output of watch, not the output of qstat.
Answer: To continue on enkrs's answer,
watch 'qstat | head -300 | tail -15'
will get you arbitrary pages into the qstat's output.
Answer: Here's a rather crude script that seems to work for several commands that I threw at it
#!/bin/bash
# ---- mywatch.sh ----

if [ $# -lt 1 && $# -gt 2 ]; then
    echo "Usage: $0 <command> <delay>"
    exit 1
fi

CMD=$1
if [ $# -eq 2 ]; then
  DELAY=$2
else
  DELAY=2 # default
fi

while : ; do
  ( (echo -e "Every ${DELAY}s: $CMD\n"; $CMD) | less )&
  PID=$!
  sleep $DELAY
  kill -9 $PID &> /dev/null
  clear
done

Used as such:
alias mywatch="~/bin/mywatch.sh"

mywatch vmstat
mywatch "ps aux" # commands in options need to be quoted
mywaych pstree 10 # change delays

Being rather pedantic, the transition between refreshes aren't as smooth as I would like it to be. Naturally, being a simple script it doesn't support highlight of diff (watch -d). Also, the parsing of input arguments can be done better.
Answer: How about just: tail  -f
Answer: I am using this:
while cat /etc/wgetrc; do sleep 10; done | pv -q -L 150 | tail -n +0 -f

Answer: I edited the script here to work with command line
#!/bin/bash
#
# watch a file and scroll
#
# keys => arrow-up/down, page-up/down, pos1, end
#
# usages:
#           swatch -n <timeout_watch> <file>
#           swatch <file>
#
# version:          1.1
# dependencies:     awk , tput , clear, read
# published:        https://unix.stackexchange.com/questions/3842/how-can-i-scroll-within-the-output-of-my-watch-command
# gif recording:    peek , https://github.com/phw/peek

#
# =============================================
# KEYCODES
# =============================================
# https://unix.stackexchange.com/questions/294908/read-special-keys-in-bash
# showkey -a

# =============================================
# DEFAULTS
# =============================================
command=""
TMPFILE=$(mktemp)
line_show_begin=1
line_show_begin_last=-1
console_lines_correction=4
timeout_watch=5
timeout_read=.1

# =============================================
# DEFINE Escape-Sequences
# =============================================

# http://ascii-table.com/ansi-escape-sequences-vt-100.php

ESC_clr_line='\033[K'
ESC_reset_screen='\033c'
ESC_clr_screen='\033[2J'
ESC_cursor_pos='\033[0;0f'
ESC_cursor_home='\033[H'

# =============================================
# FUNCTIONS
# =============================================

function fn_help() {
cat << EOF
Usage: ./$0 [-n <timeout>] [<command>]  ,  timeout >0.1s , default 5s
EOF
}

function get_options() {
    [[ "$1" == "" ]] && { fn_help ; exit 1 ; }
    while [ -n "$1" ]; do
        case "$1" in
            -h|--help)
                fn_help
            ;;
            -n)
                [[ "$2" == "" ]] && { echo "Error: option -n required <timeout>" ; exit 1 ; }
                if [[ "$(echo "$2<0.1"|bc)" == "0" ]] ; then
                    timeout_watch="$2"
                    shift
                else
                    echo "Error: timeout <0.1 not allowed"
                    exit 1
                fi
            ;;
            -*)
                echo "Error: unknown option »$1«"
                exit 1
            ;;
            *)
                #if [[ -f "$1" ]] ; then
                command=$1
                #else
                #    echo "Error: file not found »$1«"
                #    exit 1
                #fi
            ;;
        esac
        shift
    done
    [[ "$command" == "" ]] && { echo "Error: command required" ; exit 1 ; }
}

function fn_print_headline() {
    hdl_txt_right="${HOSTNAME}: $(date "+%Y-%m-%d %H:%M:%S")"
    hdl_txt_left="$command , ${timeout_watch}s , $line_show_begin"
    hdl_txt_left_length=${#hdl_txt_left}
    printf '%s%*s\n\n' "$hdl_txt_left" "$(($console_columns-$hdl_txt_left_length))" "$hdl_txt_right"
}

function fn_print_file() {
    # ---------------------------------------------------
    # file lenght can change while watch
    # ---------------------------------------------------
    eval $command > $TMPFILE
    lines_command=$(awk 'END {print NR}' $TMPFILE)
    line_last=$(($lines_command-$console_lines))
    (( "$line_last" < "1" )) && { line_last=1; clear; }
    (( "$line_show_begin" > "$line_last" )) && { line_show_begin=$line_last; clear; }

    # ---------------------------------------------------
    # print postion changed
    # ---------------------------------------------------

    if (( "$line_show_begin" != "$line_show_begin_last" )) ; then
        line_show_begin_last=$line_show_begin;
        clear
    else
        printf $ESC_cursor_home
    fi

    # ---------------------------------------------------
    # print file section
    # ---------------------------------------------------

    fn_print_headline
    eval $command > $TMPFILE
    awk -v var1="$line_show_begin" -v var2="$console_lines" 'NR>=var1 {if (NR>var1+var2) {exit 0} else {printf "%s\n",$0 } }' $TMPFILE
}

function fn_console_size_change() {
    console_columns=$(tput cols)
    console_lines=$(($(tput lines)-$console_lines_correction))
    line_show_begin_last=-1
}

function fn_quit() {
    echo "quit" $0 , $?
    setterm -cursor on ; exit 0
}

# =============================================
# GET OPTIONS
# =============================================

get_options "$@"    # pass all arguments with double-quotes

# =============================================
# INIT TRAP
# =============================================

trap "fn_console_size_change" SIGWINCH # https://en.wikipedia.org/wiki/Signal_(IPC)#SIGWINCH
trap "fn_quit" INT TERM EXIT

# =============================================
# MAIN
# =============================================

fn_console_size_change
setterm -cursor off

while true ; do
    fn_print_file
    read -rsn1 -t $timeout_watch k # char 1
    case "$k" in
        [[:graph:]])
            # Normal input handling
        ;;
        $'\x09') # TAB
            # Routine for selecting current item
        ;;
        $'\x7f') # Back-Space
            # Routine for back-space
        ;;
        $'\x01') # Ctrl+A
            # Routine for ctrl+a
        ;;
        $'\x1b') # ESC
            read -rsn1 k # char 2
            [[ "$k" == ""  ]] && return  Esc-Key
            [[ "$k" == "[" ]] && read -rsn1 -t $timeout_read k # char 3
            [[ "$k" == "O" ]] && read -rsn1 -t $timeout_read k # char 3
            case "$k" in
                A)  # Arrow-Up-Key
                    (( "$line_show_begin" > "1" )) && line_show_begin=$(($line_show_begin-1))
                ;;
                B)  # Arrow-Down-Key
                    (( "$line_show_begin" < "$line_last" )) && line_show_begin=$(($line_show_begin+1))
                ;;
                H)  # Pos1-Key
                    line_show_begin=1
                ;;
                F)  # End-Key
                    line_show_begin=$line_last
                ;;
                5)  # PgUp-Key
                    read -rsn1 -t $timeout_read k # char 4

                    if [[ "$k" == "~" ]] && (( "$line_show_begin" > "$(($console_lines/2))" )) ; then
                        line_show_begin=$(($line_show_begin-$console_lines/2))
                    else
                        line_show_begin=1
                    fi
                ;;
                6)  # PgDown-Key
                    read -rsn1 -t $timeout_read k # char 4
                    if [[ "$k" == "~" ]] && (( "$line_show_begin" < "$(($line_last-$console_lines/2))" )) ; then
                        line_show_begin=$(($line_show_begin+$console_lines/2))
                    else
                        line_show_begin=$line_last
                    fi
                ;;
            esac
            read -rsn4 -t $timeout_read    # Try to flush out other sequences ...
        ;;
    esac
done

create a file in ~/bin/cwatch.sh

nano ~/bin/cwatch.sh

change files properties to make it runnable:

chmod +x ~/bin/cwatch.sh

edit ~/.bashrc and add alias

alias cwatch="~/bin/cwatch.sh"

now you can try it:
cwatch 'ps aux | grep -v grep'

Answer: In case this could be useful to others, this is how I solved the issue on my side. In the "cmd" function, plug any command you want to monitor.
#!/bin/bash

function cmd {
  sudo lsof -i -n -P | grep 18.104.22.168:8883
}

echo "" >previous.log
while true; do
  cmd >out.log
  diff out.log previous.log >/dev/null
  cc="$?"
  if [[ "$cc" != "0" ]]; then
    date=`date --rfc-3339=seconds`
    epoch=`date +%s`
    echo ""
    echo "Changes on $date ($epoch)"
    cat out.log
    cp out.log previous.log
  fi
  sleep 0.5
done

Answer: you can try:
watch command > file

then in your file you should see the appendend output (I don't have a linux box rigth now to test this)
Comment: Change the ">" to ">>" to make it append the data to to the file?
Comment: That isn't going to do what you intend, really, it will just fill up `file` with the same output over and over. It certainly doesn't address the original question.
Comment: then I dunno :)

Is there a paging version of `watch`?


casting to string of column for pyspark dataframe throws error

Question: I have pyspark dataframe with two columns with datatypes as
[('area', 'int'), ('customer_play_id', 'int')]
+----+----------------+
|area|customer_play_id|
+----+----------------+
| 100|        8606738 |
| 110|        8601843 |
| 130|        8602984 |
+----+----------------+

I want to cast column area to str using pyspark commands but I am getting error as below
I tried below

str(df['area']) : but it didnt change datatype to str
df.area.astype(str) : gave "TypeError: unexpected type: "
df['area'].cast(str) same as error above

Any help will be appreciated
I want datatype of area as string using pyspark dataframe operation
Answer: Simply you can do any of these -
Option1:
df1 = df.select('*',df.area.cast("string"))

select - All the columns you want in df1 should be mentioned in select
Option2:
df1 = df.selectExpr("*","cast(area as string) AS new_area")

selectExpr - All the columns you want in df1 should be mentioned in selectExpr
Option3:
df1 = df.withColumn("new_area", df.area.cast("string"))

withColumn will add new column (additional to existing columns of df)
"*" in select and selectExpr represent all the columns.
Comment: but how will it be applied to complete df. What i mean is after running above command datatype gets changed but when i print df.dtypes, i get only one column and not the remaining
Comment: edited my answer. You need to assign it to a new dataframe.
Comment: yes, but after i assign it to dataframe, it reduced number of column to 1 which will be only area
Comment: You have to mention all the columns in select, I have edited my answer.
Answer: use withColumn function to change the data type or values in the field in spark e.g. is show below:
import pyspark.sql.functions as F
df = df.withColumn("area",F.col("area").cast("string"))

Answer: You Can use this UDF Function
from pyspark.sql.types import FloatType
tofloatfunc = udf(lambda x: x,FloatType())
changedTypedf = df.withColumn("Column_name", df["Column_name"].cast(FloatType()))


How to extract data from HashMap in Retrofit2?

Question: I have Spring Boot project on backend and Android app on frontend. Communication between the two happens via Retrofti2. On one of the endpoits, actually /login endpoint, is retruning a HashMap<String, Object>. That endpoint looks like this:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<?> login(@RequestBody AuthenticationRequest authenticationRequest) throws Exception {

    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("user", getUserObject());
    map.put("token", getJwtToken());

    return  ResponseEntity.ok(map);
}

Interface for method call looks like this:
public interface LoginService {

    @POST("login")
    Call<HashMap<String, Object>> testLogin(@Body Login login); //login contains username and password strings
}

The reposnse in frontend look like this:
Call<HashMap<String, Object>> call = mLoginService.testLogin(new Login(username, password));

call.enqueue(new Callback<HashMap<String, Object>>() {
    @Override
    public void onResponse(Call<HashMap<String, Object>> call, Response<HashMap<String, Object>> response) {
        if (!response.isSuccessful()){
            Toast.makeText(getApplicationContext(), "Wrong credentials!", Toast.LENGTH_SHORT).show();
            return;
        }

        //extract user & token
        HashMap<String, Object> map = response.body();

        Log.i("Test result", map.get("token").toString());
        Log.i("Test result", map.get("user").toString());

        User u = (User) map.get("user");

        //Toast.makeText(getApplicationContext(), "Welcome " + u.getUsername()   + "!", Toast.LENGTH_SHORT).show();

        startActivity(goToEmailsIntent);

    }

    @Override
    public void onFailure(Call<HashMap<String, Object>> call, Throwable t) {
        Toast.makeText(getApplicationContext(), "Cannot login, look at the console", Toast.LENGTH_SHORT).show();
        Log.i("ERRROOOOOOR during login", t.toString());
        return;
    }
});

When I look at the log statements in the console everything is okey, I get the data which I want. But when trying to cast to User object I get exception.
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.email.model.User

How to get around this? Is there any better way to send User object and a String from backend?
Answer: First method
When you can change your backend service then modify the backend service return DTO not HashMap.
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<Token> login(@RequestBody AuthenticationRequest authenticationRequest) throws Exception {
    // create your response
    Token token = new Token();

    return  ResponseEntity.ok(token);
}

Second method
Use json format to exchange data,in your onResponse method you can do like below:
HashMap<String, Object> map = response.body();
// map.get("user) may return a null value
String jsonString = new Gson().toJson(map.get("user));
User user = new Gson().fromJson(jsonString,User.class);

// do other thing as you want


overwritting content of .txt file in php

Question: I need to overwrite the content of a .txt file when I browse a file in a page.I have written a php script for it.
Form is given below
<input type="file" name="file" size="50" maxlength="25">

<input type="submit" name="upload" value="Upload">

and PHP script is
$file1=$_FILES['file'];
$out = file_get_contents($file1);

$file2 = "molecule.txt";
$filehandle = fopen($file2, "a");
$file_contents = file($file1);
$count = count(file($file1));
file_put_contents($file2, "");
$newlineno = 0;
foreach ($file_contents as $line_num => $line) {
    if (strpos($line, 'Standard orientation:') !== false) {
        for ($lineno = $line_num + 5; $lineno <= $count; $lineno++) {
            $line = $file_contents[$lineno];
            if (strpos($line, 'Rotational constants (GHZ):') != false) {
                break;
            }

            $line = preg_replace('/\s+/', ' ', $line);
            $split = explode(" ", $line);
            $symbol = $mapping[$split[2]];
            $x = $y = $z = '';

            if ($split[4] >= 0) {
                $x = ' ' . $split[4];
            } else {
                $x = $split[4];
            }
            if ($split[5] >= 0) {
                $y = ' ' . $split[5];
            } else {
                $y = $split[5];
            }
            if ($split[6] >= 0) {
                $z = ' ' . $split[6];
            } else {
                $z = $split[6];
            }

            $x = substr($x, 0, -3);
            $y = substr($y, 0, -3);
            $z = substr($z, 0, -3);
            $newlineno++;
            $newline = "ATOM\t" . $newlineno . "\t" . $x . "\t" . $y . "\t" . $z . "\t" . $symbol . "\n";

            fwrite($filehandle, $newline);
        }
    }
}

fclose($filehandle);

$lines = file($file2);
$last = sizeof($lines) - 1 ;
unset($lines[$last]);

$fp = fopen($file2, 'w');
fwrite($fp, implode('', $lines));
fclose($fp);

echo "File UPLOADED SUCESSFULLLy";

?>
<form method="POST" action="molecules.html">

<input type="submit" name="structure" value="View file">

In molecule.html file contain code for displaying the content of molecule.txt file
But it is not overwriting the content of molecules.txt file.
Do I need anything more to add? Please help me.
Thanks in Advance.
Comment: looks like data that belongs in a db
Comment: If you are trying to overwrite the content of file then open the file in write mode instead append mode.
Comment: Can you share your `molecule.html` file code?
Comment: code in molecule.html file are used for drawing 3d structure of chemical compound . It was a big file , how can I attach those file..... :(
Answer: instead of
$filehandle = fopen($file2, "a"); // this mode means append content

use
$filehandle = fopen($file2, "w"); //this mode means write file by over writing the previous content

Comment: it will erasing the content of molecule.txt file
Comment: i want to overwrite the content of molecule.txt file .
Comment: yes this remove the old content in the molecule.txt and add your new content to the file, as per my knowledge that is what overwriting means
Comment: Ya ofcourse... But it will not writing new content in molecule.txt file
Comment: Where do you wish to write your new content then?
Comment: need to write in molecule.txt file itself
Comment: as per your code you are doing the same, what you are doing in your code is appending the data to your existing data, as your title of the question says that you want to overwrite the content i suggested you to clean the file and then add new content to it, i.e the file molecules.txt
Comment: as per your requirement you need to add new content to the existing file, my solution is what you need
Answer: $filehandle = fopen($file2, "w+");

//w+ : Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Reference: http://php.net/manual/en/function.fopen.php
Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation.
I am suggesting two approach
Approach - 1 (File handling, simplest method; considering you're not doing any logical operation or string matching from the content, being read out)
molecules.html - Page containing form to upload file
<form method="POST" action="fileOverwrite.php"  method="post" enctype="multipart/form-data">
    <input type="file" name="file" size="50" />

    <input type="submit" name="upload" value="Upload" />
</form>

fileOverwrite.php - File for overwriting logic/script
<?php
$file1      = $_FILES['file']['tmp_name'];
$out        = file_get_contents($file1);
$file2  = "molecule.txt";
$filehandle= fopen($file2, "w+") or die("Unable to open file!");
fwrite($filehandle, $out);
fclose($filehandle);
echo "File UPLOADED SUCESSFULLLY";
?>
<form method="POST" action="molecules.html">

    <input type="submit" name="structure" value="View file" />
</form>

Approach - 2 (matches your requirement, where you're doing some string search)
molecules.html - Page containing form to upload file
<form method="POST" action="test.php"  method="post" enctype="multipart/form-data">
    <input type="file" name="file" size="50" />

    <input type="submit" name="upload" value="Upload" />
</form>

fileOverwrite.php - File for overwriting logic/script
<?php
// Capture the file's temp path and name
$file1  = $_FILES['file']['tmp_name'];

// Reads entire file into a string
$out    = file_get_contents( $file1 );

// Target file
$file2  = "molecule.txt";

// Open file for reading and writing
$filehandle = fopen( $file2, "w+" );

//Reads entire file into an array
$file_contents = file( $file1 );

$count = count( file( $file1 ) );

// Write a string to a file
file_put_contents( $file2, $file_contents );

$newlineno = 0;
foreach ($file_contents as $line_num => $line) {
    if (strpos($line, 'Standard orientation:') !== false) {
        for ($lineno = $line_num + 5; $lineno <= $count; $lineno++) {
            $line = $file_contents[$lineno];
            if (strpos($line, 'Rotational constants (GHZ):') != false) {
                break;
            }

            $line   = preg_replace( '/\s+/', ' ', $line );
            $split  = explode( " ", $line );
            $symbol = $mapping[$split[2]];
            $x = $y = $z = '';

            if ($split[4] >= 0) {
                $x = ' ' . $split[4];
            } else {
                $x = $split[4];
            }

            if ($split[5] >= 0) {
                $y = ' ' . $split[5];
            } else {
                $y = $split[5];
            }

            if ($split[6] >= 0) {
                $z = ' ' . $split[6];
            } else {
                $z = $split[6];
            }

            $x = substr($x, 0, -3);
            $y = substr($y, 0, -3);
            $z = substr($z, 0, -3);

            $newlineno++;
            $newline = "ATOM\t" . $newlineno . "\t" . $x . "\t" . $y . "\t" . $z . "\t" . $symbol . "\n";

            // Binary-safe file write
            fwrite($filehandle, $newline);
        }
    }
}

// Close open file pointer
fclose($filehandle);

$lines = file($file2);
$last   = sizeof($lines) - 1;
unset($lines[$last]);

$fp = fopen($file2, 'w+');
fwrite( $fp, implode( '', $lines ) );
fclose($fp);

echo "File UPLOADED SUCESSFULLLY";
?>

<form method="POST" action="molecules.html">

    <input type="submit" name="structure" value="View file" />
</form>

Comment: thanks for your response I have tried it.....But it doesnot updating content of molecule.txt file
Comment: Do you want a) new content to be added at the end of existing content while keeping the old as it is or b) replace old content with new one removing old one
Comment: I've updated this with entire code which is short as well. You may try this. It fulfils option b.


Firebase image URL not working Angular NgStyle

Question: I have a challenge rendering an image via the firebase resource image URL.
The template code is as follows:

When I inspect the element in dev tools the background-image prop is not being applied
What am I missing here?
UPDATE
I have tried sanitizing the url and used the code below

Comment: I understand but the value you are concatenating is an url (either base64 or not). So you should give it a try.
Comment: Are you getting any console errors? This might be angular's sanitization causing an issue
Comment: @MathieudeLorimier no, no errors, check the question update
Comment: Shouldn't you use `bypassSecurityTrustUrl`
Comment: No, remember it has to be background-image: url(...)
Comment: I've updated the code to be [style.background-image]="sanitizer.bypassSecurityTrustStyle('url'+ article.articleImgUrl + ')')" but still
Comment: Ohh yeah I get you now, I will give it a try, I am AFK at the moment, I will update the thread when I get it working,  thanks
Comment: @MathieudeLorimier check the answer I have posted, thanks for assisting.
Answer: I got it to work by having a function call in the template:
[style.background-image]="article.getImageUrl()";

In the class file I have an implementation of the function:
const getImageUrl = () => this.sanitizer.bypassSecurityTrustStyle(`url(${articleData.articleImgUrl})`);

Comment: Though it would be nice to understand why the above solution works, that is, why does returning the URL from a functions solves the issue?


Struct ou Classes?

Question: Fiz o código usando estrutura, queria saber se com classes seria mais eficiente. Estou fazendo no C++ Builder. A ideia do código e a seguinte: criar uma lista de problemas, onde durante a execução do código sera acrescentados e retirados inúmeros problemas (do tipo struct ou class)
struct {
 TList *cidadesvisitadas; // lista iniciada com uma cidade ,vou acrescentando ate 30 cidades
 float  distancia;
 TList *cidadescanditadas; // lista iniciada com 29 cidades , que no decorrer  do codigo vai sendo retirada uma a uma e adicionada na lista de cidades visitadas
};

Na lista de problemas, será adicionado um problema inicial (não resolvido), e depois retirado esse problema se transforma em três novos problemas (não resolvido) que são adicionados novamente a lista de problemas, depois retiro um problema novamente da lista de problemas e se transforma em outros três problemas e assim por diante. A lista no final da execução ficar vazia (acrescenta e retira, quando o problema estiver resolvido ele não volta para a lista). Os problemas já estanciados dinamicamente (serão milhões de problemas)
se eu trocar a struct (Problema) por class (Problema), o código fica mais correto?
Comment: Dê uma olha no [tour], você pode votar em tudo no site que achar que é um bom conteúdo, além de aceitar uma resposta em perguntas suas, como já sabe fazer.
Answer: Em C++ estruturas e classes são virtualmente a mesma coisa (classes possuem membros privados por padrão), então não faz diferença, nenhuma, nem de desempenho.
Como vai montar e usar o código faz diferença. É comum as pessoas deixarem struct para estruturas simples, sem métodos, ou seja, POD (Plain Old Data), e classes quando são objetos mais completos. Tem quem prefira usar struct quando o tipo será mais usado como valor e class para objetos que costumarão ser usados como referência, mas nem sempre isso funciona tão preto no branco.
Claro que classes não podem ser usadas com C. Dependendo de como use struct também não pode.
Coloquei no GitHub para referência futura.
Answer: Primeiramente, struct não é a mesma coisa que uma classe como muitos te responderam, apesar de ambas serem extremamente parecidas, tanto em questão de sintaxe (escrita no próprio código) quanto no resultado exibido.

Classe: Uma classe é uma estrutura que comporta atributos e métodos. Para acessar essas características, é necessário a criação de um objeto. Você pode acessar as informações de uma classe após a criação do objeto através da nomenclatura objeto->atributo; ou objeto->funcao();

Observação: Uma classe pode se comunicar com a outra assim como um objeto pode se comunicar com outro.

Struct: Uma struct é uma estrutura, assim como uma classe, mas que comporta somente atributos. Não há como criar métodos. Além disso, para acessar as características de uma estrutura é utilizado um mecanismo de acesso, o que é completamente diferente de um objeto. Para acessar as informações de uma struct você pode utilizar a nomenclatura acesso.atributo;

Observação: Uma struct não pode se comunicar diretamente com uma outra struct assim como um mecanismo de acesso não pode se comunicar com outro.
Em síntese, uma classe é uma estrutura extremamente mais elaborada, com interações e comunicações diretas com a funcionalidade do seu programa. Uma struct é somente uma estrutura estética, que serve para acoplar dados similares em somente um lugar, apesar de também ser funcional ao poder criar vários mecanismos de acesso e, portanto, acessar vários atributos.
A sua pergunta não é a diferença entre as duas, mas através dessas informações você pode deduzir, ao desenvolver o seu projeto, qual é a melhor opção. Pelo que eu consegui entender, class seria uma melhor opção, uma vez que você poderá elaborar a solução dos problemas exibidos através de métodos induzidos na própria classe.
Comment: Isso é simplesmente falso. `struct` é uma classe com membros públicos por padrão. Só isso. Em C, `struct`s realmente só possuem atributos, mas estamos falando de C++.

Struct ou Classes?


Time Series Regression Correlation

Question:
If I recall correctly, the equation for $R^2$ is $\frac{SST-SSE}{SST}$
So is the answer simply, $\frac{60-40}{60}=\frac{1}{3}$?
Comment: Refer to the book of Douglas C. Montgomery on Introduction to Linear Regression Analysis.
Answer: The regression model fitted is a polynomial regression model, so you may better search for Polynomial Regression model in the book of Douglas C. Montgomery on "Introduction to Linear Regression Analysis".
Answer: Please, you must review the definition of R - squared Find here the right answer.
Comment: Thank you so much! I'll study this and ask if I'm lost :D

Time Series Regression Correlation


IF, ELSE IF, ELSE ou IF IF IF. Quando usar, qual a diferença?

Question: É uma questão bem básica, porém que me intriga bastante. Vejam o código abaixo:
var bola = "redonda";
if(bola == "comestivel") return comer();
if(bola == "liquida") return beber();
if(bola == "redonda") chutar();

Agora vejam o mesmo com if, else if e else
var bola = "redonda";
if(bola == "comestivel") return comer();
else if(bola == "liquida") return beber();
else chutar();

Ou seja, o mesmo fim pode ser obtido de ambas as maneiras.
O else if e else não teriam apenas efeito semântico?
Answer: No seu exemplo, não faz mesmo diferença, por dois motivos:

Não existem duas condições que possam ser atendidas ao mesmo tempo.
Você sempre retorna quando entra em um dos if, e os seguintes não executam

Agora considere o seguinte exemplo:
var numero = 100;
if(numero <= 100) {
    console.log("menor ou igual a 100");
} else if(numero < 1000) {
    console.log("menor que 1000");
}

O else não será executado, pois já entrou no if (else quer dizer "senão"). Blocos de else e else if só executam se nenhuma das condições anteriores tiver sido atendida. Contraste com isto:
var numero = 100;
if(numero <= 100) {
    console.log("menor ou igual a 100");
}
if(numero < 1000) {
    console.log("menor que 1000");
}

Aqui ambos são executados, já que são duas condições independentes e o número 100 atende a ambas.
Answer: Semântica
As linguagens de programação costumam ter construções diferentes para dar efeitos semânticos diferentes. Raramente você precisa de uma construção diferente se não quer este resultado.
Simplicidade
Você deve tentar sempre usar o mais simples possível. Eu considero que o mais simples é o if com bloco simples (só um comando), sem condicionais extras ou contra condicional.
Como funciona bloco de if
Mas há casos em que isto não é possível. Quando você tem uma situação em que um um bloco de ação é excludente em relação ao outro, você precisa utilizar o else. Bom, na verdade não precisa. Você pode colocar um segundo if em seguida com a condição invertida, mas isto não faz muito sentido, piora a leitura e manutenção.
Isto vale também quando tem uma série de opções mutualmente exclusivas, ou seja, que apenas uma é válida. Você até pode fazer vários ifs, mas se a decisão está interligada, se é mais lógico que seja feito como uma só operação é melhor escolhê-la.
O que é melhor
Então sim, no seu exemplo você deve fazer escolher o else if principalmente por questão de semântica. Mas isto não é algo bobo que só serve para atender uma regra. Realmente facilita ler e mexer no seu código sem causar problemas no futuro.
Códigos devem ser escritos primariamente para seres humanos lerem. Então é muito útil dar o entendimento correto do que está fazendo ali. Quando todas as escolhas levam ao mesmo lugar escolha a mais simples. Podemos adaptar esta afirmação para o propósito de manutenção: se todas as formas resolvem o problema, escolha a que expressa melhor a sua intenção.
Fazer ifs separados que estão logicamente ligados passa a ideia errada. O meu entendimento é que seu código está fazendo uma única decisão lógica. Mesmo sendo mais simples usar o if simples, não é mais simples ler um código assim.
Além da questão do if
Mas existe um outro problema. Eu não diria que seus dois códigos fazem a mesma coisa. Eles não são equivalentes. Tá, eles até são da maneira como está escrito. Mas ninguém escreve código assim a não ser para exemplificar.
var bola = "redonda";
if (bola == "comestivel") return comer();
if (bola == "liquida") return beber();
if (bola == "redonda") chutar();

e
var bola = "redonda";
if (bola == "comestivel") return comer();
else if (bola == "liquida") return beber();
else if (bola == "redonda") chutar();

são equivalentes.
Coloquei no GitHub para referência futura.
Em um código real poderia haver um situação que a variável bola não vale nenhum destes textos. O seu código executará chutar() se o texto for diferente das duas opções iniciais no segundo código, mas não executará no primeiro se a primeira situação for igual. No código acima, ambos farão a mesma coisa.
Observe a resposta do bfavaretto que mostra que pode haver um outro problema quando escolhe a opção de ifs isolados. No seu exemplo não causa problema, mas quando você pode ter duas condições sendo atendidas e você quer que apenas um bloco seja executado (são mutuamente exclusivos, ou executa um ou outro), separar o if dará resultado inesperado, ele poderá executar os dois blocos e não é o que você quer.
Conclusão
Por isto achar o mais simples é complicado. É comum programadores menos experientes fazerem coisas extremamente complicadas porque não sabem como fazer o simples. Parece um contrassenso mas é o que mais acontece. O mais simples nestes casos é a estrutura que parece mais complicada (não que seja muito).

Acho que existe ainda um outro problema no código que não parece tão relevante para a pergunta (mas pode ser) e que estou apenas intuindo já que este não é um código real. No terceiro caso você está executando a função chutar() mas não está retornando o resultado desta função. Nas condições anteriores você está retornando o o resultado da função. Pode ser que não tenha resultado algum mesmo. Aí não faria diferença.
Mesmo assim eu ainda colocaria return chutar() no final a não ser que tenha um motivo para não por. É uma questão de simetria. Se a intenção é terminar a função ali, diga explicitamente que vai fazer isto. Se a intenção claramente não precisa retornar um valor em nenhum caso, você deveria então tirar todos os return para deixar claro que não está retornando um valor. Ou pelo menos chamar a função e só depois usar o return.
Por último eu prefiro dar um espaço entre o if e o ( da condição para não confundir com uma função chamada if.
Comment: Eu complementaria com:
var bola = "redonda";
if (bola == "comestivel"){
   return comer();
}else if (bola == "liquida"){
   return beber();
}
//nem um nem outro e  não precisamos fazer outras verificações?
return chutar();
Answer: As demais respostas já explicam muito bem, mas gostaria de complementar com o seguinte: com frequência existem várias maneiras de se fazer a mesma coisa, sem que exista claramente um "melhor" ou "pior", de modo que cabe a você - pela sua experiência ou pelo seu feeling - decidir qual delas usar caso a caso.
Aqui não se pode ter nenhuma instrução após aquela sendo escolhida (sem repetir código):
if(bola == "comestivel") return comer();
if(bola == "liquida") return beber();
if(bola == "redonda") return chutar();
return nenhumaDasAnteriores();

qualquerUmaDelas(); // Nunca executará

Aqui se pode fazer algo depois que a ação correta foi escolhida (mas retornar um valor é mais "chato"):
if(bola == "comestivel") comer();
else if (bola == "liquida") beber();
else if (bola == "redonda") chutar();
else nenhumaDasAnteriores();

qualquerUmaDelas(); // Seja o que for feito, isso será feito depois

Aqui se pode fazer a mesma coisa com duas ou mais condições diferentes (ou duas ou mais coisas com a mesma condição):
switch(bola) {
    case "redonda":
    case "oval":
        chutar(); // redonda ou oval, chuta
        break;
    case "comestivel":
        comer(); // comestível, só come
        break;
    case "sorvete":
        comer(); // sorvete derretendo, come...
    case "liquida":
        beber(); // ...depois bebe; liquida, só bebe
        break;
    default:
        nenhumaDasAnteriores();
}

Aqui se pode alterar as condições dinamicamente:
var acoes = {
    comestivel:comer,
    liquida:beber,
    redonda:chutar
}

var fn = acoes[bola] || nenhumaDasAnteriores;
fn();

...

acoes.leve = arremessar;

Etc. Para se determinar qual é a "mais simples", ou "mais correta", ou "mais fácil de dar manutenção" (e muito de vez em quando "mais eficiente"), somente pensando no código como um todo - e não somente se concentrando no trecho particular em que se testam as condições.
Answer: Há um efeito funcional: em uma estrutura condicional, quando um bloco é executado, os demais são ignorados.
Ou seja, no primeiro exemplo, há três estruturas condicionais, enquanto no segundo, há uma estrutura condicional divida em três blocos. No primeiro exemplo, as três estruturas são executadas; enquanto no segundo, caso uma seja executada, as demais serão ignoradas (sem perder tempo verificando, desnecessariamente, as condições dos argumentos).
Nesse caso, acredito que não haja diferença, porque aparentemente esse código está dentro de uma função, e ao retornar um valor, o resto do código não é executado.
Comment: Então um `if-else if` tem um ganho de performance por ignorar o restante?


Can the kicker alter the shape of the football before a kickoff, say by banging the tips on the ground?

Question: During the Chiefs-Broncos game in December 2017, I notice that the Chiefs' kicker banged the tips of the football on the ground before placing it in the kick stand, thus altering the shape of the football.
That doesn't seem right to me; was it legal?
Comment: Are you sure the shape was altered?
Comment: Will a football that has between 12.5 and 13.5 psi of air in it and is designed to stand up to the abuse of a game including being kicked really deform so easily?
Answer: Kickers as well as football players in general do not like to play with new balls. This is because they are harder, slicker and don't perform as well in general. Because of this they do any they can to break in balls before they use them which can include squeezing or pressing them into the ground.
There is lots of information on this available with a search.
https://www.reddit.com/r/nfl/comments/11nuzw/why_do_kickers_press_in_the_ends_of_the_football/


Basis of row space and subspace

Question: If given some vectors, and asked to find a basis for the subspace of R(n),
will the basis for the subspace be the same as the basis for the row space?
example:
given the following vectors:
(1,1,4,-3),(2,0,2,-2),(2,-1,3,2)
we can construct the matrix
<code>| 1 1 4 -3 |
| 2 0 2 -2 |
| 2 -1 3 2 |
</code>
and by reducing it to row echelon form we get
<code>| 1 1 4 -3  |
| 0 1 -5 -2 |
| 0 0 1 -0.5|
</code>
therefore:
<code>row(A) = { (1,1,-4,-3) , (0,1,-5,-2) , (0,0,1,-0,5) }
</code>
Will the basis for the subspace be the exact same thing?
Comment: Careful: $row(A) = span\{R_1, R_2,R_2\}$. The way you have it now makes it seem like there are only three vectors in the row space.
Answer: Edit:  The answer to your question is yes.
The row space of a matrix is the subspace of $\mathbb{R^n}$ spanned by its row vectors.  Therefore, the basis for your row space of this matrix will provide a basis for the subspace spanned by your original vectors.
Comment: Assuming your matrix A has m rows and n columns. The row space is a subspace of $R^n$ and the column space is a subspace of $R^m$.
Comment: Would the column space also be part of the subspace? Because when we use row operations it messes up the columns right?

Basis of row space and subspace


How to create OG image view?

Question: I facing issue with OG 7.2x and image.
I create a group content type and add new field with image. After that i upload some picture, and view with colorbox working fine.
After that, i create normal view all things is workings well. if i add contextual(OG member:group id) and relationship(member from og node), the picture disappeared and nothing display under OG view.
Would you please tell me that how to do this?
Many thanks.
Answer: Hi what you can do is that create a content pane from a view display and configure it in the following screen shot listed below.

Next in the fields section you can add the image field and other fields as per you like.

 ![Add fields accordingly][2]

Also you can clone the view that comes default with OG.
OG:CONTENT(clone this view and add fields)

Hope this helps. :)
Edit:- For displaying images
I havent done anything like this before. But I think you can do this by "rewriting" the result of the url field.
You can do this by clicking the field with the url that you will find under "FIELDS" in your view settings. Then under "Rewrite Results" you can write something like

here, 'image_url' must be the name of the field. you can verify this in the list displayed under "Replacement Patterns"
Hope this helps. :)
Comment: the Pictures still not display. when i following you step, the image field name appeared,but pictures not displayed.
Comment: @yutaolife Have edited my answer above and added for displaying images...just try if that works.
Comment: Also if you are using Image field type you can try and Click the '+' sign next to Relationships and you should most likely find one under 'Image'. Once a relationship is set up then you should see image in your fields. @yutaolife
Comment: Another helpful resource
http://www.metachunk.com/blog/adding-related-content-view-drupal-7

How to create OG image view?


Are there uncountably many $A\in M_3 (\mathbb {R})$ such that $A^8=I $?

Question: I'm working on the following problem:

Let $A \in M_3 (\mathbb {R})$ be such that $A^8=I$. Then

the minimal polynomial of $A$ can only be of degree $2$.
the minimal polynomial of $A$ can only be of degree $3$.
either $A = I$ or $ A = -I$.
there are uncountably many such $A$.

By taking $A=I $ we can eliminate options (1) & (2). For the minimal polynomial of $A$ in that case is of degree $1$. Now take
$$A =
\begin{bmatrix}
     1 & 0 & 0 \\
     0 & -1 & 0 \\
     0 & 0 & -1
\end{bmatrix}$$
Then $A^8=I $ but $A$ is neither $I$ nor $-I$. So option (3) is eliminated. Now I don't know how to proceed about with option  (4). Can someone help me please? Thanks in advance.
Comment: Hai @shwetha How was your exam?
Comment: @Failed to be a Mathematician  mmmmm....it was good. But I've made some careless mistakes in the final part. That pains a bit. You wrote this exam?
Comment: yes. me too made lot of mistakes :(
Answer: Hint: What about $$\begin{bmatrix}1&-t&0\\0&1&0\\0&0&1\end{bmatrix}\begin{bmatrix}1&0&0\\0&-1&0\\0&0&-1\end{bmatrix} \begin{bmatrix}1&t&0\\0&1&0\\0&0&1\end{bmatrix}$$
Comment: Am sorry! But I don't understand what you mean? Can you elaborate a little, please?
Answer: Hint The reflection $R$ about any $2$-dimensional subspace satisfies $R^2 = I$.
Answer: Let $O(\theta)$ be the $2 \times 2$ orthogonal matrix
$O(\theta) = \begin{bmatrix} \cos \theta & \sin \theta \\ -\sin \theta & \cos \theta \end{bmatrix}; \tag 1$
set
$P = \begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}; \tag 2$
then
$O^{-1}(\theta) = O^T(\theta) = \begin{bmatrix} \cos \theta & -\sin \theta \\ \sin \theta & \cos \theta \end{bmatrix}; \tag 3$
we have
$O^T(\theta) P O(\theta) = \begin{bmatrix} \cos \theta & -\sin \theta \\ \sin \theta & \cos \theta \end{bmatrix} \begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix} \begin{bmatrix} \cos \theta & \sin \theta \\ -\sin \theta & \cos \theta \end{bmatrix}$
$= \begin{bmatrix} \cos \theta & \sin \theta \\ \sin \theta & -\cos \theta \end{bmatrix} \begin{bmatrix} \cos \theta & \sin \theta \\ -\sin \theta & \cos \theta \end{bmatrix} = \begin{bmatrix} \cos^2 \theta - \sin^2 \theta & 2 \cos \theta \sin \theta \\ 2 \cos \theta \sin \theta & \sin^2 \theta - \cos^2 \theta \end{bmatrix}$
$= \begin{bmatrix} \cos 2 \theta & \sin 2 \theta \\ \sin 2\theta & -\cos 2 \theta \end{bmatrix}, \tag 4$
which is clearly an uncountable family of $2 \times 2$ matrices; furthermore,
$(O^T(\theta) P O(\theta))^2 = O^T(\theta) P O(\theta)  O^T(\theta) P O(\theta) =  O^T(\theta) P I P O(\theta)$
$= O^T(\theta)P^2 O(\theta) = O^T(\theta)I O(\theta) = I, \tag 5$
whence
$(O^T(\theta) P O(\theta))^8 = I \tag 6$
as well; now set
$A(\theta) = \begin{bmatrix} O^T(\theta) P O(\theta) & 0 \\ 0 & -1 \end{bmatrix}; \tag 7$
then
$A^8(\theta) = \begin{bmatrix} (O^T(\theta) P O(\theta))^8 & 0 \\ 0 & (-1)^8 \end{bmatrix} = \begin{bmatrix} I & 0 \\ 0 & 1 \end{bmatrix} = I, \tag 8$
and the family $\{ A(\theta)\mid \theta \in \Bbb R \}$ is also uncountable.
Comment: Thank you so much! But I require a 3x3 matrix. How can I extend it?
Comment: The family of matrices $A(\theta)$ defined in equation (7) are all $3 \times 3$.  Remember $O^T(\theta)PO(\theta)$ is $2 \times 2$!  In fact with $\theta = 0$ we get your $A$ matrix! Cheers!
Comment: oooooo! Thank you so much! I just missed it.... Thanks for such a lucid proof!
Comment: Your are more than welcome!  Cheers!
Answer: In fact, we can show a lot more than the OP asks, without getting tired.
In particular, in other posts, it is shown that the general solution depends on, at least, $1$ real parameter.
$\textbf{Proposition}$. The general solution of the equation (in $X$) $X^2=I_3$ depends on exactly $4$ real parameters.
$\textbf{Proof}$. Note that any solution $X\not= \pm I_3$ is similar to $\pm A$, where $A=diag(1,1,-1)$; let $Z=\{P^{-1}AP;P\in GL_3(\mathbb{R})\}$ be the similarity class of $A$. The dimension of the algebraic set $Z$ is $3^2-dim(C(A))$, where $C(A)$ is the commutant of $A$; that is, $9-(2^2+1)=4$.


Solving $4$ simultaneous linear equations modulo $26$

Question: I'm trying to solve these equations to solve a ciphertext which is encrypted by the Hill Cipher. I tried to solve these equations algebraically. (First choose two of them and try to eliminate one variable and after that choose another two and try the same thing for achieving two unknown two equations etc...)
\begin{align*}
\tag{1}7a + 24b + 6c &= 1 \mod 26 \\
\tag{2}16a + 2b + 20c &= 0 \mod 26 \\
\tag{3}9a + 13b + 13c &= 10 \mod 26 \\
\tag{4}10a + 15b + 6c &= 17 \mod 26
\end{align*}
After this method I got $a = 17$, $b = 1$ and $c = 24$ and $a = 17$, $b = 1$, $c = 11$. However, it did not work with all of the four equations. Is there another way to solve these equations?
Comment: Try the Chinese Remainder Theorem; it should make stuff easier.
Comment: How can I apply Chinese Remainder Theorem in these equation?
Comment: To solve them modulo $2$ and modulo $13$, then reconstruct the solutions. It makes deriving $a = 17$ very easy (first and third equations).
Comment: The "algebraic way" should work, provided you remember to do all your arithmetic modulo 26, and remember not to divide or multiply by anything that isn't prime to 26.
Comment: Multiplying should be harmless, though...
Comment: @Lord_Farin: Multiplying a line by zero can be very harmful...
Comment: Adding on to that: Try multiplication by 13 to equation 1. Then try multiplication by 13 to equation 2. Equation 3 times 2 is quite similar too.
Comment: Also, your solution 2 is the one that fails, on equation 3. Perhaps you divided by 2 or 13 (which is not coprime to 26) while solving for c?
Comment: Your strategy for solving does not seem correct. You eliminate two variables from two sets of equations, but still overall you have 4 equations and 4 unknowns. Be careful that you only divide or multiply by something relatively prime to 26 (or use the CRT).
Answer: As suggested by Lord_Farin, consider the equations modulo $2$ and modulo $13$ separately. Modulo $2$ you get
\begin{align}
a &\equiv 1 \mod 2 \\
0 &\equiv 0 \mod 2 \\
a + b + c &\equiv 0 \mod 2 \\
b &\equiv 1 \mod 2
\end{align}
which has solutions $\boxed{(a,b,c) \equiv (1,1,0) \mod 2}$. Modulo $13$ is a bit harder, but we get
\begin{align}
-6a - 2b + 6c &\equiv 1 \mod 13 \\
3a + 2b - 6c &\equiv 0 \mod 13 \\
-4a &\equiv -3 \mod 13 \\
-3a + 2b + 6c &\equiv 4 \mod 13
\end{align}
Using the third equation first, we get $a \equiv 4 \mod 13$, so that the other three become
\begin{align}
-2b + 6c &\equiv -1 \mod 13 \\
2b - 6c &\equiv 1 \mod 13 \\
2b + 6c &\equiv 3 \mod 13
\end{align}
Solving for $b$ and $c$, we get $b \equiv 1 \mod 13$ and $c \equiv 11 \mod 13$. So modulo $13$, the numbers $a,b,c$ satisfy $\boxed{(a,b,c) \equiv (4,1,11) \mod 13}$.
Combining the two boxes, we get the unique solution $\boxed{(a,b,c) \equiv (17,1,24) \mod 26}$.
Answer: Hint $\ $ By  $\rm (1)+(2),\,\ -3a \equiv 1\equiv 27,\:$ so $\rm\:a\equiv -9.\ $ By $\rm (2)+(4),\,\ 17b\equiv 17,\:$ so $\rm\:b\equiv 1.$  Substituting in $\rm\:(3)\:$ yields $\rm\:6c\equiv -12\:$ so $\rm\:c\equiv -2\pmod{\color{#C00}{13}}.\:$ By $\rm\:(3)\,\ mod\ 2\!:\ c \equiv -a -b = 9-1\equiv 0,\:$ hence $\rm\:c\equiv -2\pmod{\color{#C00}{26}}.\:$ Indeed $\rm\:(a,b,c)\equiv (-9,1,-2)\:$ satisfies all equations.