C pthread_barrier synchronization issues

Question: I'm new to learning about pthread_barriers and how they work. Basically I have two arrays and two threads, one thread finds the max of array A and another finds the min of array B and stores them in global variables. They need to synchronize right before they make a trade (the max of A is passed to B and the min of B is passed to A) so that array B has all higher values than A - almost like a sorting problem, if you will. I keep getting wildly incorrect results and I'm sure I'm missing something simple;
I initialize the barrier with
  pthread_barrier_t bar;
  pthread_barrier_init( &bar, NULL, 2);

The thread code for A
void *minimize_a( void *arg )
int i;
int size_a = *((int *) arg);  // first location is count of values
int *a = ((int *) arg) + 1;   // a[] will be array of values
while(1){
   i = index_of_max( a, size_a );
   max = a[i];                      // offer max for trade
   pthread_barrier_wait( &bar );
   if( max <= min ) return NULL;    // test to end trading rounds
   a[i] = min;                      // trade
}

The thread code for B
  void *maximize_b( void *arg )
  int i;
  int size_b = *((int *) arg);  // first location is count of values
  int *b = ((int *) arg) + 1;   // b[] will be array of values
while(1){
   i = index_of_min( b, size_b );
   min = b[i];                      // new min found
   pthread_barrier_wait( &bar );
   if( max <= min ) return NULL;    // test to end trading rounds
   b[i] = max;                      // trade
 }

If I'm correct in understanding, once both threads hit pthread_barrier_wait, they will have successfuly synchronized and can keep continuing, correct? I always get crazy results like the following:
Before
a: 1, 3, 5, 6, 7, 8, 9
b: 2, 4
After
a: 0, 0, 0, 0, 0, 0, 0
b: 2, 4
The values array
int values[] = {       // format of each set of values:
                     //   count of value n, then n integer values
  7, 1,3,5,6,7,8,9,  // this set of values starts at index 0
  2, 2,4,            // starts at index 8
  5, 1,3,5,7,9,      // starts at index 11
  5, 0,2,4,6,8       // starts at index 17
}

How the threads are made
rc = pthread_create( &threads[0], NULL, &minimize_a, (void *) &values[0] );
if( rc ){ printf( "** could not create m_a thread\n" ); exit( -1 ); }

rc = pthread_create( &threads[1], NULL, &maximize_b, (void *) &values[8] );
if( rc ){ printf( "** could not create m_b thread\n" ); exit( -1 ); }

Any tips, suggestions, or help please?
Comment: Can you show how you start the threads and how you declare the arrays ?
Comment: Yes they have been added to the question.
Comment: I assume `index_of_max` doesn't to anything (i.e. write) to the arrays ? You could very carefully add some printing at every step when a swap is done.
Answer: You need additional synchronization for accessing the shared variables min and max.
After reaching the barrier, the minimize_a thread reads a value from min.  Meanwhile the maximize_b thread is going to proceed to write a new value into min.  There is nothing to guarantee that the value in min will be read before maximize_b replaces it with a new value.  Try another pthread_barrier_wait at the end of each while loop.


Is it okay to use PhP include() in body of basic page?

Question: Aside from the usual warnings about using PhP, which I understand and am taking seriously, is there any drawback to using the PhP include() function in the "Body" box of the "Edit Basic page" form?
This is not for users of the site. This is only for me, the creator of the site. No one else will have permission to use PhP code on the site.
The reason I want to do this is as follows: I'm revamping an ASP site into Drupal. I have a page that builds its contents from a large amount of data drawn from a database (which I've imported from Access into MySQL). I'm going to translate the Javascript of the ASP page into PhP to do this in Drupal. But I'm getting tired of working in that little and unintelligent "Body" box in the "Edit Basic page" form. If I just put an include() in that box, then I can work on the PhP code in a file in NotePad++. Then every time I save a change to that file, I can test the effect by just refreshing the page.
Any reason not to work that way?
Comment: I am not sure why you would translate JavaScript to PHP when Drupal uses JavaScript too.
Comment: I think there is already a question about why using the PHP filter is a bad practice, which answers this question too.
Comment: @kiamlaluno - This is really interesting. After I got two really helpful answers, you disabled answering because you deem the question not susceptible to being properly answered. Then you add a comment with some additional helpful information for me that I didn't know. In any case, I'm really glad you waited until after AyeshK and tunic posted their answers before you disabled answering.
Comment: @kiamlaluno - You think there is such a question? I did a search before posting my question. If my question is redundant with an answered question, could you please post a link to it?
Comment: This question is too broad, even if you get two answers. I don't get why you worry about using PHP in a node body, when you will be the only one accessing the site.
Comment: I won't be the only one accessing the site. I'm the only one who will have access to develop that page.
Answer: In reply to your reply in the comments, I thought to post an answer instead.
There are many reasons why it's not OK to embed executable code where we expect to have actual content. This is not Drupal specific. It's not even PHP specific (this one on JS for example).
Since you indicate you are comfortable writing PHP code, why not create a new module instead, and put your code (that you expect to put in the Body) inside the module? You'll be taking a big step in the Drupal learning curve too. It's not that hard to write a simple module!
As for Drupal, the reason is because your PHP code is interpreted very lately, or sometimes, it will not be executed at all. PHP code is executed from the PHP Filter, which is only run when you output the code with this filters processed. You can easily break your PHP snippet:

Run some Rules on the Body content (such as a string match). Rules will match the raw PHP content: Not what you expect it to be.
Email: Modules such as Notifications, Mime Mail can apply different filters on your content (other than PHP Filter), which will make the email content will contain the raw PHP content.
Views: Filter rewrite features will process and output your raw PHP content.

Other than the above, you are making your core logic not controllable by version control systems we have (git for example). It's always easy to keep them in mind, but once you are done with the site and move on, your Neurons do funny things and forget the fact that you have some core logic embed somewhere (is it node 134, 314 or 420?) in the field_data_body.body_value column.
When it's barely acceptable to use PHP in the database?
Admittedly, there are some situations that we have to use some small PHP snippet here are there to save time creating whole new plugins.
Views: Views contextual filters support evaluating some PHP snippet to validate contextual filters.
Rule: Rules conditions and actions have "Execute PHP" as an action/condition.
I think above two cases are barely acceptable cases that you can use some PHP. This is because you are supposed to put some PHP code there, and the parent code that evaluates the PHP snippet is well aware that it contains some PHP code. If a field description says "Do not use ", that means the field is aware that the input contains some PHP.
Modules are safe?
To address your comment to this question, you can use PHP in the module because, well, that is where you code your logic. A malicious snippet is equally harmful regardless where you put it. But when you have it in a module, you can turn it off, other developers know that you put custom code here, and it can be versioned.
Modules are the basic logic behind the entire site. Nodes, user accounts, taxonomy, menu, blocks, they all are modules themselves. Your custom module is equally good enough to implement same hooks.
You can only put PHP code where you are asked (Views execute PHP fields, Node content, etc). But with a module, you become your own god that you can implement any hook you want, and have a far wider access to the system.
Comment: Thank you for the detailed mind transfer! You've given me some persuasive reasons that my approach is wrong. I've been telling myself not to allow myself to delay getting the sites up by getting distracted with developing modules. You've got me reconsidering that. I'm going to take a look and see what it might mean when you say "not too hard to write a simple module." In the meantime, can you say, why is it okay to have PhP in a module and not in the "Body" box? (I feel like that's got to be a stupid question, but I guess I'm just still that stupid on Drupal.)
Comment: Please see updated answer.
Comment: Would your warnings about putting PHP code on a page also apply to putting PHP code in a custom token inserted in a page by the modules "Custom tokens" and "Token filter"? "Custom tokens" does not evaluate PHP in its tokens, but passes the PHP directly to the page via "Token filter" so the page has to use a text filter that allows PHP code. Is that dangerous? Does it depend on whether the token are just little snippets or longer chunks of code?
Comment: I'm not sure I understand your question. But if your `PHP Filter` (which executes the PHP) is executed after token replacements, then it's good as other PHP code.
Also, I don't see a reason to use tokens inside PHP. In most cases, the stuff that you want to use are available as PHP variables (`$node`, `$argument`, `$view`, `$row`, etc are some examples).
Comment: First thing I'm using this for is links between sites in multi-site setup. In development, I need the links to go to local URL. Online, the links have to go to online URLs. My local URLs look like "http://site1.local", "http://site2.local", etc. With custom tokens, I was able to enter links to site1 on the other sites using a token whose content is . This solved a huge problem that was easy in my ASP pages, but I didn't know how to do in Drupal -- until now. Is ok?
Comment: Well, you could easily build links and URLs with `l()` and `url()` functions. So much easier than tinkering with tokens.
Answer: I assume that you only want to debug a certain code, so you exeute the code inside the node only temporary. I think for that task is much better to just edit the code in your favorite editor wrapped in a function and then call it inside a /devel/php page.
For example:
function my_code() {

   // Experimental code here.
}

Then goto /devel/php with Devel module enabled and complete the textarea with:
my_experimental_code();

You can edit your code and go to the browser window and push 'Execute'. You can use dpm() function to show data on the screen. See results, then modifiy your code and then you only have to go to the browser again and just click 'Execute' again.
Comment: Oh boy, in addition to not wanting to get into writing modules right away, I've also been carefully avoid downloading any modules until I really understand why I need them. Looks like I need to make this the first module I download. (If I could accept more than one answer, I'd accept this one as well. Thank you for your help.)
Comment: I wish you good luck, @NewSites on your first module. There are some modules, such as the Devel module, that can help you i your journey. Also look at the examples module (http://drupal.org/project/examples) for some decent code to inspire.
Comment: Drupal is modular, you almost always need to download modules to extend funcitonality. In fact is recommended to use a ctrontibuted module instead of writting your own (because a contrib module is more tested than own code). About answers: you can't accept two answers but you can upvote any answer if the answer is useful.


How to analyze relationship between data pairs

Question: Please change the title if it's not accurate, I might be lacking terminology.
I have two variables ($x,y$) which are directly correlated by pair. For example I have sampled 50 trees in my study area and for each tree I have tree height and annual precipitation at that location. This is what I mean by they are organized by pair. So I plot $x$ vs $y$ and I would like to know if there is any correlation between the two; does annual precipitation predict tree height, or the other way around?
I have used R to test if there is any linear correlation with the function lm(y~x) and have $p<.05$ and $R^2=0.6$, but some of my data seem as if they might be better fitted with a non-linear curve. What are some other types of statistical analysis I should use for such a problem?
Comment: You ask, "does annual precipitation predict tree height, or the other way around?" Do you want to learn the causal relationship between the two variables, or just predict one from the other?
Comment: You have separate and long-term precipitation measurements by every tree? That is very impressive data.
Comment: What does the graph plot(x,y) look like? Can you post it here?
Comment: @rnso I have different graphs for several species, some look somewhat linear, others aren't linear at all. http://postimg.org/image/ny2eoidmb/
http://postimg.org/image/n9tk5kewj/
Comment: @LizzieSilver that's a very good point, at this stage I am just exploring any relationship between the two and then I will leave the biological interpretation to someone else.
Answer: Kernel regression and smoothing splines will both fit non-linear regression functions very nicely. There's a longer list of methods, with examples, in this R-bloggers post by Wesley.
Answer: To visualize nonlinear data, try:
library(ggplot2)
ggplot(rndf, aes(x=vnum1, y=vnum2, group=vbin1, color=vbin1))+stat_smooth()

Where vnum1 and vnum2 are your x and y and vbin1 is the species or other grouping column.

Different options can be set in stat_smooth() function.
The shaded areas indicate 95% CI. Overlapping areas would indicate non-significant difference.
Comment: You may be overinterpreting the overlapping areas: after all, overlapping 95% CIs can occur even among highly significant differences. But why are you recommending these plots? How does this set of plots answer the stated question?
Comment: thanks I have tried that but how do I determine if there is anything statistially significant?
Comment: I have added a note regarding visualization of significant difference. I am not sure about calculations.
Comment: @ whuber: I am suggesting these plots only for an overview of data which may be non-linear. I thought if 95% CI are overlapping, the p value will be >0.05 i.e. not significant difference. But my experience is nowhere compared to yours. Please suggest me some links to refer to or explain briefly.
Comment: There seem to be a lot of posts on our site about overlapping confidence intervals: http://stats.stackexchange.com/search?q=overlapping+confidence+interval.
Answer: Rank correlation coefficients such as Kendall's or Spearman's can be useful to measure the strength of non-linear monotonic relationships, i.e. those that are increasing or decreasing, but not e.g. U-shaped. Calculating confidence intervals for their population values is often considered more useful than simply testing whether they're equal to zero.
If you want to predict tree height from precipitation (or vice versa) there are many approaches (see @Lizzie's links). The most basic extension of simple linear regression is simply to represent the predictor $x$ as a polynomial & estimate a coefficient $\beta_k$ for each term $k$:
$$\operatorname{E}Y =\beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3 + ...$$
where $\operatorname{E}Y$ is the predicted response. With just one predictor you might use F-tests to see how many terms are necessary (too many compared to the number of observations & you'll over-fit the model to the sample data).
Comment: The one variable is $x$ above; you can represent it with more than one term - linear, quadratic, cubic &c. - in the model equation. I'd suggest reading an introductory textbook on regression - [Faraway (2002), *Practical Regression & ANOVA Using R*](http://cran.r-project.org/doc/contrib/Faraway-PRA.pdf) might be useful, as you're using R.
Comment: Thanks for the suggestion, I am not sure how I can have a polynomial when I only have one variable that I am trying to correlate with what i am trying to predict.


Kalman filter and Box-Cox

Question: I'm interested in wind forecasting, which I have analyzed over some time by means of ARMA methods. Now I've being reading about Kalman filtering. Kalman filter is optimal when Gaussian assumption can be hold. However, wind distributions are far from normal (with Weibull the most popular). My question is, Is it correct to transform a wind speed time series by means of Box-Cox transformation before estimating the parameters of Kalman filter, so that the normality assumption holds? If it were so, why then using particle filters?
Answer: Box-Cox transformation is most often used to address non-constant variance. It doesn't convert non-Gaussian noise to Gaussian generally.
Kalman filter's a very convenient and fast method of estimation of state-space models (SSM) when the errors are Gaussian, and the models are linear. There are other ways of estimating SSM though. If you wish to venture beyond ARMA, then I would suggest reading about SSM in general, not just Kalman filters. The good book on SMM is Shumway and Stoffer, it has its own R package with code and examples. The non-gaussian estimation is in section 6.10 of 2nd edition. I didn't read the 3rd edition yet.
They have a follow up book on nonlinear modeling.

Kalman filter and Box-Cox


nginx redirect www to non-www not working over https, only over http

Question: ✅ http://example.com https://example.com
✅ http://www.example.com https://example.com
✅ https://example.com https://example.com
❌ https://www.example.com https://example.com - The site loads, but I just want the www gone.
server {
    server_name example.com;
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    }

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    }

    listen 80;
    server_name www.example.com example.com;
    return 404;

}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    }

    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

I have two A records pointing to my IP, nothing else.
♂
Comment: Great that you were able to figure it out. But please post your solution as an answer and accept it instead of editing it into your question, otherwise the question will stay as "unsolved" in the system forever.
Answer: Solved it, my last two blocks were wrong:
server {
    listen 80;
    server_name www.example.ai example.ai;
    return 301 https://example.ai$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.ai/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.ai/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    server_name www.example.ai;
    return 301 https://example.ai$request_uri;
}


Are equations with products of uninterpreted functions unsolvable in Z3

Question: The following code
(declare-fun f (Int) Real)
(declare-fun g (Int) Real)
(declare-const x Int)
(declare-const y Int)
(assert (= (* (f x) (g y)) 1.0))
(check-sat)
(get-model)

returns "unknown", even though there is an obvious solution. Eliminating arguments to f and g (effectively making them constants?) results in "sat" with expected assignments. I guess, my question is: what is special about arithmetic with uninterpreted functions?
BTW, replacing * with + also results in "sat", so the issue is not about uninterpreted functions, per se, but about how they are combined.
Additional thoughts
Making the domain (very) finite does not help, e.g.,
(declare-fun f (Bool) Real)
(declare-fun g (Bool) Real)
(declare-const x Bool)
(declare-const y Bool)
(assert (= (* (f x) (g y)) 1.0))
(check-sat)
(get-model)

returns "unknown". This is odd given that f:Bool->Real is essentially just two variables f(False) and f(True) (of course, the solver has to recognize this).
Inability to handle non-linear arithmetic over real-valued uninterpreted functions is a very severe limitation because arrays are implemented as uninterpreted functions. So, for example,
(declare-const a (Array Int Real))
(assert (= (* (select a 1) (select a 1)) 1))
(check-sat)
(get-model)

returns "unknown". In other words, any non-linear algebraic expression on real array elements involving multiplication is unsolvable:'(
Answer: It's the non-liearity introduced by the multiplication that makes the problem hard to solve, not the uninterpreted functions. In fact, you can ask the solvers why by using the get-info command:
(set-logic QF_UFNIRA)
(declare-fun f (Int) Real)
(declare-fun g (Int) Real)
(declare-const x Int)
(declare-const y Int)
(assert (= (* (f x) (g y)) 1.0))
(check-sat)
(get-info :reason-unknown)

Here're some responses I got from various solvers:
Z3:
(:reason-unknown smt tactic failed to show goal to be sat/unsat (incomplete (theory arithmetic)))

CVC4:
(:reason-unknown incomplete)

MathSAT:
(error "sat, but with non-linear terms")

So, as the solvers themselves improve and start handling more nonliear arithmetic, you might get models eventually. But, in general, nonlinear problems will always be problematic as they are undecidable when integers are involved. (Since you can code Diophantine equations using non-linear terms.)
See also How does Z3 handle non-linear integer arithmetic? for a relevant discussion from 2012.
Removing uninterpreted functions
Even if you get rid of the uninterpreted functions, you'd still be in the unknown land, so long as you mix Int and Real types and non-linear terms:
(set-logic QF_NIRA)
(declare-const f Real)
(declare-const g Real)
(declare-const x Int)
(declare-const y Int)
(assert (= (+ (* f g) (to_real (+ x y))) 1.0))
(check-sat)
(get-info :reason-unknown)

Z3 says:
(:reason-unknown "smt tactic failed to show goal to be sat/unsat (incomplete (theory arithmetic))")

So, the issue would arise with mixed types and non-linear terms.
Comment: It seems the uniterpreted functions must have something to do with "unknown" since replacing them with constants returns "sat".
Comment: Did you still mix `Int` and `Real`? If all your types are `Real`, I can see that, but if you mix `Int` and `Real` and introduce non-linear terms, I'm sure the solver will be `unknown` land pretty quickly. See my updated answer for an example.
Comment: Good point about mixing `Int` and `Real`. It looks like uninterpreted functions with domain and range `Int` can be solved for in non-linear expressions.
Comment: Quite right. However, there's hope. While there will never be a complete solver for such problems due to fundamental undecidability issues, solvers do get better in time. It wouldn't surprise me if Z3 or some other solver handled these sorts of combinations that arise in practice quite efficiently as they improve their heuristics and algorithms.


How to center an image related to bootstrap and css

Question: I am trying to center an image but after some attempts I could not make it work properly. Apparently the changes I am doing are not taking effect. The image code is the below

Shane de Abreu

Since I am newbie I don't know which file should I apply changes and after inspecting the element I realized that it was related to CSS (style.css) and Bootstrap (bootstrap.css). So I tried adding W3S recommended code to those files, the one I let below.
img {
    display: block;
    margin: auto;
}

The problem is that I did not know where exactly I had to place it, so I made some attempts, but I got no success. I tried changing the team-grid settings below
}
.team-grid{
    position:relative;
    overflow: hidden;
}

Also, tried by changing the team-grid1 settings
.team-grid1,.team-grid2{
    margin-bottom:20px;
}

Also tried changing the img settings (style.css file)
img {
    width: 100%;
}

And tried changing the img settings (bootstrap.css file)
img {
  vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
  display: block;
  max-width: 100%;
  height: auto;

}

I don't know if I should place the W3S recommended code (bootstrap or style) cause apparently one is ruling over the other, but I don't know which is. Can Someone help me to center this image? It is located at www.arquetiposhane.tk site.
Many thanks!
Answer: use below code this will make your image center
.team-grid{
  margin: 0 auto;
  float: none;
}


Validating a Checkbox in a datagrid C#

Question: I have an unbound datagrid that has two columns that are defined as checkboxes.
What I'm trying to accomplish is performing validation when a user clicks on any column that appears in the delete column. In some instances I don't want the user to be able to delete certain records.
While working on this, I discovered that neither the CellValidating or CellValueChanged methods are getting called each time I click in a cell in the Delete column.
I've read similar questions but I have yet to find exactly what I'm trying to accomplish.
Thank you in advance for your time and effort in answering my question.

var checkBox = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
            var isCheck = checkBox?.Value;
            var check = isCheck == null ? false : bool.Parse(isCheck.ToString());

            if (isCheck != null)
                checkBox.Value = !check;        // change checkbox value

            if (!check) // if value was false, it's being changed to true
            {
                string sShipToId = dataGridView1.Rows[e.RowIndex].Cells[(int)ColumnHeaders.ShipToIDColumn].Value.ToString();
                string sDelete = dataGridView1.Rows[e.RowIndex].Cells[(int)ColumnHeaders.DeleteColumn].Value.ToString();

                // need to check to see if this ship to is associated with an open order. if it is
                // we can't delete it. This mimics the functionality that P21 exhibits when you try to delete
                // a ship to from the Ship To Maintenance screen.
                // we also need to check and see if we're deleting the Ship to associated with the  current order.

                ShipToInfo Ship = new ShipToInfo(Server, Database);

                if ((string.IsNullOrEmpty(sShipTo) == false) &&
                        (sShipToId.Equals(sShipTo) == true) ||
                        (Ship.ShipToExistsInOpenOrder(sShipToId, CompanyID) == true))
                {
                    MessageBox.Show("Open orders exist for this Ship To " + sShipToId + ". It cannot be deleted.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    dataGridView1_CellContentClick(null, new DataGridViewCellEventArgs(e.ColumnIndex, e.RowIndex));
                }
            }

Answer: Add an event for Checked in the checkbox, and apply your logic there.
https://www.dotnetperls.com/checkbox-wpf
Answer: You can use the CellContentClick event to work with Checkboxes in DataGridView. I dynamically created the DataGridView object MyDataGridView. You can do it using designer as well. I am not sure how you want to use the value of the CheckBox but if you use it you should change its value manually in CellContentClick event as it is below.
private DataGridView MyDataGridView = new DataGridView();

public Form1()
{
    InitializeComponent();
    SetupDataGridView();
}

private void SetupDataGridView()
{
    this.Controls.Add(MyDataGridView);
    MyDataGridView.ColumnCount = 2;

    MyDataGridView.Name = "MyDataGridView";
    MyDataGridView.Location = new Point(10, 10);
    MyDataGridView.Size = new Size(500, 300);

    MyDataGridView.Columns[0].Name = "ID";
    MyDataGridView.Columns[1].Name = "Value";

    MyDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Default" });
    MyDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Delete" });

    MyDataGridView.Rows.Add("1", "one", true, true);
    MyDataGridView.Rows.Add("2", "two", false, true);
    MyDataGridView.Rows.Add("3", "three", true, false);

    MyDataGridView.CellContentClick += MyDataGridView_CellContentClick;
}

private void MyDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    // get value of checkbox
    var checkBox = MyDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
    var isCheck = checkBox?.Value;
    var check = isCheck == null ? false : bool.Parse(isCheck.ToString());

    if (isCheck != null)
        checkBox.Value = !check;        // change checkbox value

    if (e.ColumnIndex == 3 && check)
    {
        DialogResult dialogResult = MessageBox.Show("Are you Sure",
            "Delete Row", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            MyDataGridView.Rows.RemoveAt(e.RowIndex);
        }
    }
}

Comment: Thank you for the code. It seems to do what I want it to do. The only additional question I have is I want to uncheck the checkbox programmatically. Since this isn't a validation function can I return a value that will cause .Net to uncheck the checkbox or do I have to do that myself ?
Comment: @L.Levine You can easily uncheck the checkbox programmatically. One of the quickest solutions is to call the event handler manually. For example, call this `MyDataGridView_CellContentClick(null, new DataGridViewCellEventArgs(2, 0));` Here `2` is the `ColumnIndex` and `0` is the `RowIndex`
Comment: Worked like a charm. Thanks !
Comment: Turns out I was premature in my stating that this worked. While CellContentClickgets called again, the checkbox isn't being unchecked even though checkBox.Value is being set to false.
Comment: Calling this method is equivalent of checking/unchecking the checkbox by hand. Pay attention to the used indexes. or give me the specific example when it does not work.
Comment: test it using a button: `private void button1_Click(object sender, EventArgs e){MyDataGridView_CellContentClick(null, new DataGridViewCellEventArgs(2, 0));}`
Comment: The situation where it doesn't work is when the user selects a cell in the Delete column and I want to uncheck the cell because the row fails "validation".

Validating a Checkbox in a datagrid C#


Python3 tkinter error

Question: boa noite,
A ideia deste codigo é inserir uma imagem numa interface gráfica
porem esta sempre a dar o erro e diz que não consegue abrir a imagem
Alguem sabe pk isso esta a acontecer?
este é o meu código
class janela:
   def __init__(self,master=None): #master refere se ha janela principal
     #criaçao do conteiner pai
     self.frame=Frame(master)
     self.frame.pack()
     self.photo=PhotoImage(file='imagem.png')

root = Tk()
root.geometry('800x600')
janela(root)
root.mainloop()

Answer: O erro acontece porque não há atribuição para o atributo photo da classe janela, ele simplesmente é chamado a primeira vez em self.photo(file='imagem.png').
Para adicionar uma imagem com tkinter, um dos modos possíveis é:
from tkinter import *
from PIL import ImageTk,Image

class janela:
   def __init__(self,master=None): #master refere se ha janela principal
     #criaçao do conteiner pai
     self.frame=Frame(master)
     self.frame.pack()
     photo = ImageTk.PhotoImage(Image.open("imagem.png"))
     self.label = Label(image=photo)
     self.label.photo = photo  # necessário para manter referência
     self.label.pack()

if __name__ == '__main__':
    root = Tk()
    root.geometry('800x600')
    janela(root)
    root.mainloop()

Comentários sobre a solução:

Utilizar a PIL (Python Imaging Library) para trabalhar com uma imagem em formato .png e salvar isso em uma variável photo;
Colocar essa variável photo em algum componente, aqui optou-se por uma label;
Salvar uma referência extra da imagem;
E por fim, não acredito que seja a solução mais bonita, mas alcança o objetivo de apresentar uma imagem :)

Para mais informações, inclusive do porque é necessário manter referência para a imagem, recomendo a leitura.

Python3 tkinter error


If $\liminf z_n = 0$, then there is a null sequence $(y_n)$ such that $\sum y_n = \infty$ and $\liminf y_n/z_n = 0$

Question:
Let $(z_n)$ be a sequence in $(0, \infty)$ with $\liminf z_n = 0$. Show that there are null sequence $(y_n)$ in $(0,\infty)$ such that $\sum y_n = \infty$ and $\liminf y_n/z_n = 0$.

There is a hint told me to construct $(y_n)$ as follows: choose a convergent subsequence $(z_{n_k}) \to 0$. Set
$$
y_{n_k} = z_{n_k}^2 \text{ for all } k \in \mathbb{N}, \quad y_n = 1/n \text{ otherwise}
$$
$(y_k)$ clearly is null and safisfies $\liminf y_n/z_n = 0$. My question is, is $(z_{n_k}) \to 0$ enough to conclude $\sum y_n = \infty$? Since there are instances that can make the sequence converges under this construction (e.g. $z_k = k^{-2}$ and pick subsequence $(z_{k})$ where $k \neq 2^n$ for any $n$), how do we ensure the existence?
Comment: What happened to $z_n?$ You have it in the first line and then it disappears.
Comment: It should be fixed now.
Comment: By the way, your title is incoherent, and disserves your question... can you repair it?
Comment: No idea on how should I change the title better, paste the question instead.
Comment: Sorry, what are you trying to prove the existence of? Im a bit confused by the last sentence "how do we ensure the existence"
Comment: Sorry that I didn't write it clear, what I ask is why we can ensure that at least 1 subsequence of $(z_n)$ can make $\sum y_n$ diverge, it isn't that clear from the hint.
Comment: Ah ok I understand!
Answer: You're right, the hint seems incomplete. You might try this: Start with the subsequence $z_{n_k}\to 0.$ We then divide $n_k$ into the two subsequences $n_{2k}$ and $n_{2k+1}.$ For $n\in \{n_{2k}\},$ do as you did and set $y_{n_{2k}}= z_{n_{2k}}^2.$ For $n\in \{n_{2k+1}\},$ set $y_{n_{2k+1}}= 1/k.$ For all other $n,$ if any, set $y_n=1/n.$
Comment: That should do it. Thanks!
Answer: What one can do is slighty change the definition of $y_n$. First consider a subsequence of $(z_n)$ convergent to zero. Let $(z_{n_k})$ be that subsequence. Now consider the set of indices $A=\{n_{2k} \mid  k >0\}$ and define the complementary set of indices $B=\{n>0\mid n\notin A\}$. $B$ is an infinite set, since $\{n_{2k-1} \mid  k >0\} \subseteq B$. Now set:
$$y_n=\begin{cases} z_n^2 & n \in A\\\dfrac{1}{\operatorname{card}(\{1,2,\dots n\}\cap B)} & n\in B\end{cases} $$


I can't debug my program in intellij idea CE

Question: Disconnected from the target VM, address: '127.0.0.1:39989', transport: 'socket' on intellij idea CE. I can't debug my program. Any suggestions?
Connected to the target VM, address: '127.0.0.1:39989', transport: 'socket'
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
17/12/29 17:29:47 INFO SparkContext: Running Spark version 2.1.2
17/12/29 17:29:49 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/12/29 17:29:49 WARN Utils: Your hostname, ashfaq-VirtualBox resolves to a loopback address: 127.0.1.1; using 10.0.2.15 instead (on interface enp0s3)
17/12/29 17:29:49 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
17/12/29 17:29:49 INFO SecurityManager: Changing view acls to: ashfaq
17/12/29 17:29:49 INFO SecurityManager: Changing modify acls to: ashfaq
17/12/29 17:29:49 INFO SecurityManager: Changing view acls groups to:
17/12/29 17:29:49 INFO SecurityManager: Changing modify acls groups to:
17/12/29 17:29:49 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(ashfaq); groups with view permissions: Set(); users  with modify permissions: Set(ashfaq); groups with modify permissions: Set()
17/12/29 17:29:51 INFO Utils: Successfully started service 'sparkDriver' on port 46133.
17/12/29 17:29:51 INFO SparkEnv: Registering MapOutputTracker
17/12/29 17:29:51 INFO SparkEnv: Registering BlockManagerMaster
17/12/29 17:29:51 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
17/12/29 17:29:51 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
17/12/29 17:29:51 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-b3b48105-28be-4781-a395-c7e83cc72e8c
17/12/29 17:29:51 INFO MemoryStore: MemoryStore started with capacity 393.1 MB
17/12/29 17:29:51 INFO SparkEnv: Registering OutputCommitCoordinator
17/12/29 17:29:53 INFO Utils: Successfully started service 'SparkUI' on port 4040.
17/12/29 17:29:53 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://10.0.2.15:4040
17/12/29 17:29:53 INFO Executor: Starting executor ID driver on host localhost
17/12/29 17:29:54 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 33583.
17/12/29 17:29:54 INFO NettyBlockTransferService: Server created on 10.0.2.15:33583
17/12/29 17:29:54 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
17/12/29 17:29:54 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 10.0.2.15, 33583, None)
17/12/29 17:29:54 INFO BlockManagerMasterEndpoint: Registering block manager 10.0.2.15:33583 with 393.1 MB RAM, BlockManagerId(driver, 10.0.2.15, 33583, None)
17/12/29 17:29:54 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 10.0.2.15, 33583, None)
17/12/29 17:29:54 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, 10.0.2.15, 33583, None)
17/12/29 17:29:58 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 236.5 KB, free 392.8 MB)
17/12/29 17:29:58 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 22.9 KB, free 392.8 MB)
17/12/29 17:29:58 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on 10.0.2.15:33583 (size: 22.9 KB, free: 393.1 MB)
17/12/29 17:29:59 INFO SparkContext: Created broadcast 0 from textFile at scalaApp.scala:13
Exception in thread "main" org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/home/ashfaq/Desktop/saclaAPP/data/UserPurchaseHistory.csv
    at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:287)
    at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:229)
    at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:315)
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:202)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1968)
    at org.apache.spark.rdd.RDD.count(RDD.scala:1158)
    at ScalaApp$.main(scalaApp.scala:18)
    at ScalaApp.main(scalaApp.scala)
17/12/29 17:29:59 INFO SparkContext: Invoking stop() from shutdown hook
17/12/29 17:29:59 INFO SparkUI: Stopped Spark web UI at http://10.0.2.15:4040
17/12/29 17:29:59 INFO BlockManagerInfo: Removed broadcast_0_piece0 on 10.0.2.15:33583 in memory (size: 22.9 KB, free: 393.1 MB)
17/12/29 17:29:59 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
17/12/29 17:30:00 INFO MemoryStore: MemoryStore cleared
17/12/29 17:30:00 INFO BlockManager: BlockManager stopped
17/12/29 17:30:00 INFO BlockManagerMaster: BlockManagerMaster stopped
17/12/29 17:30:00 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
17/12/29 17:30:00 INFO SparkContext: Successfully stopped SparkContext
17/12/29 17:30:00 INFO ShutdownHookManager: Shutdown hook called
Disconnected from the target VM, address: '127.0.0.1:39989', transport: 'socket'
17/12/29 17:30:00 INFO ShutdownHookManager: Deleting directory /tmp/spark-58667739-7c15-4665-8ede-fde9c3ff1d83

Process finished with exit code 1

Comment: check if your VM has an IP and if it is the good one. if no, turn off and turn on (not a restart, you need to shutdown the machine)
Answer: It looks like, you are trying to open a file which doesn't exist. The fisrt line of the error message says so:
Exception in thread "main" org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/home/ashfaq/Desktop/saclaAPP/data/UserPurchaseHistory.csv


How to make summary of body searchable?

Question: I've already looked at this answer and tried to change the search index view so that when I ran a search, I could type in a word appearing in a summary it would appear in my search results. I also ran cron to get the site reindexed but still, nothing appears when I type in a word that only appears in a summary.
How do I make the summaries in content searchable?
Answer: I did not figure out to do this, but a workaround was to actually make a separate field called summary and remove the default body and add a new body field without a summary.

How to make summary of body searchable?


High Performance

Question: I have a requirement to refer to a set of columns in a DB and update these columns. Since this set of columns is common/ shared across multiple parallel transactions, how do I achieve a good performance without compromising on data integrity and consistency. To provide more clarity, I have a long transaction, wherein, I do some pre-processing and compute certain values. I then compare this value against the limit. The limit is the common/ shared column, which I have to update, if I am proceeding further with the transaction. The application will have multiple users, who will try to perform a similar operation and have to compare against the same 'Limit' and proceed further.
Comment: What is `Limit` - some sort of index? Could you use a hilo optimiser?
Comment: May be more suitable for programmers....
Comment: Most databases do not support parallel transactions to the same tables.  I suggest you reconsider your design if you need transactions to work concurrently.
Answer: If I understand you correctly, the limit works like a sort of semaphore. Accessing the semaphore should not be part of the normal transaction. You want to increase the limit immediately, and if you fail you would like to abort the transaction.
A way of acheiving this is to run the limit increase as a sub-transaction. If you are using transaction demarcation you can use TransactionAttributeType.html#REQUIRES_NEW.
If you want a more detailed answer, please clarify you question somewhat.

High Performance


How to retrieve the specific value from Dictionary(key,value) in c#

Question: This is my method:
///
/// Uses Dictionary(Key,Value) where key is the property and value is the field name.
/// Matches the dictionary of mandatory fields with object properties
/// and checks whether the current object has values in it or
/// not.
///
/// <param name="mandatoryFields">List of string - properties</param>
/// <param name="o">object of the current class</
/// <param name="message">holds the message for end user to display</param>
/// <returns>The name of the property</returns>
public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder  message)
{
    message = new StringBuilder();
    if(mandatoryFields !=null && mandatoryFields.Count>0)
    {
        var sourceType = o.GetType();
        var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static);
        for (var i = 0; i < properties.Length; i++)
        {
            if (mandatoryFields.Keys.Contains(properties[i].Name))
            {
                if (string.IsNullOrEmpty( properties[i].GetValue(o, null).ToString()))
                {
                    message.AppendLine(string.Format("{0} name is blank.", mandatoryFields.Values));
                }
            }
        }
        if(message.ToString().Trim().Length>0)
        {
            return false;
        }
    }
    return true;
}

In this I have params Dictionary which will hold the property name of the class and its corresponding fieldname from the UI(manually fed by developer in the business layer or UI).
So what I want is that when the property is on the way to validate, if the property is found null or blank, then its corresponding fieldname, which is actually the value of the dictionary will get added to the stringbuilder message in the method above.
I hope i am clear.
Comment: Any reason not to use classes in System.ComponentModel.DataAnnotations ?
Answer: Do the loop the other way:
public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder  message)
{
    message = new StringBuilder();
    if(mandatoryFields == null || mandatoryFields.Count == 0)
    {
        return true;
    }

    var sourceType = o.GetType();
    foreach (var mandatoryField in mandatoryFields) {
        var property = sourceType.GetProperty(mandatoryField.Key, BindingFlags.Public | BindingFlags.Static);
        if (property == null) {
            continue;
        }

        if (string.IsNullOrEmpty(property.GetValue(o, null).ToString()))
        {
            message.AppendLine(string.Format("{0} name is blank.", mandatoryField.Value));
        }
    }

    return message.ToString().Trim().Length == 0;
}

This way you iterate over the properties you want to check, so you always have a handle on the "current" property and know the corresponding key and value from the dictionary.
The snippet
if (property == null) {
    continue;
}

causes the function to treat properties that exist as names in the dictionary but not as actual properties on the type to be treated as valid, to mirror what your original code does.
Comment: need help on this http://stackoverflow.com/questions/7542793/how-to-get-the-type-of-a-property-using-switch-case-in-c


How many clusters for linear mixed models and GEE?

Question: I have a data set with repeated measurements on subjects. The total sample size is $n=118$ and the number of clusters (i.e. subjects) is $m=49$. The smallest cluster is of size 2 and the largest cluster is of size 4. In fact, about 60% of the clusters are of size 2, i.e. only two observations per subject. The outcome variable is continuous and there are 5 covariates of interest.
My plan is to fit a linear mixed model (LMM) with a random subject effect, i.e. a random intercept term. If the normality assumption of the residuals should not be satisfied and transformations do not solve the issue, I would then use GEE with identity link (i.e. a marginal model) to model the data since it does not require the normality assumption.
However, before embarking on this adventure, I had some concerns about the asymptotic propoerties of the LMMs and GEEs. I know that for GEE the asymptotic behaviours depends on the number of clusters $m$ (e.g. Li and McKeague, Statistica Sinica, 2013).
Are there any guidelines/recommendations of the number of clusters $m$, the number of observations $n$ and the minimum/maximum cluster size for the two methods?
Answer: Recommendations for the number of groups and units per group are good at the study design phase. At this point in your research, you can only hope to produce decent estimates with the data that you have at hand, and that's probably the literature that you should be studying, and questions that you should be asking.
Behavior of the GEEs are asymptotic in $m$, so the more the merrier. I would say that $m=50$ is a moderate sample size (Teerenstra et. al. (2010) give references, behind the paid walls, that in turn say that sample sizes of less than $m=40$ clusters are insufficient); $m=200$ will probably be large enough for approximately symmetric data (not necessarily large enough for low proportions like single digit %, or badly overdispersed count data), while $m=10$ will be too small to really trust asymptotics.
Hox (1998) suggests the number of groups to be $m \ge 50$, and group sizes, $n/m \ge 20$, for asymptotics of the mixed models (which social scientists call multilevel models) to work well. (Think of this recommendation as a modest size educational study: enough classrooms/teachers with 20 students per class.) Maas and Hox (2005) updated these recommendations and studied smaller $m$, down to $m=10$, but they never thought of dropping the number of units in the group anywhere below 5. Some studies with low number of units per group are coming from Bell, Ferron and Kromrey (2008, 2010), although they concentrated on proportion of singletons (groups of size 1) rather than the size per se.
Comment: I agree that these questions should be asked at the study design stage. Unfortunately, as usual, the statistician was only consulted after the data was collected. Thank you for the references. Do you have any references for the GEE results?
Comment: I am less familiar with biostat literature. I updated with just one reference for what I found with a moderate amount of googling.
Comment: is there any R library that can compute the appropriate sample size based on my data? I found "longpower" in CRAN but it is only for linear model and I need to compute it for count data (e.,g., negative bionomial).


Scala Universal Serializer PlayFramework

Question: I want to make universal JSON Serializer of different my own list types(i.e. Group, GroupView, GroupItemsView). So, I define all three Json.Format
  implicit val groupsFormat = Json.format[Group]
  implicit val groupsViewFormat = Json.format[GroupView]
  implicit val groupsItemsViewFormat = Json.format[GroupItemsView]

My function that should serialize different list items:
  def groupViewToJson(entityList: List[Any]): JsValue = {
    val jsonList = Json.toJson(
      entityList.map( m => Json.toJson(m))
    )
    jsonList
  }

It only works when for for the entityList I define particular List Type. It doesn't want to work with Any type. The error as follows:
No Json serializer found for type Any. Try to implement an implicit Writes or Format for this type.

How to make PlayFramework Scala JSON Serializer to work with my type universally?
Answer: The implicits need to be resolved at compile time. Thus, your function needs to provide the right Writes implicit to the function during compilation. You can do that by using type parameter and accepting an implicit:
def groupViewToJson[T](entityList: List[T])(implicit writer:Writes[T]): JsValue = {
    val jsonList = Json.toJson(
      entityList.map( m => Json.toJson(m))
    )
    jsonList
  }

And when calling groupViewToJson, the implicit needs to be in scope. A complete example would be:
import play.api.libs.json._
case class Group(name:String)
case class GroupView(name:String, group: Group)

implicit val groupsFormat = Json.format[Group]
implicit val groupsViewFormat = Json.format[GroupView]
//implicit val groupsItemsViewFormat = Json.format[GroupItemsView]

def groupViewToJson[T](entityList: List[T])(implicit writer:Writes[T]): JsValue = {
    val jsonList = Json.toJson(
      entityList.map( m => Json.toJson(m))
    )
    jsonList
  }

scala> val group = Group("MyGroup")
group: Group = Group(MyGroup)

scala> val groupView = GroupView("MyGroupView", group)
groupView: GroupView = GroupView(MyGroupView,Group(MyGroup))

scala> groupViewToJson(groupView :: Nil)
res4: play.api.libs.json.JsValue = [{"name":"MyGroupView","group":{"name":"MyGroup"}}]

Comment: Also, please note that Json already provides a writer for Lists, given that you have the writer for the case class, so unless you plan on adding more functionality to your groupViewToJson function, you can use it instead.
Comment: Thanks it solves my problem! I completely forgot about type parameterization.


Wildcard certificate for internal server

Question: My company sells application servers to customers; 90% of thoses servers are offline  in dedicated network.
We currently have a self signed certificate generated automatically according to the ip of the server.
Will it be possible to buy a wildcard certificate and use it on all the servers locally ?
Let's say we buy a certificate for *.mydomain.com (mydomain.com will be a real domain that we own). The certificate is installed on the servers. And on the local network we have a dns (or a modified host file) that map the servers's ip to a subdomain .
Will it be ok ? We just need to avoid the big warning in the browsers saying that the certificate is invalid. No need for EV certification or all this fancy things.
I tried it with let's encrypt and a standard certificate (not wildcard) and a modifed host file and it seems fine, but will it be ok with the "big" CA like Globalsign, Thwathe, etc ... ?
Answer: If you do not control TLS clients trust, and you do not issue certificates from any private PKI they may have, you are left with the generally trusted certificate authorities. Does not matter who issues them as long as the clients are configured to trust their CA.
Major problem with "wildcard" certs is that it is trusted for everything in *.example.com. That cert you issued to appserver.example.com can be used for evil.example.com or impersonate other servers. If you trust the app server administrator with everything in that DNS zone, fine, but sounds like you use this TLD for all your clients. RFC6125 goes as far as to say wildcards should not be used for best practice TLS domain verification.
Answer: If you have the internal DNS it should be ok, to avoid buying a certificate is that if the client computers on your client that needs to connect to this server are managed you can request your client to add your self-signed certificate and CA to the authorized and update their policies.
In case you are using let's encrypt it will be transparent for your client and the computers.


Hide Group audience/content visibility in node

Question: When displaying a node belonging to some OG, the group audience and the group content visibility is displayed at the end of the node just after the content of the node.
Is it possible to disable that ?
I would avoid code editing if possible.
Answer: In the OG content type, you will see a field for group audience. You can simply hide it in the Manage Field tab. Or, you could use CSS. In both cases, you are not hacking the core code.
Comment: Thank you for your answer. I guess you meant "manage display", right ?
Comment: As Ben asked, the correct answer here is "Manage display", as the admin might want to set group audience, but not show it in the node.
Comment: You have 2 Manage tabs on all content types: Manage Fields and Manage Display. You could remove it off the display yet if you do not need it you should remove it completely in the fields tab. :)
Comment: Awesome! Don't forget to click on the check mark to mark the answer as complete. :)


Django select_related not returning foreign table data

Question: My Models are related as below (Milestone and Ticket)
class Ticket(models.Model):
  create_date = models.DateTimeField('date created')
  project = models.ForeignKey(Project)
  milestone = models.ForeignKey(Milestone)
  title = models.CharField(max_length=200)
  priority = models.IntegerField()
  estimate = models.CharField(max_length=100)

class Milestone(models.Model):
  project = models.ForeignKey(Project)
  title = models.CharField(max_length=200)
  description = models.TextField()
  budget = models.IntegerField()

and I want to get all data from Ticket model as well as corresponding Milestone table data (JOIN Between Ticket & Milestone)
My query is
Ticket.objects.filter(project_id=10).select_related('milestone').values_list()

But this is only getting all data from Ticket model. Why Milestone model's data are not returning? What is wrong here? Please help I am new in Django
Answer: Using select_related you are caching Milestone object asociated to the current Ticket object, not retrieving its data.
You could try:
from django.db.models import F

tickets = Ticket.objects.filter(project_id=10).select_related('milestone').annotate(m_title=F('milestone__title'), m_description=F('milestone__description'), ...)

Then, the objects in the resulting queryset will have a m_title attribute.
tickets[0].m_title

Comment: Well, you have a QuerySet object in tickets. You can add `.values_list()` at the end and get a list with the annotated values included.
Comment: It depends the relationship, you can follow relationship with underscore notation '`__`'. So if `third` belogs to `milestone` it would be `milestone__third`, but if `third` belongs to `ticket` it is just `third`.
Comment: how can i get list data? for both tables. Will it return both tables all data
Comment: its working in shell. please wait testing in project
Comment: Yes this worked. Thanks a ton. Last quick question how can I do this for  `TestModel` which is override `AbstractBaseUser` Class rather than model. Is it possible
Comment: If you mean `django.contrib.auth.models.User` model, yes, you can It's a model like any other.
Comment: well can i use more than 2 table data here i.e `Ticket`, `MileStone` and `ThirdModel`...?? how will be the `select_related()` then? `select_related('milestone').select_related('third')` like this?
Comment: Problem solved, your all solution worked. Thanks you boss :)


Series$\sum _{n=0}^{\infty} x^n $ converges each $x\in[-1,1]$?

Question: Does the Series

$\displaystyle\sum _{n=0}^{\infty} x^n $ converges each $x\in[-1,1]$

Solution i tried -In the given question if i suppose $x=1$ then the series will be $\displaystyle\sum _{n=0}^{\infty} 1 $ ,which is not convergent ,but answer in my book is it is convergent ,how ?
Please help
Comment: i am suffering a lot because of this book ,every answer is wrong,
Comment: *Which* book is that?
Comment: I am using "Arihant book" for previous GATE(Mathematics national level  exam in India) questions solutions,This book is nightmare for me now, I know answers of most of time but because of this book i have to post it here.
Comment: Are you sure it does not ask about $x\in(1,-1)$?
Comment: still this is book's fault ,i am tired of this book.
Comment: @almagest in book this is [-1,1]
Comment: If that kind of thing is happening repeatedly, use a different book!
Comment: @almagest  i checked it online on GATE papers and yes you are right this is (-1,1)
Answer: The book is wrong. A series $\sum a_n$ cannot converge unless $a_n \to 0$. Hence the given series does not converge for $x=1$ and $x=-1$.


What simple functions return equally distributed random values in an arbitrary given range?

Question: For programming purposes I want a function f(x,R) that given a certain seed x returns the same random value every time, in an arbitrary range R. But, I also want the output to be equally distributed. Is this mathematically possible?
For example, I can take the 1st - nth decimal places of sin(x) such that 10^n > R and divide by R, but I'm sure that this isn't evenly distributed even for R = 10.
Otherwise (veering slightly into Stack Overflow territory here) are there existing well-established functions/algorithms for producing (pseudo)random numbers in this fashion?
Comment: Your question is unclear. The distribution of the output will depend on the distribution of the input. Besides, there is no uniform probability distribution on $\mathbb{R}$. So either you fix a range in advance or you go for some non-uniform distribution.
Comment: Thanks for the input/output clarification. So you're saying it can't be both "equally distributed" and "arbitrary size"? My comment on Jens' answer might clear things up.
Comment: Maybe I should add an example, let's say I'm writing a time-based die rolling simulator, so R is the number of sides and X is the timestamp at which the die is rolled. So I roll a d6 at 2011-03-01 15:09:00.32, so I want f(6,2011030115090032) to a value from 1-6, and the same value (1-6) every time. And f(20,2011030115090032) should also work. And f(1000,2011030115090032) too. And they should all be fair dice.
Comment: that is not what mathematicians mean when they say "arbitrary size." To a mathematician this means "any positive integer." You should say "in an arbitrary given range."
Comment: @Qiaochu: thanks, I'll fix that
Answer: To give a StackOverflowy answer, how about generating a random value in your given range for every new input and return the previously generated value if the input appears again? You'd have to store every pair, though.
I think this is the only way to introduce randomness into your setup.
The example given in your question is not random at all, it is deterministic. Are you sure that you are really looking for randomness instead of maybe a hash function?
Comment: Maybe I'm looking for human unpredictability rather than true randomness. I think a hash function that returns sufficiently large results would work - something like hash(x) mod R. What term should I be using instead of "random"? "Deterministic chaotic"?
Comment: See also my example added as a comment to the question.
Answer: As per your comment, it seems that you actually want some deterministic function $f(N,x)$ that returns a integer in $[1..N]$, and which, for a fixed $N$ and for different values of $x$ returns values that appear random in that interval. Still, this requirement is not totally clear, because one should stipulate a distribution of $x$. But, if I understand your scenario, one can assume that $x$ is uniform in some large interval (say, the range the full range of integers in you platform-language). So, a simple recipe would be to use a standard pseudorandom generator and use $x$ as a seed. For example, in Java:
static  int getrand(int N,long x) {
    Random r = new Random(x);  // random number generator, with x as seed
    return r.nextInt(N)+1;     // pseudoradom number in 1..N range
}

Or you can directly implement your own pseudorandom routine, eg,
static  int getrand2(int N,long x) {
    long a=1664525;
    long c=1013904223;
    long res = (a*x+c)&0xFFFFFFFF;
    return (int)((res % N)+1);
}

Comment: Thanks. [Linear congruential generator](http://en.wikipedia.org/wiki/Linear_congruential_generator) is basically the answer I was looking for, and of course it led me to [pseudorandom number generators](http://en.wikipedia.org/wiki/Pseudorandom_number_generator) which seems so obvious in hindsight.


How to prove $\lim_{n \to \infty} \frac{\log(n)(n^{\log(n)})} {a^n} =0, $ where $ |a|>1$

Question: How to prove $$\lim_{n \to \infty} \frac{\log(n)\left(n^{\log(n)}\right)} {a^n} =0,\;  \text{ where } \;|a|>1$$
I don't know how to employ L'Hospital here.
Comment: Take the logarithm. See that tends to $-\infty$.
Answer:
I don't know how to employ L'Hospital here.

Then, don't...
$$
\left|\frac{\log(n)\left(n^{\log(n)}\right)} {a^n}\right| =\exp\left(\log\log n+(\log n)^2-\alpha n\right)$$
with $\alpha=\log|a|\gt0$, and
$$
\log\log n+(\log n)^2-\alpha n\sim-\alpha n\to-\infty.
$$
Comment: But how do I justify that loglogn+(logn)^2−αn∼−αn→−∞.
Comment: Well, you probably know the function which dominates all the others amongst $n$, $(\log n)^2$ and $\log\log n$...
Comment: @Did, fixed the downvote, +1! The voting has been somewhat unusual recently. Downvoters on good solutions, upvotes on incorrect ones.
Comment: @ChrisK Thanks for your appreciation. Of course, this does not *fix* the downvote. True, votes have always been partly erratic but I agree with you that something is going on recently...
Answer: Let $a_n:=\log(n)n^{\log(n)}$.
First compute $\lim_n \frac{\log(n+1)}{\log(n)}=1$. We can use L'Hospital for this (It gets reduced to $\lim_n \frac{n}{n+1}=1$).
From this we get that $\lim_n [\log(n)]^{1/n}=1$ as well. This time by applying L'Hospital for sequences (Stoltz's theorem) which implies that if $\lim \frac{r_{n+1}}{r_n}=L$ then $\lim_n r_n^{1/n}=L$.
Now we compute $\lim_n n^{\log(n)/n}=\lim_{n}e^{\frac{\log^2(n)}{n}}=e^{\lim_n\frac{\log^2(n)}{n}}=1$. This we get by applying L'Hospital to the limit in the exponent $\lim_n\frac{\log^2(n)}{n}=0$, since by L'Hospital it gets reduced to $\lim_n\frac{2\log(n)}{n}$, which gets reduced to $\lim_{n}\frac{2}{n}=0$ by another application of L'Hospital.
Therefore, since $\lim_n[\log(n)]^{1/n}=1$ and $\lim_nn^{\log(n)/n}=1$, we get that $$\lim_n a_n^{1/n}=1.$$
Therefore, the radius of convergence of $\sum_n a_nx^n$ is at least $1$. Therefore $\sum_n \frac{a_n}{a^n}$ converges. Hence $$\lim_n\frac{a_n}{a^n}=0.$$

How to prove $\lim_{n \to \infty} \frac{\log(n)(n^{\log(n)})} {a^n} ＝0, $ where $ |a|>1$


Implementing an age check using InboundPathProcessorInterface

Question: I'm trying to create an age checker for a Drupal 8 site.
I've created a custom module which has a form where the user enters their DOB and my form submit saves a cookie so I know they have passed the age check. Code is as follows:
public function submitForm(array &$form, FormStateInterface $form_state) {
  $day = $form_state->getValue('day');
  $month = $form_state->getValue('month');
  $year = $form_state->getValue('year');

  $timezone = new \DateTimeZone('Africa/Johannesburg');
  $age =
    \DateTime::createFromFormat('d/m/Y', $day . '/' . $month . '/' . $year,
      $timezone)->diff(new \DateTime('now', $timezone))->y;

  if ($age < '18') {
    // if less than 18 display the age_check.fail route
    $url = Url::fromRoute('age_check.fail');
    $form_state->setRedirectUrl($url);
  } else {
    // set cookie so we know this user has passed the age check
    setcookie('age_checked', 1, time()+3600, '/');

    $original_path = $_COOKIE['age_checked_prev_path'];

    if (!empty($original_path) && $original_path != '/') {
      $redirect_url = Url::fromUserInput($original_path);
      // Add a redirect to requested page. Using $form_state built in redirects.
      $form_state->setRedirectUrl($redirect_url);
    } else {
      // For everything else, redirect to homepage.
      $form_state->setRedirect('<front>');
    }
  }

}

Cool that is working fine i get redirected to a age-check-fail page if under 18. If over 18 I should be redirected back to the page I originally wanted to go to. Now I've tried to implement this using a Path Processor.
   /**
   * Path processor for age_check.
   */
class AgeCheckPathProcessor implements InboundPathProcessorInterface {

/**
 * {@inheritdoc}
 *
 */
public function processInbound($path, Request $request) {
  $alias_manager = \Drupal::service('path.alias_manager');
  $request_alias = $alias_manager->getAliasByPath($request->getRequestUri());
  // set cookie with original request path
  setcookie('age_checked_prev_path',$request_alias, time()+3600, '/');

  //get all cookies
  $cookies = $request->cookies->all();

  if(!array_key_exists('age_checked', $cookies) && empty($cookies['age_checked'])){

      // paths to skip age check
      $skip_path = [
        0 => '/admin',
        1 => '/user',
        2 => '/user/login',
        3 => '/age-check',
        4 => '/age-check/fail'
      ];

      // loop through each skip path and if match to current request return it
      foreach ($skip_path as $key => $path) {
        $url = trim($path);
        $url_alias = $alias_manager->getAliasByPath($url);

        if ($url == $request_alias || $url_alias == $request_alias) {
          // Leave $path intact.
          return $request_alias;
        }
      }

    // show the age check page.
    return '/age-check';
  }
  return $request_alias;
}

This isn't working as intended. One main problem is that coming from the home page, submitting the age check form correctly it still redirects me back to the age check form, if i then enter the url to an article I am allowed access to the site as intended, but trying to go back to the home page still shows the age checker form.
Am I using the Inbound Path Processor class correctly?
Comment: You can also set the destination query parameter, which a form should be able to handle by default. So if you can set that when redirecting to the form itself, then you shouldn't need to do the inbound path processor.
Answer: service:
  blah.preserved_system_paths_redirect:
    class: Drupal\blah\Redirect\PreservedSystemPathsRedirect
    tags:
      - { name: event_subscriber }

--
<?php

/**
 * @file
 * Contains \Drupal\blah\Redirect\PreservedSystemPathsRedirect.
 */

namespace Drupal\blah\Redirect;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Routing\RouteMatch;

/**
 * Class PreservedSystemPathsRedirect.
 */
class PreservedSystemPathsRedirect implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST] = 'checkSystemPaths';
    return $events;
  }

  /**
   * Redirect from original system paths to their new locations.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $response
   *   The created response object that will be returned.
   * @param string $event
   *   The string representation of the event.
   * @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
   *   Event dispatcher that lazily loads listeners and subscribers from the dependency injection
   *   container.
   */
  public function checkSystemPaths(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
    $routeMatch = RouteMatch::createFromRequest($response->getRequest());
    $route_name = $routeMatch->getRouteName();

    switch ($route_name) {
      // Regional settings are now available in the blah/site settings form.
      case 'system.regional_settings':
      // Maintenance mode is now available in the blah/site setting form.
      case 'system.site_maintenance_mode':
        $url = \Drupal::url('blah.settings');
        break;
    }

    if (isset($url)) {
      $returnResponse = new RedirectResponse($url, Response::HTTP_MOVED_PERMANENTLY);
      $response->setResponse($returnResponse);
    }
  }

}


Highcharts: How to toggle between different xaxis having individual plotbands, onclick rangeselector buttons

Question: I have a chart with daily values of the month of October.
Two buttons: week and month.
Week plotband has to be identical with month plotband: First 2 days are green, next 5 days are blue in month plotband. When selecting week, the range date 1-7 should be same colour green and blue.
Highcharts.chart('container', {
    chart: {
        type: 'column',
    },

    title: {
        text: 'How long time a TR has been placed in stages longer than 48 hours'
    },
    legend: {
        enabled: true
    },
    subtitle: {
        text: 'Input - verify should max be 48 hours = green zone'
    },

    data: {
        csv: document.getElementById('csv').innerHTML
    },

    plotOptions: {
        column: {

        },
        series: {
            dataLabels: {
                enabled: false,
                format: '{point.y}'
            }
        }
    },

    tooltip: {

    },

    rangeSelector: {
        buttonSpacing: 10,
        enabled: true,
        inputEnabled: false,
        selected: 1,
        buttons: [{
            type: 'week',
            count: 1,
            text: 'Week'
        }, {
            type: 'month',
            count: 1,
            text: 'Month'
        }],
    },
    xAxis: [{
        id: 'one',
        type: 'datetime',
        dateTimeLabelFormats: {
            millisecond: '%H:%M:%S.%L',
            second: '%H:%M:%S',
            minute: '%H:%M',
            hour: '%H:%M',
            day: '%e. %b',
            week: '%e. %b',
            month: '%b \'%y',
            year: '%Y'
        },

        plotBands: [{
            from: 1538352000000,
            to: 1538524800000,
            color: '#E8F5E9'

        }, {
            from: 1538524800000,
            to: 1538870400000,
            color: '#E0ECEC'
        }, {
            from: 1538870400000,
            to: 1539475200000,
            color: "#FFFDE7"
        }, {
            from: 1539475200000,
            to: 1540944000000,
            color: "#FFEBEE"
        }],
    }, {
        id: 'two',
        type: 'datetime',
        dateTimeLabelFormats: {
            millisecond: '%H:%M:%S.%L',
            second: '%H:%M:%S',
            minute: '%H:%M',
            hour: '%H:%M',
            day: '%e. %b',
            week: '%e. %b',
            month: '%b \'%y',
            year: '%Y'
        },

        plotBands: [{
            from: 1538352000000,
            to: 1538524800000,
            color: '#E8F5E9'

        }, {
            from: 1538524800000,
            to: 1538870400000,
            color: '#E0ECEC'
        }],
    }],

    yAxis: {
        min: 0,
        max: 100,
        title: {
            text: 'TRADING RECORDS',
        }
    }
});

Please see jsfiddle
Is there a way to toggle between two xaxis with different plotBands: when clicking on the 'week' button, one plotband will display and when clicking on the 'month' button another plotband will display. So the colours of the plotband is relative to the dates?
I assume I have to use event functions like setExtremes and afterSetExtremes, but not sure how to do it?
Thanks much appreciated for help.
I managed to simulate the output with this function:
  events: {
    afterSetExtremes: function (e) {
        if (e.trigger == "rangeSelectorButton" &&
            e.rangeSelectorButton.text == "Week") {
            // it is your button that caused this,
            // so setExtrememes to your custom
            // have to do in timeout to let
            // highcharts finish processing events...
            setTimeout(function () {
                Highcharts.charts[0].xAxis[0].setExtremes(1538352000000, 1538524800000)
            }, 1);

        }

    },
}

But it only work when selecting specific: setExtremes(1538352000000, 1538524800000)
I think a scaleable solution for any 7 days would require some sort of exception functionality for remove current plotband on xaxis with addplotband
Updated fiddle
Comment: Could you explain more precisely what you're trying to achieve? Because toggling between two xaxis is not a good idea. Perhaps you should add your custom buttons and use `setExtremes` to set a specific range or use `navigator`.
Answer: I added custom buttons instead:  https://forum.highcharts.com/viewtopic.php?t=31649

         <button class="btn btn-custom" id="one">48 hours</button>
         <button class="btn btn-custom" id="two">7 days</button>
         <button class="btn btn-custom" id="three">14 days</button>
         <button class="btn btn-custom" id="four">31 days</button>
         <button class="btn btn-custom" id="all">All</button>

$.get('bm.csv', function (bmcsv) {

    var chart = new Highcharts.Chart({

        chart: {
            renderTo: 'containerbenchmark',
            type: 'areaspline',
        },

        title: {
            text: ''
        },
        legend: {
            enabled: true
        },
        subtitle: {
            text: 'Input - verify - close should max be 48 hours = green zone'
        },

        data: {
            csv: bmcsv,
        },

        plotOptions: {
            areaspline: {
                stacking: 'normal'
            },
            series: {
                dataLabels: {
                    enabled: false,
                    format: '{point.y}'
                }
            }
        },

        tooltip: {
            /*headerFormat: '{point.key}
',
            pointFormat: '{series.name}: {point.y} {point.total}
',
            footerFormat:  '{point.total}
',*/
            shared: true,
            useHTML: true,
            formatter: function () {
                var tooltip = '
' + Highcharts.dateFormat('%e/%b/%Y',
                    new Date(this.x)) + '

';
                //loop each point in this.points
                $.each(this.points, function (i, point) {
                    tooltip += '
' + point.series.name + ': 	' +
                        '' + point.y + '
'
                });
                tooltip += '
Total: 	' +
                    '' + this.points[0].total + '
' +
                    '

';
                return tooltip;
            }
        },

        rangeSelector: {
            selected: 2,
            enabled: true,
            inputEnabled: true,
            inputDateFormat: "%m/%d/%Y",
            inputEditDateFormat: "%m/%d/%Y",
            inputDateParser: function (s) {
                return Date.UTC(
                    parseInt(s.substr(6, 4)),
                    parseInt(s.substr(0, 2) - 1),
                    parseInt(s.substr(3, 2)),
                    12
                )
            }
        },

        navigator: {
            enabled: true
        },

        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: {
                millisecond: '%H:%M:%S.%L',
                second: '%H:%M:%S',
                minute: '%H:%M',
                hour: '%H:%M',
                day: '%e. %b',
                week: '%e. %b',
                month: '%b \'%y',
                year: '%Y'
            },

            plotBands: [{
                from: 1538352000000,
                to: 1538524800000,
                color: '#cae8cc',
                label: {
                    text: '> 48 hours',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }, {
                from: 1538524800000,
                to: 1538870400000,
                color: '#d0e2e2',
                label: {
                    text: '> 7 days',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }, {
                from: 1538870400000,
                to: 1539475200000,
                color: "#fff9b3",
                label: {
                    text: '> 14 days',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }, {
                from: 1539475200000,
                to: 1540944000000,
                color: "#ffb3be",
                label: {
                    text: '> 31 days',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }],

        },

        yAxis: {
            min: 0,
            title: {
                text: 'TRADING RECORDS',
            }
        }
    }, function (chart) {

        // apply the date pickers
        setTimeout(function () {
            var rangeSelector = $('#containerbenchmark input.highcharts-range-selector');

            rangeSelector.datepicker({
                autoclose: true,
                todayHighlight: true
            }) /*.datepicker('update', new Date())*/ ;

            var inputMin = rangeSelector.filter('[name=min]');
            var inputMax = rangeSelector.filter('[name=max]');

            inputMin.datepicker().on("changeDate", function (event) {
                console.log(inputMin.datepicker("getDate"));
                console.log(inputMin.datepicker("getUTCDate"));
            });
        }, 1000);
    });

    $('#one').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1538352000000,
            1538524800000
        );
    });
    $('#two').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1538524800000,
            1538870400000
        );
    });
    $('#three').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1538870400000,
            1539475200000
        );
    });
    $('#four').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1539475200000,
            1540944000000
        );
    });
    $('#all').click(function () {
        chart.xAxis[0].setExtremes(
            event.min,
            event.max
        );
    });
});


Mozart K331 Rondo Alla Turca m.55 discrepancy (Urtext vs Urtext?)

Question: I have the Wiener Urtext edition of the Mozart K331 (see cover image). As you can see in the picture, the 4th note of measure 55 of the Rondo Alla Turca is A (E#FGA). However, I saw two videos where people play the F note: E#FGF. I found an online sheet music that claims to be based on urtext editions and it also has F instead of A (somehow it's measure 59 there, not m.55)(see image).
In the preface of the Wiener edition, re available sources, it says "For two other sonatas (K.331 and K. 570), at least some fragments of the original manuscript have been preserved."
So which version is (more likely?) the original Or most adopted?
Comment: Any score from an online publisher should be viewed with *great* skepticism. I would trust the one from an established, reputable publisher.
Comment: I bought the Wiener edition because I trust it's authoritive, however so far I have seen 4 videos all playing the F, not A (e.g. https://www.youtube.com/watch?v=6-pg-lMoCFY   and   https://www.youtube.com/watch?v=oLKj1cflsAo    also that 6 year old kid :) ). Haven't found one playing the Wiener version yet.
Comment: Turns out someone had asked about the very same measure some years ago (stumbled upon by accident): https://music.stackexchange.com/questions/11071/rondo-alla-turca-bar-55  (please don't delete this question)
Answer: The below comes from the Henle commentary on their 2021 edition.

55 u: In F1 4th note indistinct, rather b2 than a2; F4 has b2; C, CPR have a2, rendered thus in our edition, cf. also M 39. Many later editions correct the reading of F4 to f#2.

The sources referenced are given substantive explanations in the commentary, but briefly:

C: Undated copyist's manuscript. It " became known in 2016. It contains numerous textual mistakes." Possibly dating to 1760s or 1770s.
CPR: Copyist's manuscript. Likely late 18th century.
Fn: First edition, nth printing.

Henle is also saying that the A is preferred over F# by comparison with m. 39, which contains the same musical material, but leading to a cadence on C# minor rather than F# minor.

Since the corresponding sections of the piece are largely parallel to each other, Henle considers the earlier passage to be the defining factor. This, given that the copyists agree, the first editions are ambiguous (or presumptively wrong), and the F# is an editorial correction not backed up by other sources.
However, the F# (instead of A) is harmonically justifiable as a necessary modification to avoid the awkward diminished fourth from A to E#.
Comment: Thank you so much! This is more detailed than I could have expected. (Does b^2 refer to the F# note, a^2 refer to the A note?)
Comment: @GrandAdagio No, b2 literally means the note b, one step above the a used in their edition.
Comment: Oh, I see, so some even printed B instead of A. Thanks again for taking the time to find the answer.


tamanho de imagens em kb para upload

Question: estou fazendo uma aplicacao para android, e tenho que trabalhar com download e upload de fotos...
ja estou redimencionando as fotos maiores que 1000x1000px para este mesmo tamanho...
e usando o metodo
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 10, out);

para diminuir o tamanho da imagem em KB para facilitar o upload e download...
meu problema é q algumas imagens passam de 3mb e usando o compress como acima, elas ficam perto de 500kb, e teria q passar mais uma vez no compress para ficarem menor
mas ao mesmo tempo existem imagens de 50kb que ao passar no compress ficam com 8kb ou seja nao precisaria do compress...
entao eu preciso de um metodo que retorne o tamanho da imagem em kb ou mb tanto faz... ai conseguiria tratar este meu problema...
agradeço desde já.
Answer: Método length() :
import java.io.File;

public class FileSizeExample
{   public static void main(String[] args)
    {   File file =new File("sua_imagem.ext");
        if(file.exists())
        {    double bytes = file.length();
             double kilobytes = (bytes / 1024);
             double megabytes = (kilobytes / 1024);
             System.out.println("bytes : " + bytes);
             System.out.println("kilobytes : " + kilobytes);
             System.out.println("megabytes : " + megabytes);
        }else
        {    System.out.println("Arquivo nem existe!");
        }

    }
}

Fonte

tamanho de imagens em kb para upload