text:
Q: Measurement of the spin of the EPR pair in two orthogonal directions and how did Einstein tackle this? Let us consider two types of measurement in the EPR experiment. In Bohm's description of this experiment, the state of the electron-positron (called the EPR pair) is given by
$$
|{\rm EPR} \rangle =\frac{1}{\sqrt{2}}\left(|e+\rangle|p-\rangle -  |e-\rangle|p+\rangle\right)
$$
CASE-I First, suppose that Alice measures the electron-spin in the $z$-direction and obtains $S_z=+1/2$. Then, if Bob measures the positron-spin in the $z$-direction, quantum mechanics predicts that he obtains $S_z=-1/2$ with probability $1$. Einstein would argue that this is because the spins-projections of the EPR pair were fixed from the very beginning the pair was created. If the spin projection of the electron was $+1/2$ in some direction, then that of the positron was $-1/2$ in the same direction or vice-versa (because the pair does not have any net spin). So Einstein's point was that the quantum state is an incomplete description of the state.
CASE-II Now, consider a second situation. Suppose that Alice again measures the spin in the $z$-direction and obtains $S_z=+1/2$. Then, if Bob decides to measure the spin not in the $z$-direction but in the $x$-direction, quantum mechanics predicts that he will obtain $S_x=+1/2$ with probability $0.5$ and $S_x=-1/2$ also with probability $0.5$. How would Einstein explain this?
If this simple prediction is borne out in the experiment, will it not demolish Einstein's argument i.e. the spin-projections were fixed from the beginning? I mean, Einstein would have said since $S_z=+1/2$ for the electron, it must have been that $S_z=-1/2$ for the position from the very beginning. But if this were really so, the probability of getting $S_x=\pm 1/2$ should both be zero. Am I wrong in this last argument?

A: I'll explain the modern understanding of this situation first, and discuss Einstein briefly at the end. It does not seem to be crucial that the pair involves an electron and positron. Instead, let's assume that two qubits are prepared in the Bell state you have written,
$$\left| \text{Bell} \right\rangle = \left( \left| 01 \right\rangle - \left| 10 \right\rangle \right)/\sqrt{2} \, ,$$
in QI notation where $Z \left| 0 \right\rangle =  \left| 0 \right\rangle$ and $Z  \left| 1 \right\rangle = -  \left| 1 \right\rangle$. We prepare this state and give one qubit to Alice and the other to Bob, who are spatially separated.
The way I represent quantum measurements is formally explained here in the case of qubits. The representation follows from the Stinespring Dilation Theorem (see also Figure 1 of this work for a nice picture). Intuitively, it's the many-worlds picture of measurement. It reduces to Copenhagen when you project onto a particular outcome.
When a quantum system is measured, the system becomes entangled with the measurement apparatus in the measurement basis. To explain the formalism, imagine measuring an operator $A$ on a qubit, where $A$ has two eigenvalues, $a^{\,}_{\pm}$. We can write this observable as
$$ A \, = \, \sum\limits_{\pm} \, a^{\,}_{\pm} \, \mathbb{P}^{(\pm)}_{\,} \, , $$
where $\mathbb{P}^{(\pm)}_{\,}$ projects onto the eigenstates of $A$ with eigenvalues $a^{\,}_{\pm}$ (i.e., $A \, \mathbb{P}^{(\pm)}_{\,} = a^{\,}_{\pm}\, \mathbb{P}^{(\pm)}_{\,}$). For a Pauli matrix $A$ (or any operator with $A^2=\mathbb{1}$), $\mathbb{P}^{(\pm)}_{\,} = \left( \mathbb{1} \pm  A \right)/2$.
If the qubit is initially in the state $\left| \psi \right\rangle$, after measuring $A$, the state becomes
$$ \left| \psi \right\rangle \, \to \, \sum\limits_{\pm} \, \left( \mathbb{P}^{(\pm)}_{\,} \,\left| \psi \right\rangle \right)^{\,}_{\rm ph} \otimes \left| \pm \right\rangle^{\,}_{\rm out} \, , $$
where the state $\left| \pm \right\rangle^{\,}_{\rm out}$ is the post-measurement state of the measurement apparatus, which encodes the measurement outcome. The $\pm$ states are orthonormal. Also note that $\mathbb{P}^{(\pm)}_{\,} \,\left| \psi \right\rangle$ is simply the unnormalized collapsed wavefunction for the physical qubit given that outcome $\pm$ was observed (i.e., in the Copenhagen picture). However, in this representation, the expression above is already normalized, and no collapse is needed! All outcomes occur. Measurement entangles the apparatus / observer with the system along a particular outcome.
Case I: Suppose Alice measures $Z$ on her qubit. The Bell state is updated according to
$$\left| \text{Bell} \right\rangle \to \left( \left| 01 \right\rangle \otimes \left| 0 \right\rangle^{\,}_A - \left| 10 \right\rangle \otimes \left| 1 \right\rangle^{\,}_A\right)/\sqrt{2} \, ,$$
where the $A$ subscript denotes the qubit that encodes the outcome of Alice's measurement. If Bob then measures, the state becomes
$$\left| \text{Bell} \right\rangle \to \left( \left| 01 \right\rangle \otimes \left| 0 \right\rangle^{\,}_A \otimes \left| 1 \right\rangle^{\,}_B - \left| 10 \right\rangle \otimes \left| 1 \right\rangle^{\,}_A \otimes \left| 0 \right\rangle^{\,}_B \right)/\sqrt{2} \, ,$$
where the $B$ state labels Bob's outcome.
Importantly, nothing drastic happened to the physical state of the two qubits. This is what Einstein didn't realize at the time. And performing these operations in either order (or simultaneously) gives the same result. This is most clear from noticing that everything is invariant under relabelling $A \leftrightarrow B$ and then flipping both qubits. Contrary to Einstein's concerns: (1) there is no collapse or update required upon measurement of this state, (2) no information is sent upon measurement, and (3) nothing nonlocal happens (the measurement locally couples the measured qubit with the nearby measurement apparatus, no information is sent, etc.).
The way we know no information is sent upon measurement is that even if Bob knows he shares this Bell state with Alice, there is no operation he can perform on his qubit to tell if she measured, what she measured, or her outcome. If he also knows she intends to measure $Z$, there's still nothing he can do to tell whether she measured yet. The reason is physical: The order of measurements does not matter, and no information is transferred by a quantum measurement alone.
Case II: Now, suppose that Bob intends to measure $X$ instead. If we write the same Bell state in the $Z$ basis for Alice and the $X$ basis for Bob, it is instead
$$\left| \text{Bell} \right\rangle = \frac{1}{2}  \left( \left| 00 \right\rangle - \left| 01 \right\rangle  -\left| 10 \right\rangle -  \left| 11 \right\rangle \right) \, ,$$
where the two numbers refer to different operator bases (this is fine as long as we remember that). However, because the state is written in the measurement basis, basically the same thing happens as in the case of the $Z$ measurements above.
After both measurements are made (in either order), the state becomes
$$\left| \text{Bell} \right\rangle \to \frac{1}{2} \left( \left| 00,00 \right\rangle -  \left| 01,01 \right\rangle - \left| 10,10 \right\rangle -  \left| 11,11 \right\rangle \right) \, ,$$
where the digits before the commas in each ket give the physical states of both qubits (in the $Z$ and $X$ basis for Alice and Bob, respectively), and the digits after the commas are the recorded outcomes (in the same bases).
Again, the structure of the physical part of the state (in the measurement basis) does not change upon measurement. There is also nothing nonlocal and no need for action at a distance. The measurement devices are simply entangled with their respective qubits in the measurement basis. Nothing drastic happens, no information can be extracted, and the order of measurements is unimportant. These are merely properties of the Bell state.
Another important remark is that, if we don't tell either Alice or Bob that they share a Bell state, then if they measure $X$, $Y$, or $Z$ multiple times to construct expectation values and extract statistics, then on average, they get both outcomes with equal probability, no matter what the other party does. If they measure all operators, they conclude that their qubit is in the maximally mixed state $\rho = \mathbb{1}/2$, which is a random classical bit that contains no quantum information. It is only if Alice measures her qubit(s), communicates the outcome(s) to Bob, and Bob correctly performs an operation on his qubit that information can be transferred from Alice to Bob (e.g., quantum teleportation). The information is in the classical signal, which obeys relativistic causality / locality.
Einstein: I personally think Einstein would have been happy with this formulation of measurement, knowing what we know now. It is completely local, the state of the universe is completely deterministic under measurement (as opposed to probabilistic), everything is unitary, and nothing shocking or concerning happens. The only randomness is in the particular experience of classical objects, which see only one outcome. This is due to decoherence, which is needed to explain the emergence of classical physics anyway. Moreover, this formulation of measurements was used in this recent work to establish locality measurements (i.e., a finite speed of quantum information even in the presence of quantum measurements of an entangled state and instantaneous classical communication).
By comparison, Bohmian mechanics intrinsically violates locality, though it is also deterministic. As I understand, the main advantage (on paper) is "realism", meaning that our particular experience upon measurement could be predicted. However, this would require knowledge of the "pilot wave". But it seems to me this knowledge is experimentally inaccessible. So, for all experimental purposes, Bohmian mechanics is not practically a "real" theory. Which means it does no better than what I've written above, but also sacrifices locality. Copenhagen is neither local nor deterministic.
Einstein really liked locality, so that's why I think he would like this. I can't say how he would have reacted in 1935 if I showed him this. But I don't think that's an instructive thought experiment. This formulation obeys the principles he cared most about.


text:
Q: Why does Interface Builder constantly update its files (changes seem arbitrary)? Everyday, I notice in Xcode 4.5 with source control, Interface Builder very frequently changes xib files.
For example, I could open a xib and click on one of the views on the left side and switch one of the inspectors on the right.  And without actually doing any work, or modifying the file, the file is marked as unsaved.  Okay so I save it.
Then the Version assistant editor will show changes that seem arbitrary, sometimes even destructive.  In example: today I saw a long list of outlets that disappeared from the file, and a minute later they were back in the file, without me changing anything.
This seems a bit frustrating because it can lead to useless commits that have no useful changes.  I've reverted some times, and other times committed with a message like "automatic system-generated changes to xib file".
Including automatic changes in commits could lead to confusion when reviewing historical changes.  Genuine changes to a xib like creating a new object or changing the class name or autoresizing mask may get lost in the sea of unnecessary changes.

This is a duplicate of another SO question: How to disable Interface Builder document versioning from auto updating?
This issue was filed on radar by calvinBhai, that was later marked as a dupe of Bug ID# 11533872

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fetching .kmz files from local disk and importing them into Google Earth via API I need to import 3D models of each building in New York City into the Google Earth API.  I fetched their .kmz files using google.earth.fetchKml.  Since this command uses the URL of the kmz files and the number of files to imported is a lot it is very slow.
Is there any way I can fetch these files from my local disk?
Are there other formats I can use instead of .kmz?  For example .dae files?

A: You cannot use a local file (non http) url to fetch your KML data.
But you could run a local webserver and use that.
For example, if you have python installed you could go to your directory with your KML files and run "python -m SimpleHTTPServer 8000", at which point pointing to http://localhost:8000/myfile.kml would load them up.
That said you should also note that the terms of use for the plugin require your site be publicly available, amongst other things - so hopefully you are only using this setup for local testing :)


text:
Q: Como exibir dados de uma consulta no Modal? Tenho um button type="button" e quero que ele capture informações das minhas texts para eu fazer uma consulta no MySQL e exibir esse resultado num modal. Porém, só estou conseguindo capturar esses dados num button type="submit" e esse type="submit" não abre meu modal.
Como resolver isso?

A: Em meu site uso os seguintes códigos:

Nessa primeira situação uso a tag , onde guardo o id para fazer a consulta. veja:

<a href="#" title="Visualizar Pedido Por Inteiro" data-toggle="modal" data-target="#modal-pedidos" data-id="<?php echo $idPedidos; ?>" onclick="mostrarModal()">

É importante que você use o data-id, pois pode ocorrer, confusão na hora de mandar o código identificador na consulta, no meu caso o id.
Pega o id do pedido mandado pelo onClick, carrega o conteudo da ff_pedidos_detalhados_php.php  com o id recebido e abre a modal

function mostrarModal(){
        $(document).ready(function() {
          $('#modal-pedidos').on('show.bs.modal', function(e) {
            var idPedidos = $(e.relatedTarget).data('id');
            var url = "../../componentes/php/ff_pedidos_detalhados_php.php";
            $('.modal-content').load(url, {idPedidos:idPedidos},
            function(resultado){
             $('#myModal').modal({show:true});
            });
          });
        });
      }

Obs.: vale lembrar que ff_pedidos_detalhados é onde estão os selects, e toda a estrutruta que falta da modal, ou seja você tem que deixar na pagina que você quer abrir a modal, o "esqueleto da modal", veja como é a minha:

A: No tal botão se utilizar o type="button" class="fazQuery" pode utilizar query via AJAX em javascript exemplo:
    $(".fazQuery").on('click', function() {

        $("#modalId").modal('show');
        $("#modalBody").html("A carregar...");
        $.ajax({
            url: "urlProcura.php",
            data: {query: "Texto a procurar??" },
            success: function(resultado) {
                 $("#modalBody").html(resultado);
            },
            error: function(erro, resultado) {
               alert("Ocorreu um erro tente novamente.");
            }
        });
    });

No caso de estar a utilizar uma modal do bootstrap a função para abrir a modal é modal('show')
Exemplo de modal a utilizar:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

           A carregar...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: How to use multiple variables read from file with looping subprocess/popen I am using python to read 2 files from my linux os.  One contains a single entry/number 'DATE':

20111125

the other file contains many entries, 'TIME':

042844UTC
044601UTC
...
044601UTC

I am able to read the files to assign to proper variables.  I would like to then use the variables to create folder paths, move files etc... such as:

$PATH/20111125/042844UTC
$PATH/20111125/044601UTC
$PATH/20111125/044601UTC

and so on.
Somehow this doesn't work with multiple variables passed at once:
import subprocess, sys, os, os.path
DATEFILE = open('/Astronomy/Sorted/2-Scratch/MAPninox-DATE.txt', "r")
TIMEFILE = open('/Astronomy/Sorted/2-Scratch/MAPninox-TIME.txt', "r")
for DATE in DATEFILE:
    print DATE,
for TIME in TIMEFILE:
    os.popen('mkdir -p /Astronomy/' + DATE + '/' TIME) # this line works for DATE only
    os.popen('mkdir -p /Astronomy/20111126/' + TIME) # this line works for TIME only
    subprocess.call(['mkdir', '-p', '/Astronomy/', DATE]), #THIS LINE DOESN'T WORK

Thanks!

A: I would suggest using os.makedirs (which does the same thing as mkdir -p) instead of subprocess or popen:
import sys
import os
DATEFILE = open(os.path.join(r'/Astronomy', 'Sorted', '2-Scratch', 'MAPninox-DATE.txt'), "r")
TIMEFILE = open(os.path.join(r'/Astronomy', 'Sorted', '2-Scratch', 'MAPninox-TIME.txt'), "r")

for DATE in DATEFILE:
    print DATE,

for TIME in TIMEFILE:
    os.makedirs(os.path.join(r'/Astronomy', DATE, TIME))

    astrDir = os.path.join(r'/Astronomy', '20111126', TIME)
    try
        os.makedirs(astrDir)
    except os.error:
        print "Dir %s already exists, moving on..." % astrDir
    # etc...

Then use shutil for any cp/mv/etc operations.

From the os Docs:

os.makedirs(path[, mode])
  Recursive directory creation function. Like mkdir(), but makes all
  intermediate-level directories needed to contain the leaf directory.
  Raises an error exception if the leaf directory already exists or
  cannot be created. The default mode is 0777 (octal). On some systems,
  mode is ignored. Where it is used, the current umask value is first
  masked out.

A: I see a couple of errors in your code.
os.popen('mkdir -p /Astronomy/' + DATE + '/' TIME) # this line works for DATE only

This is a syntax error. I think you meant to have '/' + TIME, not '/' TIME. I'm not sure what you mean by "this line works for DATE only"?
subprocess.call(['mkdir', '-p', '/Astronomy/', DATE]), #THIS LINE DOESN'T WORK

What command do you expect to call? I'm guessing from the rest of your code that you're trying to execute mkdir -p /Astronomy/<<DATE>>. That isn't what you've coded though. Each item in the list you pass to subprocess.call is a separate argument, so what you've written comes out as mkdir -p /Astronomy <<DATE>>. This will attempt to create two directories, a root-level directory /Astronomy, and another one in the current working directory named whatever DATE is.
If I'm correct about what you wanted to do, the corrected line would be:
subprocess.call(['mkdir', '-p', '/Astronomy/' + DATE])

chown's answer using os.makedirs (and using os.path.join to splice paths, rather than string +) is a better general approach, in my opinion. But this is why your current code isn't working, as far as I can tell.


text:
Q: Changing the drawable size inside a button I want to create a Button like this:

Here is my code:
<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:drawablePadding="10dp"
android:id="@+id/button"
android:text="Play Game"
android:background="@drawable/ronaldo"
android:drawableRight="@drawable/messi" />

But the messi.jpeg is too large, and it doesn't show the text in this situation. How to decrease the image size to fit the button?
May anyone help me to solve this problem?

A: If you are using API >= 23, you can put the drawable resource within a XML file like this
messi_smaller.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/messi"
        android:width="smaller_width_in_dp"
        android:height="smaller_height_in_dp">
    </item>
</layer-list>

You must make sure to keep the drawable ratio when you set the width and the height. And just use this drawable in your button:
<Button
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:layout_gravity="center"
    android:drawablePadding="10dp"
    android:id="@+id/button"
    android:text="Play Game"
    android:background="@drawable/ronaldo"
    android:drawableRight="@drawable/messi_smaller" />

By this way, you can change the drawable size just in xml code

A: Solution 1:
Adding a drawable to a button has very limited functions. You can't change the drawable size, so the best way to fix it is to add a button with an image view beside it in a linear layout like this:
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/ronaldo"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:background="@null"
        android:text="Play Game"
        android:textColor="#ff0000"
        android:textStyle="italic" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:src="@drawable/messi" />

</LinearLayout>

Solution 2:
You can also do the following if you prefer this one, but you will have to add onClickListener() for each one of them:
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/ronaldo"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:background="@null"
        android:text="Play Game"
        android:textColor="#ff0000"
        android:textStyle="italic" />

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:src="@drawable/messi" />

</LinearLayout>

Solution 3:
As you have suggested in the comments, you would do something like this:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="80dp"
    android:layout_gravity="center"
    android:background="@drawable/ronaldo">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_alignLeft="@+id/buttonLayout"
        android:layout_alignRight="@+id/buttonLayout"
        android:background="@null" />

    <LinearLayout
        android:id="@+id/buttonLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:gravity="center"
            android:text="Play Game"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#ff0000"
            android:textStyle="italic" />

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:src="@drawable/messi" />

    </LinearLayout>

</RelativeLayout>

A: I deleted the button and made a layer like a button
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@android:color/background_light"
    android:gravity="center"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:onClick="go_map"
        android:clickable="true"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/img_m0"
            style="@style/menu2img"
            app:srcCompat="@drawable/ico_m0" />
       <TextView
            android:id="@+id/textView2"
            style="@style/menu2text"
            android:text="@string/men_map" />
    </LinearLayout>

[]

A: you can use a RelativeLayout like this:
<RelativeLayout
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:background="@drawable/ronaldo">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="play game"
        />
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:background="@drawable/messi"
        android:scaleType="fitXY"
        />
</RelativeLayout>

A: Try this :
final Button button = (Button) findViewById(R.id.button1);
ViewTreeObserver vto = button.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                button.getViewTreeObserver().removeOnPreDrawListener(this);
                //scale to 90% of button height
                DroidUtils.scaleButtonDrawables(button, 0.9);
                return true;
            }
        });

A: If you are handling multiple screen sizes, creating alternative version for given screen (drawable-mdpi folder and so on...) can be solution.

A: If you are importing a vector directly you can use the following:
<vector android:height="30dp"  android:tint="#00FF41"
    android:viewportHeight="24" android:viewportWidth="24"
    android:width="30dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="@android:color/white" android:pathData="M20,6h-8l-2,-2L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,8c0,-1.1 -0.9,-2 -2,-2zM20,18L4,18L4,8h16v10zM8,13.01l1.41,1.41L11,12.84L11,17h2v-4.16l1.59,1.59L16,13.01 12.01,9 8,13.01z"/>
</vector>

A: For API >= 23 and for android.support.design.widget.FloatingActionButton(FAB) , you can put the drawable resource (SVG) within a XML file with the path: File/New/Vector Asset and save the file under the name for example: ic_water_white_24dp.xml
and add app:maxImageSize attribute to the FAB:
<android.support.design.widget.FloatingActionButton
    android:id="@+id/btnAddProduct"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="16dp"
    android:clickable="true"
    android:focusable="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:maxImageSize="40dp" // add this line to increase the icon inside the fab
    app:srcCompat="@drawable/ic_water_damage_white_24dp" />

A: Try using vector files instead of JPEG. Also, you can even convert jpeg to svg format too.
Once you import svg file into Android Studio project, you are going to see <vector> resource then just change the size as you want by width, height attributes.
viewportWidth and viewportHeight is to set size for drawing on virtual canvas.
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="20dp" <!-- fix the size here -->
    android:height="20dp"
    android:viewportWidth="40"
    android:viewportHeight="40">
  <path .../> <!-- your shapes are here -->
  <path .../>
</vector>


text:
Q: Как правильно выполнить команду grep Начал изучать grep. Взял задание "Вывести все слова которые начинаются на буквы aA,zZ,cC,dD и заканчиваются буков y. За пару часов перелопатил кучу сайтов, смог только написать первую часть, которая находить первые буквы, а как написать чтобы находило слова по заглавным буквам + последней (y) я ХЗ(((
P.S посоветуйте хороший туториал для новичков.
grep '^[aA|zZ|cC|dD]

A: grep -o '^[aAzZcCdD][^[:space:]]*y'


text:
Q: How to log the backbutton that comes with the navigationcontroller I am creating a new view using
[[self navigationController]pushViewController:newViewController animated:YES];

The new view (newViewController) stacks on the top of the previous, and comes with a backbutton. I need to access this backbutton to override it. To begin with, finding out how to NSLog a string when  the back button is pushed will be of great help.
Best, Tom

A: I found the answer myself.
I have to make a new backbutton in the viewDidLoad function, and add a selector.
-(void) viewDidLoad
{
[super viewDidLoad];

    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"myTitle"
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(mySelector:)];

    self.navigationItem.leftBarButtonItem = backButton;
}

Then the selector:
-(void)mySelector
{

NSLog(@"backButton pushed");

}


text:
Q: Is it possible to make a pattern a single word for line wrapping purposes? Edit: I changed the title to more accurately present what I am asking for. The sentence immediately below should read "is it possible to make a pattern, such as '.*' treated as a single word for line wrapping purposes?"
Using vimwiki, is it possible to prevent a link from being word-wrapped?
Currently,
Etiam iaculis tempor dui, et mollis ligula accumsan et. Nam mattis cursus lorem sit amet accumsan. [Mauris elementum turpis eget](magna) ultrices molestie. Maecenas sagittis mauris id lacus consectetur, cursus mollis ex pretium. Quisque volutpat tellus ut augue fermentum ultricies eget eu metus. In lacinia sit amet massa ut feugiat.

becomes
Etiam iaculis tempor dui, et mollis
ligula accumsan et. Nam mattis cursus
lorem sit amet accumsan. [Mauris
elementum turpis eget](magna) ultrices
molestie. Maecenas sagittis mauris id
lacus consectetur, cursus mollis ex
pretium. Quisque volutpat tellus ut
augue fermentum ultricies eget eu metus.
In lacinia sit amet massa ut feugiat.

Note the Mauris elementum turpis eget link. The link markdown is broken when the text is reformatted.
Setting a longer textwidth won't solve the issue; I prefer the width I already have, and it will still happen. Link breaking will just happen at different points.
Changing the general word wrap settings won't work either ... they are just the way I like them, except in this one case.

A: As said in the comment, text-width does limit the column count of your file. You can't turn it on and off based on a line. It is exactly like you would write a small piece of paper, there is just no space left.
Of course, vim has different options to control where exactly it breaks the line (see h formatoptions and h fo-table) , but they aren't context-sensitive. And as soon as your text between [ and ] will be longer than 80 chars, you will have the problem again.
So what are the alternatives?

*

*Don't use text-width but use wrap. This will not limit your column count at all. But will display the lines of text over multiple lines of screen space.

*set colorcolumn=80 this does not do anything for you, but highlight the column, so you can wrap the text yourself.

*Write a custom function, that does the wrapping for you.

A: I was looking at this problem the wrong way.
Vimwiki is not parsing markdown link text with multiple lines correctly, but wontfix at the moment.
So, the options described elsewhere in this question are the only choices at the moment.
I answered this myself because I wanted to include an explanation of what was going on and a  pointer to the relevant issue.


text:
Q: SELECT the customer who has ordered the greatest quantity of Products in the case of two customers I have the following ORDERS table

I know query to select the customer that has ordered the greatest quantity. However, how would it work, if say, two customers have the same quantity. What query should I write to show both the customers?

A: You can use a subquery which checks that the quantity for a given record matches the largest quantity observed in the table:
SELECT *
FROM yourTable
WHERE qty = (SELECT MAX(qty) FROM yourTable)

This will return multiple records if there are more than one customer sharing the maximum quantity.
If you only wanted to get back a single record, even in the presence of ties, you could use this approach:
SELECT *
FROM yourTable
ORDER BY qty DESC
LIMIT 1

A: I think you want sum of qty per custNum.
If so you can try like:
select custNum,
    sum(qty) as qty
  from Orders
  group by custNum
  order by sum(qty) desc;

Fiddle here:
http://sqlfiddle.com/#!9/47931b/10

A: SELECT custnum,sum(qty) as total
FROM orders
group by custnum
having sum(qty) = (SELECT MAX(qty) FROM orders);

This will return both values.


text:
Q: Call methods from Swift initializer Let's say I have the following class in Swift (which has obvious problems)
class MyClass {
    let myProperty: String

    init() {
        super.init()
        self.setupMyProperty()
    }

    func setupMyProperty() {
        myProperty = "x"
    }
}

This is overly simplified but I'm basically trying to delegate the initialization of myProperty into the setupMyProperty() method. It's a pattern I use often to break down the different parts of the setup of a class.
But of course, I can't call self until the super initializer has run, and I can't run the super initializer until all the properties have been set, so I'm in a catch 22. On top of it since setupMyProperty() isn't considered an initializer, it won't be able to assign myProperty anyway.
Can anyone tell me how to implement this pattern in Swift?

A: declare it as an implicitly unwrapped optional
class MyClass : NSObject {
    var myProperty: String!

    init() {
        super.init()
        self.setupMyProperty()
    }

    func setupMyProperty() {
        self.myProperty = "x"
    }
}

page 499 of "The Swift Programming Language" manual

A: You can't use self until your instance's memory is fully initialized (at which point you can't set constant properties anymore), so the order in which your designated initializer has to do things is:

*

*initialize all properties added by this class

*call superclass initializer (if there is a superclass)

*now you can use self, call methods, etc

I'm not sure if there's a good workaround for the case of a constant property. One alternative would be to declare the property as an implicitly unwrapped optional, so it's initially set to nil:
class MyClass {
    var myProperty: String!
    init() {
        super.init() // only if you actually have a superclass, and make sure this does not use `myProperty`
        self.setupMyProperty()
    }

    func setupMyProperty() {
        myProperty = "x"
    }
}

Be careful with this, it loses a bit of type safety, as myProperty can now be nil, and if it is when you try to access it, it will lead to a runtime error. So only do this if you're sure it'll be initialized by all your designated initializers, not be used by anything called before setupMyProperty() in the initializer chain (e.g. when a superclass initializer calls a method you override that accesses myProperty), and never set to nil explicitly.
Also, cf. the docs, especially the section on Class Inheritance and Initialization for the whole call-order stuff I explained above.

A: Try putting setupMyProperty() in a constant. Then it is there before you initialise and you can call it from init(). You can even access parameters as follows:
class MyClass {
    var myProperty: String
    let setupMyProperty : (String) -> (void) = {
        param in
        self.myProperty = param
    }

    init(x: String) {
    // removed redundant line: super.init()
        self.setupMyProperty(x)
    }
}

A: Does setupMyProperty need to access self? If not, you can achieve this with a class method:
class MyClass: NSObject {
    let myProperty: String

    init() {
        myProperty = MyClass.setupMyProperty()
        super.init()
    }

    class func setupMyProperty() -> String {
        return "foo"
    }
}

A: class MyClass {

    let myProperty: String

    init() {
        super.init()
        self.myProperty = {
          // do your logic here
          return "x"
        }()
    }
}

A: Surprised to see the top voted answer.. It risks a lot of safety using an implicitly unwrapped optional.
If you're looking reset your properties, but keep one source of truth, use a Constants struct
class MyClass {
    var myProperty = Constants.myProperty

    init() {
        reset()
    }

    func reset() {
        myProperty = Constants.myProperty
    }

    struct Constants {
        static let myProperty = "hello"
    }
}

If you want to hide complicated set up logic away from init, use a static func
class MyClass {
    var myProperty: String

    init() {
        myProperty = MyClass.setUpProperty()
    }

    static func setUpProperty() -> String {
        // Complicated set up logic goes here..
        return "hello"
    }
}

If you're looking to have different initializers for an object, use a Constants struct combined with initialization logic
class MyClass {
    var myProperty = Constants.myProperty1

    init() {
        if externalState {
            init1()
        } else {
            init2()
        }
    }

    func init1() {
        myProperty = Constants.myProperty1
    }

    func init2() {
        myProperty = Constants.myProperty2
    }

    struct Constants {
        static let myProperty1 = "hello"
        static let myProperty2 = "there"
    }
}


text:
Q: Forcing the compiler to generate code for all member functions of a template class? Say I have this program
#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

int main() {
  A<int> a;
  a.foo();
  return 0;
}

Both g++ and clang++ only generate code for A<int>::foo(), but not for A<int>::bar(). This is annoying when you want to call this function while debugging. (e.g. vector<T>::at() ).
Is there some flag or other method by which you can force the generation of code for all member functions every time a template is instantiated?

A: No compiler flags, but the rules of the language govern what is happening here, and you can use them to your advantage.
Since you are implicitly instantiating A<int>, only the functions you use are instantiated:

[C++11: 14.7.1/1]: [..] The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, scoped member enumerations, static data members and member templates; [..]

If you explicitly instantiate A<int>, instead, then the whole thing gets instantiated.
#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

template class A<int>;   // <----

int main() {
  A<int> a;
  a.foo();
}

Here is some proof: http://coliru.stacked-crooked.com/a/582126aac45d6ea4

A: Explicitly instantiate it:
template class A<int>;

A: Aside what other's said about template instantiation, you might find useful to declare some functions/methods as 'used', to prevent the optimizers from removing them if they seem unused.
http://gcc.gnu.org/onlinedocs/gcc-4.3.5/gcc/Function-Attributes.html
see attribute used


text:
Q: fsck error on boot: /dev/sda6: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY I dual boot Ubuntu and Windows 7.
I was browsing on FireFox in Ubuntu and all of a sudden I get some error message, so I rebooted.
Now when I try to boot into Ubuntu I get this message:
fsck from util-linux 2.26.2
/dev/sda6 contains a file system with errors, check forced.
/dev/sda6: Inodes that were part of a corrupted orphan linked list found.

/dev/sda6: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY.
        (i.e., without -a or -p options)
fsck exited with status code 4
The root filesystem on /dev/sda6 requires a manual fsck

Busybox v1.22.1 (Ubuntu 1:1.22.0-15ubuntu1) built in shell (ash)
Enter 'help' for a list of built-in commands.

(initramfs) _

How can I fix this?

A: Try this:
fsck /dev/sda6

(where /dev/sda6 is the partition mentioned)
And enter Yes (y) to for each error. Or press a one time for always-yes.
Then reboot and it should be fine.

A: fsck -y /dev/sda

eg:
fsck -y /dev/sda1
fsck -y /dev/sda2

A: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY means there is some file system error in the disk. Run the fsck command manually. After that it will ask  some more questions - just answer y and press enter and finally reboot the server.

A: Type exit into the prompt, and it should tell you which partition has an error, e.g. /dev/sda6. Type fsck /dev/sdaX -y where X is the partition mentioned in the error. The -y flag answers yes to all the prompts it would otherwise have given you - you don't have to use it but it is recommended. Once it has finished, type reboot into the prompt, and if prompted, select to continue normal startup.

A: I have noticed that even if you do a fsck on the disk the problem may occur again in a few days.
I have found that the problem is worse on SSD disks than the regular HDD disks. I have found some steps that may fix the problem temporarily.
fsck -fy /dev/sda1

if sda1 is the right partition - the prompt will tell you exactly which one requires fsck.
After that if the systems boots up you may have another problem with the package management system, so if you open a terminal and type sudo apt-get update you may get an error. Do not worry. Run these commands:
sudo apt-get update
sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade

My opinion is that there is serious problem in Ubuntu with regard to SSD disks. The community should fix it.
I have found a possible cause of this problem: Probably the system did not shutdown normally.

A: In  (initramfs) prompt, type the command "fsck" then the path to your hard drive, for example "fsck /deb/sda2" , after add "-y" in order to accept all the fixing errors, for example "fsck /dev/sda2 -y", then the computer will check the errors on the filesystem to repair them.


text:
Q: How to drop function if it already exist in mysql I have defined custom function in mysql (using Rails 3 btw), beginning of the definition was like that
CREATE FUNCTION SOURCE_NAME(source INT(10))

This function works fine but now i need to drop it with mysql drop function statement.
This is the list of what i've tried already, none works, they only raise exceptions:
DROP FUNCTION IF EXISTS SOURCE_NAME;
DROP FUNCTION IF EXISTS SOURCE_NAME
DROP FUNCTION IF EXISTS SOURCE_NAME();
DROP FUNCTION IF EXISTS SOURCE_NAME()
DROP FUNCTION IF EXISTS 'SOURCE_NAME'
DROP FUNCTION IF EXISTS 'SOURCE_NAME';

and i have no idea what to do next, every example i find online looks different...

A: It works in Rails 3. Try the following code inside self.up of your migration file
execute <<-SQL
   DROP FUNCTION IF EXISTS function_name;
SQL


text:
Q: Writing data from kafka to hive using pyspark - stucked I quite new to spark and started with pyspark, I am learning to push data from kafka to hive using pyspark.
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import *
from pyspark.streaming.kafka import KafkaUtils
from os.path import abspath

warehouseLocation = abspath("spark-warehouse")

spark = SparkSession.builder.appName("sparkstreaming").getOrCreate()

df = spark.read.format("kafka").option("startingoffsets", "earliest").option("kafka.bootstrap.servers", "kafka-server1:66,kafka-server2:66").option("kafka.security.protocol", "SSL").option("kafka.ssl.keystore.location", "mykeystore.jks").option("kafka.ssl.keystore.password","mykeystorepassword").option("subscribe","json_stream").load().selectExpr("CAST(value AS STRING)")

json_schema = df.schema

df1 = df.select($"value").select(from_json,json_schema).alias("data").select("data.*")

The above is not working, however after extracting data, I want to insert data to hive table.
As I am completely new, looking for help.
Appreciated in advance! :)

A: from os.path import expanduser, join, abspath

from pyspark.sql import SparkSession
from pyspark.sql import Row

# warehouse_location points to the default location for managed databases and tables
warehouse_location = abspath('spark-warehouse')

spark = SparkSession \
.builder \
.appName("Python Spark SQL Hive integration example") \
.config("spark.sql.warehouse.dir", warehouse_location) \
.enableHiveSupport() \
.getOrCreate()

# spark is an existing SparkSession
spark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")
spark.sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")


text:
Q: Adding an editable prefix to the input - react I want to add an editable prefix to the phone number input. My code looks like this
                <input
                    changeHandler={this.onInputChange}
                    errors={errors}
                    onBlur={this.onInputBlur}
                    onFocus={this.onInputFocus}
                    resetErrors={clearFieldErrors}
                    value={`+41${phoneNumber}`}/>

however, after adding the prefix I can't write anything in input. Does anyone know why this is happening and how to fix it?

A: Instead of changeHandler, you should be using onChange. See examples in
https://reactjs.org/docs/forms.html#controlled-components.
Also you might use it as uncontrolled-component and give defaultValue={'+41'} too.

A: Instead of passing hard coded "+41" in value prop, just initialize the phoneNumber useState
Try the following code, you may find want you looking for.
export default function App() {
  const [inputPhoneNumber, setInputPhoneNumber] = React.useState('');
  const [phone, setPhone] = React.useState('+41');

  const inputChangeHandler = ({ target }) => {
    setPhone(target.value);
  };

  const submitHandler = (e) => {
    e.preventDefault();
    setInputPhoneNumber(phone);
    setPhone('+41');
  };

  return (
    <>
      <form onSubmit={submitHandler}>
        <input onChange={inputChangeHandler} value={phone} />
        <button type="submit">Submit</button>
      </form>
      <h1>{inputPhoneNumber}</h1>
    </>
  );
}


text:
Q: How to make table td taking up the whole width using css? I am making a site with tables mobile responsive. How do I make table td take up the whole full width(100%) using css?

        Column One
        Column Two

It is too hard to read information in two columns close to each other.

A: This will show the cells one below the other:
td {display:block;width:99.9%;clear:both}

or, as noted by @nux,
td {display:block; box-sizing:border-box; clear:both}

either should be enough, although microsoft browser won't oblige and you might need proprietary markup for those; then again if people plan to use a browser on their phone they wouldn't buy a microsoft phone, so the problem is minor.

A: When in mobile screen, change the tr to display:flex and td set to width 100%. Like below:
@media screen and (max-width: 576px){
    tr {
      display: flex;
      flex-wrap: wrap;
    }

    td {
      width: 100%;
    }
}

If your table td has a border, you might want to remove the first columns of td border in mobile so that first column td content will looks like it is in the same columns with 2nd td in mobile:
tr td:first-child {
  border: none;
}

A: The answers above are correct but you need to also make sure you'r td element has a reference for its 100% width otherwise it may not work. You should have this rule set at the start of your stylesheet:
body, html {
    width: 100%;
}

Take a look at this thread for more info:
HTML table td not full width when using display block and 100% width attributes

A: First, you need to make sure that your table has 100% width, then you can do the same with the th and td
table, td {
   width: 100%;
}

EDIT:
since you edited your original post, you should give the first td a class

td.first {
   width: 100%;
}

This will cause the first column to use as much of the page as it can and the second td will be just wide enough for the content. You may have to give it a width too if you don't want your text to wrap or something.


text:
Q: Convert linux ldapsearch to Windows dsquery I am converting a website fro being hosted on Linux and Apache to Windows and IIS. The pages are currently written in php but new functionality will be in something along the lines of C#.net

In the php files there is a popen command calling the ldapsearch command for linux and performing a query based on the users' id. What I need to do is switch this command over to dsquery, does anyone know of an easy way to convert between the two commands.

I have looked at Microsofts' documentation for dsquery but it seems lacking compared to ldapsearch. If anyone has a suggestion that may better fit this require I am open to the idea, but using dsquery or ldifde (or another built-in command) would be best.

Thank you for your help and replies.

A: PHP code should not have called ldapsearch.
instead: http://php.net/manual/en/book.ldap.php
.net code should not call dsquery.
instead: use native tools (not as easy to find online docs)
useful(?): http://www.youcanlearnseries.com/Programming%20Tips/CSharp/LDAPReader.aspx

A: are you sure you were looking in the right place for the documentation?  Here is a link to the dsquery command.  the ldapsearch syntax should be very similar from a dsquery filter perspective.
off hte top of my head (meaning I didn't test this) to query for a user by uid:
dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(uid='100'))" -attr samaccountname -limit 0


text:
Q: Convert UnsafeMutablePointer to UnsafePointer I'm using a C library in my Swift project, and one of functions requires a UnsafePointer<UnsafePointer<UInt8>?>! as an in-out argument where I should pass my data. But the problem is that I have this data in UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>! type.
My question is - What is the most efficient and easiest way to convert UnsafeMutablePointer to UnsafePointer in Swift 3? Those pointers are not much different "on paper" and they shouldn't be much different from technical context, but I couldn't find valuable information on that topic.
Any help would be appreciated. Thanks

A: UnsafePointers can be initialized with an UnsafeMutablePointer
// Any UnsafeMutablePointer with capacity one
let ump = UnsafeMutablePointer<Any>.allocate(capacity: 1)
// `up` now contains an UnsafePointer initialized with `ump`
var up = UnsafePointer(ump)


text:
Q: Appending GeoDataFrames does not return expected dataframe I have the following issue when trying to append dataframes containing geometry types. The pandas dataframe I am looking at looks likes this:
name     x_zone     y_zone
0  A1  65.422080  48.147850
1  A1  46.635708  51.165745
2  A1  46.597984  47.657444
3  A1  68.477700  44.073700
4  A3  46.635708  54.108190
5  A3  46.635708  51.844770
6  A3  63.309560  48.826878
7  A3  62.215572  54.108190

As you can see, there are four rows per name as these represent the corners of polygons. I need this to be in the the form of a polygon as defined in geopandas, i.e. I need a GeoDataFrame. To do so, I use the following code for just one of the name (just to check it works):
df  = df[df['name']=='A1']

x = df['x_zone'].to_list()
y = df['y_zone'].to_list()
polygon_geom = Polygon(zip(x, y))
crs = {'init': "EPSG:4326"}
polygon = gpd.GeoDataFrame(index=[name], crs=crs, geometry=[polygon_geom])
print(polygon)

which returns:
                                             geometry
A1  POLYGON ((65.42208 48.14785, 46.63571 51.16575...

polygon.info()

<class 'geopandas.geodataframe.GeoDataFrame'>
Index: 1 entries, A1 to A1
Data columns (total 1 columns):
 #   Column    Non-Null Count  Dtype
---  ------    --------------  -----
 0   geometry  1 non-null      geometry
dtypes: geometry(1)
memory usage: 16.0+ bytes

So fa, so good. So, for more name I though the following would work:
unique_place = list(df['name'].unique())

GE = []
for name in unique_aisle:
    f = df[df['id']==name]
    x = f['x_zone'].to_list()
    y = f['y_zone'].to_list()
    polygon_geom = Polygon(zip(x, y))
    crs = {'init': "EPSG:4326"}
    polygon = gpd.GeoDataFrame(index=[name], crs=crs, geometry=[polygon_geom])
    print(polygon.info())
    GE.append(polygon)

But it returns a list, not a dataframe.
[                                             geometry
 A1  POLYGON ((65.42208 48.14785, 46.63571 51.16575...,
                                              geometry
 A3  POLYGON ((46.63571 54.10819, 46.63571 51.84477...]

THis is strange, because *.append(**) works very well if what is to be appended is a pandas dataframe.
What am I missing? Also, even in the first case, I am left with only the geometry column, but that is not an issue because I can write the file to a shp and read it again to have a resecond column (name).
Grateful for any solution that'll get me going!

A: I guess you need an example code using groupby on your data. Let me know if it is not the case.
from io import StringIO
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
import numpy as np

dats_str = """index  id     x_zone     y_zone
0  A1  65.422080  48.147850
1  A1  46.635708  51.165745
2  A1  46.597984  47.657444
3  A1  68.477700  44.073700
4  A3  46.635708  54.108190
5  A3  46.635708  51.844770
6  A3  63.309560  48.826878
7  A3  62.215572  54.108190"""

# read the string, convert to dataframe
df1 = pd.read_csv(StringIO(dats_str), sep='\s+', index_col='index')

# Use groupBy as an iterator to:-
# - collect interested items
# - process some data: mean, creat Polygon, maybe others
# - all are collected/appended as lists
ids = []
counts = []
meanx = []
meany = []
list_x = []
list_y = []
polygon = []
for label, group in df1.groupby('id'):
    # label: 'A1', 'A3';
    # group: dataframe of 'A', of 'B'
    ids.append(label)
    counts.append(len(group))         #number of rows
    meanx.append(group.x_zone.mean())
    meany.append(group.y_zone.mean())
    # process x,y data of this group -> for polygon
    xs = group.x_zone.values
    ys = group.y_zone.values
    list_x.append(xs)
    list_y.append(ys)
    polygon.append(Polygon(zip(xs, ys))) # make/collect polygon

# items above are used to create a dataframe here
df_from_groupby = pd.DataFrame({'id': ids, 'counts': counts, \
                                'meanx': meanx, "meany": meany, \
                                'list_x': list_x, 'list_y': list_y,
                                'polygon': polygon
                               })

If you print the dataframe df_from_groupby, you will get:-
   id  counts      meanx      meany  \
0  A1       4  56.783368  47.761185
1  A3       4  54.699137  52.222007

                                        list_x  \
0    [65.42208, 46.635708, 46.597984, 68.4777]
1  [46.635708, 46.635708, 63.30956, 62.215572]

                                      list_y  \
0  [48.14785, 51.165745, 47.657444, 44.0737]
1  [54.10819, 51.84477, 48.826878, 54.10819]

                                             polygon
0  POLYGON ((65.42207999999999 48.14785, 46.63570...
1  POLYGON ((46.635708 54.10819, 46.635708 51.844...


text:
Q: Connect ArcGIS 10.6 to Oracle 12c Enterprise Edition I want to connect ArcGIS 10.6 to an Oracle 12c Enterprise Edition. However, I found different informations on the Esri websites on how to do so.

*

*I followed this website (http://desktop.arcgis.com/de/arcmap/latest/manage-data/gdbs-in-oracle/connect-oracle.htm) and executed it step by step. All worked fine, as far as I can tell. However, I got an Error message telling me that:

Failed to connect to specified server. Do you want to continue? Cannot
  connect to database because the database client software failed to
  load. Be sure the database client software is installed and configured
  correctly.

*I found this ESRI website https://desktop.arcgis.com/de/arcmap/latest/get-started/introduction/whats-new-in-arcgis.htm where it states that "Oracle Instant client will not work.", directly contradicting the instructions on website 1.

So what is right, respectivley, how can I connect ArcGIS 10.6 to Oracle 12c?

A: I managed to establish a connection. 2 things I changed seemed to have made the difference.

*

*I installed the 64bit Instant Client of Oracle, assuming that on Windows 10 64bit and ArcGIS 64bit that would be the correct choice - which it isn't. For my setup, you have to install the 32bit version of the Oracle Instant Client.

*I changed the location of the tnsnames.ora file from
C:/oracle/instantclient_12_2
to
C:/oracle/instantclient_12_2/network/admin


text:
Q: How to add spaces between string in a list that are in a lot of lists in a text file? I'm trying to add multiple lists into a text file, but all the strings inside are closed together when I try this method. My goal is to separate the strings inside.
checkingB = [['MARKETING', 'FCL10043', 'Ms_AUNG_SAN_LWIN', '21st_JULY', '1234'],
['MARKETING', 'FCL10043', 'Ms_AUNG_SAN_LWIN', '21st_JULY', '102761697'],
['PHYSICS', 'FCL10005', 'Ms_SHELLA_GEORGINA_BEATRICE', '15th_JULY', '102761697']]

with open('subjects.txt', 'a') as delA:
    for e in checkingB:
        delA.writelines(e)
        delA.writelines(' ')
        delA.write('\n')

*

*Expected output in the text file:
MARKETING FCL10043 Ms_AUNG_SAN_LWIN 21st_JULY 1234
MARKETING FCL10043 Ms_AUNG_SAN_LWIN 21st_JULY 102761697
PHYSICS FCL10005 Ms_SHELLA_GEORGINA_BEATRICE 15th_JULY 102761697

*Real output:
MARKETINGFCL10043Ms_AUNG_SAN_LWIN21st_JULY1234
MARKETINGFCL10043Ms_AUNG_SAN_LWIN21st_JULY102761697
PHYSICSFCL10005Ms_SHELLA_GEORGINA_BEATRICE15th_JULY102761697

A: One way:
with open('subjects.txt', 'a') as f:
    for row in checkingB:
        f.write(' '.join(row)+'\n')


text:
Q: HttpURLConnection is making multiple requests...any idea I am using the below code, which makes multiple POST requests for some users even if it is  coded only for one request, and for me it works good and getresponseCode return 200 and for some others it gives null pointer exception on getresponseCode.
URL url = new URL(strURL);
lobjConn = (java.net.HttpURLConnection) url.openConnection();`enter code here`
lobjConn.setRequestProperty("Cookie", "mysession="+smCookie);
lobjConn.setDoInput(true);
lobjConn.setDoOutput(true);
lobjConn.setUseCaches(false);
lobjConn.setRequestMethod("POST");
lobjConn.setRequestProperty("Connection", "Keep-Alive");
lobjConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
lobjOS = new DataOutputStream(lobjConn.getOutputStream());
int rc = lobjConn.getResponseCode();

when the execution reaches the above last line it throws NPE and when we check the log on server, it's showing 2 request reach server, even if we are not in any loop.
Exception:
java.lang.NullPointerException at
sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:719) at
sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:646) at
COM.ibm.JEmpower.applet.http.HttpURLConnection.getInputStream(HttpURLConnection.java:411) at
COM.ibm.JEmpower.applet.http.HttpURLConnection.getHeaderField(HttpURLConnection.java:703) at
java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:399) at
WBDocSubmitOffline.getObjectId(WBDocSubmitOffline.java:240) at
WBDocSubmitOffline.NotesMain(WBDocSubmitOffline.java:98) at
lotus.domino.AgentBase.runNotes(Unknown Source)

A: It's pointless getting the response code before you've sent anything. You're supposed to send the request first, then get the response code, then get the response if required. The code as written doesn't make sense.


text:
Q: Spring 4.3+ Override Default Behavior of @RequestParam for RequestMethod.HEAD Requests TL:DR
How can we override the current behavior of Spring 4.3+ that forces the use of the RequestMethod.GET or @GetMapping for HEAD requests so we can return the Content-Length header without having to write all the data to the responses OutputStream?

Longer Version:
It has just come to my attention that Spring has changed the way that GET/HEAD requests are handled by default:

HTTP HEAD, OPTIONS
@GetMapping — and also @RequestMapping(method=HttpMethod.GET), support
HTTP HEAD transparently for request mapping purposes. Controller
methods don't need to change. A response wrapper, applied in
javax.servlet.http.HttpServlet, ensures a "Content-Length" header is
set to the number of bytes written and without actually writing to the
response.
@GetMapping — and also @RequestMapping(method=HttpMethod.GET), are
implicitly mapped to and also support HTTP HEAD. An HTTP HEAD request
is processed as if it were HTTP GET except but instead of writing the
body, the number of bytes are counted and the "Content-Length" header
set.
By default HTTP OPTIONS is handled by setting the "Allow" response
header to the list of HTTP methods listed in all @RequestMapping
methods with matching URL patterns.
For a @RequestMapping without HTTP method declarations, the "Allow"
header is set to "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS". Controller
methods should always declare the supported HTTP methods for example
by using the HTTP method specific variants — @GetMapping,
@PostMapping, etc.
@RequestMapping method can be explicitly mapped to HTTP HEAD and HTTP
OPTIONS, but that is not necessary in the common case.

Sources:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-head-options
https://stackoverflow.com/a/45412434/42962
How can we override this default behavior so we can handle the HEAD response and set the Content-Length header ourselves?
We want to do this because we serve large files (think over 10 gigs in size) through our web application we would like to not have to read all the bytes into the Response's OutputStream if possible.
Here is an example of our current code.  Only the second method (handleRequest with the RequestMethod.GET) gets called.
@RequestMapping(value = "/file/{fileName:.+}", method = RequestMethod.HEAD)
public void handleHeadRequest(@RequestParam(value = "fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {

    File file = fileRepository.getFileByName(fileName)
    response.addHeader("Accept-Ranges", "bytes");
    response.addDateHeader("Last-Modified", file.lastModified());

    Long fileSize = file.length();
    response.addHeader(HttpHeaderConstants.CONTENT_LENGTH, fileSize.toString());
}

@RequestMapping(value = "/file/{fileName:.+}", headers = "!Range", method = RequestMethod.GET)
public void handleRequest(@PathVariable(value = "fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {

    File file = fileRepository.getFileByName(fileName)
    response.addHeader("Accept-Ranges", "bytes");
    response.addDateHeader("Last-Modified", file.lastModified());

    Long fileSize = file.length();
    response.addHeader(HttpHeaderConstants.CONTENT_LENGTH, fileSize.toString());

    // Stream file to end user client.
    fileDownloadHandler.handle(request, response, file);
}

A:
The HTTP HEAD method requests the headers that are returned if the
  specified resource would be requested with an HTTP GET method. Such a
  request can be done before deciding to download a large resource to
  save bandwidth, for example.
A response to a HEAD method should not have a body. If so, it must be
  ignored. Even so, entity headers describing the content of the body,
  like Content-Length may be included in the response. They don't relate
  to the body of the HEAD response, which should be empty, but to the
  body of similar request using the GET method would have returned as a
  response.
If the result of a HEAD request shows that a cached resource after a
  GET request is now outdated, the cache is invalidated, even if no GET
  request has been made.

*

*Request has body No

*Successful response has body No

*Safe Yes

*Idempotent   Yes

*Cacheable    Yes

*Allowed in HTML forms    No

Implicit HEAD support
From Spring's MVC doc:

@RequestMapping methods mapped to "GET" are also implicitly mapped to
  "HEAD", i.e. there is no need to have "HEAD" explicitly declared. An
  HTTP HEAD request is processed as if it were an HTTP GET except
  instead of writing the body only the number of bytes are counted and
  the "Content-Length" header set.

Check point :
That means we never have to separately create a handler method for HTTP HEAD verb as spring implicitly supports that, given that GET verb is already defined for the target URL.

Example
The Controller
Let's create a very simple controller with a handler method populating some headers:
@Controller
public class MyController {
    Logger logger = Logger.getLogger(MyController.class.getSimpleName());

    @RequestMapping(value = "test", method = {RequestMethod.GET})
    public HttpEntity<String> handleTestRequest () {

        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.put("test-header", Arrays.asList("test-header-value"));

        HttpEntity<String> responseEntity = new HttpEntity<>("test body", headers);

        logger.info("handler finished");
        return responseEntity;
    }
}

JUnit Tests
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup () {
        DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
        this.mockMvc = builder.build();
    }

    @Test
    public void testGet () throws Exception {

        MockHttpServletRequestBuilder builder =
                            MockMvcRequestBuilders.get("/test");

        this.mockMvc.perform(builder)
                    .andExpect(MockMvcResultMatchers.status()
                                                    .isOk())
                    .andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void testHead () throws Exception {

        MockHttpServletRequestBuilder builder =
                            MockMvcRequestBuilders.head("/test");

        this.mockMvc.perform(builder)
                    .andExpect(MockMvcResultMatchers.status()
                                                    .isOk())
                    .andDo(MockMvcResultHandlers.print());
    }
}

Implicit OPTIONS support
From Spring's MVC doc:

@RequestMapping methods have built-in support for HTTP OPTIONS. By
  default an HTTP OPTIONS request is handled by setting the "Allow"
  response header to the HTTP methods explicitly declared on all
  @RequestMapping methods with matching URL patterns. When no HTTP
  methods are explicitly declared the "Allow" header is set to
  "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS"

Check point : That means, we never have to separately create a handler method for HTTP OPTIONS verb as spring implicitly supports that, given that all handler methods explicitly specify the HTTP method with each @RequestMapping for the target URL.

Example
Let's continue with the above example just add one more test for the HTTP OPTIONS verb:
@Test
public void testOptions () throws Exception {

    ResultMatcher accessHeader = MockMvcResultMatchers.header()
                                                      .string("Allow", "GET,HEAD");

    MockHttpServletRequestBuilder builder =
                        MockMvcRequestBuilders.options("/test");

    this.mockMvc.perform(builder)
                .andExpect(MockMvcResultMatchers.status()
                                                .isOk())
                .andExpect(accessHeader)
                .andDo(MockMvcResultHandlers.print());
}


text:
Q: Connecting to RDS Postgres from Heroku I'm in the process of migrating my Heroku app database from Heroku to AWS RDS Postgres.
On my computer, I can connect to my RDS DB using:
psql -d "postgres://user:password@XXX.rds.amazonaws.com/mydb?sslrootcert=config/amazon-rds-ca-cert.pem&sslmode=require"

However, the same psql command run from within my heroku server just hangs forever.
Also, config/amazon-rds-ca-cert.pem is the RDS certificate that I added to my package as mentioned in the documentation https://devcenter.heroku.com/articles/amazon-rds#authorizing-access-to-rds-instance and here https://stackoverflow.com/a/29467638/943524 (I did combine certificates as I am using a eu-central-1 instance).
Would someone have an idea what is blocking the connection here ?

A: From the sound of it, your Network ACL or Security Groups are blocking your access. It looks like they allow your computer (perhaps your entire company's IP) but not Heroku. Check out the NACLs and Security Groups and you should find your answer (i.e. add Heroku IP range to your NACLs and/or Security Groups).


text:
Q: How to get file from Azure services(Azure blob storage) using Azure Service Principal Name(SPN) using C#.net? In General, I want to get files from the Azure blob storage account using C#.net, and I have an SPN name.
I have tried the following ways to do it.

Note: Here Authentication key stored in KEY Vault and Azure admin
provide us only SPN Name

Way 1:
private static async Task<string> GetAccessToken()
string accessToken = "";
            try
            {
                var authContext = new AuthenticationContext($"https://login.windows.net/{TenantID}");
                var credential = new ClientCredential("{ClientID}", "{SPN Name}");
                var result = await authContext.AcquireTokenAsync("https://storage.azure.com", credential);

                if (result == null)
                {
                    throw new Exception("Failed to authenticate via ADAL");
                }
                accessToken = result.AccessToken;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception for get Blob container" + ex.Message.ToString());
            }

Way 2:
private static async Task<string> GetAccessToken()
 var serviceTokenProvider = new AzureServiceTokenProvider();

            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(serviceTokenProvider.KeyVaultTokenCallback));

            SecretBundle secretValue = null;
            try
            {
                secretValue = await keyVaultClient.GetSecretAsync("{KeyVault URI}", {SPN_Name});
            }
            catch (Exception kex)
            {
                System.Diagnostics.Trace.WriteLine("Exception for get Blob container" + kex.Message.ToString());
            }
           return secretValue.Value;

Following code to Access File from Azure Storage
public static async Task<List<IListBlobItem>> GetBlobContainer( string containerName)
        var token = await GetAccessToken();
                TokenCredential tokenCredential = new TokenCredential(token);
        //here i am getting all one day file
                DateTime date = DateTime.Now;
                date = date.AddDays(-1);

                StorageCredentials _objectCrentials = new StorageCredentials(tokenCredential);

                CloudBlobClient blobClient = new CloudBlobClient(new Uri($"{Storage Account URI}"), _objectCrentials);
                // container
                CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
                IEnumerable<IListBlobItem> listOfBlob = blobContainer.ListBlobs().OfType<CloudBlob>()
                   .OrderByDescending(b => b.Properties.LastModified > date);
                //check her do you get any list
                _list = listOfBlob.ToList();

Way 2 have gives this error.
Parameters: Connection String: [No connection string specified],
Resource: https://vault.azure.net, Authority:
https://login.windows.net/{tenantID}. Exception Message: Tried the
following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified],
Resource: https://vault.azure.net, Authority:
https://login.windows.net/{tenantID}. Exception Message: Tried to get
token using Managed Service Identity. Unable to connect to the
Instance Metadata Service (IMDS). Skipping request to the Managed
Service Identity (MSI) token endpoint. Parameters: Connection String:
[No connection string specified], Resource: https://vault.azure.net,
Authority: https://login.windows.net/{tenantID}. Exception Message:
Tried to get token using Visual Studio. Access token could not be
acquired. Exception for Visual Studio token provider
Microsoft.Asal.TokenService.exe : TS003: Error, TS005: No accounts
found. Please go to Tools->Options->Azure Services Authentication, and
add an account to be to authenticate to Azure services during
development.
Parameters: Connection String: [No connection string specified],
Resource: https://vault.azure.net, Authority:
https://login.windows.net/{tenantID}. Exception Message: Tried to get
token using Azure CLI. Access token could not be acquired. 'az' is not
recognized as an internal or external command, operable program or
batch file.

Please correct me if followed wrong steps.


text:
Q: Does there exist such function or not? There exists a function $f$ such that $\lim_{x \rightarrow \infty} \frac{f(x)}{x^2} = 25$ and $\lim_{x \rightarrow \infty} \frac{f(x)}{x} = 5$
I am confused, I do not whether it is true or not
I have a counter-example, but I think thre might be such function

A: Hint
Suppose that such a function exists. Note that
$$
25=\lim_{x \to \infty} \frac{f(x)}{x^2} = \lim_{x \to \infty} \frac{f(x)}{x}\times \lim_{x \to \infty} \frac{1}{x}.
$$

A: It can't exist since :
$$\lim_{x \rightarrow \infty} \frac{f(x)}{x^2} =\lim_{x \rightarrow \infty} \frac{1}{x}\frac{f(x)}{x}=0\cdot5=0$$

A: There is no such a function.
To prove that, let $f$ be a solution.
The conditions on the limits impose that $f$ does not vanish near $+ \infty $.
Therefore, the ratio of the too quantities is $x$ and the limit of $x$ near $ + \infty $ is $ +\infty$ and not $ 5 / 25 $.
Another way of seeing that :
If $ f(x)/x $ has 5 as a limit, $f(x)/x^2$ has $0$ as a limit.

A: In this case,
$lim_{x\to\infty}\frac{f(x)}{x^2} = 25 = 5*5 =5* lim_{x\to \infty}\frac{f(x)}{x} $
so,
$lim_{x\to\infty}\frac1x = 5$
this gives a contradiction in the statement.


text:
Q: Int Value is not changing in button.SetOnClickListener() I am trying to change the value of circuitLength when fiveMinuteButton is clicked, however, the value is not being changed.
 private Button fiveMinuteButton;
 int circuitLength;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_workout_settings_screen);

    fiveMinuteButton = (Button) findViewById(R.id.fiveminutesbuttonid);

    fiveMinuteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            circuitLength = 5;

        }
    });

XML:
<Button
    android:id="@+id/fiveminutesbuttonid"
    android:background="@drawable/whitebutton_shape"
    android:layout_below="@+id/workoutlengthtitleId"
    android:layout_marginTop="8dp"
    android:text="@string/fiveminutes_text"
    android:layout_width="90dp"
    android:layout_height="60dp" />

A: Yes, it will not be updated as you are initializing value 5 every time when you click on fiveMinuteButton (i.e. circuitLength = 5 instead write circuitLength = circuitLength + 5).
Change your code to following.
private Button fiveMinuteButton;
 int circuitLength;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_workout_settings_screen);
    fiveMinuteButton = (Button) findViewById(R.id.fiveminutesbuttonid);
    circuitLength = 5;
    InitialzeUIButtons();

    fiveMinuteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            circuitLength = circuitLength + 5;

        }
    });

A: Your code is correct make sure onclick the button call or not
i think, your onclick button is not working

A: Try this code then let me know the out then we further investigate.
 private Button fiveMinuteButton;
 int circuitLength;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_workout_settings_screen);

    Toast.makeText(this,"circuitLength value ="+circuitLength, Toast.LENGTH_LONG).show();
    fiveMinuteButton = (Button) findViewById(R.id.fiveminutesbuttonid);
    fiveMinuteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            circuitLength = 5;
            Toast.makeText(ACtivityName.this,"circuitLength value ="+circuitLength, Toast.LENGTH_LONG).show();

        }
    });

A: Your code is correct for sure. if you change any variable inside Activity it remains changed, there are three possibility it changes to initial value.

*

*Activity stopped.

*Activity Recreated.

*variable changed manually.

as you said here

I put a log. It only stores the value temporarily, then after I call
  log again outside of the OnClickListener, the value is null.

I believe you are doing something like this.
private Button fiveMinuteButton;
int circuitLength;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_workout_settings_screen);

    fiveMinuteButton = (Button) findViewById(R.id.fiveminutesbuttonid);

    fiveMinuteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            circuitLength = 5;

            Log.e("count", ""+circuitLength);
        }
    });
    Log.e("count", ""+circuitLength);
}

Now when you app starts onCreate will called by default circuitLength is null so it is obvious you are getting null in log.
I hope it is clear. if you have any query feel free to ask.


text:
Q: How to call correctly a String splitting method from another class? Im trying to access the Spring splitting method from Person class in Main class, but it doesn't show me only the last result from the text. Its working very good when im integrating System.out.prinln in Person class, in method body but In this homework im not aloud to use System.out in Person class, only in Main class. The result must split the text in "Surname , Name , City". Where am i doing wrong? Thank you!
public class Person {
    public String surname;
    public String name;
    public String city;

    public Person(String text) {

        String[] person = text.split(" ");
        for (int i = 0; i < person.length; i++) {
            String surname = person[i].split("[.]")[0];
            String name = person[i].split("[./]")[1];
            String city = person[i].split("/")[1];

            this.surname = surname;
            this.name = name;
            this.city = city;
        }

    }
    }

public class Main {
    public static void main(String[] args) {

        Person p1 = new Person("John.Davidson/Berlin Michael.Barton/Rome Ivan.Perkinson/Munich");
        System.out.println(p1.surname + p1.name + p1.city);
// the result is the only the last persons info
}
}


text:
Q: Custom leave dialog in react-router I have a form where the user can edit stuff. If the user has some unsaved changed and wants to leave the page I want to give him a custom dialog, asking him if he is sure. If then the navigation should continue and the form changed flag should be reset, otherwise the user should stay at the page.
Here you can check my current higher order component which is checking this condition. It is working, but the function leave returns a string and react-router will then display that text in a native alert.
Is there a way that I can show my custom dialog in here? And can I also get a callback or similar of the alert, so that I can dispatch an event which tells the storage, that the latest changes are not important.
import React, {Component, PropTypes} from "react";
import connectRouter from "./connectRouter";
import { connect } from "react-redux";
import {injectIntl, intlShape} from "react-intl";

export default function confirmLeave(RouteTargetComponent) {

  @injectIntl
  @connectRouter
  @connect((state, routing) => {
    return {
      studies: state.studies
    };
  })
  class ConfirmLeaveHOC extends Component { // HOC = Higher Order Component

    static propTypes = {
      router: PropTypes.object.isRequired,
      route: PropTypes.object.isRequired,
      dispatch: PropTypes.func.isRequired,
      intl: intlShape.isRequired,
      studies: PropTypes.object.isRequired,
    };

    leave = () => {
      if (this.props.studies.isChanged) {
        // lets stop the navigation
        return this.props.intl.formatMessage({ id: "confirmLeave" });
      }
      // continue the navigation
      return true;
    }

    componentDidMount() {
      this.props.router.setRouteLeaveHook(this.props.route, this.leave.bind(this));
    }

    render() {
      // render the component that requires auth (passed to this wrapper)
      return (<RouteTargetComponent {...this.props}/>);
    }
  }

  return ConfirmLeaveHOC;
}

A: Since customizing browser dialogs is not possible, you'll have to render a separate component (e.g bootstrap modal) and use a callback to determine which button was clicked, and what action to take.
I actually ran into the same problem you're facing very recently, and I was able to solve it by using routerWillLeave and using callbacks from another component.
Form component
routerWillLeave = (route) => {
  if (!this.waitingForConfirm && this._hasUnsavedChanges() && !this.clickedSave) {
    this.refs.confirmAlert._show( ((v) => {
      if (v) {
        this.context.router.push(route.pathname);
      }
      this.waitingForConfirm = false;
    }).bind(this));
    this.waitingForConfirm = true;
    return false;
  }
}

The implementation of customized dialog like this one is unfortunately quite a pain in the back. I had to use 3 variables here to correctly control the desired behavior:

*

*waitingForConfirm - necessary to prevent the logic from running a second time when the user confirms to navigate out. Specifically, when the callback is run and we do this.context.router.push(route.pathname), the routerWillLeave will run again(!), but since we've already confirmed navigation we must prevent this logic from running again.

*_hasUnsavedChanges() - checks if any input fields have changed (no reason to ask if there's no changes to be saved).

*clickedSave - don't ask for confirmation if the user clicked Save - we know we want to leave.
Dialog component
_show = (callback) => {
  this.callback = callback;
  this.setState({show: true});
}

_hide = () => {
  this.setState({show: false});
  this.callback = null;
}

_dialogAction = (input) => {
  if (this.callback) {
    this.callback(input);
  }
  this._hide();
}

render() {
  return (
    ...
    <Button onClick={this._dialogAction.bind(this, true)}>Yes</Button>
    <Button onClick={this._dialogAction.bind(this, false)}>No</Button>
  );
}

Obviously, you'll have to customize the above snippets to fit your application, but hopefully it will provide some insight into how to solve the problem.

A: A less complicated and more forward way is using a setRouteLeaveHook on your component. In accordance to the react-router v2.4.0

    import React from 'react'
    import { withRouter } from 'react-router'

    const Page = React.createClass({

        componentDidMount() {
            this.props.router.setRouteLeaveHook(this.props.route, () => {
               if (this.state.unsaved)
                 return 'You have unsaved information, are you sure you want to
                 leave this page?'
           })
         }

         render() {
            return Stuff
         }

     })

     export default withRouter(Page)

Here is the React-router version on their github page


text:
Q: Protobuf-net serialization without annotation I looked at this answer and I am in a situation where I don't need to maintain backward compatibility and I have to have a solution that works without having to decorate dozens of classes with the attributes needed for protobuf-net. So I tried using RuntimeTypeModel.Default.InferTagFromNameDefault = true; but I may be not using it correctly because the Serializer.Serialize call still throws an exception asking for a contract. Here is my quick test, what am I doing wrong?
public enum CompanyTypes
{
    None, Small, Big, Enterprise, Startup
}

public class BaseUser
{
    public string SSN { get; set; }
}

public class User : BaseUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public DateTime BirthDate { get; set; }
    public List<string> Friends { get; set; }
    public Company Company { get; set; }
}

public class Company
{
    public string Name { get; set; }
    public string Address { get; set; }
    public CompanyTypes Type { get; set; }
    public List<Product> Products { get; set; }
}

public class Product
{
    public string Name { get; set; }
    public string Sku { get; set; }
}

[TestClass]
public class SerializationTest
{
    [TestMethod]
    public void SerializeDeserializeTest()
    {
        var user = new User
                       {
                           Age = 10,
                           BirthDate = DateTime.Now.AddYears(-10),
                           FirstName = "Test First",
                           LastName = "Test Last",
                           Friends = new List<string> { "Bob", "John" },
                           Company = new Company
                                         {
                                             Name = "Test Company",
                                             Address = "Timbuktu",
                                             Type = CompanyTypes.Startup,
                                             Products = new List<Product>
                                             {
                                                new Product{Name="Nerf Rocket", Sku="12324AC"},
                                                new Product{Name="Nerf Dart", Sku="DHSN123"}
                                             }
                                         }
                       };

        RuntimeTypeModel.Default.InferTagFromNameDefault = true;
        using (var memoryStream = new MemoryStream())
        {
            Serializer.Serialize(memoryStream, user);
            var serialized = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        }
    }
}

A: The question is old, but maybe someone will need this. I implemented ProtobufSerializer class which will construct your Type graph upon use. You just need to annotate your DTO with [KnownTypeAttribute] and [DataMember]/[IgnoreDataMember] attributes. Mostly this is refactored version of another nuget project from some guy. This way you don't need to include protobuf in your contract dependencies:
    internal sealed class ProtobufSerializer
    {
        private readonly RuntimeTypeModel _model;
        private const BindingFlags Flags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        private readonly Dictionary<Type, HashSet<Type>> _subTypes = new Dictionary<Type, HashSet<Type>>();
        private readonly ConcurrentDictionary<Type, bool> _builtTypes = new ConcurrentDictionary<Type, bool>();
        private static readonly Type[] ComplexPrimitives = new [] { typeof(object), typeof(ValueType), typeof(Enum), typeof(Array)};
        private readonly object _sync = new object();

        public ProtobufSerializer()
        {
            _model = TypeModel.Create();
        }

        public void Serialize(Stream s, object input)
        {
            EnsureType(input.GetType());
            _model.Serialize(s, input);
        }

        public T Deserialize<T>(Stream s)
        {
            EnsureType(typeof(T));
            return (T)_model.Deserialize(s, null, typeof(T));
        }

        public void EnsureType(Type type)
        {
            if (_builtTypes.ContainsKey(type))
            {
                return;
            }
            lock (_sync)
            {
                if (_builtTypes.ContainsKey(type))
                {
                    return;
                }
                var all = GetGraph(type).ToArray();
                foreach (var t in all)
                {
                    InternalBuild(t);
                }
            }
        }

        private void InternalBuild(Type type)
        {
            if (IsPrimitive(type))
            {
                return;
            }

            FlatBuild(type);
            EnsureBaseClasses(type);
            EnsureGenerics(type);

            _builtTypes.TryAdd(type, false);
        }

        private bool IsPrimitive(Type type)
        {
            return type == null || type.IsPrimitive || _model.CanSerializeBasicType(type) || _builtTypes.ContainsKey(type) || ComplexPrimitives.Contains(type);
        }

        private static IEnumerable<Type> GetGraph(Type type)
        {
            return type.TraverseDistinct(GetConnections).Distinct().OrderBy(x=> x.FullName);
        }

        private static Type GetParent(Type type)
        {
            return type.BaseType;
        }

        private static IEnumerable<Type> GetChildren(Type type)
        {
            var knownTypes = type.GetCustomAttributes(typeof(KnownTypeAttribute)).Cast<KnownTypeAttribute>().Select(x => x.Type).ToArray();
            foreach (var t in knownTypes)
            {
                yield return t;
            }

            var fields = GetFields(type);
            var props = GetProperties(type);
            foreach (var memberType in fields.Select(f => f.FieldType))
            {
                yield return memberType;
            }
            foreach (var memberType in props.Select(f => f.PropertyType))
            {
                yield return memberType;
            }
        }

        private static IEnumerable<Type> GetConnections(Type type)
        {
            var parent = GetParent(type);
            if (parent != null)
            {
                yield return parent;
            }
            var children = GetChildren(type);
            if (children != null)
            {
                foreach (var c in children)
                {
                    yield return c;
                }
            }
        }

        private void FlatBuild(Type type)
        {
            if(type.IsAbstract)
                return;

            var meta = _model.Add(type, false);
            var fields = GetFields(type);
            var props = GetProperties(type);
            meta.Add(fields.Select(m => m.Name).ToArray());
            meta.Add(props.Select(m => m.Name).ToArray());
            meta.UseConstructor = false;
            foreach (var memberType in fields.Select(f => f.FieldType).Where(t => !t.IsPrimitive))
            {
                InternalBuild(memberType);
            }
            foreach (var memberType in props.Select(f => f.PropertyType).Where(t => !t.IsPrimitive))
            {
                InternalBuild(memberType);
            }
        }

        private static FieldInfo[] GetFields(Type type)
        {
            return type.GetFields(Flags).Where(x => x.IsDefined(typeof(DataMemberAttribute))).Where(x => !x.IsDefined(typeof(IgnoreDataMemberAttribute))).ToArray();
        }

        private static PropertyInfo[] GetProperties(Type type)
        {
            return type.GetProperties(Flags).Where(x => x.IsDefined(typeof(DataMemberAttribute))).Where(x=> !x.IsDefined(typeof(IgnoreDataMemberAttribute))).ToArray();
        }

        private void EnsureBaseClasses(Type type)
        {
            var baseType = type.BaseType;
            var inheritingType = type;

            while (!IsPrimitive(baseType))
            {
                HashSet<Type> baseTypeEntry;

                if (!_subTypes.TryGetValue(baseType, out baseTypeEntry))
                {
                    baseTypeEntry = new HashSet<Type>();
                    _subTypes.Add(baseType, baseTypeEntry);
                }

                if (!baseTypeEntry.Contains(inheritingType))
                {
                    InternalBuild(baseType);
                    _model[baseType].AddSubType(baseTypeEntry.Count + 500, inheritingType);
                    baseTypeEntry.Add(inheritingType);
                }

                inheritingType = baseType;
                baseType = baseType.BaseType;
            }
        }

        private void EnsureGenerics(Type type)
        {
            if (type.IsGenericType || (type.BaseType != null && type.BaseType.IsGenericType))
            {
                var generics = type.IsGenericType ? type.GetGenericArguments() : type.BaseType.GetGenericArguments();

                foreach (var generic in generics)
                {
                    InternalBuild(generic);
                }
            }
        }
    }

And also some simple extensions:
    public static IEnumerable<T> TraverseDistinct<T>(this T enumer, Func<T, IEnumerable<T>> getChildren)
    {
        return new[] { enumer }.TraverseDistinct(getChildren);
    }
    public static IEnumerable<T> TraverseDistinct<T>(this IEnumerable<T> enumer, Func<T, IEnumerable<T>> getChildren)
    {
        HashSet<T> visited = new HashSet<T>();
        Stack<T> stack = new Stack<T>();
        foreach (var e in enumer)
        {
            stack.Push(e);
        }
        while (stack.Count > 0)
        {
            var i = stack.Pop();
            yield return i;
            visited.Add(i);

            var children = getChildren(i);
            if (children != null)
            {
                foreach (var child in children)
                {
                    if (!visited.Contains(child))
                    {
                        stack.Push(child);
                    }
                }
            }
        }
    }

A: It's quite experimental at this phase but I've made a small library that takes most Types and generates the Protobuf-net serializers at run-time: https://github.com/fnicollier/AutoProtobuf

A: InferTagFromName (and it's twin, InferTagFromNameDefault) only take a hand when it is necessary to resolve a tag number for a member; they don't influence which members need to be serialized (so currently the answer to that would be: none, even if the system knew about them). The option you might have chosen would be ImplicitFields, but that is currently only available as a [ProtoContract(...)] marker. If you don't mind a little annotation, a pragmatic fix may be:
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]

on User, Company and Product, and something a bit more complex for BaseUser (because of the inheritance):
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, ImplicitFirstTag = 10)]
[ProtoInclude(1, typeof(User))]

Note we haven't had to add lots of per-member annotation. If you are really really anti-attributes, then it is also possible to configure the entire model through code, via:
RuntimeTypeModel.Default.Add(typeof(Product), false).Add("Name", "Sku");
RuntimeTypeModel.Default.Add(typeof(Company), false).Add("Name", "Address",
         "Type", "Products");
RuntimeTypeModel.Default.Add(typeof(User), false).Add("FirstName", "LastName",
         "Age", "BirthDate", "Friends", "Company");
RuntimeTypeModel.Default.Add(typeof(BaseUser), false).Add(10, "SSN")
         .AddSubType(1, typeof(User));


text:
Q: Is my SSD performing poorly? Recently I've noticed that my SSD, which is a Crucial model CT128V4SSD2, is performing really really poorly. I took a benchmark test and here's the result:

In addition, I noticed from the Task Manager dialog in Windows 8 that the response time of the drive is very long.

Is my SSD having serious problems? Is there a way to identify what's causing the slowness?

A: According to the specs for your drive:

Newegg Product Description
  Performance
  Max Sequential Read
  Up to 230 MB/s
  Max Sequential Write
  Up to 175 MB/s
  4KB Random Read
  Up to 10,000 IOPS
  4KB Random Write
  Up to 4,000 IOPS
  MTBF
  1,200,000 hours

That suggests that your read is about there, the write is a bit slow (but you aren't doing sequential in some of those tests - so not alarming).
The seek time is pretty questionable though.  Might be a sign that it was formatted poorly, oddly enough.  SSD's are a bit more particular about that (the best tool I have read of/used is Parted).

A: Look at the picture. Is tells you that you run the SSD in IDE mode (PCIIDE) instead of AHCI (MSHACI/AMD_sata). So go into the BIOS and change the mode to AHCI.
Attention, enable the AHCI drivers first or you'll get the 0x7B STOP code "INACCESSABLE_BOOT_DEVICE".
http://support.microsoft.com/kb/922976
The key is renamed in Windows 8 to StorAHCI instead of Msahci, the rest is the same.