问:
Insert adjustments document in screen AP302000 of acumatica erp through web services api
I need to insert adjusment document (bill doc) in Documents to Apply of the screen Checks and Payments (AP302000). This adjustment document need to insert based on current "Prepayment" document. I need to do this for set off the "prepayment" with the spesific "bill". Note: both of this "Prepayment" and "Bill" documents already released in previous session. So I just have to call spesific reference nbr of Prepayment Doc in header, and then call the spesific Reference Nbr of Bill Doc in Documents to Apply (detail transaction).

Please refer to this screenshot below.

I tried to provide my goal using this code below.

```<code>context.CookieContainer = new System.Net.CookieContainer();
context.Timeout = System.Threading.Timeout.Infinite;
context.Url = "http://localhost/AcuInterface/(W(3))/Soap/SOD.asmx";
LoginResult result = context.Login("admin", "123");
AP302000Content checkSchema = context.AP302000GetSchema();
List<Command> cmds = new List<Command>();
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.Type, Value = "Prepayment" });
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.ReferenceNbr, Value = "1600001331"});
cmds.Add(checkSchema.DocumentsToApply.ServiceCommands.NewRow);
cmds.Add(new Value { LinkedCommand = checkSchema.DocumentsToApply.DocumentType, Value = "Bill" });
cmds.Add(new Value { LinkedCommand = checkSchema.DocumentsToApply.ReferenceNbrAdjdRefNbr, Value = "1600003050"});
cmds.Add(new Value { LinkedCommand = checkSchema.DocumentsToApply.AmountPaid, Value = "80000" });
try
{
       cmds.Add(checkSchema.Actions.Save);
       var result = context.AP302000Submit(cmds.ToArray());
}
catch (Exception ex)
{
       MessageBox.Show(ex.Message);
}
finally
{
       context.Logout();
}
</code>```

But when I debug this code, I got this error message. Please refer to this screenshot below.

Does anyone knows to solve this issue ?

答:
On Screen with a type selector before the reference number, you must add an additional action, the insert action.

Also there seem to be an issue with how the page is structured and it is trying to commit the change on the detail level after each and every field entered. So since it doesn't have yet all the required information for it to be valid it return the error you are seeing.

Here is a code sample that should work:

```<code>context.CookieContainer = new System.Net.CookieContainer();
context.Timeout = System.Threading.Timeout.Infinite;
context.Url = "http://localhost/Demo610u05/(W(346))/Soap/AP302000.asmx";
LoginResult result = context.Login("admin@Company", "admin");
AP302000Content checkSchema = context.AP302000GetSchema();

var detailTypeNoCommit = checkSchema.DocumentsToApply.DocumentType;
detailTypeNoCommit.Commit = false;
var detailRefNbrNoCommit = checkSchema.DocumentsToApply.ReferenceNbrAdjdRefNbr;
detailRefNbrNoCommit.Commit = false;
var detailamountPaidNoCommit = checkSchema.DocumentsToApply.AmountPaid;
detailamountPaidNoCommit.Commit = false;

List<Command> cmds = new List<Command>();
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.Type, Value = "Prepayment" });
cmds.Add(checkSchema.Actions.Insert);
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.ReferenceNbr, Value = "1600001331"});
cmds.Add(checkSchema.DocumentsToApply.ServiceCommands.NewRow);
cmds.Add(new Value { LinkedCommand = detailTypeNoCommit, Value = "Bill" });
cmds.Add(new Value { LinkedCommand = detailRefNbrNoCommit, Value = "1600003050"});
cmds.Add(new Value { LinkedCommand = detailamountPaidNoCommit, Value = "80000" });
try
{
   cmds.Add(checkSchema.Actions.Save);
   var result = context.AP302000Submit(cmds.ToArray());
}
catch (Exception ex)
{
       MessageBox.Show(ex.Message);
}
finally
{
   context.Logout();
}
</code>```

Body:
I need to insert adjusment document (bill doc) in Documents to Apply of the screen Checks and Payments (AP302000). This adjustment document need to insert based on current "Prepayment" document. I need to do this for set off the "prepayment" with the spesific "bill". Note: both of this "Prepayment" and "Bill" documents already released in previous session. So I just have to call spesific reference nbr of Prepayment Doc in header, and then call the spesific Reference Nbr of Bill Doc in Documents to Apply (detail transaction).

Please refer to this screenshot below.

I tried to provide my goal using this code below.

context.CookieContainer = new System.Net.CookieContainer();
context.Timeout = System.Threading.Timeout.Infinite;
context.Url = "http://localhost/AcuInterface/(W(3))/Soap/SOD.asmx";
LoginResult result = context.Login("admin", "123");
AP302000Content checkSchema = context.AP302000GetSchema();
List<Command> cmds = new List<Command>();
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.Type, Value = "Prepayment" });
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.ReferenceNbr, Value = "1600001331"});
cmds.Add(checkSchema.DocumentsToApply.ServiceCommands.NewRow);
cmds.Add(new Value { LinkedCommand = checkSchema.DocumentsToApply.DocumentType, Value = "Bill" });
cmds.Add(new Value { LinkedCommand = checkSchema.DocumentsToApply.ReferenceNbrAdjdRefNbr, Value = "1600003050"});
cmds.Add(new Value { LinkedCommand = checkSchema.DocumentsToApply.AmountPaid, Value = "80000" });
try
{
       cmds.Add(checkSchema.Actions.Save);
       var result = context.AP302000Submit(cmds.ToArray());
}
catch (Exception ex)
{
       MessageBox.Show(ex.Message);
}
finally
{
       context.Logout();
}

But when I debug this code, I got this error message. Please refer to this screenshot below.

Does anyone knows to solve this issue ?

Body:
On Screen with a type selector before the reference number, you must add an additional action, the insert action.

Also there seem to be an issue with how the page is structured and it is trying to commit the change on the detail level after each and every field entered. So since it doesn't have yet all the required information for it to be valid it return the error you are seeing.

Here is a code sample that should work:

context.CookieContainer = new System.Net.CookieContainer();
context.Timeout = System.Threading.Timeout.Infinite;
context.Url = "http://localhost/Demo610u05/(W(346))/Soap/AP302000.asmx";
LoginResult result = context.Login("admin@Company", "admin");
AP302000Content checkSchema = context.AP302000GetSchema();

var detailTypeNoCommit = checkSchema.DocumentsToApply.DocumentType;
detailTypeNoCommit.Commit = false;
var detailRefNbrNoCommit = checkSchema.DocumentsToApply.ReferenceNbrAdjdRefNbr;
detailRefNbrNoCommit.Commit = false;
var detailamountPaidNoCommit = checkSchema.DocumentsToApply.AmountPaid;
detailamountPaidNoCommit.Commit = false;

List<Command> cmds = new List<Command>();
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.Type, Value = "Prepayment" });
cmds.Add(checkSchema.Actions.Insert);
cmds.Add(new Value { LinkedCommand = checkSchema.PaymentSummary.ReferenceNbr, Value = "1600001331"});
cmds.Add(checkSchema.DocumentsToApply.ServiceCommands.NewRow);
cmds.Add(new Value { LinkedCommand = detailTypeNoCommit, Value = "Bill" });
cmds.Add(new Value { LinkedCommand = detailRefNbrNoCommit, Value = "1600003050"});
cmds.Add(new Value { LinkedCommand = detailamountPaidNoCommit, Value = "80000" });
try
{
   cmds.Add(checkSchema.Actions.Save);
   var result = context.AP302000Submit(cmds.ToArray());
}
catch (Exception ex)
{
       MessageBox.Show(ex.Message);
}
finally
{
   context.Logout();
}


来源: stackexchange

问:
MessageDialog ShowAsync Catastrophic Failure
I try to update the MainPage UI with data received from a Serial port. Once the data is received, an event is raised, so I send a Message using MVVMLight to the MainPage hoping to update the UI with. What could be wrong here?

The following sample works just fine if I try to call the function from the Main constructor or even when updating a simple TextBlock after the Serial event has been raised.

```<code>private void OnMsgRecieved(PortMsg obj)
{
    ShowDialog(obj.StringID);
}

private async void ShowDialog(string msg)
{
    var dlg = new MessageDialog(msg);
    try
    {
      await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
        {
          await dlg.ShowAsync();
        });
    }
    catch (Exception exc)
    {
      // Catastrophic Failure
    }
}
</code>```

答:
According to the description, I think that this happens because you don't create MessageDialog on UIThread. Place it inside the Dispatcher and everything should be fine.

Other than that you may also check whether this is being called from some wrong context (e.g. from some page that is not shown anymore), but it is less likely to cause this problem.

ContentLicense: CC BY-SA 3.0

Body:
I try to update the MainPage UI with data received from a Serial port. Once the data is received, an event is raised, so I send a Message using MVVMLight to the MainPage hoping to update the UI with. What could be wrong here?

The following sample works just fine if I try to call the function from the Main constructor or even when updating a simple TextBlock after the Serial event has been raised.

private void OnMsgRecieved(PortMsg obj)
{
    ShowDialog(obj.StringID);
}

private async void ShowDialog(string msg)
{
    var dlg = new MessageDialog(msg);
    try
    {
      await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
        {
          await dlg.ShowAsync();
        });
    }
    catch (Exception exc)
    {
      // Catastrophic Failure
    }
}


问:
Multi-list iteration with default value in Python
I'm running an experiment with python simulation, and need to create a list of input cases.

Each case is an instance taken from a list of list of parameters, For example:

```<code>heights = [100,110,120]
alphas = [0.1,0.01,0.001]
C = [0.1,0.2,0.5,0.9]
B = [1,2]
</code>```

and the list of lists is:

```<code>params = [heights,alphas,C,B]
</code>```

The original amount is bigger (~30x100) so it's not efficient to address each list directly.

Eventually each input case is a tuple/namedtuple/dictionary of one parameter from each category, for example:

```<code>instance = {'height':100, 'alpha':0.1,'C:0.1, 'B':1}
</code>```

I would like to iterate the parameter space in order to create a list of instances - but here is the catch:

Instead of making a cartesian product of all of them, per each parameter I want to iterate all the options, while the rest of categories are set to a default value (the first). For example:

```<code>params = [[1,2,3],[4,5][7,8]]
</code>```

the expected set of instances (with no repeat) is:

[(1,4,7),(2,4,7),(3,4,7),(1,5,7)(1,4,8)]

where 1 is the default of first index, 4 is the default of the second index and 7 is the default of the 3rd.

Making a cartesian product is quite easy with itertools:

```<code>from itertools import product
params = [[1,2,3],[4,5],[7,8]]
list(product(*params))
</code>```

[(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

then I can filter out unnecessary instances, but it sounds ineficient to generate them at first place. Is there any elegant way to build this iteration?

答:
I propose another approach. Use openTURNS. This python library is well developed and has some classes for defining a design of experiment which is said to have good properties in terms of space filling.

See here an example LowDiscrepancySequence. Using this design you will be able to do statistical analysis, create models, etc. I am not related to them but they are well known in the field.

However, if you préfère you can stick with your method. To make it more pythonic I would build for that a generator expression or a list comprehension directly:

((I, j, k) for i, j, k in product(...))

Body:
I'm running an experiment with python simulation, and need to create a list of input cases.

Each case is an instance taken from a list of list of parameters, For example:

heights = [100,110,120]
alphas = [0.1,0.01,0.001]
C = [0.1,0.2,0.5,0.9]
B = [1,2]

and the list of lists is:

params = [heights,alphas,C,B]

The original amount is bigger (~30x100) so it's not efficient to address each list directly.

Eventually each input case is a tuple/namedtuple/dictionary of one parameter from each category, for example:

instance = {'height':100, 'alpha':0.1,'C:0.1, 'B':1}

I would like to iterate the parameter space in order to create a list of instances - but here is the catch:

Instead of making a cartesian product of all of them, per each parameter I want to iterate all the options, while the rest of categories are set to a default value (the first). For example:

params = [[1,2,3],[4,5][7,8]]

the expected set of instances (with no repeat) is:

[(1,4,7),(2,4,7),(3,4,7),(1,5,7)(1,4,8)]

where 1 is the default of first index, 4 is the default of the second index and 7 is the default of the 3rd.

Making a cartesian product is quite easy with itertools:

from itertools import product
params = [[1,2,3],[4,5],[7,8]]
list(product(*params))

[(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

then I can filter out unnecessary instances, but it sounds ineficient to generate them at first place. Is there any elegant way to build this iteration?


问:
How to get the azure account tenant Id?
My question is: Is it possible to get the azure active directory tenant id without using powershell command?

I found this two blogs and with this help, I'm already able to get the tenant ID and subscriptions ID from powershell.  Is it the only way to retrieve the tenant?

Get Windows Azure Active Directory Tenant ID in Windows PowerShell

Windows Azure AD authentication support for PowerShell

Thanks

答:
According to Microsoft:

Find your tenantID: Your tenantId can be discovered by opening the following metadata.xml document: https://login.microsoft.com/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml - replace "graphDir1.onMicrosoft.com", with your tenant's domain value (any domain that is owned by the tenant will work). The tenantId is a guid, that is part of the sts URL, returned in the first xml node's sts url ("EntityDescriptor"): e.g. "https://sts.windows.net/".

Reference:

https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-graphapi-web/

ContentLicense: CC BY-SA 4.0

Title: How to get the azure account tenant Id?


问:
Tensorflow not running on GPU in jupyter notebook
Installed Cuda and cudnn sucessfully for the GTX 1080 ti on Ubuntu, running a simple TF program in the jupyter notebook the speed does not increase in a conda environment running tensorflow-gpu==1.0 vs tensorflow==1.0.

When I run nvidia-smi :

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.66 Driver Version: 375.66 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce GTX 108... Off | 0000:01:00.0 On | N/A |
| 24% 45C P0 62W / 250W | 537MiB / 11171MiB | 0% Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 1101 G /usr/lib/xorg/Xorg 310MiB |
| 0 1877 G compiz 219MiB |
| 0 3184 G /usr/lib/firefox/firefox 5MiB |
+-----------------------------------------------------------------------------+
</code>```

I have tried putting the "with tf.device("/gpu:0"):" in front of the matrix multiplications but it just gives me an error:

"InvalidArgumentError (see above for traceback): Cannot assign a device to node 'MatMul': Could not satisfy explicit device specification '/device:GPU:0' because no devices matching that specification are registered in this process; available devices: /job:localhost/replica:0/task:0/cpu:0
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/device:GPU:0"](Reshape, softmax/Variable/read)]]"

I know cudnn is installed correctly because I get this message when running it in the terminal.

```<code>import tensorflow as tf
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcublas.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcudnn.so.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcufft.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcurand.so.8.0 locally
</code>```

I think this has to be something with the Jupiter notebook, is there a compatibility issue? When I run the TF session I get this output:

```<code>W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
Device mapping: no known devices.
</code>```

"""

答: I solved the issue. Apparently I had jupyter and regular tensorflow installed outside of my environment. Yet I had tensorflow-gpu installed within my environment. So when I ran jupyter it was calling the tensorflow outside of the environment not the tensorflow-gpu installed within the environment.</p>

Body:
Installed Cuda and cudnn sucessfully for the GTX 1080 ti on Ubuntu, running a simple TF program in the jupyter notebook the speed does not increase in a conda environment running tensorflow-gpu==1.0 vs tensorflow==1.0.

When I run nvidia-smi :

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.66 Driver Version: 375.66 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce GTX 108... Off | 0000:01:00.0 On | N/A |
| 24% 45C P0 62W / 250W | 537MiB / 11171MiB | 0% Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 1101 G /usr/lib/xorg/Xorg 310MiB |
| 0 1877 G compiz 219MiB |
| 0 3184 G /usr/lib/firefox/firefox 5MiB |
+-----------------------------------------------------------------------------+

I have tried putting the "with tf.device("/gpu:0"):" in front of the matrix multiplications but it just gives me an error:

"InvalidArgumentError (see above for traceback): Cannot assign a device to node 'MatMul': Could not satisfy explicit device specification '/device:GPU:0' because no devices matching that specification are registered in this process; available devices: /job:localhost/replica:0/task:0/cpu:0
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/device:GPU:0"](Reshape, softmax/Variable/read)]]"

I know cudnn is installed correctly because I get this message when running it in the terminal.

import tensorflow as tf
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcublas.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcudnn.so.5 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcufft.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:135] successfully opened CUDA library libcurand.so.8.0 locally

I think this has to be something with the Jupiter notebook, is there a compatibility issue? When I run the TF session I get this output:

W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
Device mapping: no known devices.

"""


问:
Django class based generic view “CreateView” form errors handling
I am new to CBV and am trying to use the generic view CreateView and understand it.

In models.py I have this model:

```<code>class CartConfig(models.Model):

    cart_key = models.CharField(
       'Chave do Carrinho', max_length=40, db_index=True
    )
    PAYMENT_OPTION_CHOICES = (
        ('cash', 'Dinheiro'),
        ...
    )
    payment_option = models.CharField(
        'Opção de Pagamento', choices=PAYMENT_OPTION_CHOICES, max_length=20,
        default='cash'
    )
    address = models.ForeignKey(Address, verbose_name='Endereço de entrega',
        blank="false"
    )

    class Meta:
        verbose_name = 'Configuração do carrinho'
        verbose_name_plural = 'Configurações do carrinho'

    def __str__(self):
        return 'Cart configs for {}'.format(self.cart_key)
</code>```

That model uses a ForeignKey to Address, which is also a ManyToManyfield in the User model.
So, in my views.py I edited the queryset of ´adress´ field to handle only the address relationed to the current User:

```<code>class CartConfigView(CreateView):
    model = CartConfig
    template_name = 'checkout/cart_config.html'
    fields = ['address','payment_option']
    success_url = reverse_lazy('index')
    def get_context_data(self, **kwargs):
        context = super(CartConfigView, self).get_context_data(**kwargs)
        context['form'].fields['address'].queryset = get_object_or_404(User, pk=self.request.user.pk).address.all()
        context['form'].fields['address'].empty_label = None
        return context
</code>```

In my template it works fine, show the right address list and creat it as well through the post form. But if the user don't select an address, it triggers the expected error NOT NULL constraint failed: checkout_cartconfig.address_id. The question is, should not the CreateView handles this error? What am I doing wrong? How can I do to the page refresh with the field.errors to show to the user the "required field" message?

答:
Your model is not set up quite correctly with blank="false". It needs to be a boolean.

```<code>address = models.ForeignKey(
    Address,
    verbose_name='Endereço de entrega',
    blank=False
)
</code>```

Fun fact about Python: When resolving to a boolean, strings evaluate to true.

```<code>>>> bool("false")
True
</code>```

Body:
I am new to CBV and am trying to use the generic view CreateView and understand it.

In models.py I have this model:

class CartConfig(models.Model):

    cart_key = models.CharField(
       'Chave do Carrinho', max_length=40, db_index=True
    )
    PAYMENT_OPTION_CHOICES = (
        ('cash', 'Dinheiro'),
        ...
    )
    payment_option = models.CharField(
        'Opção de Pagamento', choices=PAYMENT_OPTION_CHOICES, max_length=20,
        default='cash'
    )
    address = models.ForeignKey(Address, verbose_name='Endereço de entrega',
        blank="false"
    )

    class Meta:
        verbose_name = 'Configuração do carrinho'
        verbose_name_plural = 'Configurações do carrinho'

    def __str__(self):
        return 'Cart configs for {}'.format(self.cart_key)

That model uses a ForeignKey to Address, which is also a ManyToManyfield in the User model.
So, in my views.py I edited the queryset of ´adress´ field to handle only the address relationed to the current User:

class CartConfigView(CreateView):
    model = CartConfig
    template_name = 'checkout/cart_config.html'
    fields = ['address','payment_option']
    success_url = reverse_lazy('index')
    def get_context_data(self, **kwargs):
        context = super(CartConfigView, self).get_context_data(**kwargs)
        context['form'].fields['address'].queryset = get_object_or_404(User, pk=self.request.user.pk).address.all()
        context['form'].fields['address'].empty_label = None
        return context

In my template it works fine, show the right address list and creat it as well through the post form. But if the user don't select an address, it triggers the expected error NOT NULL constraint failed: checkout_cartconfig.address_id. The question is, should not the CreateView handles this error? What am I doing wrong? How can I do to the page refresh with the field.errors to show to the user the "required field" message?

Body:
Your model is not set up quite correctly with blank="false". It needs to be a boolean.

address = models.ForeignKey(
    Address,
    verbose_name='Endereço de entrega',
    blank=False
)

Fun fact about Python: When resolving to a boolean, strings evaluate to true.

>>> bool("false")
True


问:
Android FusedLocationApi.getLastLocation Synchronously
I need to convert async FusedLocationApi.getLastLocation call to the sync one. I'm not a big expert in Java and I'm not sure I've did it right.

I want to connect to GoogleApiClient and then block calling thread until location information or error is received. Timeout more than 10 seconds should be treated as an error.

Will it work this way or onConnected will be called on main thread as well and it will be locked at that moment?

I also noticed that lock.wait(TimeUnit.SECONDS.toMillis(10)); continues instantly in regular runs, but in step-by-step debugging it does wait 10 seconds as intended.

```<code>public class SyncLocationService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public GoogleApiClient mGoogleApiClient;

    public SyncLocationService(Context context) {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    private final Object lock = new Object();
    public android.location.Location mLocation;

    @Override
    public android.location.Location lastLocation() {
        mGoogleApiClient.connect();
        synchronized (lock) {
            try {
                lock.wait(TimeUnit.SECONDS.toMillis(10));
            } catch (InterruptedException e) {
                Log.i("NativeLocationService", "InterruptedException");
            }
        }
        return mLocation;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        try {
            mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            mGoogleApiClient.disconnect();
        } catch (SecurityException e) {
            Log.i("NativeLocationService", "SecurityException");
        } finally {
            synchronized (lock) {
                lock.notify();
            }
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        synchronized (lock) {
            lock.notify();
        }
    }
}
</code>```

Basically I'm trying to rewrite similar iOS code which does it's job using semaphore.

```<code>var semaphore: DispatchSemaphore!
var location: CLLocation!

func lastLocation() -> location? {
    self.semaphore = DispatchSemaphore(value: 0)
    self.locationManager.startUpdatingLocation()
    _ = self.semaphore!.wait(timeout: .now() + 10)  // seconds
    self.semaphore = nil
    return self.location
}

// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let semaphore = self.semaphore else {
        return
    }
    guard let first = locations.first else {
        return
    }
    self.location = first
    self.locationManager.stopUpdatingLocation()
    semaphore.signal()
}
</code>```

答: You can use GoogleApiClient.blockingConnect() to wait until the connection is established, then call FusedLocationApi.getLastLocation().

Body:
I need to convert async FusedLocationApi.getLastLocation call to the sync one. I'm not a big expert in Java and I'm not sure I've did it right.

I want to connect to GoogleApiClient and then block calling thread until location information or error is received. Timeout more than 10 seconds should be treated as an error.

Will it work this way or onConnected will be called on main thread as well and it will be locked at that moment?

I also noticed that lock.wait(TimeUnit.SECONDS.toMillis(10)); continues instantly in regular runs, but in step-by-step debugging it does wait 10 seconds as intended.

public class SyncLocationService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public GoogleApiClient mGoogleApiClient;

    public SyncLocationService(Context context) {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    private final Object lock = new Object();
    public android.location.Location mLocation;

    @Override
    public android.location.Location lastLocation() {
        mGoogleApiClient.connect();
        synchronized (lock) {
            try {
                lock.wait(TimeUnit.SECONDS.toMillis(10));
            } catch (InterruptedException e) {
                Log.i("NativeLocationService", "InterruptedException");
            }
        }
        return mLocation;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        try {
            mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            mGoogleApiClient.disconnect();
        } catch (SecurityException e) {
            Log.i("NativeLocationService", "SecurityException");
        } finally {
            synchronized (lock) {
                lock.notify();
            }
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        synchronized (lock) {
            lock.notify();
        }
    }
}

Basically I'm trying to rewrite similar iOS code which does it's job using semaphore.

var semaphore: DispatchSemaphore!
var location: CLLocation!

func lastLocation() -> location? {
    self.semaphore = DispatchSemaphore(value: 0)
    self.locationManager.startUpdatingLocation()
    _ = self.semaphore!.wait(timeout: .now() + 10)  // seconds
    self.semaphore = nil
    return self.location
}

// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let semaphore = self.semaphore else {
        return
    }
    guard let first = locations.first else {
        return
    }
    self.location = first
    self.locationManager.stopUpdatingLocation()
    semaphore.signal()
}


问:
Auto-populate a sample article/post in user account on signup?
I'm building a Rails app where users can write a blog post. It can take a simple title and description.

But the feature I would like to have is that when a user signs up for the app their account will already have a sample post inside of their account so they can get an idea of how a blog post can look like and the features they have.

Any ideas or other stackoverflow questions answering how I can have a post already populated in users account on signup?

答:
I have a application doing something similar. I came from the school of fat model so my account model looks like this:

```<code>#app/models/account.rb
class Account < ApplicationRecord
  has_many :posts
  after_create :seed_account
  ...
  private
  def seed_account
     ...
     posts.create(...)
     ...
  end
end
</code>```

I hope that this helps.
This way when a new account is created no mater if from the console or api  or ui your account would always be seeded with its defaults

Body:
I have a application doing something similar. I came from the school of fat model so my account model looks like this:

#app/models/account.rb
class Account < ApplicationRecord
  has_many :posts
  after_create :seed_account
  ...
  private
  def seed_account
     ...
     posts.create(...)
     ...
  end
end

I hope that this helps.
This way when a new account is created no mater if from the console or api  or ui your account would always be seeded with its defaults


答:
There is a callback after_create, which fired after records has been created(only once). Here is some example:

```<code>class User < ActiveRecord::Base
  has_many :posts
  after_create do
    posts.create(title: 'Your new article')
  end
end
</code>```

Title: Auto-populate a sample article/post in user account on signup?

Body:
I'm building a Rails app where users can write a blog post. It can take a simple title and description.

But the feature I would like to have is that when a user signs up for the app their account will already have a sample post inside of their account so they can get an idea of how a blog post can look like and the features they have.

Any ideas or other stackoverflow questions answering how I can have a post already populated in users account on signup?

Body:
There is a callback after_create, which fired after records has been created(only once). Here is some example:

class User < ActiveRecord::Base
  has_many :posts
  after_create do
    posts.create(title: 'Your new article')
  end
end


问:
How do I change the mouse cursor in Atom?
I'm using Atom 1.15.0 on Mac Sierra.  I wanted to change the mouse cursor from a thin bar to something more visible, like a block.  I opened my styles.less file and added

```<code>atom-text-editor .cursor {
  transition:opacity 0.5s linear;
}
</code>```

and then restarted Atom, but my mouse cursor appears as before (a thin line).  How do I change it?

Edit: INcluding my styles.less file

```<code>/*
 * Your Stylesheet
 *
 * This stylesheet is loaded when Atom starts up and is reloaded automatically
 * when it is changed and saved.
 *
 * Add your own CSS or Less to fully customize Atom.
 * If you are unfamiliar with Less, you can read more about it here:
 * http://lesscss.org
 */

/*
 * Examples
 * (To see them, uncomment and save)
 */

// style the background color of the tree view
.tree-view {
  // background-color: whitesmoke;
}

// style the background and foreground colors on the atom-text-editor-element itself
atom-text-editor {
  // color: white;
  // background-color: hsl(180, 24%, 12%);
}

// style UI elements inside atom-text-editor
atom-text-editor .cursor {
  transition:opacity 0.5s linear;
}

.editor .cursor {
   position: absolute;
   border: 1px solid;
   background-color: rgba(244,100,122,0.6);
}

atom-text-editor .editor-contents--private { cursor: default; }
</code>```

答:
I would direct you to this package:

https://atom.io/packages/block-cursor

Also: Changing cursor style of atom editor

Update:

These properties should apply to the mouse cursor as they do with the text cursor. As long as they're directed properly.

Try Adding this to the StyleSheet:

atom-text-editor .editor-contents--private {
   cursor: default;
   position: absolute;
   border: 1px solid;
   background-color: rgba(244,100,122,0.6);
   }

Body:
I'm using Atom 1.15.0 on Mac Sierra.  I wanted to change the mouse cursor from a thin bar to something more visible, like a block.  I opened my styles.less file and added

atom-text-editor .cursor {
  transition:opacity 0.5s linear;
}

and then restarted Atom, but my mouse cursor appears as before (a thin line).  How do I change it?

Edit: INcluding my styles.less file

/*
 * Your Stylesheet
 *
 * This stylesheet is loaded when Atom starts up and is reloaded automatically
 * when it is changed and saved.
 *
 * Add your own CSS or Less to fully customize Atom.
 * If you are unfamiliar with Less, you can read more about it here:
 * http://lesscss.org
 */

/*
 * Examples
 * (To see them, uncomment and save)
 */

// style the background color of the tree view
.tree-view {
  // background-color: whitesmoke;
}

// style the background and foreground colors on the atom-text-editor-element itself
atom-text-editor {
  // color: white;
  // background-color: hsl(180, 24%, 12%);
}

// style UI elements inside atom-text-editor
atom-text-editor .cursor {
  transition:opacity 0.5s linear;
}

.editor .cursor {
   position: absolute;
   border: 1px solid;
   background-color: rgba(244,100,122,0.6);
}

atom-text-editor .editor-contents--private { cursor: default; }


问:
DNS name from IP address
I need to create a list of IP addresses and DNS names. I
   am trying to get DNS names from IP addresses. I have tried two ways:

try/catch but it ends afterwards.

Without and it just outputs DNS names that I can't relate to the IP addresses.

Here's what I have so far:

```<code>#try {
 Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object
{([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt}
# }
 # catch {
 if ($_.Exception.Message -like "*The requested name is valid*") {
            Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt }
# }
</code>```

答:
Try this solution:

```<code>$outFile = "C:\Users\user\Documents\hostname.txt"

Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object {
    $hash = @{ IPAddress = $_
        hostname = "n/a"
    }
    $hash.hostname = ([system.net.dns]::GetHostByAddress($_)).hostname
    $object = New-Object psobject -Property $hash
    Export-CSV -InputObject $object -Path $outFile -Append -NoTypeInformation
}
</code>```

We create a objects, that have the IPaddress in it and a hostname n/a if it cannot be resolved. Then, the object gets exported into the file. You'll get something like:

192.0.0.1; Server1

Title: DNS name from IP address

Body:
I need to create a list of IP addresses and DNS names. I
   am trying to get DNS names from IP addresses. I have tried two ways:

try/catch but it ends afterwards.

Without and it just outputs DNS names that I can't relate to the IP addresses.

Here's what I have so far:

#try {
 Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object
{([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt}
# }
 # catch {
 if ($_.Exception.Message -like "*The requested name is valid*") {
            Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt }
# }

Body:
Try this solution:

$outFile = "C:\Users\user\Documents\hostname.txt"

Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object {
    $hash = @{ IPAddress = $_
        hostname = "n/a"
    }
    $hash.hostname = ([system.net.dns]::GetHostByAddress($_)).hostname
    $object = New-Object psobject -Property $hash
    Export-CSV -InputObject $object -Path $outFile -Append -NoTypeInformation
}

We create a objects, that have the IPaddress in it and a hostname n/a if it cannot be resolved. Then, the object gets exported into the file. You'll get something like:

192.0.0.1; Server1


问:
Amazon S3: What are considered PUT/COPY/POST/LIST request?
Kindly confirm if this correct:

PUT is probably uploading files to S3?

COPY is probably copying files within S3?

How about POST and LIST?

Additional question, is get_bucket_filesize() and get_object_filesize() (from PHP SDK) considered a LIST request?

答:
There is not much of a difference between PUT and POST. The following was copied from AWS S3 documentation.

POST is an alternate form of PUT that enables browser-based uploads as a way of putting objects in buckets. Parameters that are passed to PUT via HTTP Headers are instead passed as form fields to POST in the multipart/form-data encoded message body.

http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html

As others has specified LIST is for listing objects. You can find all the operations in following link.

http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketOps.html


问:
Unwind to another brach of segues in swift or Objective-C
I have a scenario like this:

```<code>        /-> C -> D \
A -> B -            -> G (Contain values of D and F,
        \-> E -> F /
</code>```

Basically at G I have a list of value produce by D and F, let us call D1 and F1.

To create a new value from G, I have to just unwind to B and user can either choose branch C or E and continue to the end G with value of D2 or F2, or he can pop back to A. Let us say the new value is F2, though ABEFG

Now I'm facing a problem, that is I want to edit the values at G, let us say D1.

I want to be able to pop back to D but also allow users pop back to C etc, but D is not in the workflow ABEFG.

My guess is that I have to back up to B and somehow prepare multiple segues up to D but I have no idea if this kind of workflow exists.

答:
Apparently, there is no such way. The solution I found is

Find the instance of B in navigationController!.viewControllers

popToViewController B

Initiate C & D from Main storyboard with identifier (they are already deallocated anyway)

Setup some properties of C & D from D1

pushViewController C & D

Body:
I have a scenario like this:

        /-> C -> D \
A -> B -            -> G (Contain values of D and F,
        \-> E -> F /

Basically at G I have a list of value produce by D and F, let us call D1 and F1.

To create a new value from G, I have to just unwind to B and user can either choose branch C or E and continue to the end G with value of D2 or F2, or he can pop back to A. Let us say the new value is F2, though ABEFG

Now I'm facing a problem, that is I want to edit the values at G, let us say D1.

I want to be able to pop back to D but also allow users pop back to C etc, but D is not in the workflow ABEFG.

My guess is that I have to back up to B and somehow prepare multiple segues up to D but I have no idea if this kind of workflow exists.


问:
Disable FIRRTL pass that checks for combinational loops
Is there a way to disable the CheckCombLoops FIRRTL pass? (These loops are false.)
If possible, I want to do this in the tester driver. I saw the option for the FIRRTL intepreter, but I still get an exception during the FIRRTL run. I also want to be able to use VCS as a backend.

```<code>class LazyStackNWait2Test extends FlatSpec with Matchers {
  behavior of "LazyStackNWait2"
  it should "work" in {
    chisel3.iotesters.Driver.execute( Array( "--fr-allow-cycles", "--backend-name", "firrtl"), () => new LazyStackN(10, () => new LazyStackWait2)) { c =>
      new LazyStackNTester( c)
    } should be ( true)
  }
}
</code>```

Here is part of the log:

```<code>[info] [1.057] Done elaborating.
[info] - should work *** FAILED ***
[info]   firrtl.passes.PassExceptions:
firrtl.passes.CheckCombLoops$CombLoopException:  @[:@5437.2]: [module LazyStackN] Combinational loop detected:
</code>```

The build is from the latest github HEAD.

答:
EDIT: This is now supported via the --no-check-comb-loops. Relevant PR

There currently is not a way but I've created an issue to add this feature and it shouldn't be that difficult to do. https://github.com/ucb-bar/firrtl/issues/600

Just out of curiosity, what kind of false combinational loops are you seeing? We find that they are pretty rare* and usually easy to work around, so if you have any examples you can share I would greatly appreciate it.

* For example, they usually happen with aggregate types that have a dependence between subelements if the aggregate gets cast to bits and back (through a chisel3.util.Mux1H for example). Just trying to see what other common use patterns can cause false loops.

Body:
Is there a way to disable the CheckCombLoops FIRRTL pass? (These loops are false.)
If possible, I want to do this in the tester driver. I saw the option for the FIRRTL intepreter, but I still get an exception during the FIRRTL run. I also want to be able to use VCS as a backend.

class LazyStackNWait2Test extends FlatSpec with Matchers {
  behavior of "LazyStackNWait2"
  it should "work" in {
    chisel3.iotesters.Driver.execute( Array( "--fr-allow-cycles", "--backend-name", "firrtl"), () => new LazyStackN(10, () => new LazyStackWait2)) { c =>
      new LazyStackNTester( c)
    } should be ( true)
  }
}

Here is part of the log:

[info] [1.057] Done elaborating.
[info] - should work *** FAILED ***
[info]   firrtl.passes.PassExceptions:
firrtl.passes.CheckCombLoops$CombLoopException:  @[:@5437.2]: [module LazyStackN] Combinational loop detected:

The build is from the latest github HEAD.


问:
Starting different activities from MainActivity
I'm new here and I think I have made a mistake in Java but I have no idea how to correct it. Most of the people with similar issue had much more complicated projects and I couldn't resolve my issue by looking at their code.

I want to use different buttons (9 of them) to start different activities, but when I started with adding the second, only the activity 1 (LeftArmActivity) popped up. Whatever I changed in the XML to call the proper method for HeadActivity to launch, only the LeftActivity launches. I've got a hint from other topics that it may be caused by overwriting of the intent, but I have no idea how to fix this. I tried to use getActivity() but it just crashed. Could you please help me with this?

@UPDATE

Okay, I used the switch recommended below, but now the app won't start at all :/

```<code> public class MainActivity extends AppCompatActivity {

Context context = this;
Button LeftArmOpener = (Button) findViewById(R.id.LeftArmOpener);
Button HeadOpener = (Button) findViewById(R.id.HeadOpener);
Button RightArmOpener = (Button) findViewById(R.id.RightArmOpener);
Button CreditsOpener = (Button) findViewById(R.id.CreditsOpener);
Button TrunkOpener = (Button) findViewById(R.id.TrunkOpener);
Button NextOpener = (Button) findViewById(R.id.NextOpener);
Button RightLegOpener = (Button) findViewById(R.id.RightLegOpener);
Button ExitOpener = (Button) findViewById(R.id.ExitOpener);
Button LeftLegOpener = (Button) findViewById(R.id.LeftLegOpener);

protected View.OnClickListener mClick;

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

    mClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.RightArmOpener: {
                    Intent i1 = new Intent(context, LeftArmActivity.class);
                    startActivity(i1);
                    break;
                }
                case R.id.HeadOpener: {
                    Intent i2 = new Intent(context, HeadActivity.class);
                    startActivity(i2);
                    break;
                }
                case R.id.LeftArmOpener: {
                    Intent i3 = new Intent(context, LeftArmActivity.class);
                    startActivity(i3);
                    break;
                }
                case R.id.CreditsOpener: {
                    Intent i4 = new Intent(context, CreditsActivity.class);
                    startActivity(i4);
                    break;
                }
                case R.id.TrunkOpener: {
                    Intent i5 = new Intent(context, TrunkActivity.class);
                    startActivity(i5);
                    break;
                }
                case R.id.NextOpener: {
                    Intent i6 = new Intent(context, NextActivity.class);
                    startActivity(i6);
                    break;
                }
                case R.id.RightLegOpener: {
                    Intent i7 = new Intent(context, RightLegActivity.class);
                    startActivity(i7);
                    break;
                }
                case R.id.ExitOpener: {
                    Intent i8 = new Intent(context, ExitActivity.class);
                    startActivity(i8);
                    break;
                }
                case R.id.LeftLegOpener: {
                    Intent i9 = new Intent(context, LeftLegActivity.class);
                    startActivity(i9);
                    break;
                }
                //create this for all 9 buttons
            }

        }

    };

    LeftArmOpener.setOnClickListener(mClick);
    HeadOpener.setOnClickListener(mClick);
    RightArmOpener.setOnClickListener(mClick);
    CreditsOpener.setOnClickListener(mClick);
    TrunkOpener.setOnClickListener(mClick);
    NextOpener.setOnClickListener(mClick);
    RightLegOpener.setOnClickListener(mClick);
    ExitOpener.setOnClickListener(mClick);
    LeftLegOpener.setOnClickListener(mClick);

}
</code>```

}

答:
Update your Code with this

```<code>public class MainActivity extends AppCompatActivity {

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

}

public void openHead(View view){
    startActivity(new Intent(MainActivity.this, LessonOne.class));
    //startActivity(t);
}

public void openLeftArm(View view){
    Intent i = new Intent(MainActivity.this, LeftArmActivity.class);
    startActivity(i);
}
}
</code>```

//the problem is you are calling startActivity() two time and Passing getActivity() from Actvity.

Body:
I'm new here and I think I have made a mistake in Java but I have no idea how to correct it. Most of the people with similar issue had much more complicated projects and I couldn't resolve my issue by looking at their code.

I want to use different buttons (9 of them) to start different activities, but when I started with adding the second, only the activity 1 (LeftArmActivity) popped up. Whatever I changed in the XML to call the proper method for HeadActivity to launch, only the LeftActivity launches. I've got a hint from other topics that it may be caused by overwriting of the intent, but I have no idea how to fix this. I tried to use getActivity() but it just crashed. Could you please help me with this?

@UPDATE

Okay, I used the switch recommended below, but now the app won't start at all :/

 public class MainActivity extends AppCompatActivity {

Context context = this;
Button LeftArmOpener = (Button) findViewById(R.id.LeftArmOpener);
Button HeadOpener = (Button) findViewById(R.id.HeadOpener);
Button RightArmOpener = (Button) findViewById(R.id.RightArmOpener);
Button CreditsOpener = (Button) findViewById(R.id.CreditsOpener);
Button TrunkOpener = (Button) findViewById(R.id.TrunkOpener);
Button NextOpener = (Button) findViewById(R.id.NextOpener);
Button RightLegOpener = (Button) findViewById(R.id.RightLegOpener);
Button ExitOpener = (Button) findViewById(R.id.ExitOpener);
Button LeftLegOpener = (Button) findViewById(R.id.LeftLegOpener);

protected View.OnClickListener mClick;

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

    mClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.RightArmOpener: {
                    Intent i1 = new Intent(context, LeftArmActivity.class);
                    startActivity(i1);
                    break;
                }
                case R.id.HeadOpener: {
                    Intent i2 = new Intent(context, HeadActivity.class);
                    startActivity(i2);
                    break;
                }
                case R.id.LeftArmOpener: {
                    Intent i3 = new Intent(context, LeftArmActivity.class);
                    startActivity(i3);
                    break;
                }
                case R.id.CreditsOpener: {
                    Intent i4 = new Intent(context, CreditsActivity.class);
                    startActivity(i4);
                    break;
                }
                case R.id.TrunkOpener: {
                    Intent i5 = new Intent(context, TrunkActivity.class);
                    startActivity(i5);
                    break;
                }
                case R.id.NextOpener: {
                    Intent i6 = new Intent(context, NextActivity.class);
                    startActivity(i6);
                    break;
                }
                case R.id.RightLegOpener: {
                    Intent i7 = new Intent(context, RightLegActivity.class);
                    startActivity(i7);
                    break;
                }
                case R.id.ExitOpener: {
                    Intent i8 = new Intent(context, ExitActivity.class);
                    startActivity(i8);
                    break;
                }
                case R.id.LeftLegOpener: {
                    Intent i9 = new Intent(context, LeftLegActivity.class);
                    startActivity(i9);
                    break;
                }
                //create this for all 9 buttons
            }

        }

    };

    LeftArmOpener.setOnClickListener(mClick);
    HeadOpener.setOnClickListener(mClick);
    RightArmOpener.setOnClickListener(mClick);
    CreditsOpener.setOnClickListener(mClick);
    TrunkOpener.setOnClickListener(mClick);
    NextOpener.setOnClickListener(mClick);
    RightLegOpener.setOnClickListener(mClick);
    ExitOpener.setOnClickListener(mClick);
    LeftLegOpener.setOnClickListener(mClick);

}

}

Body:
Update your Code with this

public class MainActivity extends AppCompatActivity {

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

}

public void openHead(View view){
    startActivity(new Intent(MainActivity.this, LessonOne.class));
    //startActivity(t);
}

public void openLeftArm(View view){
    Intent i = new Intent(MainActivity.this, LeftArmActivity.class);
    startActivity(i);
}
}

//the problem is you are calling startActivity() two time and Passing getActivity() from Actvity.


问:
MYSQL query to get average rating value for review site?
This is regarding a review website.

I'm trying to sort a list of items based on their overall average rating value. I do understand there is an AVG function but not sure how to incorporate it. Also, the review_category_list is in my query to deal with displaying other data and isn't specifically relevant to the rating question.

Here is the query I have so far but need to somehow work in averaging the rating for each item:

```<code>SELECT DISTINCT (
item_id
), item_name, des_location, address, city, state, zip, country, dedicated, item_desc, abv, item_type
FROM review_category_list, review_items
LEFT JOIN review ON review.review_item_id = review_items.item_id
WHERE category_id =14
AND category_id != -1
AND cat_id_cloud =14
ORDER BY review.rating DESC
LIMIT 0 , 10
</code>```

Here is my table structure:

```<code>CREATE TABLE `review_category_list` (
  `cat_id_cloud` int(11) NOT NULL AUTO_INCREMENT,
  `category` varchar(255) NOT NULL DEFAULT '',
  `catorder` tinyint(4) NOT NULL DEFAULT '0',
  `parent` varchar(255) NOT NULL DEFAULT '',
  `parent_id` int(11) NOT NULL DEFAULT '-1',
  `abv` char(2) NOT NULL,
  `olditemid` int(11) NOT NULL COMMENT 'item_id from the review_items_orig table',
  PRIMARY KEY (`cat_id_cloud`),
  UNIQUE KEY `category` (`category`,`parent_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

CREATE TABLE `review_items` (
  `item_id` int(11) NOT NULL AUTO_INCREMENT,
  `item_name` varchar(250) NOT NULL DEFAULT '',
  `item_desc` longtext NOT NULL,
  `item_type` varchar(250) NOT NULL DEFAULT '',
  `category` varchar(250) NOT NULL DEFAULT '',
  `category_id` int(11) DEFAULT '-1',
  `sortorder` tinyint(4) NOT NULL DEFAULT '0',
  `item_image` varchar(12) NOT NULL DEFAULT '',
  `item_aff_url` varchar(250) NOT NULL DEFAULT '',
  `item_aff_txt` varchar(250) NOT NULL DEFAULT '',
  `item_aff_code` varchar(250) NOT NULL DEFAULT '',
  `des_location` varchar(250) NOT NULL,
  `address` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `state` varchar(50) NOT NULL,
  `zip` varchar(20) NOT NULL,
  `country` varchar(255) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `lat` float(10,6) NOT NULL DEFAULT '0.000000',
  `lon` float(10,6) NOT NULL DEFAULT '0.000000',
  `dedicated` enum('yes','no','dontknow') NOT NULL DEFAULT 'no',
  `des_contact` varchar(64) NOT NULL,
  `chapterid` int(5) NOT NULL DEFAULT '0',
  `oldcat` int(11) NOT NULL,
  PRIMARY KEY (`item_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `review` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rating` varchar(4) NOT NULL DEFAULT '',
  `summary` varchar(250) NOT NULL DEFAULT '',
  `review` longtext NOT NULL,
  `source` varchar(250) NOT NULL DEFAULT '',
  `location` varchar(250) NOT NULL DEFAULT '',
  `review_item_id` int(11) NOT NULL DEFAULT '0',
  `visitorIP` varchar(15) NOT NULL DEFAULT '0',
  `date_added` date NOT NULL DEFAULT '0000-00-00',
  `useful` int(11) NOT NULL DEFAULT '0',
  `notuseful` int(11) NOT NULL DEFAULT '0',
  `approve` enum('y','n') NOT NULL DEFAULT 'n',
  `username` varchar(50) NOT NULL DEFAULT '',
  `sig_show` enum('y','n') NOT NULL DEFAULT 'n',
  `rating2` char(3) NOT NULL DEFAULT '',
  `user_image` varchar(75) NOT NULL DEFAULT '',
  `oldid` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`),
  KEY `id_2` (`id`),
  FULLTEXT KEY `summary` (`summary`,`review`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6443 ;
</code>```

Any help on this would be much appreciated!

Tim

答:
I understand that you need a MySQL query, but I suppose computing average rating each time you show the list is not the best way to achieve what you want: showing items based on their average rating.

Instead, what I would do is actually add the 'average_rating' and 'number_of_reviews' fields to the 'item' table.

Then, upon a new review insertion for an item, you can just update the item table the following way:

Update the 'average_rating' field using the formula: (item.average_rating*item.number_of_reviews + review.rating)/(item.number_of_reviews+1) (Of course you need to take care of corner cases when there is no reviews so item.number_of_reviews is 0 etc.)

Increment the 'item.number_of_reviews' field

Next time you need to get a list of items ordered by average rating, you just do very simple SELECT query with ORDER BY clause, something like that:

```<code>SELECT * FROM item ORDER BY average_rating DESC;
</code>```

I think this whole approach would work much faster, be more reliable and supportable.

Body:
This is regarding a review website.

I'm trying to sort a list of items based on their overall average rating value. I do understand there is an AVG function but not sure how to incorporate it. Also, the review_category_list is in my query to deal with displaying other data and isn't specifically relevant to the rating question.

Here is the query I have so far but need to somehow work in averaging the rating for each item:

SELECT DISTINCT (
item_id
), item_name, des_location, address, city, state, zip, country, dedicated, item_desc, abv, item_type
FROM review_category_list, review_items
LEFT JOIN review ON review.review_item_id = review_items.item_id
WHERE category_id =14
AND category_id != -1
AND cat_id_cloud =14
ORDER BY review.rating DESC
LIMIT 0 , 10

Here is my table structure:

CREATE TABLE `review_category_list` (
  `cat_id_cloud` int(11) NOT NULL AUTO_INCREMENT,
  `category` varchar(255) NOT NULL DEFAULT '',
  `catorder` tinyint(4) NOT NULL DEFAULT '0',
  `parent` varchar(255) NOT NULL DEFAULT '',
  `parent_id` int(11) NOT NULL DEFAULT '-1',
  `abv` char(2) NOT NULL,
  `olditemid` int(11) NOT NULL COMMENT 'item_id from the review_items_orig table',
  PRIMARY KEY (`cat_id_cloud`),
  UNIQUE KEY `category` (`category`,`parent_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

CREATE TABLE `review_items` (
  `item_id` int(11) NOT NULL AUTO_INCREMENT,
  `item_name` varchar(250) NOT NULL DEFAULT '',
  `item_desc` longtext NOT NULL,
  `item_type` varchar(250) NOT NULL DEFAULT '',
  `category` varchar(250) NOT NULL DEFAULT '',
  `category_id` int(11) DEFAULT '-1',
  `sortorder` tinyint(4) NOT NULL DEFAULT '0',
  `item_image` varchar(12) NOT NULL DEFAULT '',
  `item_aff_url` varchar(250) NOT NULL DEFAULT '',
  `item_aff_txt` varchar(250) NOT NULL DEFAULT '',
  `item_aff_code` varchar(250) NOT NULL DEFAULT '',
  `des_location` varchar(250) NOT NULL,
  `address` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `state` varchar(50) NOT NULL,
  `zip` varchar(20) NOT NULL,
  `country` varchar(255) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `lat` float(10,6) NOT NULL DEFAULT '0.000000',
  `lon` float(10,6) NOT NULL DEFAULT '0.000000',
  `dedicated` enum('yes','no','dontknow') NOT NULL DEFAULT 'no',
  `des_contact` varchar(64) NOT NULL,
  `chapterid` int(5) NOT NULL DEFAULT '0',
  `oldcat` int(11) NOT NULL,
  PRIMARY KEY (`item_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `review` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rating` varchar(4) NOT NULL DEFAULT '',
  `summary` varchar(250) NOT NULL DEFAULT '',
  `review` longtext NOT NULL,
  `source` varchar(250) NOT NULL DEFAULT '',
  `location` varchar(250) NOT NULL DEFAULT '',
  `review_item_id` int(11) NOT NULL DEFAULT '0',
  `visitorIP` varchar(15) NOT NULL DEFAULT '0',
  `date_added` date NOT NULL DEFAULT '0000-00-00',
  `useful` int(11) NOT NULL DEFAULT '0',
  `notuseful` int(11) NOT NULL DEFAULT '0',
  `approve` enum('y','n') NOT NULL DEFAULT 'n',
  `username` varchar(50) NOT NULL DEFAULT '',
  `sig_show` enum('y','n') NOT NULL DEFAULT 'n',
  `rating2` char(3) NOT NULL DEFAULT '',
  `user_image` varchar(75) NOT NULL DEFAULT '',
  `oldid` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`),
  KEY `id_2` (`id`),
  FULLTEXT KEY `summary` (`summary`,`review`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6443 ;

Any help on this would be much appreciated!

Tim

Body:
I understand that you need a MySQL query, but I suppose computing average rating each time you show the list is not the best way to achieve what you want: showing items based on their average rating.

Instead, what I would do is actually add the 'average_rating' and 'number_of_reviews' fields to the 'item' table.

Then, upon a new review insertion for an item, you can just update the item table the following way:

Update the 'average_rating' field using the formula: (item.average_rating*item.number_of_reviews + review.rating)/(item.number_of_reviews+1) (Of course you need to take care of corner cases when there is no reviews so item.number_of_reviews is 0 etc.)

Increment the 'item.number_of_reviews' field

Next time you need to get a list of items ordered by average rating, you just do very simple SELECT query with ORDER BY clause, something like that:

SELECT * FROM item ORDER BY average_rating DESC;

I think this whole approach would work much faster, be more reliable and supportable.


问:
Mocked CloseableHttpClient still passes connection to real server while testing
i try to test a method which uses a CloseableHttpClient Connection. I decided to go for Mockito and mocked all relevant classes and methods. But still, as soon as I start the test it goes straight to the real server instead of being intercepted by the mocked CloseableHttpClient.

The test

```<code>  @Test
    public void testBid() throws IOException {
        //given:
        HttpGet httpGet = mock(HttpGet.class);
        HttpResponse httpResponse = mock(HttpResponse.class);

        StatusLine statusLine = mock(StatusLine.class);

        ObserverImp observer = mock(ObserverImp.class);

        CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);

        //and:
        when(statusLine.getStatusCode()).thenReturn(200);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);
        when(closeableHttpClient.execute(httpGet)).thenReturn(closeableHttpResponse);
        when(observer.getKey()).thenReturn("##213");

        Buy buy = new Buy(observer);
        buy.bid(14455);
    }
</code>```

And the related Implementation

```<code>public void buy(double price) {
        String queryArgs = "command=order&amount=1" + "&price=" + String.valueOf(price); // generates query

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("wwww.hm.edu/projectGroup1");
        post.addHeader("Key", observer.getKey());
        try {
            post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            System.out.println("Exception in run");
        }
        List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("command", "order"));
        params.add(new BasicNameValuePair("amount", "1"));
        params.add(new BasicNameValuePair("price", String.valueOf(price)));
        try {
            post.setEntity(new UrlEncodedFormEntity(params));
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            Scanner in = new Scanner(entity.getContent());
            String orderNumber = "";
            while (in.hasNext()) {
                orderNumber = in.nextLine();
            }
            String[] findOrderNumber = orderNumber.split(".");
            long lastOrderNumber = -1;
            try {
                lastOrderNumber = Long.valueOf(findOrderNumber[3]);
            } catch (NumberFormatException exception) {
                System.out.println("NumberFormatException");
            } finally {
                if (lastOrderNumber != -1) {
                    observer.setOrderNumber(lastOrderNumber);
                }
            }
            in.close();
            EntityUtils.consume(entity);
            httpClient.close();
        } catch (IOException e) {
            System.out.println("Exception occured during process");
        }
    }
</code>```

I tried several code snippets of tests I found in tutorials or similar questions here but with no success. Can you please tell me what I do wrong here?

Thank you :)

答:
You can inject CloseableHttpClient httpClient via constructor:

```<code>public class Buy {
    private ObserverImp observer;
    private CloseableHttpClient httpClient;

    public Buy (ObserverImp observer, CloseableHttpClient httpClient) {
       this.observer = observer;
       this.httpClient = httpClient;
    }

    public void buy(double price) {
       ...

       // Comment or remove the line below and use the injected instead...
       // CloseableHttpClient httpClient = HttpClients.createDefault();

       ...
    }
}
</code>```

And to test it, follows:

```<code>@Test
public void testBid() throws IOException {
    //given:
    HttpGet httpGet = mock(HttpGet.class);
    HttpResponse httpResponse = mock(HttpResponse.class);

    StatusLine statusLine = mock(StatusLine.class);

    ObserverImp observer = mock(ObserverImp.class);

    CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
    CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);

    //and:
    when(statusLine.getStatusCode()).thenReturn(200);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(closeableHttpClient.execute(httpGet)).thenReturn(closeableHttpResponse);
    when(observer.getKey()).thenReturn("##213");

    Buy buy = new Buy(observer, closeableHttpClient);
    buy.bid(14455);
}
</code>```

Body:
i try to test a method which uses a CloseableHttpClient Connection. I decided to go for Mockito and mocked all relevant classes and methods. But still, as soon as I start the test it goes straight to the real server instead of being intercepted by the mocked CloseableHttpClient.

The test

  @Test
    public void testBid() throws IOException {
        //given:
        HttpGet httpGet = mock(HttpGet.class);
        HttpResponse httpResponse = mock(HttpResponse.class);

        StatusLine statusLine = mock(StatusLine.class);

        ObserverImp observer = mock(ObserverImp.class);

        CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);

        //and:
        when(statusLine.getStatusCode()).thenReturn(200);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);
        when(closeableHttpClient.execute(httpGet)).thenReturn(closeableHttpResponse);
        when(observer.getKey()).thenReturn("##213");

        Buy buy = new Buy(observer);
        buy.bid(14455);
    }

And the related Implementation

public void buy(double price) {
        String queryArgs = "command=order&amount=1" + "&price=" + String.valueOf(price); // generates query

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("wwww.hm.edu/projectGroup1");
        post.addHeader("Key", observer.getKey());
        try {
            post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            System.out.println("Exception in run");
        }
        List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("command", "order"));
        params.add(new BasicNameValuePair("amount", "1"));
        params.add(new BasicNameValuePair("price", String.valueOf(price)));
        try {
            post.setEntity(new UrlEncodedFormEntity(params));
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            Scanner in = new Scanner(entity.getContent());
            String orderNumber = "";
            while (in.hasNext()) {
                orderNumber = in.nextLine();
            }
            String[] findOrderNumber = orderNumber.split(".");
            long lastOrderNumber = -1;
            try {
                lastOrderNumber = Long.valueOf(findOrderNumber[3]);
            } catch (NumberFormatException exception) {
                System.out.println("NumberFormatException");
            } finally {
                if (lastOrderNumber != -1) {
                    observer.setOrderNumber(lastOrderNumber);
                }
            }
            in.close();
            EntityUtils.consume(entity);
            httpClient.close();
        } catch (IOException e) {
            System.out.println("Exception occured during process");
        }
    }

I tried several code snippets of tests I found in tutorials or similar questions here but with no success. Can you please tell me what I do wrong here?

Thank you :)

Body:
You can inject CloseableHttpClient httpClient via constructor:

public class Buy {
    private ObserverImp observer;
    private CloseableHttpClient httpClient;

    public Buy (ObserverImp observer, CloseableHttpClient httpClient) {
       this.observer = observer;
       this.httpClient = httpClient;
    }

    public void buy(double price) {
       ...

       // Comment or remove the line below and use the injected instead...
       // CloseableHttpClient httpClient = HttpClients.createDefault();

       ...
    }
}

And to test it, follows:

@Test
public void testBid() throws IOException {
    //given:
    HttpGet httpGet = mock(HttpGet.class);
    HttpResponse httpResponse = mock(HttpResponse.class);

    StatusLine statusLine = mock(StatusLine.class);

    ObserverImp observer = mock(ObserverImp.class);

    CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
    CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);

    //and:
    when(statusLine.getStatusCode()).thenReturn(200);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(closeableHttpClient.execute(httpGet)).thenReturn(closeableHttpResponse);
    when(observer.getKey()).thenReturn("##213");

    Buy buy = new Buy(observer, closeableHttpClient);
    buy.bid(14455);
}


问:
mysql remove duplicate month
I want to remove duplicate month

this is my data

i want remove duplicate and show like this

this is my code

```<code><?php
    include "connect.php";
    $query = "select * from mydata";
    $result = mysqli_query($con,$query);
    while($data  = mysqli_fetch_array($result)){
        $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
    }
    $s1 = array();
    $s2 = array();
    $a  = array();
    $b  = array();

    echo "<table border='1'>

            <tr>
                <th>Month</th>
                <th>Week</th>
                <th>Total</th>
                <th>s1</th>
                <th>s2</th>
                <th>a</th>
                <th>b</th>
            </tr>
            ";
        foreach ($dbasearray as $index => $datah){

            $data = explode(",", $datah);

            echo "<tr>";
            echo "<td align='center'>".$data[0]."</td>";
            echo "<td align='center'>".$data[1]."</td>";
            echo "<td align='center'>".$data[2]."</td>";
                if($index==0){
                    echo "<td>".$s1[$index] = $data[2]."</td>";
                    echo "<td>".$s2[$index] = $data[2]."</td>";
                }
                else {
                    echo "<td>".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."</td>";
                    echo "<td>".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."</td>";
                }
                echo "<td>".$a[$index] = 2*$s1[$index]-$s2[$index]."</td>";
                echo "<td>".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."</td>";
            echo "</tr>";
        }
    echo "</table>";
    ?>
</code>```

i don't know to remove/hidden my code, i'm cannot using group by
help me. Thank's

答:
It should be abundantly clear from what follows that I'm no PHP coder, but it should give the idea...

Sample data set:

```<code>DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,month INT NOT NULL, user VARCHAR(12) NOT NULL
);

INSERT INTO my_table (month,user) VALUES
(1,'Ben'),
(2,'Ben'),
(3,'Tom'),
(1,'Gary'),
(2,'Jessica'),
(3,'Dean'),
(1,'Elizabeth');
</code>```

Sample query and result:

```<code>SELECT * FROM my_table ORDER BY month,id;
+----+-------+-----------+
| id | month | user      |
+----+-------+-----------+
|  1 |     1 | Ben       |
|  4 |     1 | Gary      |
|  7 |     1 | Elizabeth |
|  2 |     2 | Ben       |
|  5 |     2 | Jessica   |
|  3 |     3 | Tom       |
|  6 |     3 | Dean      |
+----+-------+-----------+
</code>```

Sample PHP code...

```<code><?php

require('path./to/connection/stateme.nts');

$query = "SELECT month, user FROM my_table ORDER BY month , id;";

$result = mysqli_query($conn,$query);

$x = null;

echo "<table>";
while($row = mysqli_fetch_assoc($result)){
if($row['month']==$x)
  { $month = ''; }
  else
  { $month = $row['month'];}

echo "<tr><td>$month</td><td>".$row['user']."</td></tr>";

$x = $row['month'];
}
echo "</table>";
?>
</code>```

Outputs:

```<code>1   Ben
    Gary
    Elizabeth
2   Ben
    Jessica
3   Tom
    Dean
</code>```

Title: mysql remove duplicate month

Body:
I want to remove duplicate month

this is my data

i want remove duplicate and show like this

this is my code

<?php
    include "connect.php";
    $query = "select * from mydata";
    $result = mysqli_query($con,$query);
    while($data  = mysqli_fetch_array($result)){
        $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
    }
    $s1 = array();
    $s2 = array();
    $a  = array();
    $b  = array();

    echo "

                Month
                Week
                Total
                s1
                s2
                a
                b

            ";
        foreach ($dbasearray as $index => $datah){

            $data = explode(",", $datah);

            echo "
";
            echo "".$data[0]."	";
            echo "".$data[1]."	";
            echo "".$data[2]."	";
                if($index==0){
                    echo "".$s1[$index] = $data[2]."	";
                    echo "".$s2[$index] = $data[2]."	";
                }
                else {
                    echo "".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."	";
                    echo "".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."	";
                }
                echo "".$a[$index] = 2*$s1[$index]-$s2[$index]."	";
                echo "".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."	";
            echo "
";
        }
    echo "
";
    ?>

i don't know to remove/hidden my code, i'm cannot using group by
help me. Thank's

Body:
It should be abundantly clear from what follows that I'm no PHP coder, but it should give the idea...

Sample data set:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,month INT NOT NULL, user VARCHAR(12) NOT NULL
);

INSERT INTO my_table (month,user) VALUES
(1,'Ben'),
(2,'Ben'),
(3,'Tom'),
(1,'Gary'),
(2,'Jessica'),
(3,'Dean'),
(1,'Elizabeth');

Sample query and result:

SELECT * FROM my_table ORDER BY month,id;
+----+-------+-----------+
| id | month | user      |
+----+-------+-----------+
|  1 |     1 | Ben       |
|  4 |     1 | Gary      |
|  7 |     1 | Elizabeth |
|  2 |     2 | Ben       |
|  5 |     2 | Jessica   |
|  3 |     3 | Tom       |
|  6 |     3 | Dean      |
+----+-------+-----------+

Sample PHP code...

<?php

require('path./to/connection/stateme.nts');

$query = "SELECT month, user FROM my_table ORDER BY month , id;";

$result = mysqli_query($conn,$query);

$x = null;

echo "<table>";
while($row = mysqli_fetch_assoc($result)){
if($row['month']==$x)
  { $month = ''; }
  else
  { $month = $row['month'];}

echo "<tr><td>$month</td><td>".$row['user']."</td></tr>";

$x = $row['month'];
}
echo "</table>";
?>

Outputs:

1   Ben
    Gary
    Elizabeth
2   Ben
    Jessica
3   Tom
    Dean


问:
React + Redux : reducer won't reload component
I wrote a generic Table component, instancied twice with two differents datasets. I use a Redux store to hydrate props and I try to delete a row when I click on it.

Components are well displayed and onClick function is fired and reducer is called. The new returned state returns the previous state without the element clicked.

My problem is that the components are not re-rendered.
According to the troubleshouting page (http://redux.js.org/docs/Troubleshooting.html), it seems that I don't mutate the previous state (maybe I just don't understand how to do), I'm calling the dispatch() function and my mapStateToProps seems to be right as datas are well displayed on the page load.

I tried to define initial state in reducer.js > table function instead of doing it with createStore function, I tried to split 'tables' reducer into 'domains' and 'hosts' reducers (duplicate code), I tried to not use combineReducers() as I have only one (but I will have more in the future), and I tried so many things so I can't remember.

I bet it's not a big deal but I just not able to figure out what's going on. Can you help me please ? Thank you very much.

reducer.js

```<code>import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = Object.assign({}, state)

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    switch (action.type) {
        case DELETE_HOST:
            return Object.assign({}, state, {
                hosts: deleteItem(state.hosts, action.host)
            })

        case DELETE_DOMAIN:
            return Object.assign({}, state, {
                domains: deleteItem(state.domains, action.domain)
            })

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers
</code>```

actions.js

```<code>export const DELETE_DOMAIN = 'DELETE_DOMAIN'
export const DELETE_HOST = 'DELETE_HOST'

export function deleteDomain(domain) {
    return { type: DELETE_DOMAIN, domain }
}

export function deleteHost(host) {
    return { type: DELETE_HOST, host }
}
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './reducers'

const initialState = {
    tables: {
        domains: {
            headers: {
                id: 'Id',
                domain: 'Domain',
                host: 'Hoster',
            },
            items: [
                {
                    id: 1,
                    domain: 'dev.example.com',
                    host: 'dev',
                },
                {
                    id: 2,
                    domain: 'prod.example.com',
                    host: 'prod',
                }
            ]
        },
        hosts: {
            headers: {
                id: 'Id',
                label: 'Label',
                type: 'Type',
                hoster: 'Corporation',
            },
            items: [
                {
                    id: 1,
                    label: 'Server 1',
                    type: 'Server type',
                    hoster: 'Gandi',
                },
                {
                    id: 2,
                    label: 'Server 2',
                    type: 'Server type',
                    hoster: 'OVH',
                }
            ]
        }
    }
}

let store = createStore(reducers, initialState)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);
</code>```

app.js

```<code>import React from 'react';
import Domains from './modules/domains.js';
import Hosts from './modules/hosts.js';
import Nav from './modules/nav.js';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom'

export default class App extends React.Component {
    render() {
        return (
            <Router>
                <div className="container-fluid col-md-6">
                    <Nav />
                    <Route path="/domains" component={Domains}/>
                    <Route path="/hosts" component={Hosts}/>
                </div>
            </Router>
        );
    }
}
</code>```

domain.js

```<code>import React from 'react';
import Table from './../components/table.js';
import { connect } from 'react-redux'
import { deleteDomain } from './../actions'

const mapStateToProps = (state) => {
    return state.tables.domains
}

const mapDispatchToProps = (dispatch) => {
    return {
            onRowClick: (id) => {
                dispatch(deleteDomain(id))
            }
        }
}

class DomainsView extends React.Component {
    render() {
        return (
            <Table headers={this.props.headers} items={this.props.items} onRowClick={this.props.onRowClick} />
        )
    }
}

const Domains = connect(
    mapStateToProps,
    mapDispatchToProps,
)(DomainsView)

export default Domains
</code>```

hosts.js
Same as domains.js with differents const / class names and props

答:
You should "flatten" your state. One of the reasons for this is immutably updating state can get verbose and hard to understand pretty quickly when it contains nested items. See this example in the Redux docs on this topic: http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html#correct-approach-copying-all-levels-of-nested-data

Check out this part of the Redux docs on producing a flatter state: http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html. You basically create a mini-relational database. In your example you would separate headers and items into their own arrays, each item in the array having a unique id. For domains and hosts you would have a key of header_ids and item_ids which contain an array of ids for the referenced data.

This simplifies adding and removing headers and items too because you just delete them by id from their own array and remove their id from the domains or hosts list of header or item ids.

Again, this part of the Redux docs will show you exactly how to do this with examples: http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html.

Side note: this is not my favorite aspect of Redux!

Body:
I wrote a generic Table component, instancied twice with two differents datasets. I use a Redux store to hydrate props and I try to delete a row when I click on it.

Components are well displayed and onClick function is fired and reducer is called. The new returned state returns the previous state without the element clicked.

My problem is that the components are not re-rendered.
According to the troubleshouting page (http://redux.js.org/docs/Troubleshooting.html), it seems that I don't mutate the previous state (maybe I just don't understand how to do), I'm calling the dispatch() function and my mapStateToProps seems to be right as datas are well displayed on the page load.

I tried to define initial state in reducer.js > table function instead of doing it with createStore function, I tried to split 'tables' reducer into 'domains' and 'hosts' reducers (duplicate code), I tried to not use combineReducers() as I have only one (but I will have more in the future), and I tried so many things so I can't remember.

I bet it's not a big deal but I just not able to figure out what's going on. Can you help me please ? Thank you very much.

reducer.js

import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = Object.assign({}, state)

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    switch (action.type) {
        case DELETE_HOST:
            return Object.assign({}, state, {
                hosts: deleteItem(state.hosts, action.host)
            })

        case DELETE_DOMAIN:
            return Object.assign({}, state, {
                domains: deleteItem(state.domains, action.domain)
            })

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers

actions.js

export const DELETE_DOMAIN = 'DELETE_DOMAIN'
export const DELETE_HOST = 'DELETE_HOST'

export function deleteDomain(domain) {
    return { type: DELETE_DOMAIN, domain }
}

export function deleteHost(host) {
    return { type: DELETE_HOST, host }
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './reducers'

const initialState = {
    tables: {
        domains: {
            headers: {
                id: 'Id',
                domain: 'Domain',
                host: 'Hoster',
            },
            items: [
                {
                    id: 1,
                    domain: 'dev.example.com',
                    host: 'dev',
                },
                {
                    id: 2,
                    domain: 'prod.example.com',
                    host: 'prod',
                }
            ]
        },
        hosts: {
            headers: {
                id: 'Id',
                label: 'Label',
                type: 'Type',
                hoster: 'Corporation',
            },
            items: [
                {
                    id: 1,
                    label: 'Server 1',
                    type: 'Server type',
                    hoster: 'Gandi',
                },
                {
                    id: 2,
                    label: 'Server 2',
                    type: 'Server type',
                    hoster: 'OVH',
                }
            ]
        }
    }
}

let store = createStore(reducers, initialState)

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

app.js

import React from 'react';
import Domains from './modules/domains.js';
import Hosts from './modules/hosts.js';
import Nav from './modules/nav.js';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom'

export default class App extends React.Component {
    render() {
        return (
            <Router>

                    <Route path="/domains" component={Domains}/>
                    <Route path="/hosts" component={Hosts}/>

            </Router>
        );
    }
}

domain.js

import React from 'react';
import Table from './../components/table.js';
import { connect } from 'react-redux'
import { deleteDomain } from './../actions'

const mapStateToProps = (state) => {
    return state.tables.domains
}

const mapDispatchToProps = (dispatch) => {
    return {
            onRowClick: (id) => {
                dispatch(deleteDomain(id))
            }
        }
}

class DomainsView extends React.Component {
    render() {
        return (

        )
    }
}

const Domains = connect(
    mapStateToProps,
    mapDispatchToProps,
)(DomainsView)

export default Domains

hosts.js
Same as domains.js with differents const / class names and props


问:
Why might cache-manifest fail to get mobile Safari to cache site while working as expected on desktop?
I'm playing around with a simple web app locally, and can't quite figure out why it is not caching correctly on the iPhone.  I am serving a <code>.manifest</code> file with the correct MIME-type, and the site works perfectly fine with my local server turned on or off on desktop Safari, Chrome and Firefox.  It is only mobile Safari that is failing to cache the site.  Any ideas why this might be? </p>

答:
I had a similar issue but Safari and iPhone were both NOT working whilst IE and Firefox were working. The reason was complex. One was a misspelling of the word "manifest" in the HTML tag. Silly mistake and very frustrating that IE and FF still worked offline. The other issue was that I was using default.asp as the main page of my app and not including this in the manifest.

My app was mydomain.com/myapp/ and thus the browser never saw the "default.asp". Also, according to the HTML5 spec, the main page need not be in the manifest but apparently Safari sees that a little differently...

ContentLicense: CC BY-SA 2.5

Body: I'm playing around with a simple web app locally, and can't quite figure out why it is not caching correctly on the iPhone.  I am serving a .manifest file with the correct MIME-type, and the site works perfectly fine with my local server turned on or off on desktop Safari, Chrome and Firefox.  It is only mobile Safari that is failing to cache the site.  Any ideas why this might be?


问:
Where are the node.js app files installed in an AWS elastic beanstalk instance?
In an AWS elasticbeanstalk instance, where are the node.js app files deployed to?  I wanted to ssh to the machine and debug some issues and wanted to check that the files were deployed correctly.  I checked /var/ but didn't see an app directory there.</p>

答:
It's in the /tmp/deployment/application folder during deployment and then it is moved to /var/app/current.

The node logs are in /var/log/nodejs/nodejs.log


问:
Loading multiple GSM files into R with a loop?
I’m trying to load multiple GSM files into R via a loop, but I think that I’m missing something obvious.</p>

```<code>#Use i to loop through NCBI files GSM9714940 through GSM971948

for (i in 971940:971948){
  (GSMName <- paste("GSM", i, sep = "")) #Define the actual file name as found on NCBI
  GSMName <- getGEO(GSMName, destdir=".") #Use GSMName variable to pull data from NCBI
  #This doesn't work b/c I'm using a variable to redefine itself, but
  #I need the NCBI file name to also be the variable name
  }
</code>```

答:
You can use assign():

```<code>for (i in 971940:971948){
  GSMName <- paste("GSM", i, sep = "")
  assign(GSMName, getGEO(GSMName, destdir="."))
}
</code>```

Body:
I’m trying to load multiple GSM files into R via a loop, but I think that I’m missing something obvious.

#Use i to loop through NCBI files GSM9714940 through GSM971948

for (i in 971940:971948){
  (GSMName <- paste("GSM", i, sep = "")) #Define the actual file name as found on NCBI
  GSMName <- getGEO(GSMName, destdir=".") #Use GSMName variable to pull data from NCBI
  #This doesn't work b/c I'm using a variable to redefine itself, but
  #I need the NCBI file name to also be the variable name
  }

Body:
You can use assign():

for (i in 971940:971948){
  GSMName <- paste("GSM", i, sep = "")
  assign(GSMName, getGEO(GSMName, destdir="."))
}


问:
How to read a value in text file in batch

So I need use the GPU temperature as a variable in batch but I haven't quite understood how to pick only it, nothing else. I need the the latest temperature every 10 seconds. How to pick always the latest temperature from the text file and set it as %temperature%

答:
```<code>@echo off
:loop
for /f "tokens=3 delims=, " %%a in (input.txt) do set "temperature=%%a"
echo %temperature%
timeout /t 10 >nul
goto :loop
</code>```


问:
How to retrieve a form's validator
What is the correct way to get the current jQuery validator object for an existing form?

Note, the validator is being configured using the jQuery Unobtrusive validation plugin hence why I don't have a reference to it.

答:
From documentation:

The validate method returns a Validator object

Next code will gets existing validator or init it

```<code>var validator = $("form_selector").validate();
</code>```

Title: How to retrieve a form's validator

Body:
From documentation:

The validate method returns a Validator object

Next code will gets existing validator or init it

var validator = $("form_selector").validate();


问:
Fatal Error: 'openssl/conf.h' file not found
I'm using a compiler to try to make a set of files I've been given and the line #include  breaks with the error: Fatal Error: 'openssl/conf.h' file not found.

I've already installed openssl using brew, but it doesn't seem to work. Do I need to somehow connect openssl with my folder that I'm working in?

I'm on the newest mac OS sierra.

答:
Running:

```<code>brew info openssl
</code>```

gives the solution :

```<code>For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include
</code>```

Body:
Running:

brew info openssl

gives the solution :

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include