text:
Q: Java: What type of list to use in my multi-threaded app I'm new to using threads and just trying to figure things out. My end game is to have a list of URLs, my program will take one URL from the list at a time and perform an action using that URL. There'll be a lot of URLs and this list may possibly be added to while some threads are using the same list.
To start experimenting and learning I'm using a simple ArrayList filled with numbers and am using a threaded pool to get the URLs. Here's my code:
public static void main(String[] args) {

    for (int i = 0; i < 200; i++){
        test.add(i);
    }

    SlothTest runner = new SlothTest();
    Thread alpha = new Thread(runner);
    Thread beta = new Thread(runner);

    ExecutorService tasker = Executors.newFixedThreadPool(10);

    while (!listEmpty()){
        tasker.submit(new SlothTest());
    }

    tasker.shutdown();
    System.out.println("Complete...");
}

@Override
public void run() {
    getLink();
    try {
        Thread.sleep(20);
    } catch (InterruptedException e) {
    }
}

private synchronized String getLink(){
    link = Thread.currentThread().getName() + " printed " + test.indexOf(test.size()-1);
    test.remove(test.size()-1);
    System.out.println(link);
    return link;
}

private synchronized static boolean listEmpty(){
    if (test.size() > 0){
        return false;
    } else {
        return true;
    }
}

I'm running into some concurrency issues while running the program and getting some -1's for my output. I'm not sure why this is happening and I know my above code is rough but I'm really in the learning stage a multi-threaded apps. Can anyone help me first off with fixing my concurrency issue and then if you can give me any pointers about my above code that would also be great

A: One problem is that
while (!listEmpty()){
    tasker.submit(new SlothTest());
}

is not atomic. So listEmpty might return false, but become true by the time you reach the next statement.
Another one is that you synchronize on two different monitors:
private synchronized String getLink(){ //synchronized on this

private synchronized static boolean listEmpty(){//synchronized on this.class

Have you considered using a BlockingQueue instead of a list, which has useful methods for what you are trying to achieve.

A: You're not globally synchronizing. By using synchronized methods you are locking the current instance, which is different for each task. You should use a global lock instead:
final static Object globalLock = new Object();

private String getLink() {
   synchronized (globalLock) {
      link = Thread.currentThread().getName() + " printed " + test.indexOf(test.size()-1);
      test.remove(test.size()-1);
   }
   System.out.println(link);
   return link;
}

private boolean listEmpty(){
    synchronized (globalLock) {
       if (test.size() > 0){
          return false;
       } else {
          return true;
       }
    }
}

A: Try using a ConcurrentLinkedQueue for your list of URLs. This is a good implementation often used in producer-consumer examples, similar to yours (although you don't have an active 'producer', per-se).


text:
Q: Мобильное меню с visibility При появлении во время анимации появляется сначала под контентом, потом всплывает сверху и становится на своё место.
Хочу сделать, чтобы меню всплывало поверх всеъ элементов. прописывал z-index - не помогает.
В JS меню меняется по visibility от hidden до visible и меняется Opacity.

A: Ответил на свой вопрос сам - position-absolute не задал менюшке... XD

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django Error : userprofile matching query does not exist I am newbie to Django. I am trying to create UserProfile. First I created one model and its handler in models.py as follows..
class UserProfile(models.Model):
    user = models.ForeignKey(User,null=False)

    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

Then edited settings.py with
AUTH_PROFILE_MODULE = "lib.UserProfile"

where lib is root folder which contains init.py ,models.py and all.
Then I deleted all the current user in the collection , and when i reentered them from admin panel , a new collection lib_userprofile is automatically created with fields i mentioned in model. Now I crearted a view as follows
  class CurrentUser(APIView):
        authentication_classes = (authentication.TokenAuthentication,)
        def get(self,request):
            if request.user.is_authenticated():
                        profile=request.user.get_profile()
                        return Response(profile)

But is giving me following error..
UserProfile matching query does not exist.
Request Method: GET
Request URL:    http://pawan.demoilab.pune/api/currentuser
Django Version: 1.3.7
Exception Type: DoesNotExist
Exception Value:
UserProfile matching query does not exist.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/query.py in get, line 351
Python Executable:  /usr/bin/python
Python Version: 2.7.3
Python Path:
['/var/www/pawan.demoilab.pune/web/api',
 '/usr/local/lib/python2.7/dist-packages/Fabric-1.8.0-py2.7.egg',
 '/usr/local/lib/python2.7/dist-packages/paramiko-1.12.0-py2.7.egg',
 '/usr/local/lib/python2.7/dist-packages/ecdsa-0.10-py2.7.egg',
 '/usr/local/lib/python2.7/dist-packages/pymongo-2.6.3-py2.7-linux-i686.egg',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/pymodules/python2.7']

Any help would be appreciated please.. I found out many questions on this error , but i was not able to resolve error..

A: I have resolved the error. I am answering my own question as it might help someone facing same problem.
I encountered error in get_profile function , So I checked the code of models.py file located at /contrib/auth/models.py at 383 line in get_profile() function by replacing user__id__exact=self.id with user = self.id  And it worked Fine.


text:
Q: How can make 2 columns with table in angular I have this code in angular template which just makes the header on left and data on right from top to bottom.

                {{ f }}
                {{ data[f] }}

But instead of one field in one row i want to have 2 fields in one row and 3rd field and 4th field in second row and so on.
so that i have 2 columns layout

{{ f }}
 {{ data[f] }}
 {{ f }}
 {{ data[f] }}

field = ['id', 'name', 'username', 'email', 'age']

data = [{id:1, name: 'john', username: 'john', age: 20, email: 'test'}]

The result i want is

id:	1	name:	john

username:	john	age:	20

This should be done with ng-repeat rather hard coding stuff

A: Here's an answer. I'm not sure it's exactly what you want but I think it comes close: http://plnkr.co/edit/ADKu2WEb9TyvEXASOJyz?p=preview
Note that I'm using ng-repeat-start/ng-repeat-end to handle the multi-line thing you want to do:

      {{ label(0) }}:
      {{ value(row, 0) }}
      {{ label(1) }}:
      {{ value(row, 1) }}

      {{ label(2) }}:
      {{ value(row, 2) }}
      {{ label(3) }}:
      {{ value(row, 3) }}

The rest is just a super simple module and controller:
angular.module('example', [])
  .controller('ExampleController', function ($scope) {
    var fields = [ 'id', 'name', 'username', 'email', 'age' ];
    $scope.data = [{id:1, name: 'john', username: 'john', age: 20, email: 'test'}];

    $scope.label = function (fieldNumber) {
      return fields[fieldNumber];
    };

    $scope.value = function (row, fieldNumber) {
      return row[fields[fieldNumber]];
    }
  });

A: Hi I tried but you have to change your response into below format
$scope.data = {
    data1: {
        id: 1,
        name: 'john',
    },
    data2: {
        username: 'john',
        age: 20
    }
};

and you don't need field variable
Below is how to have to repeat in you html
although I haven't given you on two columns

                {{key}} : {{val}}


text:
Q: Inconsistent jquery button click behaviour Im a bit new to jquery so this may be a common probably but I am unable to find what I need on the web.
The issue:
I have a div(inner1) inside a div(outer), the inner1 div is hidden until a button is clicked, when clicked the inner1 div is shown and fades out the background. Within inner1 I have another div(inner2) with similar functionality. When inner1 shows a button is displayed to show inner2. The above works fine. My issue is that if I click the button to show inner1, then exit(hide) the shown div(inner1) then push the button to show it again it now shows both of the inner divs(inner1, inner2). Does this make sense? I have no idea why this is happening.
The Code:
Html:

 x
Text1
        <input type="button" id="btnsm1" value="t1" />

 x Text2

<input type="button" id="btnsm" value="t" />

Jquery:
$(document).ready(function () {
    $('#btnsm').on('click', function () {
        $('.documentlist>.modalBackground').toggleClass('show');
        $('.documentlist>.modalContent').toggleClass('show');
    });
    $('#btnsm1').on('click', function () {
        $('.documentdetails>.modalBackground').toggleClass('show');
        $('.documentdetails>.modalContent').toggleClass('show');
    });
    $('.close-modal').on('click', function () {
        $('.modalBackground').toggleClass('show');
        $('.modalContent').toggleClass('show');
    });

    $('.modalBackground').on('click', function () {
        $('.modalBackground').toggleClass('show');
        $('.modalContent').toggleClass('show');
    });
});

A Fiddle of the above.
Does anyone have any ideas?

A: You need to explicitly say removeClass since .toggle() adds 'show' if not there and removes 'show' if present, cant rely on that in close where you always want to remove the show class from both the elements
Here is what you want to do
$('.close-modal,.modalBackground').on('click', function () {
    $('.modalBackground').removeClass('show');
    $('.modalContent').removeClass('show');
});

Edit 2: I didn't check you had to use back as close trigger updated fiddle $('.close-modal,.modalBackground')
Updated fiddle

A: $(document).ready(function () {
    $('#btnsm').on('click', function () {
        $('.documentlist>.modalBackground').toggleClass('show');
        $('.documentlist>.modalContent').toggleClass('show');
    });
    $('#btnsm1').on('click', function () {
        $('.documentdetails>.modalBackground').toggleClass('show');
        $('.documentdetails>.modalContent').toggleClass('show');
    });
    $('.close-modal').on('click', function () {
        $('.modalBackground').removeClass('show');
        $('.modalContent').removeClass('show');
    });

    $('.modalBackground').on('click', function () {
        $('.modalBackground').removeClass('show');
        $('.modalContent').removeClass('show');
    });
});

Check this


text:
Q: Why does the array store different unwanted numbers in the given problem?? This causes false outputs I want to use the memcmp() function in the program. But unwanted numbers get stored in the arr4 array variable when I assign it values passed from another function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int print(int arr4[], int arr5[], int arr6[]);

int main(int argc, char const *argv[])
{
    int arr1[4] = {1, 2, 3, 4}, arr2[4] = {5, 6, 7 ,8}, arr3[4] = {9, 10, 11, 12}, arr4[4], value;
    arr4[3] = print(arr1, arr2, arr3);
    arr4[2] = 5;
    printf("\n\nElements in arr4 array: \n");
    for(int i = 0; i < 4; i++)
        printf("%d ", arr4[i]);
    printf("Press Enter...\n");
    getchar();
    value = memcmp(arr4, arr3, 4 * sizeof(int));
    printf("\nThe value is: %d\n", value);
    if(value == 0)
        printf("\nThe arr3 and arr4 are the same!!!\n");
    else if(value < 0)
        printf("The arr3 is greater than arr4!!!\n");
    else if(value > 0)
        printf("The arr4 is greater than arr3!!!\n");
    printf("\nDone with the print program!!\n\n\a");
}

int print(int arr4[], int arr5[], int arr6[])
{
    int num[4];
    memcpy(num, arr4, 4 * sizeof(int));
    printf("The First 4 numbers stored: \n");
    for(int i = 0; i < 4; i++)
        printf("%d ", num[i]);
    printf("\nThe second set of numbers stored: \n");
    memcpy(num, arr5, 4 * sizeof(int));
    for(int i = 0; i < 4; i++)
        printf("%d ", num[i]);
    printf("\nThe third set of numbers stored in the array: \n");
    memcpy(num, arr6, 4 * sizeof(int));
    for(int i = 0; i < 4; i++)
        printf("%d ", num[i]);
    return num[3];
}

Output:
The First 4 numbers stored:
1 2 3 4
The second set of numbers stored:
5 6 7 8
The third set of numbers stored in the array:
9 10 11 12

Elements in arr4 array:
-465963304 32766 5 12 Press Enter...

The value is: 207
The arr4 is greater than arr3!!!

Done with the print program!!

-465963304 32766 these are the unwanted numbers that get stored and cause problems in the program output. Why do these come? Also, when I compile and run it the second time, -465963304 changes to another number: -408901928 and keeps changing when I compile and run it another time...
However, when I pass the arr4 array variable to the void function print(), the output comes as desired...
What is the problem with the first version of the program?
In addition to these, when I return num[4], the suggestion comes as
warning: array index 4 is past the end of the array (which contains 4 elements) [-Warray-bounds]
    return num[4];
           ^   ~
note: array 'num' declared here
    int num[4];
    ^

But there is no warning when I have it as return num[3].
Why does this happen?

A: you are not initialize arr4 array,so the value storage in arr4 is random.int arr4[4]={0};


text:
Q: stay vue-cli@5 How to switch pictures to online
*

*Direct conversion of small files (Base64)

*Conduct the server on a large file and replace the path

*likeness url-loader -> fallback
    config.module
      .rule('images')
      .set('parser', {
        dataUrlCondition: {
          maxSize: 500 * 1024,
        },
      })
      .set('generator', {
        filename: 'img/[name].[hash:8].[ext]'
      })
      .end();


text:
Q: How to push the data from Azure Data Lake to SSAS ( Azure analysis Service) ? Is it possible? Azure data lake is my data source. I want to push data from azure data lake to Azure Analysis Service (SSAS). How i can do that?

A: I think it is not supported. In following documentation of Azure Analysis Services, Azure Data Lake is not listed in Data Source providers list:
https://opbuildstorageprod.blob.core.windows.net/output-pdf-files/en-us/Azure.azure-documents/live/analysis-services.pdf

A: This is supported.
You need to use a compatibility level of 1400. I have the latest Azure Data Lake plugin for VS2015. You would need to add Data Lake Store as a data source.
There is a good series of blogs here which give you insight of building azure analysis service on top of BLOB storage. The same principle can be applied to data lake store as well:

*

*Part 01 :
https://blogs.msdn.microsoft.com/analysisservices/2017/05/15/building-an-azure-analysis-services-model-on-top-of-azure-blob-storage-part-1/

*Part 02 :
https://blogs.msdn.microsoft.com/analysisservices/2017/05/30/building-an-azure-analysis-services-model-on-top-of-azure-blob-storage-part-2/

*Part 03 :
https://blogs.msdn.microsoft.com/analysisservices/2017/06/22/building-an-azure-analysis-services-model-on-top-of-azure-blob-storage-part-3/

Update
This blog goes in details how to do this. the basic premise is the same as the blob storage backed SSAS process. They however introduced a data lake store connector.

https://blogs.msdn.microsoft.com/analysisservices/2017/09/05/using-azure-analysis-services-on-top-of-azure-data-lake-storage/


text:
Q: Is the harmonic oscillator potential unique in having equally spaced discrete energy levels? I was wondering if the good old quadratic potential was the only potential with equally spaced eigenvalues. Obviously you can construct others, such as a potential that is infinite in some places and quadratic in others, but that's only trivially different. I am not referring to equally spaced as a limiting behavior either, I mean truly integer spaced.
Any ideas? If not, is there a proof for its uniqueness?
If there are other potentials with equally spaced eigenvalues, can one use them as starting points for a free-field QFT? It would be interesting to know if there is a deeper mathematical relation between all of these potentials and whether they could be used to study interacting systems.

A: I believe my answer here to the question "How does one determine ladder operators systematically?" gives at least a partial answer to your question. It is a partial answer because I assume a little more than your bare question, but then, as we see by looking carefully at yuggib's answer observes you can obviously write down a hamiltonian with equally spaced eigenvalues and then characterise the whole family of such hamiltonians. It becomes clear that you need to talk about more than simply the Hamiltonian to answer your question: we need to define other observables and how they behave to define something akin to a "potential".
Let's look at yuggib's answer. You can obviously write down a hamiltonian with equally spaced eigenvalues. Then, as you counter, in your comment:

"Does this really qualify as a proof? Sure you can make operators with any set of discrete eigenvalues, but how do you know that they are not all just equivalent to each other and the harmonic potential? Also, I should say that I really mean a potential, because obviously you can write a Hamiltonian as a matrix and give it equally spaced eigenvalues, but how could you know what potential gave rise to it?"

For this question, I choose energy eigenstates bounded from below. Otherwise, you could get arbitrarily negative energy states and there would be no quantum ground state. This may or may not be more than what you want to assume, but I think it is physically reasonable. As I said, I'm giving a partial answer. So now our index set $I$ becomes in fact the set of semi positive integers $\mathbb{N}$. So, in the notation of yuggib's answer, choose an orthonormal basis $\left\{Y_j\right\}_{j=0}^\infty$ for our assumed separable (this is yet another assumption we must bring to bear) Hilbert space of quantum states with $P_j Y_k = \delta_{j\,k} Y_k$, where $\delta$ is clearly the Kronecker delta and $P_j$ are the projection operators onto the basis vectors. Then, the most general Hamiltonian with equispaced eigenvalues is as written in yuggib's answer with:
$$\lambda_i = E_0 + \sigma(i) \Delta$$
where $E_0$ is the ground state energy, $\Delta$ the energy spacing and $\sigma:\mathbb{N}\to\mathbb{N}$ a bijection between $\mathbb{N}$ and itself. So there are an infinite number of Hamiltonians with equispaced energy levels. All members of each family of such Hamiltonians defined by the family's ground state energy $E_0$ and spacing $\Delta$ are unitarily equivelent to one another: two members $\hat{H}_1,\,\hat{H}_2$ are equivalent by $\hat{H}_1 = U\,\hat{H}_2\,U^\dagger$ with $U$ some unitary operator.
So now, how to work this into something like a "potential"? My solution is then to abstractly define position and momentum observables $\hat{X},\,\hat{P}$ and we make our final three assumptions:

*

*They fulfill the canonical commutation relationship $\hat{X}\,\hat{P} - \hat{P}\,\hat{X}=i\,\hbar\,\mathrm{id}$;

*Measurements by these observables vary sinusoidally with time;

*Our observables are Hermitian operators.
So now we Writing a general quantum state as:
$$\psi = \sum\limits_{j\in\mathbb{N}} \psi_j e^{-i\,\left(j\,\omega_0+\frac{E_0}{\hbar}\right)\,t}$$
so that the mean of a general observable $\hat{A}$ is:
$$\left<\left.\psi\right|\right.\hat{A}\left.\left|\psi\right.\right> = \sum\limits_{j=0}^\infty a_{j,j}|\psi_j|^2  + 2\,{\rm Re}\left(\sum\limits_{j=0}^\infty\sum\limits_{k=j+1}^\infty a_{j,k} \psi_j \psi_k^* \exp(i\,\omega_0\,(k-j)\,t)\,\right)$$
we can readily see that observables with sinusoidally varying measurement means must have two symmetrically placed, complex conjugate off-leading-diagonal diagonal stripes. Moreover the displacement from the leading diagonal must be the same for both $\hat{X},\,\hat{P}$ if they are to fulfill the CCR. The simplest case is when the two stripes are immediately above and below the leading diagonal. In this case, the means of the observables will vary like $\cos(\omega_0\, t + \phi_0)+const.$: if the two stripes are displaced $N$ steps either side of the leading diagonal, then we have variation varies like $\cos(N\,\omega_0\, t + \phi_0)+const.$. The case with the stripes displaced $N$ from the leading diagonal yield analyses that are essentially the same as the below as discussed in my other answer: they essentially pertain to a quantum oscillator with $N$ times the energy spacing of the one we talk about here.
So now, without loss of generality, in our assumed basis we can write the Hermitian observables as:
$$\begin{array}{ll}\hat{X} = \sqrt{\frac{\hbar}{2}}\left(\tilde{X} + \tilde{X}^\dagger\right)  \\
\hat{P} = \sqrt{\frac{\hbar}{2}}\left(\tilde{P} + \tilde{P}^\dagger\right)\end{array}$$
where:
$$\tilde{X} = \left(\begin{array}{ccccc}0&x_1&0&0&\cdots\\0&0&x_2&0&\cdots\\0&0&0&x_3&\cdots\\\cdots&\cdots&\cdots&\cdots&\cdots\end{array}\right)\quad\tilde{P}=\left(\begin{array}{ccccc}0&p_1&0&0&\cdots\\0&0&p_2&0&\cdots\\0&0&0&p_3&\cdots\\\cdots&\cdots&\cdots&\cdots&\cdots\end{array}\right)$$
are both arbitrary lone-striped upper triangular matrices. You'll need to look at my other answer that I referenced above for full details, but by writing down the CCR we find that:
$$\begin{array}{ll}\hat{X} = \sqrt{\frac{\hbar}{2\,m\,\omega_0\,\cos\chi}}\left(a^\dagger\,e^{-i\,\xi} + a\,e^{i\,\xi}\right)  \\
\hat{P} =  i\,\sqrt{\frac{\hbar\,m\,\omega_0}{2\,\cos\chi}}\left(a^\dagger\,e^{-i\,(\xi+\chi)} - a\,e^{i\,(\xi+\chi)}\right)  \end{array}$$
where we have defined the arbitrary complex constant $\alpha = -i\,m\,\omega_0\,e^{i\,\chi}$ by writing it in terms of a second real positive magnitude $m$ with the dimensions of mass and an arbitrary phase factor $\chi$ and where we have also defined:
$$a = \left(\begin{array}{ccccc}0&\sqrt{1}&0&0&\cdots\\0&0&\sqrt{2}&0&\cdots\\0&0&0&\sqrt{3}&\cdots\\\cdots&\cdots&\cdots&\cdots&\cdots\end{array}\right)$$
and its Hermitian conjugate as the wonted ladder operators.
One can quite straighforwardly show that our derived $\hat{X},\,\hat{P}$ must have continuous spectrums. So, if we change our co-ordinates so that we work in position co-ordinates, i.e. where $\hat{X}$ becomes the diagonal (multiplication) operator $\hat{X}f(x) = x f(x)$ for $f(x)\in \mathcal{H} = \mathbf{L}^2(\mathbb{R}^3)$, then we can argue as I do in my answer here that there is needfully such a co-ordinate system wherein $\hat{X}f(x) = x f(x)$ and $\hat{P} f(x) = -i\,\hbar\,\nabla f(x)$. So now the Hamiltonian in these co-ordinates is:
$$\begin{array}{lcl}\hat{H} &=& \hbar\,\omega_0 \left(a^\dagger\,a + \frac{1}{2}I\right) + \left(E_0 - \frac{\hbar\,\omega_0}{2}\right)I\\
 &=& \frac{1}{2\,m\,\cos\chi} \hat{P}^2 + \frac{1}{2\,\cos\chi}\,m\,\omega_0^2\,\hat{X}^2 - \frac{\omega_0\,\tan\chi}{2}(\hat{X}\hat{P} + \hat{P}\hat{X}) +\left(E_0 - \frac{\hbar\,\omega_0}{2}\right)I\end{array}$$
so that the Schrödinger equation in these co-ordinates is:
$$i\hbar\partial_t \psi = -\frac{1}{2\,m\,\cos\chi} \nabla^2 \psi + \frac{1}{2\,\cos\chi} m\,\omega_0^2 |\vec{x}|^2 \psi + i\,\hbar\,\omega_0\,\tan\chi\,\vec{x}\cdot\nabla \psi + \left(E_0 +i\,\frac{\tan\chi\,\hbar\,\omega_0}{2} - \frac{\hbar\,\omega_0}{2}\right)\psi$$
and more "traditional" Schrödinger equation is recovered when $\chi = 0$ and $E_0 = \hbar\,\omega_0/2$:
$$i\hbar\partial_t \psi = -\frac{1}{2\,m} \nabla^2 \psi + \frac{1}{2} m\,\omega_0^2 |\vec{x}|^2 \psi$$
and we see that we must have a quadratic potential. So, in summary, let's list the assumptions that lead to this conclusion:

*

*Separable quantum state space;

*Equispaced energy levels bounded from below;

*The existence of Hermitian position and momentum observables fulfilling the CCR and

*Measurements from the observables vary sinusoidally with time.

I have not yet analysed the case where we relax the assumption 4. From the above, we see that equispaced energy levels implies periodic variations of measurements with time, and it seems to me that this relaxation would likely yield a much more general potential in position co-ordinates.

A: Very interesting problem! I will propose it to my students.
However the answer is positive up to isomorphisms of Hilbert spaces if assuming that every eigenspace has dimension $1$.
I stress that the result below holds true even if the initial Hamiltonian $H$ is not of Schroedinger form.
Proposition. Let $H$ be an (unbounded) self-adjoint operator over the Hilbert space $\cal H$ such that for a real constant $\omega \neq 0$
$$\sigma(H)= \sigma_p(H) = \{\omega n \:|\: n=0,1,2,\ldots\}\tag{1}$$ and every eigenspace has dimension $1$.
Under these hypotheses there is a unitary map $U: {\cal H} \to L^2({\mathbb R}, dx)$ such that, for some uniquely fixed real numbers  $\alpha, \beta$
$$U H U^{-1} = \alpha H_0 + \beta I\tag{2}$$
where $H_0$ is the standard (self-adjoint) Hamiltonian of the harmonic oscillator.
Proof. Let $\psi_n$ be the unit eigenvector of the eigenvalue $\omega n$ defined up to a phase. The finite span $D$ of the $\psi_n$ is dense, since they define the spectral measure of $H$ from (1).
We can define the standard ladder operators over the common domain $D$
$$a \psi_n = \sqrt{n}\psi_{n-1}$$ (with $\psi_{-1}:=0$) and $$a^\dagger \psi_n = \sqrt{n+1}\psi_{n+1}\:.$$ Evidently,$D$ turns out to be invariant under $a$ and $a^\dagger$.
Next define, over the dense domain $D$, the symmetric (not yet selfadjoint) operators
$A = \frac{1}{\sqrt{2}}(a+a^\dagger)$ and $B=\frac{i}{\sqrt{2}}(a-a^\dagger)$.
We have $A^2+B^2 = (\omega H + \frac{1}{2}I)|_D$.
Here is the crucial observation, since the $\psi_n$ are a Hilbert basis of eigenvectors of $H$, $D$ is a core for $H$ and also for $A^2+B^2+ I$ since those vectors are analytic vectors for $H$ and thus also for trivially related symmetric operator $A^2+B^2+I^2$
By a known theorem by Nelson [1]  $A^2+B^2+I^2$  is essentially self-adjoint over $D$.
A famous theorem by Nelson (Nelson theorem about unitary representations [1]) assures that there exist a strongly-continuous unitary representation of the unique connected simply-connected Lie group whose Lie-algebra is generated by $A,B,I|_D$. It easy to see that this Lie algebra is nothing but that of Heisenberg group.
Finally, Nelson's theorem also establishes that the unique self-adjoint extensions of $A$, $B$ and $I|_D$ are the self-adjoint generators of the three fundamental one-parameter groups of Heisenberg group.
In other words, we have found that $exp(-iuA)$ and $exp(-ivB)$ have the same commutation relations of $exp(-iuX)$ and $exp(-ivP)$
Here Stone-von Neumann theorem enters the game (in the generalized version due to Mackay, without requiring the irreducibility of the representation).
There exist a unitary operator $U : {\cal H} \to \bigoplus_{k\in K}L^2(\mathbb{R}, dx)$ such that $$U(\omega H + \frac{1}{2}I)U^{-1} = \bigoplus_{k\in K} H_0$$
so that
$$H = \frac{1}{\omega} U^{-1}\left(\bigoplus_{k\in K} H_0- \frac{1}{2}I\right) U$$
It is clear that if $K$ contains more than one element, $\omega H + \frac{1}{2}I$ would have more than one eigenvector for a given eigenvalue contrarily to our hypotheses. So that $K$ includes only one element and we can write
$$H =  U^{-1} \left(\frac{1}{\omega}H_0- \frac{1}{2\omega}I\right) U\:.$$
QED
[1] Nelson, E.: Analytical vectors, Annals of Mathematics, 70, 572-615 (1969).

A: According to Inverse spectral theory as influenced by Barry Simon Fritz Gesztesy
(Submitted on 2 Feb 2010) page 4:

A particularly interesting open problem in inverse spectral theory
  concerns the characterization of the isospectral class of potentials $V$ with purely discrete spectra (e.g., the harmonic oscillator $V(x) = x^2$ ).

A: There are, in general, infinitely many operators with equally spaced eigenvalues. Suppose a self-adjoint operator $A$ has a purely discrete spectrum (i.e. it is either compact or with compact resolvent) and denote by $\{\lambda_i\}_{i\in\mathbb{I}}$ its real eigenvalues ($I\subseteq \mathbb{N}$): then by the spectral theorem it can be written (on its domain of definition) as
$$A=\sum_{i\in I} \lambda_i P_i$$ where $P_i$ is the orthogonal projector on the eigensubspace corresponding to $\lambda_i$.
Now this equality, read from right to left defines the operator $A$, choosing the eigenvalues and the (mutually disjoint) orthogonal projections. So playing with projections and eigenvalues you will define different operators, with equally spaced eigenvalues if you want. However it may be then necessary to prove the resulting operator is self-adjoint on a suitable domain (if the operator is unbounded).

A: It's been a while since I have done Quantum Mechanics, however your question reminded me of Supersymmetric Quantum Theory.  In simpler words it is a theorem that states that for every potential ($V(x)$) there exists a supersymmetic (SUSY) partner potential ($\tilde{V}(x)$) that has the same functional form for the energy levels and differ in in there energies by a shift.
Quantum Mechanics by Schwabl has a section devoted to this (19) and actually have the Harmonic Oscillator as an example (19.2.3).  However the answer was not satisfying because the SUSY potentials they got to be for it were...
$$V(x) = \frac{1}{2}\omega^2 x^2 -\frac{1}{2}\omega$$
$$\tilde{V}(x) = \frac{1}{2}\omega^2 x^2 +\frac{1}{2}\omega$$
Which are essentailly equivalent because adding constants to a Hamiltonian only shifts the energy.
So according to SUSY QM the Harmonic Oscillator can only be mapped to a Harmonic Oscillator with a constant energy shift.
Don't know if I completely answered your question, but I hope it helps!

A: The harmonic potential is not the only potential with evenly spaced energy levels.
Consider a potential $V(X)$ that is $\frac{1}{2} m \omega_1 x^2 - \frac{1}{2} \hbar \omega_1$ for $x > 0$ and $\frac{1}{2} m \omega_2 x^2 - \frac{1}{2}\hbar \omega_2$ for $x < 0$. If $\omega_2$ is a square-free multiple of $\omega_1$ then the energy levels will be spaced with levels $2 \hbar \omega_1$. The reason for this is that we can use the even $\omega_1$ energy eigenstates for the $x > 0$ part of the function and the corresponding $\omega_2$ energy eigenstates for the $x < 0$ part. At $x = 0$ we can set the functions to be equal, and the first derivative is $0$ there as well. We can not use the odd solutions because the first derivatives of the odd solutions will never be equal at $x = 0$ assuming that $\omega_2/ \omega_1$ is square-free. This is because the wave function is given by a Hermite polynomial $H_n(\sqrt{\frac{m \omega}{\hbar}} x)$ times the Gaussian curve, and for the odd solutions, the $x$ term in $H_n$ is always an integer.
In any case, let us now restrict our attention to even potentials $V(x)$, which. If $V(x)$ is even, then the harmonic potential is the only potential that has evenly spaced energy levels.
If the energy levels are evenly spaced with spacing $\Delta E$, then the time evolution operator
$$U(t) := e^{i \hat H t / \hbar}$$
will satisfy
$$U(t + \tfrac{2 \pi}{ \omega}) = e^{i \theta} U(t)$$
for all $t$, where $\omega = \Delta E/\hbar$ and $\theta$ is a physically irrelevant phase that can be set to $0$ by adding a constant to our Hamiltonian (such as setting the ground state energy to $0$).
This means that under time evolution, all state will return to their initial state every period $\frac{2 \pi}{\omega}$. Also note that by Erenfests theorem, the classical position expectation value will follow the classical equation of motion, so that too will return to its initial state after the same period.
I will now prove that the harmonic potential is the only symmetric 1D potential for which all solutions are periodic with the same period. Therefore, it is the only potential with evenly spaced energy levels.
First note that $V(x)$ must have only one minimum and no maximums. If there were a maximum, then there would exist "slow roll" solutions, rolling off of the hill, that can take arbitrarily long times to leave the hill, such that not all solutions would be periodic with the same period. Therefore, $V(x)$ must reach a minimum (WLOG at $x=0$) and increase as $|x|$ gets larger.
From the conservation of energy
$$\frac{1}{2} m v^2 = E - V(x)$$
$$v = \sqrt{\frac{2}{m}(E - V(x))}$$
$$v = \frac{dx}{dt}$$
$$\frac{dx}{\sqrt{\frac{2}{m}(E - V(x))}} = dt$$
$$\int \frac{dx}{\sqrt{\frac{2}{m}(E - V(x))}} = \int dt$$
We can consider the interval from the maximum value of $x$ that the particle reaches, $V^{-1}(E)$, to $0$.
$$\int_0^{V^{-1}(E)} \frac{dx}{\sqrt{\frac{2}{m}(E - V(x))}} = T$$
We need the right hand side to be independent of $E$ if all solutions are to have the same period. (From here on out we will suppress constants like $2$ and $m$, only wanting the integral to be independent of $E$.)
First we change variables to integrate with respect to $V$:
$$\int_0^{E} \frac{1}{V'}\frac{dV}{\sqrt{E - V}}$$
where $V' = \frac{dV}{dx}$.
Because $V$ only has one minimum, we can express $V'$ as some function $f(V)$.
$$\int_0^{E} \frac{1}{f(V)}\frac{dV}{\sqrt{E - V}}$$
In order for this integral to be independent of $E$, it must be dimensionless. The only way to accomplish this is for $f(V) \propto \sqrt{V}$. Indeed, the quantity
$$\int_0^{E} \frac{1}{\sqrt{V}}\frac{dV}{\sqrt{E - V}}$$
can also be explicitly evaluated to be independent of $E$. (It is $\pi$.)
This means that $V \propto x^2$, which is the harmonic potential. This is what we wanted to show.


text:
Q: CSS background image cropping issue Link:
Image Cropped Preview
In my HTML page is not showing full image and I want to show it full without cropping How can I resolve it?

A: what about background-size: contain; ?

A: you can add this css:
background-size: 100% 100%;


text:
Q: Calculating the Standard Error and Confidence Interval for Cohen's Quadratic Kappa I need to evaluate the performance of a machine learning application. One of the evaluation metrics chosen is Cohen's Quadratic Kappa. I found this Python tutorial on how to calculate Cohen's Quadratic Kappa. What is missing, however, is how to calculate the confidence interval.
Let's walk through my example (I use a smaller data set for the sake of simplicity). I use NumPy and Scipy Stats for this purpose:
from math import sqrt
import numpy as np
from scipy.stats import norm

This is my confusion matrix:
# x: actuals, y: predictions
confusion_matrix = np.array([
    [9, 5, 2, 0, 0, 0],
    [4, 7, 1, 0, 0, 0],
    [1, 2, 4, 0, 1, 0],
    [0, 1, 1, 5, 1, 0],
    [0, 0, 0, 1, 2, 1],
    [0, 0, 0, 0, 0, 1],
], dtype=np.int)
rows = confusion_matrix.shape[0]
cols = confusion_matrix.shape[1]

I calculate a weight matrix and histograms:
weights = np.zeros((rows, cols))
for r in range(rows):
    for c in range(cols):
        weights[r, c] = float(((r-c)**2)/(rows*cols))
hist_actual = np.sum(confusion_matrix, axis=0)
hist_prediction = np.sum(confusion_matrix, axis=1)

The expected prediction quality by mere chance is calculated as follows:
expected = np.outer(hist_actual, hist_prediction)

This matrix, and the actual confusion matrix, are normalized:
expected_norm = expected / expected.sum()
confusion_matrix_norm = confusion_matrix / confusion_matrix.sum()

Now I calculate the numerator (actual observed agreement) and the denominator (expected agreement by chance):
for r in range(rows):
    for c in range(cols):
        numerator += weights[r, c] * confusion_matrix_norm[r, c]
        denominator += weights[r, c] * expected_norm[r, c]

Cohen's Kappa can now be calculated as:
weighted_kappa = (1 - (numerator/denominator))

Which gives me a result of 0.817.
Now to my question: I need to calculate the standard error, in order to calculate the confidence interval. Here's my approach:
#            p(1-p)
# sek = sqrt -------
#            n(1-e)²
#
# p: numerator (actual observed agreement)
# e: denominator (expected agreement by chance)
# n: total number of predictions
total = hist_actual.sum()
sek = sqrt((numerator * (1 - numerator)) / (total * (1 - denominator) ** 2))

Can I use the total number of predictions, even though I calculate with a normalized numerator and denominator? This would result in a standard error of kappa of 0.023.
The 95% confidence interval then is just straightforward:
alpha = 0.95
margin = (1 - alpha) / 2  # two-tailed test
x = norm.ppf(1 - margin)
lower = weighted_kappa - x * sek
upper = weighted_kappa + x * sek

Which gives an interval of [0.772;0.861].

A: Since I don't know anything about Cohen's Quadratic Kappa beyond what you have written, I would fall back to the bootstrap method.
To bootstrap sample the CQK score, resample with replacement from your set of predicted ratings. Run these resampled predictions through the CQK score calculation, and you will get a new CQK score. Compute new CQK scores in this way a number of times, at least 100. The standard deviation of this bootstrapped CQK sample is the standard error of the mean CQK score.
Using this approach, I get a standard error around 0.057, from which you know how to find the confidence interval. Another approach is to directly calculate 2.5 and 97.5 percentiles (np.percentile) of the bootstrapped CQK scores as your confidence interval.
def extract_data_from_confusion_matrix(confusion_matrix):
    y_true = []
    y_pred = []
    for i, row in enumerate(confusion_matrix):
        for j, qty in enumerate(row):
            y_true.extend([i]*qty)
            y_pred.extend([j]*qty)

    return y_true, y_pred

def bootstrap_cqk(y_true, y_pred):
    num_resamples = 100

    Y = np.array([y_true, y_pred]).T

    weighted_kappas = []
    for i in range(num_resamples):
        Y_resample = np.array(random.choices(Y, k=len(Y)))
        y_true_resample = Y_resample[:, 0]
        y_pred_resample = Y_resample[:, 1]
        weighted_kappa = cqk_score(y_true_resample, y_pred_resample)
        weighted_kappas.append(weighted_kappa)

    return weighted_kappas

def calculate_standard_error():

    confusion_matrix = np.array([
        [9, 5, 2, 0, 0, 0],
        [4, 7, 1, 0, 0, 0],
        [1, 2, 4, 0, 1, 0],
        [0, 1, 1, 5, 1, 0],
        [0, 0, 0, 1, 2, 1],
        [0, 0, 0, 0, 0, 1],
    ], dtype=np.int)

    y_true, y_pred = extract_data_from_confusion_matrix(confusion_matrix)
    weighted_kappas = bootstrap_cqk(y_true, y_pred)
    return np.std(weighted_kappas)


text:
Q: Bazaar -- remove ALL local changes The bzr documentation states http://doc.bazaar.canonical.com/bzr-0.10/bzr_man.htm
bzr update: ... If you want to discard your local changes, you can just do a
bzr revert instead of bzr commit after the update.

However this is not what I am getting. I have new files in my repo and all I want is to have the latest revision in my working directory and to have bzr status show anything as being changed.
Is this possible?

A: First of all, you're looking at an extremely old version of the doc.
As of version 2.6 (current stable),
the description of bzr update is longer, and very different:

Description:
  This will perform a merge of the destination revision (the tip of the
  branch, or the specified revision) into the working tree, and then make
  that revision the basis revision for the working tree.

  You can use this to visit an older revision, or to update a working tree
  that is out of date from its branch.

  If there are any uncommitted changes in the tree, they will be carried
  across and remain as uncommitted changes after the update.  To discard
  these changes, use 'bzr revert'.  The uncommitted changes may conflict
  with the changes brought in by the change in basis revision.

  If the tree's branch is bound to a master branch, bzr will also update
  the branch from the master.

  You cannot update just a single file or directory, because each Bazaar
  working tree has just a single basis revision.  If you want to restore a
  file that has been removed locally, use 'bzr revert' instead of 'bzr
  update'.  If you want to restore a file to its state in a previous
  revision, use 'bzr revert' with a '-r' option, or use 'bzr cat' to write
  out the old content of that file to a new location.

  The 'dir' argument, if given, must be the location of the root of a
  working tree to update.  By default, the working tree that contains the
  current working directory is used.

Aliases:  up
See also: pull, status-flags, working-trees

Your question is not very clear.
When you're working in centralized mode,
you have a working tree you created with bzr checkout,
the bzr update command will bring in the new revisions that were added in the central repository.
If your working tree was clean (bzr status showing no changes) before bzr update,
then your working tree will be updated to the latest version (as it is on the central server),
and your working tree will be still clean.
If your working tree wasn't clean before bzr update,
then Bazaar will try to merge the new revisions on the server into your working tree,
and conflicts may happen.
If the changes you had were exactly as what the new revisions changed,
then you will end up with a clean working tree, which is extremely rare.
Most commonly,
if your working tree had changes before bzr update,
it will most probably have changes after, and possibly conflicts too.
The bzr status will tell you what they are.
It's best to not have pending changes before running bzr update.


text:
Q: Creating Random Corresponding Arrays in Android I made a question earlier on the same project but now I have a different problem. My goal is to have a password field that is stored locally and when a password is put in that is equal to the variable a screen will display. I have accomplished this but know I want to spice it up a little. I want to make it so that when the background color is red the password is red and so on for yellow and blue. I need to create two arrays that both randomly pick the same variable. I know this is possible because I have done it within Phaser but I am struggling on doing it in Android Studio. Anyways here is my code so far and my attempt at making an array.
Thanks for all the help,
Murdoc
package com.example.murdocbgould.passwordpt4;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.murdocbgould.passwordpt4.R;
import com.example.murdocbgould.passwordpt4.Welcome;

import java.security.AccessController;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

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

        final String apassword[] = {"rootr", "rootb", "rooty"};

        final String acolors[] = {"red", "blue", "yellow"};

        Random rn = new Random();
        int answer = rn.nextInt(3) + 1;

        final EditText editText = (EditText) findViewById(R.id.editText);
        Button button = (Button) findViewById(R.id.button);
        final TextView textView2 = (TextView) findViewById(R.id.textView2);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                textView2.setText(editText.getText().toString().trim());
                if(editText.getText().toString().trim().equals(apassword)){
                    Intent myIntentR1 = new Intent(view.getContext(), Welcome.class);
                    startActivity(myIntentR1);
                } else {
                    Intent a = new Intent(view.getContext(), FTry.class);
                    startActivity(a);
                }
            }
        });

    }
}

A: Just write a bunch of if statements or use a switch statement. If you are going to write a serious app you would not store passwords in an array! I understand your in High School but consider using sqlite database it will open up a new world to develop apps. Storage of data is a wonderful learning experience. Back to your question here is a small snippet of IF code. In your case grab the password from the array and hard code the color to look for a match.
A better solution would be a HashMap key-value search the Map with the random password as the key and this will give a value that is a color. If you want both password and color to be random then use the IF statement concept
                if(!etPW.getText().toString().equals(etCPW.getText().toString())){
                Toast.makeText(MainActivity.this,"Password Does NOT\n"+"Match Confirm Password",Toast.LENGTH_LONG).show();
                etPW.setText("");
                etCPW.setText("");
                etPW.requestFocus();
                return;
            }


text:
Q: How to call React component function from Electron main.js using contextBridge As the title states, I would like to call a function defined in one of my React components from the Electron main.js file. I know how to do it the other way around, where for example the user clicks a button and it calls a function in main.js and then returns to the React component. I need it to be the opposite, where main.js calls the React function and then returns the result to main.
I cannot simply have all the functionality in main.js since I cannot pass DOM objects to main from React (it has resulted in the error "object cannot be cloned"). So I figure it shouldn't be too hard to just send the request to React, have the React side of my app do the stuff, and then return the resulting string back to main.
I have found a number of other similar posts here where various solutions are offered, but none specifically for this exact problem. #1 exposes ipcRenderer which is a bad security practice I can't afford. #2 and #3 only explain it for vanilla Javascript, not React components. And while #4 does deal with React, it does not deal with Electron, and it is designed for React classes (I'm using functional components).
My resulting attempt looks like this mess:
    const [mounted, setMounted] = useState(false)

    if(!mounted){
        window.reactFunction = myFunction;
    }

    useEffect(() =>{
      setMounted(true)
    },[])

    window.electron.receive("fromMain", async () => {
        return myFunction();
    });

    async function myFunction()
    {
        return "result";
    }

However, the function instead gets called during rendering and is not called by the contextBridge. Here is my preload.js:
contextBridge.exposeInMainWorld('electron', {

    receive: async (channel, func) => {
        let validChannels = ["fromMain"];
        if (validChannels.includes(channel)) {
            return await ipcRenderer.on("fromMain", (event, ...args) => func(...args));
        }
    }
});

For some reason the preload.js script is not executed. And here is main.js:
       const result = window.webContents.send('fromMain');

I have also found this discussion where it is made clear the security issues associated with calling ipcRenderer directly and so I would like to use contextBridge (which I'm already using for calling main functions from React anyway). It's also where my preload.js code comes from. But that example doesn't use React either.
Is this even possible? Or am I supposed to go about this problem a different way?

A: Looks like I made a typing mistake on this line:
return await ipcRenderer.on("fromMain", (event, ...args) => func(...args));
In this line I'm returning the function, so the function itself is not getting called. Remove the "return" and it will work. "Await" doesn't seem to make a difference.
However, once you do call the function, it can't actually return anything. So you need to make another call from renderer back to main, like this:
    window.electron.receive("fromMain", async () => {
        const returnValue = await myFunction();
        window.electron.sendReturnValue(returnValue);
    });

    async function myFunction()
    {
        return "result";
    }

Unless there is a still better way of doing it, but this solves my issue for now, and hopefully helps others.


text:
Q: NSUbiquitousKeyValueStore not so ubiquitous? I am trying to store key-values with NSUbiquitousKeyValueStore. They seem to store fine while the app is installed, but if I delete the app off the device and run the app again, the key-values seem to be lost. Is this expected behaviour, or perhaps is there something I'm missing?
I am storing and retrieving values like so:
-(void)setString:(NSString*)stringValue forKey:(NSString*)keyValue {
    NSUbiquitousKeyValueStore *iCloudStore = [NSUbiquitousKeyValueStore defaultStore];
    [iCloudStore setString:stringValue forKey:keyValue];
    [iCloudStore synchronize];
}
-(NSString*)getStringForKey:(NSString*)keyValue {
    NSUbiquitousKeyValueStore *iCloudStore = [NSUbiquitousKeyValueStore defaultStore];
    return [iCloudStore stringForKey:keyValue];
}

What I've already checked:

*

*I have enabled iCloud and key-value storage in Target Capabilities.

*iCloud Drive is enabled on my device and the app itself is enabled.

*I have waited for some time before trying to load the values to be sure it wasn't just a syncing problem.

*I have registered an observer in the NSNotificationCentre as per Apple docs for NSUbiquitousKeyValueStoreDidChangeExternallyNotification. My observer is never called, on first run after install, or subsequent runs. My code(stripped back from Apple docs)
NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(updateKVStoreItems:)                                                         name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
                                       object:store];
[store synchronize];

- (void)updateKVStoreItems:(NSNotification*)notification {
    NSLog(@"RECEIVED DATA");
}

Additional questions -

*

*Is there a way of telling when your data has synced to the cloud?(i.e. uploaded data)

*Or the reverse, is there a way of telling when your app has synced successfully from the cloud?(i.e. downloaded data) I would have hoped that NSUbiquitousKeyValueStoreDidChangeExternallyNotification would notify for this, but since I'm not receiving this notification, I suspect it's just for when another device has updated the data while the app is open, a suspicion that seems to be confirmed by Apple docs:

NSUbiquitousKeyValueStoreServerChange - A value changed in iCloud. This occurs when another device, running another instance of your app and attached to the same iCloud account, uploads a new value."

A: Did you enable iCloud in the Application Services for the app id in the Apple Developer Portal? After that you also have to create a provisioning profile for the app.
The only difference I see in my code is the "name:" parameter. You need to specify that you want to observe NSUbiquitousKeyValueStoreDidChangeExternallyNotification
[[NSNotificationCenter defaultCenter]
 addObserver: self
 selector: @selector (storeDidChange:)
 name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification
 object: [NSUbiquitousKeyValueStore defaultStore]];

Your code throws a warning in my environment
Instance method '-addObserver:selector:object:' not found (return type defaults to 'id')
I also have been using setObject:forKey: instead of setString:forKey:


text:
Q: C loop complexity I'm preparing for an exam and these are some of problems from last year's tests. The task is to calculate both exact and asymptotic complexity. How would you solve it? Universally, if possible.
for ( i = j = 0; i < n; j ++ ) {
  doSomething ();
  i += j / n;
  j %= n;
}

for ( i = 0; i < 2 * n; i += 2 )
  for ( j = 1; j <= n; j <<= 1 )
    if ( j & i )
      doSomething ();

for (i = 0; i < 2*n; i++) {
  if ( i > n )
    for (j = i; j < 2 * i; j ++ ) doSomething();
  else
    for (j = n; j < 2 * n; j ++ ) doSomething();
}

Thanks in advance

A: My solution for the third loop is
t(n) = [ (n-1)*n +  ((n-1)*n)/2 ] *D  + [ n^2 +n ] *D + [ 2n ]*I

so it is in O(n^2) given that doSomething() has a constant time
and that i and j are integers.
The second term ( [ n^2 +n ] *D ) is fairly easy.
The loop
for (j = n; j < 2 * n; j ++ ) doSomething();

gets called while i <= n so it will be called n+1 times, since it starts from 0.
The loop for (j = n; j < 2 * n; j ++ ) calls doSomething() n times, so we have (n+1)*n*D = [n^2+n] *D. I assume that doSomething() has a constant time which is equal to D
The first term is a little bit more complex.
for (j = i; j < 2 * i; j ++ ) doSomething();

gets called when i>n so it will be called n-1 times.
The loop calls doSomething() i times.
The first time it gets called n+1, the second time ´n+2´ and so on until it is 2n-1 which is equal to n + (n-1).
So we get a sequence likes this {n+1, n+2, n+3, ... , n+(n-1)}.
If we sum up the sequence we get n-1 times n and the sum 1+2+3+...+ (n-1).
The last term can be solved with the "Gaußsche Summenformel" (sorry I don't have the English name for it but you can see the formula in the German wiki link) so it is equal to ((n-1)*n)/2
So the first term is (n-1) * n + ((n-1)*n)/2 *D
And the last term is therefor the if statement which is called 2*n*I, where I is the time to execute the If statement.

A: Well, the question here is, for all three loop structures, how the amount of iterations changes in proportion to n, right? so let's look at the loops. I'll omit the first one, since you solved it already.
for ( i = 0; i < 2 * n; i += 2 )
  for ( j = 1; j <= n; j <<= 1 )
    if ( j & i )
      doSomething ();

the outer for loop obviously runs exactly n times. the inner loop runs log_2(n) times, because of the bitwise shift operation. The if clause runs in constant time, so the entire loop is in O(n * log_2(n)), assuming that doSomething() is in constant time as well.
Does that make it clearer? :)

A: As per request, I will explain how I came to the result that the first loop is equal to a construction like this:
int i, j;
for (i=0; i < n; i++) {
    for (j=0; j <= n; j++) {
        doSomething();
    }
}

First of all, I must admit that before I really thought about it, I just wrote a little sample program including the first of the three for-loops that prints out i and j during the iteration. After I've seen the results, I was thinking about why the results are like this.
In the comment, I forgot to add that I defined n=200.
Explanation
We can say, that although j is incremented regularly every step in the iteration, it will never exceed a value of n. Why? After n iterations, j==n. It will be set to 0 in the statement j %= n after i has been incremented. In the statement i += j / n, i will be incremented by 0 n-1 times, and at the nth time, it will be incremented by 1. This starts all over again until i >= n.


text:
Q: How to save image server side when send from javascript I'm was making a drag and drop upload script by reading a bunch of tutorials, but they only cover the javascript part, and i'm having issues on the php part.
I'm uploading a image as this:
$('#drop-zone').bind('drop', drop);

function drop(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer = e.originalEvent.dataTransfer;
    traverseFiles(e.dataTransfer.files);
}

traverseFiles makes a foreach loop for every file and calls upload funcion, there i do this:
xhr = new XMLHttpRequest();

//some event listners for processing, on load

xhr.open("post", "core/plugins/upload/upload.class.php", true);

xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);

xhr.send(file);

then in php i found using this will get me raw data of the image
$file = file_get_contents('php://input');

EDIT: solution found
$fh = fopen($savedir, 'w') or die("can't open file");
fwrite($fh, $file);
fclose($fh);

A: Assuming you have managed to get the raw file from the PHP input, it's likely going to be base64 encoded. A simple example would be to do this:
<?php
//decode file
$image = base64_decode($file);

// write it
$filename = "myfile.png";
$fh = fopen($filename, 'w') or die("can't open file");
fwrite($fh, $image);
fclose($fh);

Edit
See comments, the file wasn't encoded as a result of the request.

A: move_uploaded_file is not what you want.  If you had sent the file with a normal POST request (rather than through Ajax), that's when you'd use move_uploaded_file.
$file contains the raw binary data for the image.  All you have to do is write that data into a file (taking note to properly handle linebreaks) and you're good to go.  Start with fopen and see how far you get.
I'm assuming that $file has been successfully populated with the binary data and that you've tested this.  If not, then you've got  another problem on the javascript side.
Edit: you may also find this helpful.


text:
Q: Should I connect to QNetworkReply::error() as well? I have created a POST request and I connect to the finished() signal:
QNetworkReply *reply = manager->post(request, postData.encodedQuery());
connect(reply, SIGNAL(finished()), this, SLOT(accept()));

I want to be notified when the POST request has finished, regardless of whether it failed or succeeded.
I have noticed in the documentation that there is also a QNetworkReply::error() signal, do I need to connect to it, too, or will finished() be called in all cases?

A: The documentation for error() says, "the finished() signal will probably follow", so no, finished() ought to be sufficient. Don't forget to check the error() getter in the signal handler, though.

A: Qt documentation states:

void QNetworkReply::error(QNetworkReply::NetworkError code) [signal]
This signal is emitted when the reply detects an error in processing.
  The finished()     signal will probably follow, indicating that
  the connection is over.

From what I've seen in Qt sources (was checking absolutely same issue recently), everywhere after error(), there is a finished() call afterwards. In 5.1.0 I haven't found a place where error is not followed by finished()
for example
void QNetworkReplyImpl::close()
{
    Q_D(QNetworkReplyImpl);
    if (d->state == QNetworkReplyImplPrivate::Aborted ||
        d->state == QNetworkReplyImplPrivate::Finished)
        return;

    // stop the download
    if (d->backend)
        d->backend->closeDownstreamChannel();
    if (d->copyDevice)
        disconnect(d->copyDevice, 0, this, 0);

    QNetworkReply::close();

    // call finished which will emit signals
    d->error(OperationCanceledError, tr("Operation canceled"));
    d->finished();
}


text:
Q: Logic for inserting form with/without optional inputs into MySQL Using: Brackets Html editor, MySQL Workbench
Simplified, I have a database with these tables

*

*(main table) person

*

*idperson PK NN UN AI

**fk_job NN UN (foreign key refering to idjob)

*fn NN

*ln NN

*job

*

*idjob PK NN UN AI

*jobname NN

*adress

*

*idadress PK NN UN AI

**fk_person NN UN (foreign key refering to idperson)

*adress NN

and this form. In the form it is required to fill on one adress, and optional to fill in a second one.
<?php
$con = new mysqli("localhost","user","password","database");
if ($con->

connect_error) {
    die('Error : ('. $con->connect_errno .') '. $con->connect_error .'');
    }

$job_sql = "SELECT idtype, typename FROM type;";
$job_data = $con->query($job_sql);

//insert if(isset()) here

$con->close();
?>
<form method="post">
 <select name="typeSlc" required>
  <option disabled selected>_</option>
  <?php while($row = mysqli_fetch_array($job_data)) { ?>
  <option value="<?php echo $row['jobid'];?>"><?php echo $row['jobname'];?></option>
  <?php } ?>
 </select>
 <input name="fnTxt" required type="text">
 <input name="lnTxt" required type="text">
 <input name="adressTxt" required type="text">
 <input name="cityTxt" required type="text">
 <input name="opt_adressTxt" type="text">
 <input name="opt_cityTxt" type="text">
 <input name="submit" value="submit" type="submit">
</form

Issue:
I want to send a transaction with one batch of queries to the server when 'opt_adress' isset and another when it is not, namely:
if(isset($_POST['submit'])) {
 if(isset($_POST['opt_adress'])) {
  $sql = sprintf  ("BEGIN;
                    INSERT INTO person (fk_job, fn, ln)
                        VALUES (%s, '%s', '%s');
                    SELECT LAST_INSERT_ID() INTO @id;
                    INSERT INTO adress (fk_person, adress)
                        VALUES (@id, '%s');
                    INSERT INTO adress (fk_person, adress, city)
                        VALUES (@id, '%s', '%s');
                    COMMIT;",
                    $con->real_escape_string($_POST['jobSlc']),
                    $con->real_escape_string($_POST['fnTxt']),
                    $con->real_escape_string($_POST['lnTxt']),
                    $con->real_escape_string($_POST['adressTxt']),
                    $con->real_escape_string($_POST['cityTxt']),
                    $con->real_escape_string($_POST['opt_adressTxt']),
                    $con->real_escape_string($_POST['opt_cityTxt']))
  ;
 } else {
  $sql = sprintf  ("BEGIN;
                    INSERT INTO person (fk_job, fn, ln)
                        VALUES (%s, '%s', '%s');
                    INSERT INTO adress (fk_person, adress, city)
                        VALUES (LAST_INSERT_ID(), '%s', '%s');
                    COMMIT;",
                    $con->real_escape_string($_POST['jobSlc']),
                    $con->real_escape_string($_POST['fnTxt']),
                    $con->real_escape_string($_POST['lnTxt']),
                    $con->real_escape_string($_POST['adressTxt']),
                    $con->real_escape_string($_POST['cityTxt']))
  ;
 }
 $con->query($sql);
 header("Location: samepage.php");

When I try to run the query it does not go through to the database (I am using MySQL Workbench). There are no error messages, yet the query is unsuccesful.
I want to insert batches if queries in a transaction if there are existing values in the optional inputs. Is this the correct string for that? Or is there a sleeker code I can use?
The form and database in this question is a simplified version on the one I use in reality.
Thanks in advance, -burrdie

A: You have to understand the difference between a query and a batch of queries.
Since you have to execute several separate queries, you have to make several separate query() calls as well.
So change your code like this
$con->query("BEGIN");
$con->query(sprintf ("INSERT INTO person (fk_job, fn, ln)...");
$con->query("SELECT LAST_INSERT_ID() INTO @id");
// ...so on

and you'll be set.
Besides, it will let you write sleeker code, as you will be able to add your condition in the middle of the execution, thus not duplicating the code.


text:
Q: Executing JavaScript Within a User Control I'm trying to create an ASP.NET user control that will load a specified RSS feed given the feed's URL. Ideally I wanted to keep everything wrapped up in the user control so that it can simply be put into a page, set the feed URL and be done with it. I'm using jQuery AJAX to keep the page more responsive. Here's the barest of skeletons I've started with:
Inside an ASP.NET Web Form:

    <ResellerViewControls:RssFeedListAjax FeedUrl="http://www.samplelist.com/rss/" />

The user control's innards:
<%@ Control Language="C#" ClassName="RssFeedListAjax" %>

The web form's master page has references to all the necessary jQuery stuff. When browsing the page using FireFox developer tools, I can't find the actual user control's javascript anywhere. I guess it's not getting rendered.
Any assistance in getting this or something similar to work is greatly appreciated.

A: Doh. After looking through it again, I realized I was omitting a critical thing: the 'runat=server' attribute on the user control. That did the trick.


text:
Q: Actionscript package naming and directory structure I've got some actionscript which begins with:
package obfus_plugin{
    import org.flowplayer.model.Plugin;
    import org.flowplayer.util.Arrange;
    import org.flowplayer.model.PluginModel;
    import org.flowplayer.view.Flowplayer;
        public class obfus extends Sprite implements Plugin {
and when I try to publish, I get the error:
5001: The name of package 'obfus_plugin' does not reflect the location of this file. Please change the package definition's name inside this file, or move the file. C:\flowplayer\url_secure\src\actionscript\obfus_plugin\obfus.as

the location of the .as file is:
C:\flowplayer\url_secure\src\actionscript\obfus_plugin\obfus_plugin.as

In my classpaths I have:
C:\flowplayer\url_secure\src\actionscript\obfus_plugin

What am I doing wrong? Did I miss a directory somewhere? All help is GREATLY appreciated.

A: Have you tried moving the file to the suggested location?
`C:\Documents and Settings\***\My Documents\My Dropbox\Public\obfus_plugin\obfus_plugin.as`

It's telling you that's where it should be placed. From the classpath root, the actionscript file should live in a nest of folders that reflects the package name.
Say you have an actionscript file with class in package X.Y.Z, the file should live in folder %classpath%\X\Y\Z

A: The directory structure should match the package structure, with classpath as it's root.
package{} matches %classpath%.
package A{} matches %classpath%/A.
So, instead of:
C:\flowplayer\url_secure\src\actionscript\obfus_plugin

You should use, as classpath:
C:\flowplayer\url_secure\src\actionscript

or place the file in a new folder:
C:\flowplayer\url_secure\src\actionscript\obfus_plugin\obfus_plugin

or even use the default package in the .as file:
package {
    import [...]
}


text:
Q: Unable to use jquery in my mvc .net project I've just started working with ASP.Net MVC4 project. I want to work with jQuery for click events in my project, but I am unable to get success even when I included jQuery in my layout.cshtml and Index(home) pages as follows,
Index(home):
 @Scripts.Render("~/bundles/jquery")

 $("#searchId").click(function () {
        alert("Serach was clicked.");
    });

Layout.cshtml:

    @Scripts.Render("~/bundles/jquery")

<input type="button" value="search" id="searchId" />

Can anybody help me please to get a solution?

A: Your DOM might not be ready when you are registering the event handlers, try encapsulating the event handlers in document ready like this
 $(document).ready(function(){
    $("#searchId").click(function () {
        alert("Serach was clicked.");
    });
 });

Also I don't see the @RenderBody() method being called in your layout, that might give you an error too.

A: First thing is, you are rendering Jquery bundle 2 times both in Index and Layout page.
As Layout.cshtml is a master page so you have to put Jquery bundle only in master page not in the child index page.
And in the child index page just use following code:
$(document).ready(function(){
   $("#searchId").click(function () {
    alert("Serach was clicked.");
   });
 });

or
$( "#searchId" ).on( "click", function() {
  alert("Serach was clicked.");
});

Let me know if you still have the problem.


text:
Q: Equal on an open subset implies equal on the whole space? Let $X$ be an irreducible algebraic set. Let $U \subset X$ be an open subset with respect to
the Zariski topology over X. Let $f_1 : X \to \mathbb{C}$, $f_2 : X \to \mathbb{C}$ be regular functions on $X$.
Is it true that $f_1|_U = f_2|_U$ implies $f_1 = f_2$?
If yes, how should I proceed to prove it?

A: Yes, if $U$ is nonempty.
Let $Z$ be the zero set of the regular function $f_1 - f_2 : X \to \mathbb{C}$. Then, $Z$ is a closed set (in the topology on $X$). On the other hand, $U$ is an open set, so that $X \setminus U$ is a closed set.
Assume that $U$ is nonempty and that $f_1 \mid_U = f_2 \mid_U$. Then, $\left(f_1 - f_2\right) \mid_U = f_1 \mid_U - f_2 \mid_U = 0$ (since $f_1 \mid_U = f_2 \mid_U$), so that $U \subseteq Z$ (since $Z$ is the zero set of $f_1 - f_2$). Thus, $X = \underbrace{U}_{\subseteq Z} \cup \left(X \setminus U\right) \subseteq Z \cup \left(X \setminus U\right)$. Hence, the topological space $X$ is the union of its two closed sets $Z$ and $X \setminus U$. Hence, one of these two closed sets $Z$ and $X \setminus U$ must be $X$ (because $X$ is irreducible, and therefore, if $X$ is the union of two closed sets, then one of these two closed sets must be $X$). Since $X \setminus U \neq X$ (because $U$ is nonempty), this shows that $Z = X$. But $Z$ was defined as the zero set of $f_1 - f_2$. Therefore, $Z = X$ shows that $f_1 - f_2 = 0$, whence $f_1 = f_2$.


text:
Q: jQuery параметры плагина Здравствуйте!
Возникла проблема с плагином jQuery (самописка). Параметры, которые я записываю в переменную плагина при каждой новой инициализации перекрываются более новыми. В параметрах я храню селекторы для элементов.
В моем случае, постоянно перезаписывается объект data (я имею несколько .fixed-block на странице).
Сам вопрос: могу ли я хранить параметры для каждой отдельной инициализации плагина? Мне необходимо сохранять параметры для каждого проинициализированного блока.

(function($){
    jQuery.fn.fixedBlock = function(options){
        $.extend({

        },options);

        var data = {
            fixed: false,
            original: null,
            copy: null
        };

        var init = function(){
            //
        };

        var check = function() {
            //
        };

        var copyElement = function(jQueryElement) {
            //
        };

        var calcTopValue = function() {
            //
        };

        return this.each(init);
    }
}(jQuery));

$('.fixed-block').fixedBlock();

A: судя по коду  параметры никуда не сохраняются, потому что extend объединяет все в целевой объект, а он у тебя даже не определен , соответственно, так как он у тебя нигде не определен, то он и превращается в мусор.
По поводу $.extend:
Если задать два или более объекта, то результатом будет их объединение. В случае, если вы зададите только один объект, функция extend() добавит его содержимое в глобальный объект $ (jQuery). Таким образом можно расширять возможности библиотеки, добавляя свои функции в ее пространство имен. Это может быть полезно при написании плагинов.
Напомним, что в результате объединения объектов, первый из них будет изменен (он же будет возвращен в качестве результата выполнения функции extend()). Если нужно, чтобы ни один из заданных объектов не был изменен, то можно задать в качестве параметра target пустой объект:
var object = $.extend({}, object1, object2);

Eсли сохранять все аргументы в сам объект jquery, то он быстро превратится в мусорку данных, и потом дебажить код будет почти невозможно.

A: Собственно, решил свою проблему, немного переписав плагин. Параметры проинициализированного элемента можно сохранять в дата-параметры. Пример кода:
(function($){
    var methods = {
        init : function (options) {
            options = $.extend({
                fixedClass: 'fixed-top',
                invisibleClass: 'invisible',
                copyClass: 'copy'
            }, options);

            return this.each(function() {
                var $this = $(this),
                    data = $this.data('fixedBlock');

                if (!data) {
                    $this.data('fixedBlock',{
                        original: $this,
                        copy: copy($this)
                    }); // Здесь я сохраняю нужные мне данные в дата-параметр "fixedBlock"

                }
            });
        },

        destroy : function () {

        }
    };

    $.fn.fixedBlock = function (method) {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error('Метод с именем ' + method + ' не существует для jQuery.fixedBlock');
        }
    };
})(jQuery);


text:
Q: Collecting data from two data frames to store in a new data frame I would like to somehow create a third data frame which is a combination of two existing data frames.
The dates in both the data frames are not consistent, I would like to take the dates common to both data frames and load them into the third data frame along with 'company_name' from the first and 'count' from second data frame.
The input looks like this:
**Data Frame 1:**
Date    Company_Name
10/18/2013  AFAM
10/17/2013  SMN
10/16/2013  SMN
10/15/2013  AFAM
10/14/2013  AFAM

**Data Frame 2:**
data_date   normalized_company_name count
10/18/2013  Almost Family   1
10/16/2013  somename    2
10/15/2013  somename    3
10/14/2013  Almost Family   4
10/13/2013  Almost Family   5

And this is what I want:
**Data Frame 3:**
Date    Company_Name    count
10/18/2013  AFAM    1
10/15/2013  AFAM    4

I would also like to mention that the format of the date columns in all data frames is Date. I have done a lot of acrobatics with this already but can't seem to reach a conclusion. I would really appreciate if I could get some help on this.
Here is some code I have been trying to use which does not seem to work:
finalData$Total.Job.Count[
  as.character(finalData$Date) %in%
    intersect(as.character(finalData$Date[finalData$Company_Name=='AFAM']) ,
  as.character(jobs$data_date[jobs$normalized_company_name=='Almost Family'])) &
    finalData$Company_Name=='AFAM']
<-
jobs$job_count_total[
  as.character(jobs$data_date) %in%
    intersect(as.character(finalData$Date[finalData$Company_Name=='AFAM']) ,
  as.character(jobs$data_date[jobs$normalized_company_name=='Almost Family'])) &
    jobs$normalized_company_name=='Almost Family']

Any help would be greatly appreciated.
TIA

A: merge( finalData, jobs[ , c("data_date", "count")] , by.x=1, by.y=1 )


text:
Q: How to fill users variable with data from GET request in React I am making a GET call request to an API in order to fetch some data in my React component and save it to my users variable, but the data does not get saved, I get undefined when I console.log it. How can I set the response data from my GET call and save it in the users variable? Here is my attempt:
 const [users, setPosts] = React.useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((data) => console.log(data));

    setPosts(users.data);
  }, []);

A: In the code you have posted, you aren't saving the data to users. Try this:
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => response.json())
  .then(setPosts);
}, []);

A: This is how it should be do it:
const [users, setPosts] = React.useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((data) => setPosts(data););
  }, []);

That way you set your users as data
Also as a hook rule you should define your state as follow const [users, setUsers] = useState()


text:
Q: ServiceReference not fetching the all class names for activation I'm using the below code to fetch the all reference classes in-order to activate it :
String filter = "(component.factory=com.requestclasses.mypack)";
bundleContext = componentContext.getBundleContext();
ServiceReference[] references = bundleContext.getAllServiceReferences(ComponentFactory.class.getCanonicalName(), filter);

But in reference i'm not getting all the classes.I'm not sure whether the issue is with code or AEM 5.6 .
Any suggestions ?

A: I generally wouldn't recommend querying for service references using low level APIs like these.
You might be better off retrieving those references using the @Reference annotation like so:
@Reference(
   name = "componentFactories",
   referenceInterface = ComponentFactory.class,
   cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE,
   policy = ReferencePolicy.DYNAMIC
)
protected List<ComponentFactory> componentFactories = new ArrayList<ComponentFactory>();


text:
Q: Google Kickstart Truck Delivery Partially Correct Answer I was trying to solve the Truck Delivery problem from Google Kick Start 2021 Round B (4th Question)
and I came across a problem with my code that I can't figure out;
import sys
import math

sys.stdin = open('input.txt', 'r')

def solve(index):
    if index == 0 :
        return
    else:
        for j in range(len(roads)):
            if roads[j][0] == index:
                if roads[j][2] <= w:
                    fines.append(roads[j][3])
                    solve(roads[j][1])

T = int(input())
for case in range(1, T+1):
    n, q = [int(x) for x in input().split(" ")]
    roads = []

    for rd in range(n-1):
        road = [int(x) for x in input().split(" ")]

        if road[0] < road[1]:
            temp = road[1]
            roads.append([road[1], road[0], road[2], road[3]])
        else:
            roads.append(road)
    roads.sort(reverse=True)

    result = ""
    for query in range(q):
        c, w = [int(x) for x in input().split(" ")]
        fines = []
        solve(c)

        if len(fines) != 0:
            result += str(math.gcd(*fines)) + " "
        else:
            result += "0 "

    print("Case #{}: {}".format(case, result))

And I get a partially correct answer from the sample case, my output is;
Case #1: 1 0 0 5 7
Case #2: 0 5

The correct output should be;
Case #1: 1 4 0 5 7
Case #2: 10 5

For some reason my recursion doesn't append the fine in case 1 day 1 and case 2 day 0. Can you guys spot the problem? Also feel free to inform me with the bad practices in my code etc.
PS: I am not looking for the best answer to this question, I am just trying to solve it on my own

A: The cause for failing those two test cases is that your solve code exits recursion as soon as it finds a road where no toll has to be paid. But this is not right: the rest of the path to city #1 may still have other roads that will incur a toll.
So move the recursive call out of the if block, like this:
            if roads[j][2] <= w:
                fines.append(roads[j][3])
            solve(roads[j][1])

Although this will solve the issue you bumped into, there are more problems ahead:
Your algorithm assumes that the path from a city k to city #1 will always go from a city with a greater number to a city with a lesser number. Although this is the case with the 2 sample test cases, this is not guaranteed. It might well be that the path would run from city 20 to city 80 and then to city 1.
To resolve that problem, you'll have to change your approach. I would suggest to create a list where the index is a city number and the value is a tuple (parent, maxweight, toll), such that parent is the city's parent node when the tree is rooted with as root node city #1.
In order to make that list, I would suggest first creating an adjacency list, then run through that graph in a depth-first traversal starting at city 1. During that traversal you can register which are the "upward" edges towards the root, and create that data-structure described in the previous paragraph.
Here is some (untested) code:
def solve(parent, city, weight):
    fines = []
    while city > 1:
        if weight >= parent[city][1]:
            fines.append(parent[city][2])
        city = parent[city][0]
    return math.gcd(*fines) if fines else 0

def buildtree(roads):
    # Adjacency list:
    adj = [[] for _ in range(n + 1)]  # index is city number (1 .. N).
    for city1, city2, maxweight, toll in roads:
        # Add road in both directions to adjacency list
        adj[city1].append((city2, maxweight, toll))
        adj[city2].append((city1, maxweight, toll))

    # Each node has only one parent in a rooted tree.
    #   Find that parent for each node, when node #1 is the root:
    visited = [False] * (n + 1)
    parent = [None] * (n + 1)

    def recur(city):
        visited[city] = True
        for nextcity, maxweight, toll in adj[city]:
            if not visited[nextcity]:
                parent[nextcity] = (city, maxweight, toll)
                recur(nextcity)

    recur(1)  # build `parent` data structure
    return parent

sys.stdin = open('input.txt', 'r')
numcases = int(input())
for case in range(1, numcases + 1):
    numcities, numqueries = [int(x) for x in input().split(" ")]

    roads = [
        [int(x) for x in input().split(" ")]
        for road in range(numcities - 1)
    ]
    queries = [
        [int(x) for x in input().split(" ")]
        for query in range(numqueries)
    ]

    parent = buildtree(roads)

    result = " ".join(
        str(solve(parent, city, weight)) for city, weight in queries
    )

    print("Case #{}: {}".format(case, result))


text:
Q: Monitor ppp0 traffic usage with Linux Hey I'm developing a 3G connected device with a raspberry Pi. My mobile provider allows me to use 50 MB/month.
This device will be installed somewhere nobody can have physically access to.
My concern is to avoid data traffic overuse. I need a tool to measure all the accumulated traffic going through (in and out) the ppp0 interface in order to disconnect the interface until next month if the 50MB limit is reached.
I tried with ifconfig but since I have some disconnections the counter is always reset at each reconnection.
I tried ntop and iftop but from what I understood these are tools for measuring real-time traffic.
I'm really looking for some kind of cumulative traffic use, like we usually can find on smartphones.
Any idea?

A: try vnstat with vnstati
Its quiet easy to install, most Linuxdistros have it in their repos and it generates beautyful images:
SCREENIE


text:
Q: Execute an SQL query inside another SQL query Ok, I assume that the title is not the best title, but let me explain my problem: I'm creating a website that needs to show posts of people (anyway), and I have to show their gravatar's profile picture, so this what I did:
<?php
            function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
                $url = 'https://www.gravatar.com/avatar/';
                $url .= md5( strtolower( trim( $email ) ) );
                $url .= "?s=$s&d=$d&r=$r";
                if ( $img ) {
                    $url = ' $val )
                        $url .= ' ' . $key . '="' . $val . '"';
                    $url .= ' />';
                }
                return $url;
            }
            require("db.php");
            $sql = "SELECT * FROM posts ORDER BY date DESC";
            foreach ($db->query($sql) as $row) {
                // var_dump($row);
                $user = $row['user_id'];
                $sql_user = "SELECT email FROM users WHERE id = $user";
                foreach ($db->$sql_user as $row_user) {
                    var_dump($row_user);
                    echo "";
                }
                echo "
".$row['title']."

";
                echo "
".$row['content']."

";
            }

But, it doesn't work (well, it works, but it doesn't shows me the profile picture of the user, only the post).
So, I think the problem is that I can't call 2 times the variable $db at the same time, but I'm not sure, so that's m=why I'm asking if there is a way to fix my problem or to select 2 tables at the same time.

A: you can short your logic
$sql="SELECT u.email "
                    . "FROM posts AS p "
                    . "LEFT JOIN users AS u "
                    . "ON u.id=p.user_id "
                    . "ORDER BY p.date DESC";

A: use join
SELECT * FROM users join posts  on users.id =Posts.user_id ORDER BY date DESC

A: You could just use JOIN

JOIN clause is used to combine rows from two or more tables, based on
  a related column between them.

A: you  don't apply query to  sql string   in second foreach
  foreach ($db->query($sql_user) as $row_user) {

A: see your second foreach you miss to put query function
foreach ($db->query($sql) as $row) {

foreach ($db->query($sql_user) as $row_user) {


text:
Q: Вызвать $this внутри функции Вот класс
class ClassName{
    public $array = array('1','2');

    function __construct() {
        ....
    }

    function init() {

        function add_class($classes) {
            foreach( $this->array as $class ){
               array_push($classes, $class)
            }
            return  $classes;
        }
        add_filter('post_class', 'add_class');

    }

    function init2() {

        function add_metaboxes() {
            foreach( $this->array as $metaboxes ){
               $checked = ( get_post_meta($post->ID, 'app_category_'.$metaboxes , true) ) ? 'checked' : '';

               echo '<input type="checkbox" '.$checked.' >';

            }
        }

        add_meta_box( 'app_category_box', 'BlaBlaBla', 'add_metaboxes');

    }
}

В ооп не силен, когда пытаюсь так сделать - пишет "Using $this when not in object context in"

A: В вашем коде у вас имеется класс, в котором определены функции. В данных функциях, вы обяъвляете другие функции. Это просто объявления, к самому классу они не будут никак относится. После вызова метода Init у вас все так же будет оставаться класс, а также для вызова в других местах кода станет доступна функция add_class.
Замечу, что при повторном вызове функции init интерпретатор упадет с ошибкой fatal error при попытке объявить заново функцию add_class.
Поскольку объявленная функция ни коим боком не будет относится к классу (который ее объявил), то, конечно, речи о доступе к $this там быть  не может. О чем и сказано в сообщении об ошибке.
Как вариант решения (если используете данный массив единственном экземпляре) может стать объявление массива как статического члена класса.
public static $array = [1,2];

В дальнейшем для обращения к массиву из сторонних функций будут иметь следующий вид:
foreach( ClassName::$array as $class ){
}

Повторюсь, что статические свойства существуют в единственном экземпляре и одинаковы межде всеми экземплярами класса. Но по всей видимости, класс у вас используется тоже в единственном экземпляре.


text:
Q: How I will show the touch point in another view with zoom (OpenCV cropping) I can crop an image easily by openCV. But I want a zooming view will be created when crop rect point is touched. But get nothing related this. Moreover, this is my 1st openCV project. I want Like this image:

My crop operation is given below:
-(void)singlePan:(UIPanGestureRecognizer *)gesture{
CGPoint posInStretch = [gesture locationInView:_cropRect];
if(gesture.state==UIGestureRecognizerStateBegan){
    [_cropRect findPointAtLocation:posInStretch];
}
if(gesture.state==UIGestureRecognizerStateEnded){
    _cropRect.activePoint.backgroundColor = [UIColor grayColor];
    _cropRect.activePoint = nil;
    [_cropRect checkangle:0];
}
[_cropRect moveActivePointToLocation:posInStretch];

}

Crop action is here:
- (IBAction)doneAction:(id)sender {

_titleOutlet.text = NSLocalizedString(@"Rotation", @"Message");

if([_cropRect frameEdited]){

    //Thanks To stackOverflow
    CGFloat scaleFactor =  [_sourceImageView contentScale];
    CGPoint ptBottomLeft = [_cropRect coordinatesForPoint:1 withScaleFactor:scaleFactor];
    CGPoint ptBottomRight = [_cropRect coordinatesForPoint:2 withScaleFactor:scaleFactor];
    CGPoint ptTopRight = [_cropRect coordinatesForPoint:3 withScaleFactor:scaleFactor];
    CGPoint ptTopLeft = [_cropRect coordinatesForPoint:4 withScaleFactor:scaleFactor];

    NSLog(@"ptBottomLeft=%@", NSStringFromCGPoint(ptBottomLeft));
    NSLog(@"ptBottomRight=%@", NSStringFromCGPoint(ptBottomRight));
    NSLog(@"ptTopRight=%@", NSStringFromCGPoint(ptTopRight));
    NSLog(@"ptTopLeft=%@", NSStringFromCGPoint(ptTopLeft));

    CGFloat w1 = sqrt( pow(ptBottomRight.x - ptBottomLeft.x , 2) + pow(ptBottomRight.x - ptBottomLeft.x, 2));
    CGFloat w2 = sqrt( pow(ptTopRight.x - ptTopLeft.x , 2) + pow(ptTopRight.x - ptTopLeft.x, 2));

    CGFloat h1 = sqrt( pow(ptTopRight.y - ptBottomRight.y , 2) + pow(ptTopRight.y - ptBottomRight.y, 2));
    CGFloat h2 = sqrt( pow(ptTopLeft.y - ptBottomLeft.y , 2) + pow(ptTopLeft.y - ptBottomLeft.y, 2));

    CGFloat maxWidth = (w1 < w2) ? w1 : w2;
    CGFloat maxHeight = (h1 < h2) ? h1 : h2;

    cv::Point2f src[4], dst[4];
    src[0].x = ptTopLeft.x;
    src[0].y = ptTopLeft.y;
    src[1].x = ptTopRight.x;
    src[1].y = ptTopRight.y;
    src[2].x = ptBottomRight.x;
    src[2].y = ptBottomRight.y;
    src[3].x = ptBottomLeft.x;
    src[3].y = ptBottomLeft.y;

    dst[0].x = 0;
    dst[0].y = 0;
    dst[1].x = maxWidth - 1;
    dst[1].y = 0;
    dst[2].x = maxWidth - 1;
    dst[2].y = maxHeight - 1;
    dst[3].x = 0;
    dst[3].y = maxHeight - 1;

    cv::Mat undistorted = cv::Mat( cvSize(maxWidth,maxHeight), CV_8UC4);
    cv::Mat original = [MMOpenCVHelper cvMatFromUIImage:_adjustedImage];

    NSLog(@"%f %f %f %f",ptBottomLeft.x,ptBottomRight.x,ptTopRight.x,ptTopLeft.x);
    cv::warpPerspective(original, undistorted, cv::getPerspectiveTransform(src, dst), cvSize(maxWidth, maxHeight));

    [UIView transitionWithView:_sourceImageView duration:0.1 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{

        _sourceImageView.image=[MMOpenCVHelper UIImageFromCVMat:undistorted];
        _cropImage=_sourceImageView.image;

        //         _sourceImageView.image = [MMOpenCVHelper UIImageFromCVMat:grayImage];//For gray image

    } completion:^(BOOL finished) {
        _cropRect.hidden=YES;
        //        [UIView animateWithDuration:0.5 animations:^{
        //        scrollView.frame=CGRectMake(0, 0, self.view.bounds.size.width, 64);

        //        }];

    }];

    original.release();
    undistorted.release();
}
else{
    UIAlertView  *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert", nil) message:NSLocalizedString(@"Invalid Rect", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
    [alertView show];
}
}

A: Find origin of your "lens" ROI, crop it to separate image, scale it say factor=2 each dimension, then crop from scaled ROI central part with offset dx=(ROI_width-ROI_width*factor)0.5  and dy=(ROI_height-ROI_heightfactor)*0.5, size=(ROI_width,ROI_height), and put new cropped image back to your initial ROI on source image. You can also apply round mask as on your image, on copying.


text:
Q: Simple raw_input code not working I honestly have no clue why this code isn't working. When the code runs, no matter what I input, it always returns "Goodbye. Have a nice day!" Can anyone see why?
again = raw_input("Would you like to restart? ").lower()
if again == "no" or "n":
    print "Goodbye. Have a nice day!"
    loop = 0
elif again == "yes" or "y":
    loop = 1
else:
    print "Answer invalid. Have a nice day!"
    loop = 0

(There is a section of code before this which is in a loop when 'loop' variable is 0. That's why there are loop variable edits following the 'if', 'elif', and 'else' statements.


text:
Q: Ajax Call Request every 5 Seconds And Wait Before Sending The Request Until The Previous Request Is sent I want to send ajax Request every 5 seconds And each request waits until the previous request is sent successfully , This is my code it works but it sends requests even if the previous request was not sent successfully.
Here My Code :
$(document).ready(function() {
  $('#myform').on('submit', function(e) {
    e.preventDefault();
    $("#sending").show();
    $("#send").attr('disabled', true);
    $("#send").attr('value', "Sending ...");

    var ajax_call = function() {

      $.ajax({
        url: "fbshr.php",
        type: "POST",
        data: {
          postURL: $('#postURL').val()
        },
        success: function(data) {
          $(data).appendTo($("#response")).before("");
          $('#response').animate({
            scrollTop: $('#response').prop("scrollHeight")
          }, 500);
          $("#num-msg-1").html($('#response p.alert-success').length);
          $("#num-msg-2").html($('#response p.alert-danger').length);

        }
      });
    };

    var interval = 5000;

    setInterval(ajax_call, interval);
  });
});


text:
Q: Not able to write to an exisitng file in Flutter I am trying to overwrite the contents of a CSV file in my app_name/assets/file.csv path. I'm using path_provider and csv for these operations.
Here's the code that is supposed to write to the existing CSV file:
updateQuantity(customer, index, qty, list) async {
    list[index][2] = qty;
    String updatedCsv = const ListToCsvConverter().convert(list);
    print(updatedCsv);

    final dir = await getApplicationDocumentsDirectory();
    String path = "${dir.path}/assets/$customer.csv";

    File file = await File(path);
    file.writeAsString(updatedCsv);
  }

The error I receive:
E/flutter ( 4352): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.example.data_collection_2/app_flutter/assets/Test.csv' (OS Error: No such file or directory, errno = 2)

I have scoured the internet but nothing seems to be helping me write to the file.
Thanks in advance

A: Are you sure that the directory assets already exists? If the CSV does not already exist then it will fail since the directory assets probably does not exist either.
The way to fix this is to do File file = await File(path).create(recursive: true);.
This will create the file and the directory assets if they do not already exist. If they do exist it will do nothing and will not fail so it is safe either way.


text:
Q: Filter post by users creation date I am working on a membership site and my client would like to hide member's only content from new subscribers. EX. If I create a new member today how can I keep the new member seeing previously created content?
TIA!


text:
Q: Perform POST request with Lazarus How can I perform a POST request with Lazarus?
I found that it is possible to do using Indy for Lazarus, but the installation of Indy itself is a bit of a hassle, having to recompile and all. Is there another way?

A: Of course you can use other library like Synapse. There is httpsend unit with functions like HttpPostURL(), it also supports SSL/TLS. I used this library with both Delphi and FPC.
If you do not need to use SSL/TLS, proxy or other more complicated things then it is not very complicated to create your own HTTP simple client based on socket and many HTTP tutorials.

A: Using Indy with Lazarus is very easy, if you do not need the components in the palette but create them at run time.
Just add <indy>/Lib/Core, <indy>/Lib/Protocols and <indy>/Lib/System to the search path.

A: Nowdays there is the fphttpclient unit supplied with FPC. So no need external libs/components to send POST, GET etc methods.


text:
Q: How do you set the default value of a field or set of choices in a rails form? I'm trying attempting the (ought to be) simple feat of setting a radiobox pair in a Rails form_for block to default to "1 hour" when given the choice between "1/2 hour" or "1 hour" as options. The documentation that I've looked at doesn't indicate how to do this. Any advice?

A: Make sure you're passing an instance to form_for, and that its attribute is pre-set.
@post = Post.new :time => "1 hour"

Then in your view
form_for @post do |f|
  f.radio_button :time, "1/2 hour"
  f.radio_button :time, "1 hour"
end

If this is not a db attribute, do this instead:
form_for @post do |f|
  f.radio_button :time, "1/2 hour"
  f.radio_button :time, "1 hour", {:checked => true}
end

A: I think the easiest way is to put that value inside your controller.
For example:
def new
  @entry = Entry.new(:radio_box_attribute => 'my default value') # 1 hour
end