"Read more" button references the front page

Question: I manually created a view page with 3 fields: image, title, and body.
The body field has a Read more link which, instead of pointing to the specific node listed in the blog, it redirects to the front page.
I didn't track anything that would cause it. Maybe I'm missing something.

I also tried to use the [node:nid] token, but it didn't help.
Answer: The problem here is 2 issues:

You're missing a field on your view to reference. In order to reference the Node ID in your view you'll need to add the field Content: ID so that it can be referenced in replacement patterns. It will also need to be ordered before your body field so that its value can referenced. You can use the Exclude from display option if you do not want it appearing in your view.
The format for token replacement has changed with D8. It's now Twig-like: {{ field_name }}. By default the Content: ID field should use the field name nid so your More link path value should be /node/{{ nid }}.


Layout name cannot be resolved in android

Question: In my activity there is an error in this line (Home.this,android.R.layout.activity_home, searchResults)); which says "activity_home cannot be resolved" but if i give as single_list_item_1 as mentioned in one of the tutorial, error disappears, for this error i had checked in res for capital letters, then cleaned the project but still not able to get rid of this.
searchBox.addTextChangedListener(new TextWatcher() {
                 public void onTextChanged(CharSequence s, int start, int before, int count) {

                   //get the text in the EditText
                   String searchString=searchBox.getText().toString();
                   int textLength=searchString.length();
                    //clear the initial data set
                   searchResults.clear();
                   for(int i=0;i<songsList.size();i++)
                   {
                  String playerName=songsList.get(i).get("title").toString();
                  if(textLength<=playerName.length()){
                  //compare the String in EditText with Names in the ArrayList
                      if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
                   Toast.makeText(getApplicationContext(),playerName,1).show();
                    searchResults.add(songsList.get(i));
                  }

                  list.setAdapter(new ArrayAdapter<HashMap<String, String>>
                  (Home.this,android.R.layout.single_list_item, searchResults));

                   }

                   adapter.notifyDataSetChanged();
                 }

            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
              }

                   public void afterTextChanged(Editable s) {

                   }
                  });

Comment: What is the package name of R.java in your code?
Comment: package com.search @ShailAdi
Answer:
android.R.layout.activity_home

Something which starts with android is a predfined android resource.
if you want to use your own layout like activity_home.xml
you must use it this way

R.layout.activity_home

which means your application resource.
Answer: you have to learn the difference between android.R.layout.activity_home and R.layout.activity_home. the first one will try to load layout from android's predefined layout collection, while the other one is located in your projects layout folder
Comment: i was not knowing this, thanks alot for the info @Tomislav Novoselec


How to find the transform from an empiric distribution to another empiric distribution

Question: I have two datasets, each dataset is a pool of samples, and each sample contains multiple observations. Data-wise, we can represent one sample as a vector of floats, and a dataset as a matrix where each row is a sample.
I would like to find a transform to project the first dataset into the "space" of the second dataset. I think I am looking for a way to estimate and then project an empirical distribution into another empirical distribution. There might be a dependency between samples of one dataset, but not between datasets.
Bonus reward if the answer also suggests a way to account for the number of samples (because there is a big dataset and the other one is much smaller, thus a distribution estimation will likely be much more approximate for the latter).
Clarification: I have (and can't get) no apriori on the underlying distribution of any of the datasets. They are generated by a natural phenomenon, and no theory model correctly these distributions yet.
/EDIT: I will try to clarify with a concrete example close to what I am working on.
Let's say I am working on a machine learning application to automatically recognize objects shapes in a scanned image. To make it simpler, let's say these images are only in grayscale (no color, only pixel intensity remains).
The problem I am facing is that I have images coming from several different scanners, and each scanner has a different "intensity space", so that it is difficult to transpose a machine learning model learnt on one scanner to the next scanner, because of the scanner-induced variability in intensity.
More formally, using pseudo-Python code, my data and code would look like this:
<code># Images are represented as a row vector, each value is one pixel intensity
# They are the samples
scanner1_im1 = [1, 255, 3, 73, ...]
scanner1_im2 = [4, 83, 2, 190, ...]
scanner2_im1 = [8, 29, 1, ...]
scanner2_im2 = [37, 29, 4, ...]

# We can constitute a pool of image samples for each scanner, which I call a dataset
scanner1_images = [scanner1_im1, scanner1_im2]
scanner2_images = [scanner2_im1, scanner2_im2]

# TODO: normalization step, where the scanner2_images gets normalized/projected into scanner1_images space, or whatever technique that would allow to represent both datasets in an approximately similar space
scanner2_images_norm = norm_project_images(scanner2_images, scanner1_images)

# Machine learning modeling on normalized images
ml.learn(scanner1_images, scanner2_images_norm)
</code>
What statistical/probabilistic techniques may I use to project all scanners/datasets into a similar space of intensities (and thus reduce inter-scanner variability while retaining inter-images/intra-scanner variability as much as possible)?
Comment: @gaborous: I hope you don't mind, but I posted a related question [here](https://stats.stackexchange.com/questions/330937/projecting-a-spatial-matrix-onto-another-spatial-matrix), in an attempt to clarify some aspects of this question.  If my question correctly interprets yours, you may feel free to steal any of it for an edit.
Comment: How do you know that you even need to do this? The right machine learning technique could very well be robust to the differences between scanners. Convolutional neural nets can recognize letters and numbers under all sorts of distortions, illumination conditions, noise, corruption...
Comment: This question needs to be modified to give a clear explanation for what the vector of pixels actually represents: Do they represent an image in two dimensions?  If so, what are the dimensions, and how are the pixels ordered?  Are the vectors of pixels from the scanners the same length?  If the image spaces are different, what is the difference in pixel vectors?  Etc., etc.  The information presently given is insufficient to clarify the question.
Comment: @Ben: we can consider the image in two dimensions, in a row vector (eg, first i pixels represent the first row in the image, i+i the second row of pixels, i*2+i the third row etc). They are not necessarily the same length but I'm OK if this is assumed to be equal for simplification.
Comment: @Paul: You're right that a machine learning model might account for that, I didn't think about it. But in my real application, I am not going to use a machine learning model, at least not until after more processing that is so down in the pipeline that it cannot account for differences in scanner variation. However, using a machine learning model specifically to fix the scanner variation might be a solution, feel free to propose an answer with this!
Comment: If you want to fix this and not just be robust to it, then you really need a model for the scanners and their variation - something much simpler than the 100 parameter model. What does the signal input/output curve look like? Is it linear? Is it the same for each pixel in the scanner? Is there spatial distortion or blur? Do you have any lab calibration data that could help constrain the solution?
Comment: You should also look deeper and try to understand the 100 parameter model. Most likely there are only a few "effective parameters" that account for most of the variation between the scanners. Any lab measurements you may have you should make use of.
Comment: You really, really can't solve this problem without more information or assumptions. It's way too ill-posed. I say that as a person who has solved similar problems in the past on space instruments. Don't fool yourself going down the path of some canned "method" that supposedly works in another discipline.
Comment: How do you even measure your success in solving this problem? If two scanners never take images of the same thing, how would you know whether differences between scanner results are because the transfer functions are off or the objects being imaged are just different?
Comment: Thank you all very much for your very helpful comments. @Paul: we can assume that the average image of each scanner is representing the same thing (eg, a table), so that's what I use as a reference (the average image of scanner A should be pretty similar to scanner B's), but of course this is an approximation... Modeling the parameters would be ofc the best way, but the scanners are changing quite fast, they are not open and doing such a study would take years if not decades.
Comment: @Ben I don't mind at all, thank you very much! Your reframing is very close to my problem, a solution to yours would surely be applicable to mine.
Comment: Assuming the average latent image is the same across scanners is a huge help for constraining the problem. Now all you need is a decent empirical model of the scanners. What drives the variation? See my questions above regarding input/output sensitivity, nonlinearity, spatial distortion, blur, etc. If a given scanner can be approximated as applying a fixed linear operator to each image, you're in business.
Comment: A fixed linear operator is not that constrained of an assumption. It can accommodate pixel dependent bias and sensitivity, spatial distortion, blur, etc. A bit of nonlinearity can probably be worked in but not too much. It would be easiest if the imaging operator was something like a multiplicative "mask" representing pixel variations in sensitivity from scanner to scanner.
Comment: @Paul: yes, I think a multiplicative mask per scanner would totally fit the bill! The issues you list are on-point, so if it can accomodate that it would be perfect. I did not think this was a possibility.
Comment: If you assume a multiplicative mask and nothing else, the best estimate for the A-to-B transfer function would just be B/A, where A and B are the average images from scanners A and B respectively. There are various ways to potentially improve upon this baseline, depending on the noise characteristics of the scanners and prior information you may have about the average image.
Comment: To make this work, the average images have to be carefully aligned so they're as similar as possible. Any differences of object position, orientation, etc must be eliminated using some image registration technique before taking the B/A ratio.
Comment: Handling all of these issues at once (sensitivity, blur, etc) would be pretty difficult. You need to pick one or two most important issues and handle those, or try to handle them one at a time / separately. The important point is that if you have linearity, the operator of averaging over all input images commutes with the scanner transfer function, so you can figure things out from the observed average images rather than the latent "true" average images which you don't have.
Comment: @Paul please post this as an answer, you can consider perfect co-registration to be possible (in practice we have algorithms to do that in my specific field). I am not sure the real transform is linear, but it's perfectly fine for me to do that as an approximation of the real transform if I make this a clear assumption.
Comment: The question is unclear: what do you mean by a pool of sample? Do you seek a distribution $F(x)$ such that $x$ is one sample?
Comment: I tried to clarify with the second sentence, but with your notation, it would be `F(X1, X2, ..., Xn)` where `Xi` is a vector.
Comment: To clarify, because this might be a difficult edge case, `X1, ..., Xn` might all have some intrinsic variability, but I am interested in the whole variability, the parameters of the "parent" distribution that is shared across all Xs. If I am not clear enough, please tell me.
Comment: Also I expect the difference between Xi and Yi (2nd dataset) to be greater than any Xi vs Xj or Yi vs Yj. This is this (extrinsic) difference that I would like to quantify and reduce, even if approximately.
Comment: Do you have a method to solve your problem in the case df1 has 1 column, m rows; df2 has 1 column, n rows; and samples of df1 are independent, samples of df2 are independent? If you can describe the problem and a solution is this case, it could help us to understand the problem clearly
Comment: Try to show with a snippet how your data looks like.
Comment: I added an example that is close to mine. I cannot show a snippet of my data as I did not generate it yet, but this example should be very analog.
Comment: There is not enough information for a solution yet. We need to know something about the scanners and how they differ, or something about the things being scanned, to get anywhere.
Comment: Q1: In your example, do you have images of the same object taken with both scanners and, if so, are these images spatially co-registered (e.g. does each pixel of `scanner1_im1` represent the same position on the same object as the matching pixel in `scanner2_im1`?). Q2: Does the way the scanners differ change across space/pixels, or is it constant? Q3: Do the scanners have different noise characteristics (and does this matter to you)?
Comment: @Paul: There is about a 100 different parameters or more than can influence the way the scanners behave: this is exactly the problem. And in addition there is no model that quantify the impact of each. I cannot model the parameters explicitly, it needs to be done approximately and implicitly from empiric observations, that's the gist of my question.
Comment: @user20160: Q1: No, but we can consider the objects similar enough that an average image from one dataset should be expected close to the other dataset (eg: same kind of object such as apples, but the shape and color can change, although the orientation is the same). The images can be co-registered (even non-linearly, but keep in mind that we might be comparing different  apples "flavours"). Q2: If you mean to ask whether the variability per scanner change from scan to scan, yes but we can consider it negligible. If you mean in terms of space, then yes the variability can be anywhere.
Comment: @user20160: Q3: The scanners have different noise characteristics, in fact this is I want to reduce (ie, the difference in scanner's noise/variability). Q1 again: to make it clearer: if you take any object from dataset D1 and compare to an object in D2, then you can't expect same to be the same, but if you take the "average" model of an object in D1 and compare with the average of D2, then you can expect to be the same (this is an approximation but it's OK). However due to scanner's induced variability, the average can be very different between datasets.
Answer: I believe that the field that you are interested in is called Calibration transfer or more generally Transfer learning. A lot of litterature can be found in the Spectroscopy field which I believe is quite close to image processing in terms of methods.
There are two different situations:
Either you have common images that have been scanned by the different scanners, in that case, I will just describe a bit the simpler and the most used methods. A review of all different methods can be found here [1]

One of the easiest and oldest one: A method that has been developed by Wang et al [2]. The underlying principle is quite simple: a multi response and multi variate regression between the pixels response of the original instrument and the second.
I believe the most used one now is the double window piecewise direct standardization (DWPS). Which is somehow similar to the simplest one but you using a size defined window to regress each pixel. [3]

If you don't have common images scanned by each scanner (all the images are different) there are two different approaches:
(1) The samples from the initial scanner can be reweighted in order to have the closest features distribution than the samples from the new scanner. A numerous of methods have been developed to find the appropriate weights [4,5,6,7,8]. Then you will have to re-train the model with the reweighted initial samples to predict on the new scanner.
(2) Then I think it's the approach you are most interested in: you can re-estimated a feature representation where samples form the old and new scanner are in closer proximity. Some methods have been developed to find the new representation space, you can find them here:[9,10,11]
The source 11 is a good review of all methods!
These sources in general are not specifically for image processing (and I changed the term 'wavelength' to pixel) but I belive the methods can be used for it. I don't think they explicitely take into account the size of each dataset. Hope this helps anyway!
References
[1] Feudale, R. N., Woody, N. A., Tan, H., Myles, A. J., Brown, S. D., & Ferré, J. (2002). Transfer of multivariate calibration models: a review. Chemometrics and Intelligent Laboratory Systems, 64(2), 181-192.
[2] Y.D. Wang, D.J. Veltkamp, B.R. Kowalski, Anal. Chem. 63
(1991) 2750–2756.
[3] Greensill, C. V., Wolfs, P. J., Spiegelman, C. H., & Walsh, K. B. (2001). Calibration transfer between PDA-based NIR spectrometers in the NIR assessment of melon soluble solids content. Applied spectroscopy, 55(5), 647-653.
[4] Huang, J., Smola, A. J., Gretton, A., Borgwardt, K. M., and Scholkopf, B.: Correcting Sample Selection Bias by Unlabeled Data, in: Pro-
5 ceedings of the 19th International Conference on Neural Information Processing Systems, NIPS'06, pp. 601–608, MIT Press, Cambridge,
MA, USA, http://dl.acm.org/citation.cfm?id=2976456.2976532, 2006.
[5] Sugiyama, M., Nakajima, S., Kashima, H., Buenau, P. V., and Kawanabe, M.: Direct Importance Estimation with Model Selection
and Its Application to Covariate Shift Adaptation, in: Advances in Neural Information Processing Systems 20, edited 63 by Platt, J. C., Koller, D., Singer, Y., and Roweis, S. T., pp. 1433–1440, Curran Associates, Inc., http://papers.nips.cc/paper/3248-direct-importance-estimation-with-model-selection-and-its-application-to-covariate-shift-adaptation.pdf, 2008.
[6]Kim, S., Kano, M., Nakagawa, H., and Hasebe, S.: Estimation of active pharmaceutical ingredients content using locally
weighted partial least squares and statistical wavelength selection, International Journal of Pharmaceutics, 421, 269 – 274,
https://doi.org/https://doi.org/10.1016/j.ijpharm.2011.10.007, 2011.
[7] Hazama, K. and Kano, M.: Covariance-based locally weighted partial least squares for high-performance adaptive modeling, Chemometrics
25 and Intelligent Laboratory Systems, 146, 55 – 62, https://doi.org/https://doi.org/10.1016/j.chemolab.2015.05.007, 2015.
[8]Zhang, X., Kano, M., and Li, Y.: Locally weighted kernel partial least squares regression based on sparse nonlinear fea30
tures for virtual sensing of nonlinear time-varying processes, Computers & Chemical Engineering, 104, 164 – 171,
https://doi.org/https://doi.org/10.1016/j.compchemeng.2017.04.014, 2017.
[9]Culp, M. and Michailidis, G.: An Iterative Algorithm for Extending Learners to a Semi-Supervised Setting, Journal of Computational and
20 Graphical Statistics, 17, 545–571, https://doi.org/10.1198/106186008X344748, 2008.
[10] Gujral, P., Amrhein, M., Ergon, R., Wise, B. M., and Bonvin, D.: On multivariate calibration with unlabeled data, Journal of Chemometrics,
25, 456–465, https://doi.org/10.1002/cem.1389, 2011.
[11] an, S. J. and Yang, Q.: A Survey on Transfer Learning, IEEE Transactions on Knowledge and Data Engineering, 22, 1345–1359,
https://doi.org/10.1109/TKDE.2009.191, 2010.
Comment: Thank you very much, I will review all these references! I spotted spectroscopy methods before but I was not sure they were applicable to other domains, I will have a look!


Why would all theme background colors disappear after moving to different server?

Question: A site using MAYO 7.x-1.2 was moved from a Windows IIS to a Linux server. Shortly thereafter, all background colors defined in MAYO settings (and also any custom CSS) have disappeared. Also gone is the custom background color for dropdown Nice menus – it just goes transparent. Other than the bg color, main content and layout are OK. Perhaps there is no relationship of this to the server change, but in any case I haven't been able to debug this with anything I tried. The PHP version is now 7.2, maybe that is related, and I'm not sure what it was under the Windows server. Site needs to stay in D7 for now, although a D8 upgrade is planned.
Also note, I was aware that this is an old version of MAYO that should have been updated long ago. I hesitated to update because I had modified the template file to get an additional region, and wasn't sure how to apply the update while preserving the custom region. (Could use some advice there.) In reading the docs about the security update, it seems the circumstances for risk don't really apply for this site.
Advice on either of these issues will be much appreciated.
Comment: @Charles you need to change the folder's `owner/group`. Without the proper `owner/group` it wont work even when perm is set to `777`.
Comment: Missing CSS, files folder not writeable, tmp not writeable, locations of these dirs changed... could be anything. There must be some logs around this.
Comment: Often this is due to missing or misconfigured `.htaccess`. Yeah, or as @Kevin suggests, file/folder permissions/ownership.
Comment: Setting 777 permissions on the theme folder, or on /files inside /default, didn't help. I'm aware of .htacces but not familiar with all its purposes. Can anyone comment: If a site is moved from a Windows server to Linux, should .htaccess need some changes?
Answer: First , Check Administrator -> Configuration -> Media -> File System to personalize your tmp path. Make sure to use relative paths and have the right privileges for your webserver.
After than Check permission of the /sites/default/files and make sure it's writeable by your web server.
Comment: @Charles, yes 777 is writeable but very dangerious. you should set the owner and group of the files by your webserver then set it to 755 later.
Comment: Pardon my lack of deeper knowledge on server matters, but if /files is set to 777 permissions, should that mean it's "writeable by the server"?
Comment: @Charles,any update? have this solution worked for you?
Comment: Yes, that was solved. Since a variety of things were being done including changes made by a hosting server admin, I am not completely sure which modification was the one that fixed that particular problem. But I think it was server-specific changes in the settings.php file.


Calcular média de tempo de atendimento

Question: Galera, estou precisando tirar a média de tempo de atendimentos e tenho os seguintes dados:
00:12:35
00:05:10
00:01:42
00:08:12
00:01:01
{...}

A pergunta é, como que posso fazer? Pesquisei uma maneira de fazer isso usando AVG do Mysql mas não tive sucesso... Tentei somar e dividir pela quantidade de registros mas o numero ficou quebrado... Alguém já passou por algo parecido?
Agradeço antecipadamente pela ajuda!
Comment: dê uma olhada neste link  https://pt.stackoverflow.com/questions/127231/calcular-diferen%C3%A7a-entre-horas-no-php
Comment: Possível duplicata de [Calcular diferença entre horas no php](https://pt.stackoverflow.com/questions/127231/calcular-diferen%c3%a7a-entre-horas-no-php)
Comment: O comentário acima resolve seu problema. Já que ensina retirar a diferença entre horas e o tempo médio do atendimento é a soma das diferenças dividida pela quantidade de atendimentos.
Answer: Faça a média com valores inteiros convertendo os tempos para segundos e depois convertendo para tipo tempo novamente:
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(`tempo_atendimento`)))

Calcular média de tempo de atendimento


Programmatically Create Checkbox Column inside a Gridview in ASP.NET

Question: I often use this code to create template fields for buttons, checkboxes, labels etc. inside a gridview:
<code><asp:TemplateField HeaderText="Data_1" ShowHeader="False" Visible="True">
 <ItemTemplate>
  <asp:Button ID="Button1" runat="server"
  CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
  CommandName="Button1_Command" CssClass="round_button"
  Height="20px" Width="20px" />
  </ItemTemplate>
  </asp:TemplateField>
</code>
But this time, the number of columns with checkbox are uncertain. (I need to pull a certain data in the database to determine how many checkbox columns I would need). How do I programmatically create a checkbox column upon page load?
Thanks :)
Answer: Hope the below codes help you. It's not a complete code but it would give you hint or idea on how to create checkbox column programmaticaly. Thanks.
<code> <asp:GridView runat="server" ID="grdView">
        <Columns>
            <asp:TemplateField HeaderText="Button" ShowHeader="False" Visible="True">
                <ItemTemplate>
                    <asp:Button ID="Button1" runat="server"
                        CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
                        CommandName="Button1_Command" CssClass="round_button"
                        Height="20px" Width="20px" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

Public Class _Default
    Inherits Page

    Public Class GridViewCustomColumn
        Public Property ColumnName As Boolean
        Public Property HeaderName As String
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Dim lists As New List(Of GridViewCustomColumn) From { _
            New GridViewCustomColumn() With {.ColumnName = False, .HeaderName = "TestHeaderName1"}, _
            New GridViewCustomColumn() With {.ColumnName = True, .HeaderName = "TestHeaderName2"}}

        grdView.AutoGenerateColumns = False

        Dim templateField As New TemplateField()
        templateField.ItemTemplate = New CheckBoxTemplateImpl("ColumnName")
        grdView.Columns.Add(templateField)
        grdView.DataSource = lists
        grdView.DataBind()

    End Sub

    Public Class CheckBoxTemplateImpl
        Implements ITemplate

        Public Property ColumnName As String
        Public Sub New(columnName As String)
            Me.ColumnName = columnName
        End Sub

        Public Sub InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
            Dim chkBox As New CheckBox()
            AddHandler chkBox.DataBinding, AddressOf chkBox_DataBinding
            container.Controls.Add(chkBox)
        End Sub

        Private Sub chkBox_DataBinding(sender As Object, args As EventArgs)
            Dim chkBox As CheckBox = DirectCast(sender, CheckBox)
            Dim gridViewRow As GridViewRow = DirectCast(chkBox.NamingContainer, GridViewRow)
            Dim bindValue As Object = DataBinder.Eval(gridViewRow.DataItem, ColumnName)
            If bindValue IsNot Nothing Then
                chkBox.Text = bindValue.ToString()
            End If
        End Sub
    End Class
End Class
</code>
Comment: oh. okay. I get it. I will try it now. Thank you!


groupby objects dont update with updated dataframes

Question: THE QUESTION HAS BEEN EDITED, PLEASE READ EDIT FIRST.
I'm using groupby method to group data in a dataframe and then use the outcome to modify the dataframe (for example, changing a bool value in one of its columns) I've tried the modification in two ways:

Modify the df outside an groupby.apply method - this changes the df but when entering the applied method again, those changes are gone.

Modify the df by applying a modification method via groupby. this does not change the df and changes do not take effect next time I'm entering an applied method.

So either way, the groupby.apply always referring to the original df, no matter how and if it was modified.
To illustrate:
In [1]:
df = DataFrame({'a':[1,1,1,3,3,3],'b':[2,2,2,4,4,4],'c':[True,True,True,True,True,True]})
df
Out[1]:
a   b   c
0    1   2   True
1    1   2   True
2    1   2   True
3    3   4   True
4    3   4   True
5    3   4   True

now using groupby:
In [2]:

def modify(grp):
    if grp.name==1:
        grp.c = False

def print_group(grp):
    print '\ngroup value is:' + str(grp.name)
    print grp.c

gb = df.groupby('a')
gb.apply(modify);
gb.apply(print_group);

group value is:1
0    True
1    True
2    True
Name: c, dtype: bool

group value is:3
3    True
4    True
5    True
Name: c, dtype: bool

So no change to the 'c' column
Now if I'm modifying the df outside:
In [3]:

df.ix[df.a==1,'c'] = False
df
Out[3]:
a   b   c
0    1   2   False
1    1   2   False
2    1   2   False
3    3   4   True
4    3   4   True
5    3   4   True

In [4]:

gb.apply(print_group);

group value is:1
0    True
1    True
2    True
Name: c, dtype: bool

group value is:3
3    True
4    True
5    True
Name: c, dtype: bool

So it seems that by using groupby, a copy of the df is created, and changes applied to it by .apply, goes where? What is going on under the hood here? And how do I make it work as necessary? running .groupby again every time I'm modifying an element in the df? that sounds extremely expansive and redundant to me.. Can someone explain?
EDIT:
I understand now the source for most of my problems using groupby. To my taste, the groupby mechanism is logically too ambiguous and the design encourages the user to use it in the wrong why. The way I saw this, the whole idea behinds data analysis with pandas is to group and apply. I thought grouping is the most expensive task, so I imagined the proper use would be to group only once, and then do what ever you want with the groups. as long as the group members doesn't change, you shouldn't regroup a dataframe. This idea is also implied from the design, as you can save a groupby object, which for me implies that the author of pandas wanted as to create a groupby object only once.
From the answer below me, though, and from the "inconsistency" that ill describe below, It seems this is not the right use. I'm now beginning to think the proper use is to regroup for each operation, even if the groups themselves didn't change. I don't know if that really regroups or just using a grouping object which is a member of the dataframe. (if the same grouping was done in the past).
Bottom line, I missed used the groupby operation, which gave me strange results, as you can see here:
First, I defined the following function:
In [138]:

from pandas import *
def modify(grp):
    if grp.name==1:
        grp.c = False
    return grp
def print_group(grp):
    print '\ngroup value is:' + str(grp.name)
    print grp.c

Then, two similar operations gave me different result, an "inconsistency" allegedly:
In [165]:
df = DataFrame({'a':[1,1,3,3],'b':[2,2,4,4],'c':[True,True,True,True]})
gb = df.groupby('a')
df = gb.apply(modify);
gb.apply(print_group);
df
group value is:1
0    True
1    True
Name: c, dtype: bool
group value is:3
2    True
3    True
Name: c, dtype: bool
Out[165]:
a   b   c
0    1   2   False
1    1   2   False
2    3   4   True
3    3   4   True

Here I changed df by assigning it the results of the modify function, then I called the printing function to see if the it "sees" the change. as can be seen, it is not.
Trying something a little different, gave different results:
In [168]:

df = DataFrame({'a':[1,1,3,3],'b':[2,2,4,4],'c':[True,True,True,True]})
gb = df.groupby('a')
df.ix[df.a==1,'c'] = False
gb.apply(print_group);
df
group value is:1
0    False
1    False
Name: c, dtype: bool
group value is:3
2    True
3    True
Name: c, dtype: bool
Out[168]:
a   b   c
0    1   2   False
1    1   2   False
2    3   4   True
3    3   4   True

Here I created a dataframe, created a groupby object, changed the dataframe in place (that is important) and then called the printing function to see if groupby object "sees" the change. it did.
earlier in this post, it didn't (see In[3], In[4] and Out[4] in the original post)
So as you can see, something is very inconsistent here. Here is my explanation to all this mess:

In the first case, when I assigned to df what returned from the modifying function, I actually created a new variable in memory. the groupby object was referring to a different df variable, i.e. a different place in memory. thus the df holding different info than what groupby "sees".

In the second case, the changes was made "inplace", i.e. in the same memory allocation. therefore groupby saw what df saw.

In the original case (see In[3], In[4] and Out[4]) the changes were made to df, but in a new place in memory. so groupby referred to one place, and the modified df to a different place.

It seems that changing a dataframe by  df[cond, 'column_name'], which was suggested here not to create a copy but a view of the dataframe, might be creating a view, but in a different memory allocation (i.e a copy of the df is made in a memory spot,changed, and than the original name is assigned the location of the new memory spot, leaving the groupby element referring to now abandoned memory location)
This is the only way I can explain those results. Would like your confirmation on that. The only solution i see to that improper use is to call groupby each and every time. One can only hope that df.groupby saves a groupby object as a member of the df, so if the same groupby call is being made again and again, it is not called every time from scratch.
If I'm right, the linkage between a groupby element to a dataframe is quite weak, and the results of several dataframe modifications and groupby operations cannot be fully anticipated. So what is the solution? Running groupby for each and every apply operation? that seems redundant..
Answer: You just need to return the frame in your function. Apply takes the output of the function and creates a new frame (of the applied data); if you return None in your function then it uses the original (and if you don't return a value, then you are implicity returning None)
In [22]: def f(x):
   ....:     if x.name == 1:
   ....:         x.c = False
   ....:     return x
   ....:

In [24]: df.groupby('a').apply(f)
Out[24]:
   a  b      c
0  1  2  False
1  1  2  False
2  1  2  False
3  3  4   True
4  3  4   True
5  3  4   True

Comment: Sorry, didn't get it completely.. what do you mean by "if you return NONE n your function then it uses the original" you mean that the underlying dataframe is determined according to my apply function returning or not returning a value? Im still confused about what going on under the hood here. I thought that a groupby object simply holds the index of all gruop and their members. but this is clearly not so. So what, groupby object holds a copy of the original dataframe? Please elaborate more and be more clear..
Comment: also, this implies regrouping the dataframe for each apply operation, which can be expensive and redundent (see my edits..)
Comment: Maybe you can explain in a simple example what your problem is. Optimizing is often the last step. Make sure you have correctness first. Profile, THEN optimize if needed. Groupby is a cheap operation; the apply can be more expensive. But unless you have LOTS of groups this shouldn't matter.
Comment: Im doing a similar thing to what you see here, only in much larger scales. I have groups containing overlapping indexes. for example, imagine a data frame indexed by files, containing two groups which have overlap in the index (i.e. some files belong to both groups). now im doing an iterative process, in which in each step im choosing files by some critiria, then im marking the used files by setting the 'isUsed' column in my dataframe to true for the choosen files. then im choosing files again and vice versa until I choose all files.
Comment: why don't you group by both columns then? If your process is iterative then just groupby (and apply after each iteration)
Comment: It doesnt fit the problem. i need groups that have unique X attribute, and im selecting which files to use by the why the file interacts with the rest of the group members. thats is why i have to keep the groups as they are, and not break them down to smaller groups. But once a file was selected under a certain group attribute, I dont want it to be used ever again.
Comment: you might try using pandas to calculate the groups then just put them in a dict of you want then
Comment: Just to make clear, imagine im grouping files by their category tags. files that have more then one category tag will appear in more then one group. Now imagine that im selecting in each iteration one file from all of the groups. Im doing it as such: for each group, I sort all files by their sizes. then im looking for the file that have the biggest difference in size for its follower. then I compare the biggest differences in all group and select the highest valued file. than i want to remove that file from all groups, and start over. Was that clear?
Comment: The dict option is ok, i tried it. but it is less elegent and missing the whole point of using pandas...
Comment: ok...maybe if you put up a more complete example. As I said, groupby is pretty cheap to do. Unless you have say 100k groups what I showed will work just fine. After that you might want to do it slightly different. It all depends on the bottleneck. Optimize at the end. Profile.


Ending a measure in "and!"

Question: I am transposing Nocturne Op.9 into 3/4 instead of 12/8. In one of the measures it counts one-and-a-two-and-a-three-and. I am not sure if this is allowed because I am self-taught. Is this OK or do I have to re-do my entire piece?
Comment: I'm guessing this is Chopin, Op. 9/2 in E-flat?
Comment: you are going to have a very hard time turning 3 into 4
Comment: Iv'e already started
Comment: What you are aiming is not entirely unheard of, you are in essence trying to give a piece a swing beat, just keep it to three time, so just pick 9/8
Comment: @NeilMeyer - trying to give a swing beat, one more often goes from 4/4 to 12/8 either physically, or with the equivalent quaver/triplet sign at the top of the sheet. By going straight into 3/4, and doubling the value of each note, it'll work fine. 9/8 won't really work, from 12/8.
Answer: well, 3/4 and 12/8 are completely different to start with. You seem to know that Compound time is counted differently (from the comments section), You have to understand that Time Signatures, although only used to keep time most of the time in a non-classical context, matters significantly in genre of music. Not just in counting but also the way music is felt. i'd suggest that you read up more on Time signature.
And for your question, you have to mention the context. Sometimes bars end without full measure's counts ending because of anacrusis (up beat).
If you are talking about Op.9 No.2, It starts with an anacrusis of 1 quaver. So At the last bar of a section, bar will be short of 1 quaver.
Comment: That is the answer I needed I wasn't sure if I could end it one and or if it had to be exactly on three.
Answer: Neck on the line here! It could have, quite conceivably, been written in 3/4. Double the value of each note, and it will fit fine. It's usually played with such rubato that the 12/8 rhythm becomes a little lost anyway.
By splitting each bar into four separate bars, it has to work.

Ending a measure in “and!”


Netboot OS X installation from an Ubuntu Linux system

Question: I'm interested in netbooting an OS X install (Snow Leopard) from my Ubuntu box. I've made an ISO of the install dvd, but I'm not sure how to proceed from here. I know it's possible to do this from an OS X server, but can it be done from Linux as well?
The Macs that need to receive the netinstall are all intel versions.
Comment: I'm not sure why there's a vote to move this to superuser - netboot is a systems admin thing.
Answer: Never tried it myself - I do netboot from OSX server because its nice and easy - but there is a guide to doing this available at afp548.com, here. The example talks about CentOS but I guess you can either adapt the steps to work with Ubuntu or install CentOS on another box.
Comment: An anonymous user noted that your link has died. :(
Comment: Thanks @HopelessN00b - updated link to another guide I know.
Answer: Here's an (admittedly old) article about making any Mac a Netboot server: http://www.macgeekery.com/hacks/hardware/make_any_mac_a_netboot_server
The author does say the idea of a Linux based netboot server is probably possible:

And for good measure, I'll show you how to do this without having to use BSDP at all (Debian NetBoot server, anyone?).

But I can't find any info on that ever having been accomplished.


What is wrong with my Model and Interface? (Java Spring Boot webapp)

Question: I have an error during running that says (with full directories omitted for brevity:

Error creating bean with name 'idea_Service' defined in file
  [...com\vincentsnow\brightideas\services\Idea_Service.class]:
  Unsatisfied dependency expressed through constructor parameter 0;
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'idea_Repository': Invocation of init method
  failed; nested exception is java.lang.IllegalArgumentException: Not a
  managed type: class java.lang.Object

and another:

Error creating bean with name 'idea_Repository': Invocation of init
  method failed; nested exception is java.lang.IllegalArgumentException:
  Not a managed type: class java.lang.Object

I haven't used these lowercase names anywhere. I can't make sense of this message...I'm guessing it's trying to compile but changing the filenames for some reason. No errors are caught by STS in my files. Here they are:
Idea_Service.java (service)
    package com.vincentsnow.brightideas.services;

import java.util.List;
import org.springframework.stereotype.Service;
import com.vincentsnow.brightideas.models.Idea;
import com.vincentsnow.brightideas.models.User;
import com.vincentsnow.brightideas.repositories.Idea_Repository;

@Service
public class Idea_Service {
    private Idea_Repository ideaRepository;
    public Idea_Service(Idea_Repository ideaRepository){
        this.ideaRepository = ideaRepository;
    }

    public List<Idea> allIdeas(){
        return ideaRepository.findAllIdeas();
    }

    public void createUser(String idea, User posted_by){
        ideaRepository.save(idea, posted_by);
    }

    public Idea oneIdea(Long id) {
        return ideaRepository.getSingleIdeaWhereId(id);
    }

    public List<Idea> likesof(Long id){
        return ideaRepository.getLikesOfIdea(id);
    }
}

Idea.java (model)
package com.vincentsnow.brightideas.models;

import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.constraints.Size;
import com.vincentsnow.brightideas.models.User;

@Entity
public class Idea {

        @Id
        @GeneratedValue
        private Long id;

        @Column
        @Size(min=3, max=5000)
        private String idea;

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name="idea_id")
        private User posted_by;

        @ManyToMany(fetch = FetchType.LAZY)
        @JoinTable(
            name = "likes",
            joinColumns = @JoinColumn(name = "idea_id"),
            inverseJoinColumns = @JoinColumn(name = "user_id")
            )
            private List<Idea> likes;

}

Idea_Repository.java (repository)
package com.vincentsnow.brightideas.repositories;

import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.vincentsnow.brightideas.models.Idea;
import com.vincentsnow.brightideas.models.User;

@Repository
public interface Idea_Repository extends CrudRepository {

    @Query("SELECT a FROM ideas a")
    List<Idea> findAllIdeas();

    @Query(value="INSERT INTO ideas (idea, posted_by) VALUES (?1, ?2, ?3, ?4)", nativeQuery=true)
    Idea save(String idea, User posted_by);

    @Query("SELECT a FROM ideas a WHERE id=?1")
    Idea getSingleIdeaWhereId(Long id);

    @Query(value="SELECT likes WHERE idea_id = ?1", nativeQuery=true)
    List<Idea> getLikesOfIdea(Long id);

}

What is wrong with them? What does this error mean? What is STS trying to do?
Comment: Please show persistence.xml file
Comment: you appear to have pasted Idea.java under Idea_Service.java
Comment: Ah, so I have! Edited, thank you.
Comment: I do not have any persistence.xml file. Do you mean the pom.xml?
Comment: You don't have a persistence.xml because you don't yet need one: Spring Boot looks after that for you, providing sensible defaults, inferring things from annotations and jars on the classpath, etc.
Comment: You're using raw types. Pay attention to your IDE's warnings about that.
Answer: CrudRepository takes two formal parameters, being the type that it manages and the type of that type's ID. Since you haven't provided these parameters, they are effectively Object and Object: the error message is pointing out that Object isn't a manageable object (it's not annotated with @Entity). You need to tell Spring Data that the class your repository is actually trying to manage is Idea. Try:
public interface Idea_Repository extends CrudRepository<Idea, Long> {
    // ..
}

Also, you don't need findAllIdeas, save or getSingleIdeaWhereId; equivalent methods are provided by Spring Data JPA for free.


Generate link to clone or duplicate a post from wordpress frontend

Question: I've found a number of plugins for wordpress that add a link to the table in the backend to clone or duplicate a post or page (Duplicate Post, Clone Post, and Post Duplicator). This is nice, but I'm building a bit of an app on wordpress where I'm using a custom post type as an entry and would like to be able to quickly copy an entry with a link from the frontend of the site (similar to how edit_post_link works but without jumping into the backend).
I'm using Gravity Forms for the create and edit functionality for entries on the frontend, but I can't quite figure out the best approach for a secure way to submit a request, execute the clone query, and the return to the same page I was on before (i.e. not jumping into the backend). Gravity Forms Post Updates plugin does something similar with a do_action call to generate a link. I've looked through this function and generally get what's happening, but I'm not sure if I need all of the extra plugin class structure.
I was hoping to find an example of a function that could create a secure url with a nonce and then another function we validate the url and execute the query and return to the previous page. Is this the right way to go or am I barking up the wrong tree? If so, any code samples or examples that might be able to help get me started?
Much appreciated!
Answer: I found this post (http://rudrastyh.com/wordpress/duplicate-post.html) and was able to figure out what I needed to. Instead of adding a filter to include the link in the backend, I instead created an action that can be called with do_action and generates the link. I also have a page and page template that is solely for executing the call and then redirecting back to the referring url.


Material Theme for Visual Studio 2019

Question: For the last years, I have used Solarized Dark and VS Color Theme Editor themes in Visual Studio 2017 and after trying Material Theme in Visual Studio Code, I wanted to use this wonderful theme in Visual Studio 2019 as well. However, there is no compatible version of Material Theme for VS2019 unfortunately. I am wondering if there is a possibility to transform this theme i.e. with the help of an export tool as Extension Manager mentioned on Use your favorite extensions with Visual Studio 2019. Or is there any theme available similar to Material Theme for Visual Studio 2019?
Answer: You can install the Color Themes for Visual Studio extension, from Microsoft DevLabs.
As of the date of this post, the extension includes a Material Dark theme, among others (refer to the GiHub Repository for more information).
NOTE: You can also customise an existing theme, using the Color Theme Editor, for VS 2017 and VS 2019.
Comment: Where we can put the xml files directly which is mentioned in the [Github Repository](https://github.com/microsoft/VS-ColorThemes/tree/master/VSColorThemes/Themes)
Answer: Check out the colour themes from Dainty for Visual Studio.
https://dainty.site/vs
You will need Node and Yarn installed to build the theme(s) you want.  Not all the themes work perfectly with VS2019 but they do have a couple of Material Themes.
Comment: The dainty is no longer maintained see [GitHub Project](https://github.com/dainty-color-theme-generator/dainty-vs)
Comment: These look great. I wonder why he makes his themes for Visual Studio Code available via the VS Marketplace, but not those for Visual Studio? Any idea?
Comment: @Max link is broken, user is gone.

Material Theme for Visual Studio 2019


Difference between charts of rcauchy(10000) and geom_function(fun = dcauchy)

Question: In R, suppose you generate $10^7$ random variates of the standard Cauchy distribution. Then you plot a histogram and density of this simulated data with the actual standard Cauchy density on top of it. For some reason, the charts don't match:
n = 10^7
tibble(cauchy_real = rcauchy(n)) %>%
  filter(cauchy_real >= -10, cauchy_real <= 10) %>%
  ggplot() +
  geom_density(aes(x = cauchy_real)) +
  geom_function(fun = dcauchy, colour = 'red') +
  geom_hline(yintercept = 1/pi)

R output:

Observations: 1. We filter the sample generated via rcauchy because it can generate some extreme outliers, and 2. We plot the horizontal bar on $y = 1/ \pi$ because, generally, in a Cauchy distribution, the peak of the distribution is at $y = 1/(\pi \gamma)$. 3. This discrepancy doesn't go away even if you increase n.
Why does this happen?
Comment: Hint: Please explain in more detail what you believe `filter` does here.  Another hint: do the same thing with, say, a Normal distribution, but filter out all values more extreme than one SD from the mean.
Comment: See what happens if you replace `geom_function(fun = dcauchy, colour = 'red')` with `geom_function(fun = (\(x)(1/(2*atan(10) + 2*x^2*atan(10)))), colour = 'red')`. The second function is the density of a truncated Cauchy distribution at $-10$ and $+10$.
Comment: @Sigma `xlim` in `ggplot` deletes observation outside of it's range. You could use `coord_cartesian(xlim = c(-10, 10))` but `geom_density` doesn't cope well with extreme range you get from 10^7 Cauchy values
Comment: Filter simply removes extreme data. In the particular case of the cauchy distribution, if you run ``rcauchy(10000)`` you get values such as -4000 which completely distort the graph. Another option is to use ``xlim(-5, 5)`` but the same thing happens.

The cauchy doesn't have a closed form for SD so you cannot really compare the two.
Comment: Your red curve should have a peak at `1/pi`  $\approx 0.32$ while your black curve should have a peak at `1/pi/(pcauchy(10)-pcauchy(-10))`  $\approx 0.34$ and that seems to be what you see
Answer: There is nothing surprising here since you're comparing a kernel density estimate based on a sample from a truncated Cauchy distribution with the theoretical pdf of an untruncated Cauchy.
If what you're trying to do is to plot a kernel density estimate based on a sample from an untruncated Cauchy over a range not including the whole sample and compare that to the theoretical pdf, this can be done straightforwardly in base R:
n <- 10^6
x <- rcauchy(n)
f <- density(x, from = -10, to = 10)
plot(f, col="red", main="")
curve(dcauchy, add=TRUE, lty=2)

From what I can tell (but I'm not an expert on tidyverse), there is no simple way to specify this range in the geom_density function in the tidyverse similar to how the to and from arguments in the density function is used in the above code.  Adding coord_cartesian(xlim = c(-10, 10)) (as suggested by @LukasLohse) and something like n = 1e+6 in the calls to geom_density and geom_function would potentially work but would make the code painfully slow and memory intensive.
Comment: You got the weird chart because the software chose a *huge* radius for the kernel and must have discretized it over *huge* bins.  I'll bet the part of the plot you drew was composed of just a few connected line segments.  But again, I think the issue raised by your question concerns what the density of a *truncated* distribution is and the code I offered shows how to compute the proper normalization factor.
Comment: This doesn't appear to address the question.  To match the OP's approach you should be plotting the truncated density, as in `x <- rcauchy(1e6);
a <- 10;
hist(x[abs(x) <= a], freq = FALSE, breaks = seq(-a, a, length.out = 100));
curve(dcauchy(x) / diff(pcauchy(c(-a, a))), add = TRUE, lwd = 2, col = "Red"); abline(h = 1/pi)` Setting `a` to smaller values ought to make the situation abundantly clear.
Comment: @Sigma Yes, I should add that the (in my mind) ugly tidyverse "solution" I propose would only sometime work.  You may need to increase `n` (the number of evaluation points of the density estimate and the theoretical pdf) to an even larger number depending on how large the difference is between the largest and smallest value in the simulated random sample.
Comment: Maybe @hadley can comment on the "proper" tidyverse way of doing this.
Comment: "Adding coord_cartesian(xlim = c(-10, 10)) (as suggested by @LukasLohse) and something like n = 1e+6 in the calls to geom_density and geom_function would work but would make the code painfully slow and memory intensive."

I tried this and actually got just a weird chart that looks nothing like the cauchy or even a density. Anyway, thanks for providing a method using base R graphics.
Answer: If it is too difficult to scale the black line you can scale the red one and the horizontal line instead. In the following code you get overlap:
n = 10^7
tibble(cauchy_real = rcauchy(n)) %>%
  filter(cauchy_real >= -10, cauchy_real <= 10) %>%
  ggplot() +
  geom_density(aes(x = cauchy_real)) +
  geom_function(fun = function(x){dcauchy(x) / (pcauchy(10) - pcauchy(-10))}, colour = 'red') +
  geom_hline(yintercept = 1/pi / (pcauchy(10) - pcauchy(-10)))


rspec testing getter and setter methods

Question: task.rb
#executor (user class) has one profile and has many tasks.

def task_name_company
  [executor.try(:profile).try(:first_name), executor.try(:profile).try(:last_name), executor.try(:profile).try(:company)].join(' ')
end

def task_name_company=(name)
  self.executor = User.joins(:profile).where("CONCAT_WS(' ', first_name, last_name, company) LIKE ?", "%#{name}%").first if name.present?
rescue ArgumentError
  self.executor = nil
end

task_spec.rb
let(:task) = { create(:task) }
let(:user) = { create(:user) }
let(:profile = { create(:profile) }

# I tested the getter like this and seems to be working
it "task_name_company getter" do
  task.executor.profile = profile
  expect(task.task_name_company).to eq("John Doe ABC Inc")
end

# I don't know how to test the setter method

it "task_name_company setter" do
end

UPDATE FOR LET VS LET!
user.rb
def decrease_new_chat_notifications
  decrement!(:new_chat_notification) if self.new_chat_notification > 0
end

def decreasing_post_notification_number(post_id)
  notifications.this_post_comments(post_id).unchecked.each do |notification|
    checking_and_decreasing_notification(notification)
  end
end

user_spec.rb
let(:user) { create(:user) }
let(:post_notification) { create(:notification, notifiable_type: "Post", recipient: user, sender: sender, checked_at: nil, notifiable_id: post.id)}

it "decrease_new_chat_notifications if greater than 0" do
  user.new_chat_notification = 1
  expect{user.decrease_new_chat_notifications}.to change{user.new_chat_notification}.by(-1)
end

it "decreasing_post_notification_number" do
  expect(user).to receive(:checking_and_decreasing_notification).with(post_notification)
  user.decreasing_post_notification_number(post.id)
end

Answer: Something like this:
describe '#task_name_company=' do
  let(:profile) { create(:profile, first_name: 'name', last_name: 'last', company: 'company') }
  let!(:user) { create(:user, profile: profile) }
  subject { create(:task) }

  it 'sets the executor' do
    subject.task_name_company = 'name last company'
    expect(subject.user).to eql user
  end
end

UPDATE to answer the let! vs let
describe '#task_name_company=' do
  let(:profile) { create(:profile, first_name: 'name', last_name: 'last', company: 'company') }
  let(:user) { create(:user, profile: profile) }
  subject { create(:task) }

  it 'sets the executor' do
    user # I'm explicitly calling user here
    subject.task_name_company = 'name last company'
    expect(subject.user).to eql user
  end
end

Comment: Ahh I tried something similar without the exclamation point. Mario, could you tell me when to use `let` and when `let!`?
Comment: The difference is that all `let!` is always evaluated, while `let` is lazily evaluated, so in the code above if you replace the `let!` with `let` then the `user` is created after the `expect(subject.user).to eql user` and your spec fails because you need the user before.
Comment: Also, see my updated answer to show the two versions
Comment: Mario, thx for the update. I asked it the wrong way. I mean I don't understand when it has to be defined before. I updated the question with 2 examples. So, why those work with `let` and why the setter only works with `let!`? Thanks a lot!
Comment: The setter could work with `let` if you explicitly call `user` before the calling that setter. When it has to be defined before? I think that it depends on your logic.
Comment: For example I'm calling an instance method in the new example on the user. As I see user has to be defined if I wanna call a method on it. Or am I mistaken?
Comment: You're not mistaken.
Answer: Something like this?
it "task_name_company setter" do
  expect(lambda {
    task.task_name_company = "blah"
  }).to  change{task.executor}.from(nil).to(user)
end

Comment: Nicholas, is this for the setter?
Comment: Yes, since you are checking that the setter actually sets the value. Your setter is `def task_name_company=(name)`, yes?
Comment: Not working :(. This method should return a user not the text.
Comment: ah, then try `user` instead of `"blah"` for the expectation? Perhaps you should investigate rspec a bit more http://rspec.info/documentation/. You need to understand exactly what you expect as output from your inputs..
Answer: I was able to get this to work like so...
expect {
 subject.total_batch_jobs = 1
}
.to change(subject, :total_batch_jobs)
.by(2)

1) expect takes a block
2) change requires an object with a message and/or a block { subject.total_batch_jobs }

rspec testing getter and setter methods


"Could not complete the operation" when trying to add an authorized network to Cloud SQL instance

Question: I'm trying to add an authorized network to our cloud sql instance, but each time I click Save I get told Could not complete the operation. That's it unfortunately, there's no explanation as to what the problem might be.
Any ideas?
Answer: Seems like it was a GCP issue. Waited a few hours and now it works.
Answer: Just in case anyone else is looking here, I found this could mean that you've reached your daily quota of cloud sql api queries. The quota starts at 100k per day and it resets at midnight pacific time.


Excel-VBA macro to transform cell content into a comment of another cell

Question: I have a seemingly simple goal to turn the content of column B into comments of column A.

I have tried using the following code from @Dy.Lee mentioned here, but unfortunately it gives me a Run-time error '1004' Application-defined or object-defined error...
Sub Komentari()
Dim rngDB As Range, rngComent As Range
Dim rng As Range
Dim cm As Comment, i As Integer
Set rngComent = Range("A1:A50")
Set rngDB = Range("B1:B50")

For Each rng In rngComent
    i = i + 1
    If Not rng.Comment Is Nothing Then
        rng.Comment.Delete
    End If
    Set cm = rng.AddComment
    With cm
        .Visible = False
        .Text Text:=rngDB(i).value
    End With
Next rng
End Sub

Can somebody, please, spot the mistake or suggest a better solution for this?
Comment: Try `.Text Text:=rngDB(i).text` to make sure it's a string?
Comment: on which line is the error?
Comment: @QHarr - error is on  .Text Text:=rngDB(i).value
Answer: I'd go this way (explanations in comments):
Public Sub Komentari()
    Dim rng As Range

    With Range("A1:A50") ' reference comments range
        .ClearComments ' clear its comments
        For Each rng In .Offset(, 1).SpecialCells(xlCellTypeConstants) ' loop through refrenced range adjacent not empty cells
            With rng.Offset(, -1).AddComment ' add comment to current rng corresponding comment range cell
                .Visible = False
                .Text rng.Value2
            End With
        Next
    End With
End Sub

Answer: Sub Komentari()
Dim rngDB As Range, rngComent As Range
Dim rng As Range
Dim cm As Comment, i As Integer
Set rngComent = Range("A1:A50")

For Each rng In rngComent
    i = i + 1
    If Not rng.Range("B1").Comment Is Nothing Then
        rng.Range("B1").Comment.Delete
    End If
    rng.Range("B1").AddComment (rng.Text)
Next rng
End Sub

Answer: Something like the following where you can use Offset to get the adjacent range, you drop the = when adding the text value to the comment, test that there is actually a value present first as well, and ensure you state the sheet to avoid implicit Activesheet reference.
Option Explicit
Public Sub Komentari()
    Dim rngComent As Range
    Dim rng As Range, cm As Comment

    With ThisWorkbook.Worksheets("Sheet1")
        Set rngComent = .Range("A1:A50")
        For Each rng In rngComent
            If Not rng.Comment Is Nothing Then
                rng.Comment.Delete
            End If
            Set cm = rng.AddComment
            With cm
                .Visible = False
                If rng.Offset(, 1) <> vbNullString Then .Text rng.Offset(0, 1).Value
            End With
        Next
    End With
End Sub

Rather than add blank comments you could also flip this round to:
Option Explicit
Public Sub Komentari()
    Dim rngComent As Range
    Dim rng As Range, cm As Comment

    With ThisWorkbook.Worksheets("Sheet1")
        Set rngComent = .Range("A1:A50")
        For Each rng In rngComent
            If Not rng.Comment Is Nothing Then
                rng.Comment.Delete
            End If

            If rng.Offset(, 1) <> vbNullString Then
                Set cm = rng.AddComment
                With cm
                    .Visible = False
                    .Text rng.Offset(0, 1).Value
                End With
            End If
        Next
    End With
End Sub


Filtrar Dataset a partir de um groupby

Question: Tenho o seguinte dataframe (df_reviews) e preciso remover as versões do App que foram baixadas menos que 10 vezes e tentei fazer os passos abaixo e um for para realizar o filtro no dataset original, mas não obtive exito
Abaixo coloquei o passo-a-passo do meu caminho...

Pelo "App Version Name" fiz um filtro para avaliar quantas vezes cada versão foi baixada:
App_version = df_reviews.groupby('App Version Name').agg({'Star Rating': ['mean', 'min', 'max', 'count']})
E o resultado foi o seguinte:

Após isso criei uma condição para limpar o df_reviews, onde a versão com menos que 10 downloads devia ser dropada do df:
condicao1 = df_reviews['App Version Name'].value_counts() < 10

E para filtrar o df_reviews, fiz um for para remover as linhas cujo a versão possui menos de 10 downloads, mas o for não está dando certo.
for i in range (0, df_reviews.shape[0]):#buscando em linha por linha
    if df_reviews.at[i, "App Version Name"] == condicao1:#serve para acessar o label
        df_reviews['Teste1'] = df_reviews['Teste1'].append(condicao1.loc[[i]])```

Comment: Tente `df_reviews[df_reviews['App Version Name'].isin(condicao1[condicao1 == False].index)]`. Isso escolhe os nomes que estão entre os que são False em condicao1.
Comment: Deu certo! Muito obrigado (E muito mais prático)
Answer: Tente
df_reviews[df_reviews['App Version Name'].isin(condicao1[condicao1 == False].index)]
Isso escolhe os nomes que estão entre os que são False em condicao1. – Jorge Mendes 1 hora atrás
por Jorge Mendes: https://pt.stackoverflow.com/users/150167/jorge-mendes

Filtrar Dataset a partir de um groupby


equivalent of docker option --config in docker-compose

Question: I'm trying to run mongo with docker-compose. From the docker mongo page I have the following command
$> docker run --name some-mongo -v /my/custom:/etc/mongo -d mongo --config /etc/mongo/mongod.conf

version: '3'
services:
  db:
    image: mongo:4
    ports:
      - "27017:27017"
    volumes:
      - ./storage/mongo:/data/db:rw

Now I would also like to define the mongod.conf; --config /etc/mongo/mongod.conf but how can you do that inside docker-compose?
Answer: The --config is part of mongo, not docker. You may still use it with docker-compose like
docker-compose run db --config /etc/mongo/mongod.conf

Answer: You can use command
services:
  db:
    image: mongo:4
    command: "mongo --config /etc/mongo/mongod.conf"
    ports:
      - "27017:27017"
    volumes:
      - ./storage/mongo:/data/db:rw


Using Cauchy's Theorem/ Cauchy's Integral Formula for Higher Derivatives or otherwise, evaluate, with justification, the following integrals:

Question: $$\int \frac{5 \cos(\pi z)}{(z+3i)(z-7i)}dz$$
i) where γ is the circle centre 0 and radius 4;
ii)γ is the circle centre 0 and radius 10
For part i) I have calculated using CIF that because z=-3i is only valid in γ that f(z)=(5cos(πz))/(z-7i) and so
$$\int \frac{5 \cos(\pi z)}{(z+3i)}dz =-\pi \cos(-3\pi i)$$
However for part ii) because both $z=-3i$ and $ z=7i$ are valid in γ I do not know what to set as my f(z).
Answer: Hint: if you want use Cauchy (using residues is better), do a partial fraction decomposition of $5/(z+3i)(z−7i)$.
Comment: why is the cos(πz) not included in this partial fraction decomposition?
Answer: You can either split your contour in 2, or use partial fractions.
If $\gamma_1$ is the right half side of the contour, $\gamma_2$ is the left half side, and $\gamma_3$ is vertically bisecting the contour, we see $$\oint _{\gamma} \frac{5cos(\pi z)}{(z+3i)(z-7i)} = \oint_{\gamma_1+\gamma_3}\frac{\frac{5cos(\pi z)}{z+3i}}{z-7i}+ \oint_{\gamma_2-\gamma_3} \frac{\frac{5cos(\pi z)}{z-7i}}{z+3i} $$ Evaluating both component integrals thru Cauchy Integral Formula gives $$2\pi i (\frac{5cos(\pi 7i)}{7i+3i})+ 2\pi i(\frac{5cos(-\pi 3i)}{-3i-7i})= \pi cos (\pi 7i) - \pi cos (-\pi 3i)$$ and simplify. This is essentially the residue theorem using CIF.
You could also just decompose into partial fractions and solve using the same contour, but that's more complicated.

Using Cauchy’s Theorem/ Cauchy’s Integral Formula for Higher Derivatives or otherwise, evaluate, with justification, the following integrals:


Iannis Xenakis' Artistic Aesthetic and Public Perception

Question: Did Iannis Xenakis write any music with intentions beyond absolute music?  For example, music paired with other forms of art?
For example, Terretektorh (diagram pictured below) illustrates that Xenakis indicates for the piece to be played within and amongst the audience.  Would anyone be able to elaborate on this piece or suggest any others?  Here is a performance of Terretektorh.

Since everyone can perceive music differently, my question is not only about how musicians interpret a composer's intentions, but also how composers expect the public to perceive their work.
It would be helpful is someone could provide any specific stylistic ideas Xenakis had about his (or some of his) music.
EDIT: The question is intended to make emphasis in Xenakis' expectations as how the public consumes some of his compositions. In Terrektorh he expects the public to be around the musicians but ultimately it can be seen as a request for the musicians to be inside the public. Incidentally the public will be around the musicians. I would be interested to see if he made some demands or suggestions that are specific to how the public should consume some music of his. A ridiculous example: Ask the public to listen to this music while taking breakfast, or something like that.
Another request he could have made that is not very specific to the musicians performing the piece is if Xenakis asks certain composition to be listened while looking at certain painting, or some sculpture, any other form of art going beyond the music. It might probably be interesting if examples are given from other composers but I was interested specifically if Xenakis did this sort of requests.
Comment: This is very interesting! I'm not totally sure what is being asked here beyond detailed information about [Xenakis's catalogue](http://en.wikipedia.org/wiki/List_of_compositions_by_Iannis_Xenakis), which isn't really a great question. Perhaps the scope could be broadened a bit to apply to composers and composition in general?
Comment: @jjmusicnotes  One would hope the educated answers were legally permissible (illicit -- elicit) :-).  Signed, your local musical grammar nitpicker.
Comment: @NReilingh  good point.  Consider, for example, Vaclav Nelhybel / Antiphonale for Brass Sextet and Band.   As to audience expectation, I fear that will lead to flame wars about when to applaud and similar topics :-) .
Comment: @NReilingh - I find this question to be fairly broad as it is.  The question speaks more to public perception and the composer's artistic aesthetic than a pure catalog analysis. That said I think the question is also specific enough to illicit some good, educated answers (I plan on answering myself at some point :) ) without dissent into opinionated discussion.
Comment: @jjmusicnotes It's possible that my difficulty is purely mechanical--the question should probably be edited at least for grammar and wording.
Comment: @CarlWitthoft Excellent! Care to have a go at the question above with the community edit function? `:-)`
Comment: @CarlWitthoft - haha, yes, very astute - I realized my error after I posted my comment, but for some reason was unable to edit it, and I was too lazy to delete and re-type the comment. :)  That said, a case could be made for my syntax as Xenakis was an interesting fellow...
Comment: In my question I intended to make some emphasis in Xenakis' expectations as how the public consumes some of his compositions. In Terrektorh he expects the public to be around the musicians but ultimately it can be seen as a request for the musicians to be inside the public. Incidentally the public will be around the musicians. I would be interested to see if he made some demands or suggestions that are specific to how the public should consume some music of his. I don't remember if I gave some ridiculous example, like ask the public tolisten tothismusicwhiletakingbreakfast,orsomethinglikethat.
Comment: Another request he could have made that is not very specific to the musicians performing the piece could be if Xenakis asks certain composition to be listened while looking at certain painting, or some sculpture, any other form of art going beyond the music. It might probably be interesting if examples are given from other composers but I was interested specifically if Xenakis did this sort of requests. I went recently to a conference about Xenakis and Math but didn't get to ask this question to the experts on Xenakis. (A not-musician-mathematician -->)
Comment: What? The musicians in that performance are not scattered among the audience. How can that be authentic? Furthermore, since when does Ricky Martin conduct? :)
Comment: It is true there are a few people outside, but if you look carefully you can see there is some public among the musicians. For example at 1:01 you can see them.
Answer: Did Xenakis compose music intended for settings where other art forms were an integral part? Certainly. Look up Polytope de Cluny and Persépolis for a start (8 track electroacoustic works with light show).
The question of his intentions is thorny and I do not wish to speculate about them. However, you can find in Formalized Music a description of Duel, a kind of game where two conductors compete against one another. Is that a concept beyond absolute music? Probably one can argue that it is.
Xenakis' famous description of a political demonstration with a crowd shouting slogans, ending with a brutal confrontation, which you can find in the first pages of Formalized Music, clearly relates to his use of stochastic principles of organization in his compositions. Does that make them program music? Not necessarily.


How to fix "The Method[] was called on null"

Question: I was trying to make a class for scanning barcodes with "fast_qr_reader_view: ^0.1.5" dependencies. But when I call this class on my main.dart this error came out "NoSuchMethodError: The method[] was called on null.Receiver:null. Tried calling:"
I already tried writing on the main.dart and works, but when Im calling it from a different class doesn't work
This is my code that shows me the error main.dart
import 'package:flutter/material.dart';
import 'RegistroTrajetaOCedulaWidget.dart';
import 'package:pay_id/Screens/testScan.dart';
import 'Screens/dashboard.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scan();
  }
}

testScan.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:fast_qr_reader_view/fast_qr_reader_view.dart';
import 'package:lamp/lamp.dart';

List<CameraDescription> cameras;

Future<Null> main() async {
  // Fetch the available cameras before initializing the app.
  try {
    cameras = await availableCameras();
  } on QRReaderException catch (e) {
    logError(e.code, e.description);
  }
  runApp(new Scan());
}

void logError(String code, String message) =>
    print('Error: $code\nError Message: $message');

class Scan extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<Scan> with SingleTickerProviderStateMixin {
  QRReaderController controller;
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  AnimationController animationController;

  @override
  void initState() {
    super.initState();

    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 3),
    );

    animationController.addListener(() {
      this.setState(() {});
    });
    animationController.forward();
    verticalPosition = Tween<double>(begin: 0.0, end: 300.0).animate(
        CurvedAnimation(parent: animationController, curve: Curves.linear))
      ..addStatusListener((state) {
        if (state == AnimationStatus.completed) {
          animationController.reverse();
        } else if (state == AnimationStatus.dismissed) {
          animationController.forward();
        }
      });

    // pick the first available camera
    onNewCameraSelected(cameras[0]);
  }

  Animation<double> verticalPosition;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: const Text('Prueba escaner'),
      ),
      floatingActionButton: FloatingActionButton(
        child: new Icon(Icons.check),
        onPressed: () {
          Lamp.turnOn();
        },
      ),
      body: Stack(
        children: <Widget>[
          new Container(
            child: new Padding(
              padding: const EdgeInsets.all(0.0),
              child: new Center(
                child: _cameraPreviewWidget(),
              ),
            ),
          ),
          Center(
            child: Stack(
              children: <Widget>[
                SizedBox(
                  height: 300.0,
                  width: 300.0,
                  child: Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.red, width: 2.0)),
                  ),
                ),
                Positioned(
                  top: verticalPosition.value,
                  child: Container(
                    width: 300.0,
                    height: 2.0,
                    color: Colors.red,
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// Display the preview from the camera (or a message if the preview is not available).
  Widget _cameraPreviewWidget() {
    if (controller == null || !controller.value.isInitialized) {
      return const Text(
        'No camera selected',
        style: const TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
        ),
      );
    } else {
      return new AspectRatio(
        aspectRatio: controller.value.aspectRatio,
        child: new QRReaderPreview(controller),
      );
    }
  }

  void onCodeRead(dynamic value) {
    showInSnackBar(value.toString());
    // ... do something
    // wait 5 seconds then start scanning again.
    new Future.delayed(const Duration(seconds: 5), controller.startScanning);
  }

  void onNewCameraSelected(CameraDescription cameraDescription) async {
    if (controller != null) {
      await controller.dispose();
    }
    controller = new QRReaderController(cameraDescription,
        ResolutionPreset.high, [CodeFormat.qr, CodeFormat.pdf417], onCodeRead);

    // If the controller is updated then update the UI.
    controller.addListener(() {
      if (mounted) setState(() {});
      if (controller.value.hasError) {
        showInSnackBar('Camera error ${controller.value.errorDescription}');
      }
    });

    try {
      await controller.initialize();
    } on QRReaderException catch (e) {
      logError(e.code, e.description);
      showInSnackBar('Error: ${e.code}\n${e.description}');
    }

    if (mounted) {
      setState(() {});
      controller.startScanning();
    }
  }

  void showInSnackBar(String message) {
    _scaffoldKey.currentState
        .showSnackBar(new SnackBar(content: new Text(message)));
  }
}

Answer: cameras did not init
you can init cameras in testScan.dart directly
_asyncMethod() async {
    cameras = await availableCameras();
    onNewCameraSelected(cameras[0]);
    print('camera ${cameras.length}');
  }

  @override
  void initState() {
    super.initState();
    ...
    _asyncMethod();
  }

demo for init cameras in testScan.dart directly

fulll test demo for testScan.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:fast_qr_reader_view/fast_qr_reader_view.dart';
import 'package:lamp/lamp.dart';

List<CameraDescription> cameras;

/*Future<Null> main() async {
  // Fetch the available cameras before initializing the app.
  try {
    cameras = await availableCameras();
  } on QRReaderException catch (e) {
    logError(e.code, e.description);
  }
  runApp(new Scan());
}*/

void logError(String code, String message) =>
    print('Error: $code\nError Message: $message');

class Scan extends StatefulWidget {
  @override
  _ScanState createState() => new _ScanState();
}

class _ScanState extends State<Scan> with SingleTickerProviderStateMixin {
  QRReaderController controller;
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  AnimationController animationController;

  _asyncMethod() async {
    cameras = await availableCameras();
    onNewCameraSelected(cameras[0]);
    print('camera ${cameras.length}');
  }

  @override
  void initState() {
    super.initState();

    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 3),
    );

    animationController.addListener(() {
      this.setState(() {});
    });
    animationController.forward();
    verticalPosition = Tween<double>(begin: 0.0, end: 300.0).animate(
        CurvedAnimation(parent: animationController, curve: Curves.linear))
      ..addStatusListener((state) {
        if (state == AnimationStatus.completed) {
          animationController.reverse();
        } else if (state == AnimationStatus.dismissed) {
          animationController.forward();
        }
      });

    // pick the first available camera
    _asyncMethod();
  }

  Animation<double> verticalPosition;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: const Text('Prueba escaner'),
      ),
      floatingActionButton: FloatingActionButton(
        child: new Icon(Icons.check),
        onPressed: () {
          Lamp.turnOn();
        },
      ),
      body: Stack(
        children: <Widget>[
          new Container(
            child: new Padding(
              padding: const EdgeInsets.all(0.0),
              child: new Center(
                child: _cameraPreviewWidget(),
              ),
            ),
          ),
          Center(
            child: Stack(
              children: <Widget>[
                SizedBox(
                  height: 300.0,
                  width: 300.0,
                  child: Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.red, width: 2.0)),
                  ),
                ),
                Positioned(
                  top: verticalPosition.value,
                  child: Container(
                    width: 300.0,
                    height: 2.0,
                    color: Colors.red,
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// Display the preview from the camera (or a message if the preview is not available).
  Widget _cameraPreviewWidget() {
    if (controller == null || !controller.value.isInitialized) {
      return const Text(
        'No camera selected',
        style: const TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
        ),
      );
    } else {
      return new AspectRatio(
        aspectRatio: controller.value.aspectRatio,
        child: new QRReaderPreview(controller),
      );
    }
  }

  void onCodeRead(dynamic value) {
    showInSnackBar(value.toString());
    // ... do something
    // wait 5 seconds then start scanning again.
    new Future.delayed(const Duration(seconds: 5), controller.startScanning);
  }

  void onNewCameraSelected(CameraDescription cameraDescription) async {
    if (controller != null) {
      await controller.dispose();
    }
    controller = new QRReaderController(cameraDescription,
        ResolutionPreset.high, [CodeFormat.qr, CodeFormat.pdf417], onCodeRead);

    // If the controller is updated then update the UI.
    controller.addListener(() {
      if (mounted) setState(() {});
      if (controller.value.hasError) {
        showInSnackBar('Camera error ${controller.value.errorDescription}');
      }
    });

    try {
      await controller.initialize();
    } on QRReaderException catch (e) {
      logError(e.code, e.description);
      showInSnackBar('Error: ${e.code}\n${e.description}');
    }

    if (mounted) {
      setState(() {});
      controller.startScanning();
    }
  }

  void showInSnackBar(String message) {
    _scaffoldKey.currentState
        .showSnackBar(new SnackBar(content: new Text(message)));
  }
}


Importance of placement of accents for chords (Chopin mazurka, op 59, no 3)

Question: Consider the placement of accents for chords that are split between the bass and treble (Chopin Mazurka op. 59, no 3, bar 34) :

and bar 101:

I suddenly became unsure if the accent for the second case (bar 101) is only for the treble chord (Ciss octave) and not to be played for the b in the bass?
Answer: Typesetters add modifying symbols such as stress marks, dots, staccato's etc. per voice or staff, not per system. So in your second example, the accent mark is only applying to the right hand octave.
Comment: Thanks! This seems like a reasonable assumption. So for the case of bar 34, the accent applies to both staffs? But if it instead was moved below the bass staff, it would only apply to the bass?
Comment: From a musical point of view, I would only put emphasis on the right hand in bar 34. It's the upper F# that's important, as it is being tied to the next measure. All other notes on this last beat are on the non emphatic part of the cadence. Also, based on the context of the following measures, you see a pattern of stressed third beats in the melody (the upper notes of the right hand), but not in the accompaniment. I'm not sure why the editor put the accent mark between the two staves, but it seems to belong to the upper F#.


Existence of a set function

Question: Consider the set S of all subsets of {1, 2, 3, 4}. Show that there exists a function h : S → [0, 1] that satisfies all following conditions:
Condition 1: h(∅) = 0
Condition 2: h({1, 2, 3, 4}) = 1
Condition 3: h(·) is monotone, i.e. that for all A ∈ S and B ∈ S such that A ⊆ B, h(A) ≤ h(B)
Condition 4: h(·) is submodular, i.e. that for all A ∈ S and B ∈ S, h(A ∪ B) ≤ h(A) + h(B) − h(A ∩ B)
Condition 5: h(·) respects the following form of symmetry.
h({1}) = h({2}) = h({3}) = h({4}) , h({1, 2}) = h({3, 4}) , h({1, 4}) = h({2, 3}) , h({1, 3}) = h({2, 4}) , h({1, 2, 3}) = h({1, 3, 4}) = h({1, 2, 4}) = h({2, 3, 4}).
Condition 6: h({1, 3}) > h({1, 4})
Any tips would be greatly appreciated. This is a critical part of my entrance into a Ph.D. program (not a Math Ph.D. program).
Comment: The symmetry conditions in condition 5 implies that there are only $5$ degrees of freedom when choosing your function. Have you tried simply to write down the inequalities between the 5 function values that come from conditions 3 and 4 and look for a solution to those?
Comment: Thanks for the tips. Working on this now. @HenningMakholm
Answer: Let $h(\emptyset)=0$, $h(A)=\frac 12$ if $|A|=1$ or $A=\{1,4\}$ or $A=\{2,3\}$, $h(A)=1$ otherwise.
Then conditions 1, 2, 3, 5 are met. To check condition 4 for $A\not\subseteq B$ and $B\not\subseteq A$, verify that $h(A\cap B)= \frac12$ can only occur if one of $h(A)$, $h(B)$ equals $1$, and $h(A\cap B)=1$ can only occur if $h(A)=h(B)=1$.
Comment: Thanks, I do have one additional question. How is condition 6 accounted for in this solution?

Existence of a set function


Geometric sequences; partial sums with sum notation going from n=1 to infinity.

Question:
Possible Duplicate:
Value of $\sum\limits_n x^n$

I have been working on this problem for awhile and have made efforts to try to resolve it. The question is:
$$\sum_{n=1}^\infty 7(0.1)^{n−1}$$
Comment: thank you for responding, but i was asking if anyone knows how to find the partial sum of this expression.
Comment: I don't see any question, but a formula!
Answer: For the "partial sum", I assume you meant
$\sum_{n=1}^k 7(0.1)^{n−1}$ for any positive integer $k$.
Taking the $7$ out of the sum, and shifting the exponent,
we get
$7\sum_{n=0}^{k-1} 0.1^n$.
All this needs now is the standard formula
$\sum_{n=0}^{k-1} x^n = (x^k-1)/(x-1) = (1-x^k)/(1-x)$.
Putting $x = 0.1$,
$\sum_{n=0}^{k-1} 0.1^n = (1-0.1^k)/0.9$.


Can this setup cause frequently occurring WiFi packet loss?

Question: a couple of weeks ago we've had a company install four access points and perform the initial setup. We asked to have three different WiFis, one for our primary work devices, one for our personal devices and a third one for guests. Three of those access points are on one side of the building and the fourth is on the other side where we have a single meeting room. They installed the APs and did the initial config, then gave us the admin credentials for the config UI.
For the past two weeks we've had individual complaints of "slow WiFi" or "Confluence not responding" until we had people run ping 184.108.40.206 throughout the day. We quickly discovered how the observed problems coincides with their machines suffering from packet loss, e.g.
87 packets transmitted, 48 packets received, 44.8% packet loss
round-trip min/avg/max/stddev = 19.603/93.004/459.626/84.396 ms

Please note that at one point I was sitting right next to an affected colleague while my connection was fine. At that time were connected via different channels, so we had a look at the output of /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s:
            SSID BSSID             RSSI CHANNEL HT CC SECURITY (auth/unicast/group)
       NeighborD 74:67:xx:xx:fe:50 -83  13      Y  DE WPA2(PSK,FT-PSK/AES/AES)
 WiFi 3 (Guests) dc:08:xx:xx:2b:eb -64  60      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 1 dc:08:xx:xx:2b:ea -63  60      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 2 dc:08:xx:xx:2b:e9 -62  60      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
 WiFi 3 (Guests) dc:08:xx:xx:69:8b -47  60      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 2 dc:08:xx:xx:69:8a -47  60      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 1 dc:08:xx:xx:69:89 -47  60      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
       NeighborD 74:67:xx:xx:22:00 -91  136,-1  Y  DE WPA2(PSK,FT-PSK/AES/AES)
       NeighborA 00:1a:xx:xx:2c:9b -89  132,+1  Y  DE NONE
       NeighborB 5c:49:xx:xx:8b:0d -73  124     Y  DE WPA2(PSK/AES/AES)
       NeighborA 00:1a:xx:xx:2c:93 -72  11      Y  DE NONE
          WiFi 1 dc:08:xx:xx:2b:e2 -56  11      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
 WiFi 3 (Guests) dc:08:xx:xx:2b:e3 -57  11      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 2 dc:08:xx:xx:2b:e1 -57  11      Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 1 dc:08:xx:xx:73:c2 -80  6       Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
 WiFi 3 (Guests) dc:08:xx:xx:69:83 -50  6       Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 2 dc:08:xx:xx:69:82 -50  6       Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 1 dc:08:xx:xx:69:81 -50  6       Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
       NeighborC cc:ce:xx:xx:d8:48 -81  1       Y  DE WPA2(PSK/AES/AES)
  NeighborC Gast ce:ce:xx:xx:d8:49 -82  36      Y  DE WPA2(PSK/AES/AES)
       NeighborC c8:0e:xx:xx:c4:1b -77  36      Y  DE WPA2(PSK/AES/AES)
       NeighborC cc:ce:xx:xx:d8:49 -82  36      Y  DE WPA2(PSK/AES/AES)
  NeighborC Gast ca:0e:xx:xx:c4:1b -77  36      Y  DE WPA2(PSK/AES/AES)
 WiFi 3 (Guests) dc:08:xx:xx:2b:f3 -67  149     Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 1 dc:08:xx:xx:2b:f2 -67  149     Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 2 dc:08:xx:xx:2b:f1 -66  149     Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
 WiFi 3 (Guests) dc:08:xx:xx:69:93 -47  100     Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 2 dc:08:xx:xx:69:92 -47  100     Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)
          WiFi 1 dc:08:xx:xx:69:91 -47  100     Y  US WPA(PSK/AES,TKIP/TKIP) WPA2(PSK,FT-PSK/AES,TKIP/TKIP)

This tells me that two APs are using channel 60 and might therefor create interference among the different APs. Unfortunately we've also received complaints for channel 100 so I'm guessing WiFi 1, WiFi 2 and WiFi 3 also shouldn't share channels... Is that correct? Any input is welcome!
Comment: Are your 3 "Wifi's" (actually WLANs) available on each of the four access points?
Comment: Yes, they are centrally configured with the master AP (one of the four) and then all four of them use the same WLAN SSID and password.
Answer: Always setup access points in a way so the channels are as much apart as they can be. If two access points are working on the same channel the client with worse antenna (like a cell phone or just different laptop) might want to try to switch over from one AP to another and back again which will cause significant packet loss or even disconnections for a brief period of time.
From you log I see that you have two AP's on channel 60 which is not good. Switch any of them to a different channel - ideally that's not being used by other AP's (not just yours). For example you can use channel 116.
Another thing is channel width - do you use 20,40,80 MHz wide channels ?
Have a look at 5 GHz channel table here to understand better how to they work.
And here's even more to help you. These are the best practices for setting up a good performing wi-fi network.
Depending on hardware you use you can do a spectrum scan to tell you what is the least used channel. Mikrotik, Ubiquiti and some other devices have this feature ready for use.


How to set up a ptr record to allow my ip for sending email?

Question: I'm trying to set up a raspberrypi 4 as a mail server.
Since I own a domain name using a provider (gandi.net), I use this domain name for my mail server (with mx records, redirection to the raspberry, etc.)
Using the tutorial of Makeuseof, I did configure the pi to send mail. But the thing is, when I try to send a mail to, for example, my gmail account, I receive the error :
IP you're using to send 550-5.7.1 mail is not authorized to send email directly to our servers.
I have read other posts about it, so I went to https://check.spamhaus.org/ and tried to allow my IP address to be removed from the ban list (which I'm still waiting for).
But another solution that I've seen is to set a ptr record, redirecting my IP address back to my domain name.
For that, I've installed dnsmask, and I've set a redirection in my /etc/hosts file, by adding this line :
2001:0db8:85a3:0000:0000:8a2e:0370:7334       mail.example.com.
For obvious reason, those are not the actual address that I'm using, but the principle is here, and yes, I'm hosting everything under my ipv6 address.
So my question is : will this manipulation work, redirecting my ipv6 address toward the domain name, and is the ptr record settled correctly? Or is there another way to convince google servers that my mails are send using my domain name?
Thanks by advance for those who will read this.
Comment: Check your SPF record first to see which host names or IP addresses are authorized to send out mails from your domain.
Answer: You can't really "fake" reverse DNS.
For the internet at large to be able to query reverse DNS records, PTR records, the applicable Reverse DNS records must be configured by the owner of the IP-address range from which your  IP-address (range) is allocated.
Some providers will delegate control of reverse DNS records to their users via DNS when requested,
others provide a control panel where the current users of an IP-address (range) can configure their preferred records (usually a sanity check is performed to confirm that a forward A/AAAA record exists and points to your IP-address before your custom FQDN is assigned as the PTR record)
and others don't support that at all.

Note that that particular error message is not about missing/incorrect reverse DNS though:
See https://support.google.com/a/answer/3726730 & https://support.google.com/mail/answer/10336

The IP you're using to send email is not authorized...'
...
In order to prevent spam, Gmail refuses mail from IP addresses that are not authorized to send mail. The determination of whether or not an IP address is authorized to send mail is made by the ISP that provides you with the IP address. This list typically contains consumer IP ranges offered for dialup, DSL, or other broadband access.
What can I do to fix this?
Your ISP may provide SMTP relays which will accept mail from your IP, and these servers should be authorized to send mail. Some ISPs may provide a way to get an IP that is authorized, either by upgrading to business class service or static IP service. You should reach out to your ISP to see what options are available.
Another alternative is to send mail through your own domain's servers (that use a different IP-address)  ...
Answer: No, changes made locally using dnsmask or /etc/hosts are not affecting the PTR record for the IP address globally, so anyone including the Google servers won't see it. The PTR records has to be configured in the reverse zone for the reverse .in-addr.arpa. zone for IPv4 or .ip6.arpa. zone for IPv6, e.g.,

For 198.51.100.1, 100.51.198.in-addr.arpa.

For 2001:DB8::1, 18.104.22.168.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. IN PTR.

These zones are controlled by the owner of the IP block; typically the ISP. Contact them to see whether it is possible to configure the PTR record to match your HELO hostname. If it is not, you could always change the hostname advertised in the HELO command to match with the current reverse name.
Comment: In addition to that, I'd also make sure that for the name in the PTR record there exits an A record pointing to that IP address. If it doesn't exist, some servers may still reject the mail. Only the owner of the domain in the PTR record can fix this. Also, various public anti-spam blocklists block certain ranges of IP addresses, and it's ISP who must contact a black list maintainer to exclude it from the range. Ow, I meant Spamhaus... chances are, the OP *has* to contact the ISP.