Is the orthogonal polar factor the unique retraction $\operatorname{GL}_n^+ \to \operatorname{SO}_n$?

Question: $\newcommand{\psym}{\text{Psym}_n}$
$\newcommand{\sym}{\text{sym}}$
$\newcommand{\Sym}{\operatorname{Sym}}$
$\newcommand{\Skew}{\operatorname{Skew}}$
$\renewcommand{\skew}{\operatorname{skew}}$
$\newcommand{\GLp}{\operatorname{GL}_n^+}$
$\newcommand{\SO}{\operatorname{SO}_n}$
This might be silly, but I wonder:

Let $F:\GLp \to \SO$ be a continuous retract. Is it true that $F$ must be the orthogonal polar factor, i.e. $F(A)=O$, where $A=OP,O \in \SO,P\in\psym$. Does anything changes if we assume $F$ is a deformation retract? Or if it is a smooth deformation retract?
Answer: Retractions are a very "soft" concept so there is a huge number of those. Take any continuous function $f:PSym_n\to SO_n$ and define $F_f(A):=O\cdot f(P)$ for $A=OP$. Then this is clearly a retraction and it even is a defomormation retraction, which is smooth if $f$ is smooth.
Comment: Thanks, I was just thinking something similar myself: we can take e.g. $F(A)= O\det A$ or $F(A)= O\frac{\| A\|}{\sqrt n}$ or variations on these. However, both of these retractions are "proportional" to the orthogonal polar factor. A more interesting question is: are there retractions $GL^+ \to SO$ which are not proportional to it? (By your construction, it suffices to find a continuous non constant map $f:Psym \to SO$ which is the identity on $SO$. Is it trivial such a map exists?)
Comment: In fact, therer are no conditions on the map $f$, so lots of such maps exist


Failed registering Scalable Target when defining auto scale option for ECS

Question:
But I am getting this error:

Failed registering Scalable Target
Scalable Target could not register
  scalable target: 1 validation error detected: Value '' at 'roleARN'
  failed to satisfy constraint: Member must have length greater than or
  equal to 1 (Service: AWSApplicationAutoScaling; Status Code: 400;
  Error Code: ValidationException; Request ID:
  dff37db1-4be5-11e7-8739-df4df785c602)

I really don't know how to resolve this issue.
I have used an account play-admin to create all these cluster and service. It has the following rights:

The task is run using this role play-ecs:

I have also put in the trust relationship to this role:
My Question:
What permission do I need to grant to get the autoscaling to work? What confuse me greatly is in the message: "Member must have length greater than or
 equal to 1 ", what does this member refer to? The IAM account I used to create this autoscaling? The role of the task? Or the newly created 'IAM autoscale role' (see the following screen shot)? If it is the last one, it seems like it is beyond my control.
*This screensot shows that a step IAM Autoscale role: <create_new> is executed by ECS
Answer: For what it's worth, I had to add the trust relationship of "application-autoscaling.amazonaws.com" on my "ecsAutoscaleRole".
Answer: I had the same issue today and it appears that when you're setting up the configuration it creates a new IAM role but at the moment of executing the steps you mentioned something happens and that ARN is not passed (this is an AWS bug, I already reported it).
So what I did was try to configure the auto scaling for the service again, but this time it didn't create the ecsAutoscaleRole because it was already created, so it worked :)


Drush for drupal 8

Question: i upgraded drush to 7.0-dev and within my drupal 8 folder drush status throws error
Drush command terminated abnormally due to an unrecoverable error.
Error: Call to undefined function drupal_bootstrap() in /usr/local/Cellar/drush/HEAD/libexec/includes/bootstrap.inc, line 836
Answer: What version of Drupal 8 are you using?  Your Drush and Drupal versions must track closely, so if you are using today's HEAD of Drush 7, you should use today's HEAD of d8.  If you are using d8-beta10, you should use Drush 7.0-rc2, and if you are using d8-beta9, you should use Drush 7.0-rc1.
Update
Just tried this with today's HEAD of Drush 7:

drush qd dev-d8-test --core=drupal-8.0.x --db-url='mysql://mysqluser@localhost:/devd8test'
Worked great.  Adjust db credentials to match your needs, of course.

Drush for drupal 8


Determine the numerical method

Question: Please, help to understand the method which is used in the following snippet:
<code>% delta - time step
% d - x step

% initialization
for all x from 0 to 1 in increments of delta
   f[x,0] = 1/2 * x^2

% run the differential equation forward
for t from 0 to T in increments of d

  % Compute the derivative
  for all x
    fderiv[x,t] = f[x,t] - f[x-d,t]  % adjust this appropriately at the boundary x = 0

  % Step the differential equation forward one unit
  for all x from 0 to 1 in increments of delta
    f[x,t+delta] = ( x - f[x,t])/fderiv[x,t] - x

    % f[x, t+delta] must stay <= x and >= 0
    if f[x, t+delta] > x then set f[x, t+delta] = x
    if f[x, t+delta] < 0 then set f[x, t+delta] = 0
  end;

end;
</code>
If you are not familiar with programming, here is the same thing in the math notation:
$$f(x, 0) := \frac{x^2}{2}$$
$$f'(x, t) := f(x, t) - f(x - \delta_x, t)$$
$$f(x, t + \delta_t) := \min\left(\max\left(\frac{x - f(x, t)}{f'(x,t)} - x, x\right), 0\right)$$
This is the foreign code and it may contain errors. It looks like the method of solving some differential equation using the finite differences, but have only brief knowledge in this field. Thank you in advance!
Comment: As this is not a programming site, it may be advisable to leave only the math part of the question and expand it as well.
Comment: What is the context?
Comment: @Tpofofn It doesn't have a context. I was asked to translate this pseoudo-code to some programming language, but without understanding the meaning of the function I can't fix some bugs.
Comment: @nbubis I think that people are unfamiliar with programming will just skip it, but it may help to those who are familiar. Can you give an advice about expanding the math part?
Answer: It looks like you're trying to solve the PDE:
$$ \partial_t f \cdot \partial_x f + f(1 + \partial_x) = x$$
With the initial condition:
$$f(x,t = 0) = x^2/2$$
It moreover looks like the code is neglecting to put in $dx,dt$ when calculating the derivatives.
Comment: Thanks! Now it makes much more sense for me. Can you suggest how to set the right values at the boundary: $f'(x,t) := f(x,t) - f(x - \delta_x, t)$ ? Here the left finite difference is used. Can I change it to the right finite difference (i.e. $f(x + \delta_x, t) - f(x, t)$), when $x$ equals $0$?
Comment: You can always change it to the right difference, but you have to be consistent throughout - i.e. you should't mix left an right differences in the the same implementation, which won't really help you to much. To know the value of the derivative there, I think you need to know a little bit more about the problem - a.k.a what the derivative is at the boundary.

Determine the numerical method


Describing Results from Logistic Regression with Restricted Cubic Splines Using rms in R

Question: Updated
I have been developing a logistic regression model based on retrospective data from a national trauma database of head injury in the UK. The key outcome is 30 day mortality (denoted as "Survive" measure). Other measures with published evidence of significant effect on outcome in previous studies include:
Yeardecimal - Date of procedure (expressed as decimal of year) = 1994-2013
Age - Age of patient = 16.0-101.5
ISS - Injury Severity Score = 16-75
Sex - Gender of patient = Male or Female
inctoCran - Time from head injury to craniotomy in minutes = 0-2880 (After 2880 minutes is defined as a separate diagnosis)
Mechanism - Mechanism of injury = Fall <2m, Fall >2m, Shooting/stabbing, RTC (Road Traffic Collision), Other
neuroFirst - Location of first admission (Neurosurgical Unit) = NSU vs. Non-NSU
rcteye - Pupil reactivity = NA / Both unreactive = O, 1 reactive = 1, both reactive = 2
rcteyeYN - dummy = 0 or 1 for presence or absence of data
GCS - Glasgow Coma Scale = 3-15
GCSYN - dummy = 0 or 1 for presence or absence of data

Dummy variables were included to enable a larger sample size where the majority of cases were excluding  GCS and rcteye variables (missing not at random).
In order to test for interactions, initially I ran the following:
rcs.ASDH<-lrm(formula = Survive ~ (rcs(Age) + rcs(ISS) +
     neuroFirst + Mechanism + rcteye + rcteyeYN + GCS + GCSYN + rcs(Yeardecimal))^2, data = ASDH_Paper1.1)

but when I did I got the following error:
singular information matrix in lrm.fit (rank= 151 ).  Offending variable(s):
GCSYN * Yeardecimal''' GCSYN * Yeardecimal' GCSYN * Yeardecimal GCS * Yeardecimal''' GCS * Yeardecimal GCS * GCSYN rcteyeYN * Yeardecimal''' rcteyeYN * Yeardecimal'' rcteyeYN * Yeardecimal rcteyeYN * GCSYN rcteye * Yeardecimal''' rcteye * Yeardecimal rcteye * rcteyeYN Mechanism=RTC * Yeardecimal''' Mechanism=Other * Yeardecimal''' Mechanism=Fall > 2m * Yeardecimal''' Mechanism=Shooting / Stabbing * Yeardecimal Mechanism=RTC * Yeardecimal Mechanism=Other * Yeardecimal Mechanism=Fall > 2m * Yeardecimal neuroFirst * Yeardecimal ISS'' * Yeardecimal''' ISS * Yeardecimal''' ISS'' * Yeardecimal'' ISS'' * Yeardecimal ISS' * Yeardecimal ISS * Yeardecimal ISS'' * GCSYN ISS'' * rcteyeYN ISS'' * Mechanism=RTC Age'' * Yeardecimal''' Age'' * Yeardecimal'' Age''' * Yeardecimal' Age''' * Yeardecimal Age'' * Yeardecimal Age' * Yeardecimal Age * Yeardecimal Age'' * GCSYN Age''' * rcteyeYN
Error in lrm(formula = Survive ~ (rcs(Age) + rcs(ISS) + neuroFirst + Mechanism +  :
  Unable to fit model using "lrm.fit"

The only way I could run the model is with an adjustment. Yeardecimal is excluded from any interaction as is the interaction of GCS:GCSYN and rcteye:rcteyeYN which produced the same error as written above. It made sense to exclude the interactions between a variable and its missing dummy but I am not sure what to do about Yeardecimal:
rcs.ASDH<-lrm(formula = Survive ~ (rcs(Age) + rcs(ISS) +
     neuroFirst + Mechanism + rcteye + rcteyeYN) * (rcs(Age) + rcs(ISS) +
     neuroFirst + Mechanism + GCS + GCSYN) + rcs(Yeardecimal), data = ASDH_Paper1.1)

From this model the following interactions were identified with an anova output:
> anova(rcs.ASDH)
                Wald Statistics          Response: Survive

 Factor                                                Chi-Square d.f. P
 Age  (Factor+Higher Order Factors)                    130.42      52  <.0001
  All Interactions                                      78.68      48  0.0034
  Nonlinear (Factor+Higher Order Factors)               46.53      39  0.1901
 ISS  (Factor+Higher Order Factors)                    181.65      42  <.0001
  All Interactions                                      52.43      39  0.0738
  Nonlinear (Factor+Higher Order Factors)               55.01      28  0.0017
 neuroFirst  (Factor+Higher Order Factors)              37.68      16  0.0017
  All Interactions                                      11.54      15  0.7136
 Mechanism  (Factor+Higher Order Factors)               63.72      52  0.1277
  All Interactions                                      58.35      48  0.1455
 rcteye  (Factor+Higher Order Factors)                 242.07      15  <.0001
  All Interactions                                      19.39      14  0.1507
 rcteyeYN  (Factor+Higher Order Factors)               204.58      15  <.0001
  All Interactions                                      29.88      14  0.0079
 GCS  (Factor+Higher Order Factors)                    162.81      15  <.0001
  All Interactions                                      11.62      14  0.6365
 GCSYN  (Factor+Higher Order Factors)                   94.50      15  <.0001
  All Interactions                                      41.74      14  0.0001
 Yeardecimal                                            51.96       4  <.0001
  Nonlinear                                             10.27       3  0.0164
 Age * ISS  (Factor+Higher Order Factors)               11.90      12  0.4534
  Nonlinear                                              9.40      11  0.5851
  Nonlinear Interaction : f(A,B) vs. AB                  9.40      11  0.5851
  f(A,B) vs. Af(B) + Bg(A)                               7.96       6  0.2411
  Nonlinear Interaction in Age vs. Af(B)                 8.75       9  0.4605
  Nonlinear Interaction in ISS vs. Bg(A)                 8.58       8  0.3790
 Age * neuroFirst  (Factor+Higher Order Factors)         2.66       4  0.6166
  Nonlinear                                              2.05       3  0.5624
  Nonlinear Interaction : f(A,B) vs. AB                  2.05       3  0.5624
 Age * Mechanism  (Factor+Higher Order Factors)         17.58      16  0.3493
  Nonlinear                                             13.82      12  0.3127
  Nonlinear Interaction : f(A,B) vs. AB                 13.82      12  0.3127
 Age * GCS  (Factor+Higher Order Factors)                6.24       4  0.1819
  Nonlinear                                              3.89       3  0.2741
  Nonlinear Interaction : f(A,B) vs. AB                  3.89       3  0.2741
 Age * GCSYN  (Factor+Higher Order Factors)             20.11       4  0.0005
  Nonlinear                                              8.86       3  0.0312
  Nonlinear Interaction : f(A,B) vs. AB                  8.86       3  0.0312
 ISS * neuroFirst  (Factor+Higher Order Factors)         3.23       3  0.3571
  Nonlinear                                              0.87       2  0.6480
  Nonlinear Interaction : f(A,B) vs. AB                  0.87       2  0.6480
 ISS * Mechanism  (Factor+Higher Order Factors)         23.95      12  0.0206
  Nonlinear                                             20.66       8  0.0081
  Nonlinear Interaction : f(A,B) vs. AB                 20.66       8  0.0081
 ISS * GCS  (Factor+Higher Order Factors)                0.77       3  0.8570
  Nonlinear                                              0.42       2  0.8102
  Nonlinear Interaction : f(A,B) vs. AB                  0.42       2  0.8102
 ISS * GCSYN  (Factor+Higher Order Factors)              6.53       3  0.0886
  Nonlinear                                              2.35       2  0.3085
  Nonlinear Interaction : f(A,B) vs. AB                  2.35       2  0.3085
 neuroFirst * Mechanism  (Factor+Higher Order Factors)   2.45       4  0.6533
 neuroFirst * GCS  (Factor+Higher Order Factors)         0.00       1  0.9726
 neuroFirst * GCSYN  (Factor+Higher Order Factors)       1.39       1  0.2382
 Mechanism * GCS  (Factor+Higher Order Factors)          0.10       4  0.9987
 Mechanism * GCSYN  (Factor+Higher Order Factors)        1.74       4  0.7828
 Age * rcteye  (Factor+Higher Order Factors)             8.66       4  0.0702
  Nonlinear                                              7.29       3  0.0633
  Nonlinear Interaction : f(A,B) vs. AB                  7.29       3  0.0633
 ISS * rcteye  (Factor+Higher Order Factors)             4.18       3  0.2424
  Nonlinear                                              1.49       2  0.4744
  Nonlinear Interaction : f(A,B) vs. AB                  1.49       2  0.4744
 neuroFirst * rcteye  (Factor+Higher Order Factors)      0.10       1  0.7460
 Mechanism * rcteye  (Factor+Higher Order Factors)       3.44       4  0.4867
 rcteye * GCS  (Factor+Higher Order Factors)             2.30       1  0.1297
 rcteye * GCSYN  (Factor+Higher Order Factors)           2.57       1  0.1090
 Age * rcteyeYN  (Factor+Higher Order Factors)           7.23       4  0.1242
  Nonlinear                                              7.23       3  0.0649
  Nonlinear Interaction : f(A,B) vs. AB                  7.23       3  0.0649
 ISS * rcteyeYN  (Factor+Higher Order Factors)           2.47       3  0.4814
  Nonlinear                                              0.11       2  0.9462
  Nonlinear Interaction : f(A,B) vs. AB                  0.11       2  0.9462
 neuroFirst * rcteyeYN  (Factor+Higher Order Factors)    0.12       1  0.7280
 Mechanism * rcteyeYN  (Factor+Higher Order Factors)     1.81       4  0.7701
 rcteyeYN * GCS  (Factor+Higher Order Factors)           3.70       1  0.0543
 rcteyeYN * GCSYN  (Factor+Higher Order Factors)         8.74       1  0.0031
 TOTAL NONLINEAR                                       102.74      64  0.0015
 TOTAL INTERACTION                                     178.52     103  <.0001
 TOTAL NONLINEAR + INTERACTION                         241.87     111  <.0001
 TOTAL                                                 889.91     123  <.0001

The summary function revealed the following results:
             Effects              Response : Survive

 Factor                                    Low    High   Diff. Effect       S.E.   Lower 0.95 Upper 0.95
 Age                                         37.6   72.0 34.40         0.15   0.38   -0.58      8.900000e-01
  Odds Ratio                                 37.6   72.0 34.40         1.16     NA    0.56      2.430000e+00
 ISS                                         20.0   26.0  6.00        -1.34   0.31   -1.95     -7.400000e-01
  Odds Ratio                                 20.0   26.0  6.00         0.26     NA    0.14      4.800000e-01
 neuroFirst                                   0.0    1.0  1.00        -0.23   0.37   -0.95      5.000000e-01
  Odds Ratio                                  0.0    1.0  1.00         0.80     NA    0.39      1.650000e+00
 rcteye                                       0.0    2.0  2.00         3.20   0.50    2.22      4.170000e+00
  Odds Ratio                                  0.0    2.0  2.00        24.41     NA    9.24      6.452000e+01
 rcteyeYN                                     0.0    1.0  1.00        -3.34   0.44   -4.21     -2.480000e+00
  Odds Ratio                                  0.0    1.0  1.00         0.04     NA    0.01      8.000000e-02
 GCS                                          0.0   12.0 12.00         1.94   0.49    0.98      2.890000e+00
  Odds Ratio                                  0.0   12.0 12.00         6.94     NA    2.67      1.799000e+01
 GCSYN                                        0.0    1.0  1.00        -1.32   0.45   -2.20     -4.400000e-01
  Odds Ratio                                  0.0    1.0  1.00         0.27     NA    0.11      6.400000e-01
 Yeardecimal                               2005.5 2012.4  6.85         0.20   0.12   -0.03      4.400000e-01
  Odds Ratio                               2005.5 2012.4  6.85         1.22     NA    0.97      1.550000e+00
 Mechanism - Fall > 2m:Fall < 2m              1.0    2.0    NA        -0.89   0.35   -1.58     -2.000000e-01
  Odds Ratio                                  1.0    2.0    NA         0.41     NA    0.21      8.200000e-01
 Mechanism - Other:Fall < 2m                  1.0    3.0    NA         0.25   0.42   -0.58      1.080000e+00
  Odds Ratio                                  1.0    3.0    NA         1.28     NA    0.56      2.930000e+00
 Mechanism - RTC:Fall < 2m                    1.0    4.0    NA        -0.68   0.43   -1.52      1.700000e-01
  Odds Ratio                                  1.0    4.0    NA         0.51     NA    0.22      1.190000e+00
 Mechanism - Shooting / Stabbing:Fall < 2m    1.0    5.0    NA        18.97 116.63 -209.63      2.475600e+02
  Odds Ratio                                  1.0    5.0    NA 172906690.96     NA    0.00     3.272814e+107

Adjusted to: Age=54.2 ISS=25 neuroFirst=0 Mechanism=Fall < 2m rcteye=1 rcteyeYN=0 GCS=3 GCSYN=0

Remaining questions are:
1 - Is my dummy variable treatment for variables missing not at random appropriate, including the exclusion of interactions with the main term?
2 - Can I resolve the issues with assessing interaction of the Yeardecimal term?
3 - Should I exclude non-significant interaction terms? I read that exclusion only of a "chunk" is advised - Including the interaction but not the main effects in a model
4 - Is the odds ratio for each variable the "Effect" column? If so, is this the OR between the lowest and highest value of each variable?
Comment: Question you should be asking is how to present the spline fit to allow someone to understand & use your model. `rcspline.restate` can be useful in this respect.
Comment: Consider adding to the question or asking a new one rather than editing so drastically that nothing remains of the original.
Answer: You are assuming linearity for time and age.  This is unlikely to be correct.  You have not included a possible nonlinear interaction between age and sex.  You don't need x=TRUE, y=TRUE if you are not bootstrapping or using robust covariance matrix estimation.
To answer your questions, a graph is the best summary of a partial effect, and you can include a small graph in an abstract, which also makes the abstract more likely to be read.
The other approach is to estimate odds ratios and their confidence limits.  The summary function (full name: summary.rms) makes this easy.  By default it gives you the inter-quartile-range odds ratios.  You can easily override the covariate settings to ask for odds ratios for any two levels of the covariate you choose.  The help file for summary.rms has lots of examples.
Your limiting sample size is 629, so you can reliably fit roughly $\frac{629}{15}$ parameters or 42.  So you are in pretty good shape in terms of avoiding overfitting, otherwise you might need to greatly emphasize rigorous internal validation using the bootstrap.  It is still worth doing this to obtain a smooth overfitting-corrected calibration curve using the calibrate function.
Comment: Yes.  I recommend predictive mean matching.  You can look at the R `Hmisc` package `aregImpute` function.  There is no amount of missing data that would make it better to drop variables or observations entirely.  The indicator variable method fails even with a small fraction of missings.  Of course your model will be limited when missingness is high, e.g., high standard errors and more dependence on assumptions.
Comment: Post has been updated to reflect your feedback with further questions. Many thanks for your help so far.
Comment: It is not correct to use indicator variables for missing values.  Use multiple imputation instead.  I wouldn't include all two-way interactions but would talk to subject matter experts about what interactions would make sense.
Comment: Clear on interactions. My concern is that for these missing values not missing at random, there is very little data for the sample. For instance, pupil reactivity was only recorded partially from 2007 in the database, resulting in only 44% of cases with values. Similarly, only 63% of cases have a recorded GCS value. If multiple imputation is possible, are standard approaches such as in your textbook feasible for application here?


Is there a way to provide a Select All / Check All checkbox for a field that displays multiple checkboxes in Drupal 7?

Question: Seems like there is no core config to setup a "Check All" checkbox unless I missed where it is. I'm creating a content type and have a taxonomy reference field and I have alot of terms, which means alot of boxes I have to check. Anyway to provide a checkbox to select everything?
Answer: You can do a form alter. hook_form_alter and attach your js to the form.
$form['#attached']['js'] = array(
  drupal_get_path('module', 'YOURMODULE') . '/YOURMODULE.js',
);

Then add the code as in here
Comment: Link is broken.
Answer: Here's a quick snippet for anyone looking for a quick check all functionality. It will basically make your field LABEL a check all button. No need to add any extra HTML elements or modules. This just works.
You can pretty much copy this into your js file and it will just work as i restrained it to working only on content Edit pages.
Obviously this isn't a long term solution, but mainly as a quick band aid patch.
jQuery(document).ready(function($) {
  var $checkBoxes = $('input[type="checkbox"]');
  $('body.page-node .form-type-checkboxes > label').click(function() {
      $checkBoxes.attr('checked', true);
  });
});

Answer: Here is an updated version of @duckx code, it has the following improvements :
- only select the checkboxes of the label that has been clicked
- allows to toggle checkboxes
Drupal.behaviors.selectAll = {
  attach: function (context, settings) {
    $('body.page-node .form-type-checkboxes > label').click(function() {
        $(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');
    });
  }
};

Comment: which file does Drupal.behaviros.selectAll go?
Comment: I generally put this in a script.js inside my theme, don't forget to wrap it inside `(function ($) { ... })(jQuery);` as usual.
Answer: This contrib module appears to do the trick: https://www.drupal.org/project/checkall
Answer: There is no core config option for something like this, it would have to be JavaScript/jQuery (http://jsfiddle.net/PtMrM/).
Check All
<input type="checkbox" name="ny"> New York
<input type="checkbox" name="bos"> Boston
<input type="checkbox" name="sfo"> San Francisco
<input type="checkbox" name="dc"> Wasington DC

Please note, that is very quick js, and won't be very user friendly (e.g., they click on it, there is no way to uncheck)


Stream remote framebuffer into NSView

Question: I'm trying to implement a simple VNC client in Swift using LibvnccClient.
I have created a subclass of NSView. I create a CGContext and pass the data pointer to the library for use as the framebuffer. libvncclient updates the framebuffer as contents of the screen changes and calls my provided callback.
Here is the relevant code
class VNCClient {

    var localClient: rfbClient
    var view: NSView

    init(view: NSView) {
        guard let client_ptr = rfbGetClient(8, 3, 4) else {
            fatalError("Trouble")
        }

        self.view = view
        self.localClient = client_ptr.pointee

        localClient.MallocFrameBuffer = resize
        localClient.GotFrameBufferUpdate = update
        let fbPointer = UnsafeMutablePointer<UInt8>(OpaquePointer((view as! RFBView).buffer))
        localClient.frameBuffer = fbPointer
        rfbClientSetClientData(&localClient, &viewTag, &self.view)
        var argc: Int32 = 0
        let b = rfbInitClient(&localClient, &argc, nil)
        if b == RFB_TRUE {
            print("Connected!")
        }
        Timer.scheduledTimer(withTimeInterval: 0.001, repeats: true) {_ in
            if WaitForMessage(&self.localClient, 1) > 0 {
                HandleRFBServerMessage(&self.localClient)
            }
        }
    }

func update(client: UnsafeMutablePointer<rfbClient>?, x: Int32, y: Int32, w: Int32, h: Int32) -> Void {
    let cl = client!.pointee
    let view_ptr = rfbClientGetClientData(client, &viewTag)
    let view = view_ptr?.assumingMemoryBound(to: RFBView.self).pointee
    view?.setNeedsDisplay(NSRect(x: Int(x), y: Int(y), width: Int(w), height: Int(h)))
}

class RFBView: NSView {

    let ctx = CGContext(data: nil, width: 800, height: 600, bitsPerComponent: 8, bytesPerRow: 4 * 800, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!

    var buffer: UnsafeMutableRawPointer? {
        return ctx.data
    }
    override func draw(_ dirtyRect: NSRect) {

        let image = ctx.makeImage()

        NSGraphicsContext.current()?.cgContext.draw(image!, in: frame)

   }

It works but the display is not smooth. The server is running on the same machine in a VM so no network issues.
I'm redrawing the whole image for every update which I assume is the cause of the problem. So how can I redraw only the part of the framebuffer that is updated?
Is CoreGraphics fast enough for this or should I use NSOpenGLView?
Comment: no need to redraw it 1000 times per second. try 15fps `Timer.scheduledTimer(withTimeInterval: 1/15,` the lesser the better. It doesn't need to look like a movie
Comment: I did try playing with the frame rate, but I can't get acceptable performance out of it.
Answer: I assumed that HandleRFBServerMessage would call update function once per iteration if there was an update. But that is not the case.
I replaced update with a stub that printed to console, and noticed it was being called more than thousand times when there was a lot of activity on the screen.
However, with the setNeedsDisplay call inside update, it was only being called a few hundred times. Since it was spending too much time rendering it was missing out on a few frames in between.
I moved the drawing code inside the Timer and it works perfectly now.
localClient.GotFrameBufferUpdate = { _, _, _, _, _ in needs_update = true }
Timer.scheduledTimer(withTimeInterval: 0.016, repeats: true) {_ in
    if needs_update {
        view.display()
        needs_update = false
    }
    if WaitForMessage(&self.localClient, 1) > 0 {
        HandleRFBServerMessage(&self.localClient)
    }
}

Stream remote framebuffer into NSView


A mistake causes the function to be rendered infinity

Question: I tried to add a button to my code, To change some properties of an array by clicking on it. To do this, I used Context and Reducer. But there is a problem!
When I comment the dispatch, the problem is solved and the function is rendered only once. but when I use Reducer, the function rendered infinite times! please help me :(
It is worth mentioning that this reducer has been used in other components, but this problem has not occurred.

App.js : (only reducer)

 const [goodsState, goodsDispatch] = useReducer(GoodsReducer, {
    goods: [
      {name : 'x', price : 126000, selected : false, key : 1},
      {name : 'y', price : 123000, selected : false, key : 2},
      {name : 'z', price : 126000, selected : false, key : 3},
          ]
  });

Cart.js :

import React, { useContext } from "react";
import GoodsContext from "../Contexts/GoodsContext";

export default function Cart(){
  const goodsContext = useContext(GoodsContext);
  const selectItem = (key) => {
  goodsContext.goodsDispatch({ type: "buy-item", payload: { key: key } });
};

return (

{selected[0].name}

{selected[0].price}

        <button onClick={selectItem(selected[0].key)}>+</button>
        //some cod

    );
};

GoodsReducer.js :

export default function GoodsReducer(state, action) {
  switch (action.type) {
    case "buy-item":
      return buyItem(state, action);

    default:
      return state;
  }
}

const buyItem = (state, action) => {
  let key = action.payload.key;
  changedGoods.selected = true;
  const otherGoods = state.goods.filter((good) => good.key !== key);
  return {
    ...state,
    goods: [...otherGoods, changedGoods]
  };
};

Answer: You have to add a Callback to your onClick:
onClick={() => selectItem(selected[0].key)}

Otherwise the selectItem will be called on every render, resulting in an infinte loop of renders. It has nothing to do with useReducer.


Does a Normal Distribution imply a natural process?

Question: I am excluding the case where someone generates a normal distribution by a Human, non Nature process.
Specifically to determine if humans are managing outcomes to achieve some result, say a higher score,
wouldn't the distribution be positively skewed?  Where a normal distribution might imply that either
no human interference is involved or it is ineffective.
Edit: Sorry for the confusion. By natural I meant Non Human.
I should have asked: what information can I glean from the lack of a skewed distribution (Normal Distribution) OR from a + of - skewed distribution?
Is the only implication of a skewed distribution that my data sample is not from
a single homogenous population?
Comment: What do you mean by a non-natural process? This is not entirely clear to me. Also... Why do you believe that non-natural processes can't result in normal distributed variables (and as a consequence a normal distribution implies a natural process)?
Comment: Re "only implication:" skewness does not, of itself, imply a population is "inhomogeneous."
Answer: Great question. There are many natural processes that exist, and that is a reason why the normal distribution is so popular and abundant in statistics, life-sciences, etc. However, broad statements like that require caution.
For example, I would simply add that the reverse is not true. That is, there are many 'natural' processes that are non-normal.
In genomics, gene expression is measured when transcription occurs inside the cell, producing RNA that can be measured by the total amount of transcripts produced by that gene. This results in count data, which is usually modeled by Poisson or Negative Binomial regression. There are transformations that can help lead to normality, but the data itself is non-normal.
There are plenty of other examples, but just wanted to point out natural, non-normal processes exist, thus the implication is one-sided and not both-sided.
Comment: To claim there may be exceptions, when focusing on a single gene RNA as noted in human-based experiments (contrary to the text of the question) does not deny my comment of at least consistency.
Answer: Yes, the normal distribution is somewhat 'natural' due to its finite variance, but perhaps more of a general averaging construct. To quote a source:

The average of a sequence of values from any distribution will approach the normal distribution, provided the original distribution has finite variance...
The condition of finite variance is true for almost all systems of practical interest.

And further:

What is the engineering significance of this averaging process (which is really just a weighted sum)? Many of the quantities we measure are bulk properties, such as viscosity, density, or particle size. We can conceptually imagine that the bulk property measured is the combination of the same property, measured on smaller and smaller components. Even if the value measured on the smaller component is not normally distributed, the bulk property will be as if it came from a normal distribution.

So, per the question, 'Does a Normal distribution imply a natural process?', my answer is that [EDIT], at least,[END EDIT] it is certainly consistent with naturally occurring bulk processes.
[EDIT] Further, I would argue that the question is clear, not even a repeated human orchestrated homogeneous reaction system with varying parameters, but, as occurs in nature, so-called heterogeneous chemistry. So particle sizes, for example, are further averaged over many compounds.
To claim such a natural heterogeneous system is not at least consistent with a so-called normal distribution associated averaging process is suspect in my view.
Comment: This is probably a matter of opinion, but plenty of people have found--through experience--that many (if not most) "natural processes" don't produce anything like Normal data.  I'm sure the sense of "most" is rather personal and tailored to one's specialty and experiences: but at the least, so that you do not mislead many readers, that implies you need to be much more specific about your statement and what you mean by "naturally occurring bulk processes."
Comment: The implicit assumption, which is incorrect, is that "naturally occurring bulk process" will produce normally distributed values.
Comment: Correction on Whuber assertion use of the verbs "will produce". Clearly stated in my last sentence, the phrase "is certainly consistent" with naturally occurring bulk processes. Being consistent is hardly arguing any definiteness as mis-asserted by the word "producing". I will edit further adding the words "at least".
Comment: The bulk property being normal distributed is only the case when the bulk stems from a sum of many little components. There are possibilities that break this situation. The bulk property might stem from a product of variables (in [which case](https://stats.stackexchange.com/questions/480967) the distribution will be log-normal distributed). Another way that you do not get a normal distribution is when you have a mixture distribution. For instance the bulk property might be a mixture of components, e.g. the strength of chocolate depends on the state of the crystals and will be multimodal.
Comment: Well, one can disagree with the claimed engineering-related conceptualization of "naturally occurring bulk processes" as an "averaging process", per my cited source, not myself. The latter bulk processes are only briefly enumerated, for example, as "viscosity, density, or particle size".
Comment: Another way is when the bulk property is some function of another bulk property. That's how spectral line intensity can follow a Lorentz distribution (Cauchy distribution for statisticians). In the case of particle size distributions one often finds distributions that vary a lot from a normal distribution (because the steps in the random growth process and the different particles are not independent, e.g. think about Ostwald ripening).
Comment: Sextus Empiricus: Staying with the particle size distribution, if one is manufacturing nano-particles, the particle size distribution can be a function of annealing temperature and duration of annealing. Repeating production with varying conditions, could per my opening comment derived from the CLT, to quote: "The average of a sequence of values from any distribution will approach the normal distribution, provided the original distribution has finite variance".


Questions about the surface and counter plot of copula functions

Question: I applied a copula model to my data. Then I plot the surface plot for each selected copula function. As I understand, each colour in the plot indicates the strength of the dependency. For example, red (strong dependency), yellow (moderate dependency), and blue (no dependency). Based on this, I supposed that the plot for Frank and Gaussian copula will give me red colour in the middle and blue at the tails! However, I got the opposite. However, for Clayton and Joe copulas, the situation is different. That is, the tails are presented in red colour! For example, please see the plots in this paper here.
So my first question is, is my understanding regarding the colour of the surface plot correct? I think the surface plot presents the tails in red colour as they are extreme values. Is that correct?
My second question, copula contour plots show numbers inside the plots, what are these numbers for? That is, what does 0.3,0.2,0.15 refer to? Do these values explain the level of dependency?
Answer: To answer your first question: yes you are correct. The standard color maps usually are like in this figure:

The number that you see represented in the contour plot there are the level curve values. It means that your function assumes those values when you "cut" it with a horizontal plane at different "heights".


R: Calculating mean and standard error of mean for factors with lm() vs. direct calculation -edited

Question: When dealing with data with factors R can be used to calculate the means for each group with the lm() function. This also gives the standard errors for the estimated means. But this standard error differs from  what I get from a calculation by hand.
Here is an example (taken from here Predicting the difference between two groups in R )
First calculate the mean with lm():
    mtcars$cyl <- factor(mtcars$cyl)
    mylm <- lm(mpg ~ cyl, data = mtcars)
    summary(mylm)$coef

                Estimate Std. Error   t value     Pr(>|t|)
  (Intercept)  26.663636  0.9718008 27.437347 2.688358e-22
  cyl6         -6.920779  1.5583482 -4.441099 1.194696e-04
  cyl8        -11.563636  1.2986235 -8.904534 8.568209e-10

The intercept is the  mean for the first group, the 4 cylindered cars.
To get the means by direct calculation I use this:
  with(mtcars, tapply(mpg, cyl, mean))

         4        6        8
    26.66364 19.74286 15.10000

To get the standard errors for the means I calculate the sample standard variation and divide by the number of observations in each group:
 with(mtcars, tapply(mpg, cyl, sd)/sqrt(summary(mtcars$cyl)) )

         4         6         8
   1.3597642 0.5493967 0.6842016

The direct calculation gives the same mean but the standard error is different for the 2 approaches, I had expected to get the same standard error.
What is going on here? It is related to lm() fitting the mean for each group and an error term?
Edited:
After Svens answer (below) I can formulate  my question more concise and clearly.
For categorical data we can calculate the means of a variable for different groups is by using lm() without an intercept.
  mtcars$cyl <- factor(mtcars$cyl)
  mylm <- lm(mpg ~ cyl, data = mtcars)
  summary(mylm)$coef

      Estimate Std. Error
  cyl4 26.66364  0.9718008
  cyl6 19.74286  1.2182168
  cyl8 15.10000  0.8614094

We can compare this with an direct calculation of the means and their standard errors:
  with(mtcars, tapply(mpg, cyl, mean))

         4        6        8
    26.66364 19.74286 15.10000

  with(mtcars, tapply(mpg, cyl, sd)/sqrt(summary(mtcars$cyl)) )

         4         6         8
   1.3597642 0.5493967 0.6842016

The means are exactly the same but the standard errors are different for these 2 methods (as Sven also notices). My question is why are they different and not the same?
(when editing my question, should I delete the original text or adding my edition as I did )
Answer: The difference in standard errors are because in the regression you compute a combined estimate of the variance, while in the other calculation you compute separate estimates of the variance.
Comment: Thank you for clarifying this. I just found a very good answer for a similar question here, with a nice worked example:

http://stats.stackexchange.com/questions/29479/difference-between-ci-of-anova-level-coefficients-vs-t-test-ci-which-one-is-c?rq=1
Comment: Yes, that looks relevant. Well spotted.
Answer: The lm function does not estimate means and standard errors of the factor levels but of the contrats associated with the factor levels.
If no contrast is specified manually, treatment contrasts are used in R. This is the default for categorical data.
The factor mtcars$cyl has three levels (4,6, and 8). By default, the first level, 4, is used as reference category. The intercept of the linear model corresponds to the mean of the dependent variable in the reference category. But the other effects result from a comparison of one factor level with the reference category. Hence, the estimate and standard error for cyl6 are related to the difference between cyl == 6 and cyl == 4. The effect cyl8 is related to the difference between cyl == 8 and cyl == 4.
If you want the lm function to calculate the means of the factor levels, you have to exclude the intercept term (0 + ...):
summary(lm(mpg ~ 0 + as.factor(cyl), mtcars))

Call:
lm(formula = mpg ~ 0 + as.factor(cyl), data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max
-5.2636 -1.8357  0.0286  1.3893  7.2364

Coefficients:
                Estimate Std. Error t value Pr(>|t|)
as.factor(cyl)4  26.6636     0.9718   27.44  < 2e-16 ***
as.factor(cyl)6  19.7429     1.2182   16.21 4.49e-16 ***
as.factor(cyl)8  15.1000     0.8614   17.53  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.223 on 29 degrees of freedom
Multiple R-squared: 0.9785, Adjusted R-squared: 0.9763
F-statistic: 440.9 on 3 and 29 DF,  p-value: < 2.2e-16

As you can see, these estimates are identical to the means of the factor levels. But note that the standard errors of the estimates are not identical with the standard errors of the data.
By the way: Data can be aggregated easily with the aggregate function:
aggregate(mpg ~ cyl, mtcars, function(x) c(M = mean(x), SE = sd(x)/sqrt(length(x))))

  cyl      mpg.M     mpg.SE
1   4 26.6636364  1.3597642
2   6 19.7428571  0.5493967
3   8 15.1000000  0.6842016

Comment: Thanks for the response. I already know that coefficients are not the means, as I wrote the intercept is the mean of the first level, the other coefficents are the difference in mean of the other levels to that level. You also notice that with your remark "standard errors of the estimates are not identical with the standard errors of the data."
Does that mean that lm() estimates the means and calculate standard errors for those estimates
Comment: Ooops, I wanted to edit that comment for clarity but did not know I only could edit for 5 minutes, can I delete a comment?

I did not realize that I could get mean estimates directly by omitting the intercept, thanks for that tip.

If I understand you correctly, the standard errors of the estimated means are not the same as the standard errors calculated directly from the data. Is it a different set of equations used in each case? And what are these equations? I would like to have some more details to u nderstand the difference better
Answer: In addition to what Sven Hohenstein said, the mtcars data is not balanced. Usually one uses aov for lm with categorical data (which is just a wrapper for lm) which specifically says on ?aov:

aov is designed for balanced designs, and the results can be hard to
  interpret without balance: beware that missing values in the
  response(s) will likely lose the balance.

I think you can also see this on the weird correlations of the model matrix:
mf <- model.matrix(mpg ~ cyl, data = mtcars)
cor(mf)
            (Intercept)       cyl6       cyl8
(Intercept)           1         NA         NA
cyl6                 NA  1.0000000 -0.4666667
cyl8                 NA -0.4666667  1.0000000
Warning message:
In cor(mf) : the standard deviation is zero

Hence, the standard errors obtained from aov (or lm) will likely be bogus (you can check this if you compare with lme or lmer standard errors.
Comment: How would you apply lme  here?
Comment: The correlations of the model matrix values are not weird. Since the constant (intercept) inherently is equal to one, there's no variation between its values. Due to this, you can't compute a correlation coefficient between a variable and the constant.
Answer: Y = matrix(0,5,6)
Y[1,] = c(1250, 980, 1800, 2040, 1000, 1180)
Y[2,] = c(1700, 3080,1700,2820,5760,3480)
Y[3,] = c(2050,3560,2800,1600,4200,2650)
Y[4,] = c(4690,4370,4800,9070,3770,5250)
Y[5,] = c(7150,3480,5010,4810,8740,7260)

n = ncol(Y)
R = rowMeans(Y)
M = mean(R)

s = mean(apply(Y,1,var))

v = var(R)  -s/n

#z = n/(n+(E(s2)/var(m)))
Q = 6/(6+(s/v))
t = Q*R[1] + (1-Z)*M

Comment: This is unreadable and lacks any sort of commentary about what it means or does. Can you edit it to give more clarity?
Comment: It is not possible to understand the answer. It does require some commentary to explain what you are doing.


How do i print image title in custom node for image gallery

Question: I use content types for image gallery and write own custom node for image gallery all images are show in custom node by following code but i don't know how to print the image title.
In this code i have given static title 'Circles and Cycles ' and i need dynamically title of every image.
<div id="node-<?php print $node->nid; ?>" class="node-gallery">

    <?php
        $imgcount = count($node->field_gallery_image['und']);
        for ($i = 0; $i < $imgcount; $i++) {
        $image_uri = $node->field_gallery_image['und'][$i]['uri'];
            // url
            $masthead_raw = image_style_url('gallery-thumb', $image_uri);

    ?>

          <a href="<?php print file_create_url($node->field_gallery_image['und'][$i]['uri']); ?>" rel="group-<?php print $node->nid; ?>" class="product-link">

 <img class="image<?php print ($i + 1);?>" src="<?php print $masthead_raw; ?>" />

Circles and Cycles

      <?php
        }?>

Answer: Create a view of your content type, then in this view select the fields as your content and then select the title and the image. then every image will have its own title. you can also theme it in any way that you want.
you need to output this view in your node page, so simply in your template.php and in hook_preprocess_node function suggest a theme hook for this content type (for example page--node--gallery.tpl.php) and then in the page--node--gallery.tpl.php output the view using views_embed_view("view_name","display").
Comment: sir, i want to print the image title programmatically at node--gallery.tpl.php like image without making view.
Comment: It is possible to create a view and embed it in the node page. But I'm surprising why you are insisting on doing this with out the views while views make it very easy !


Distorted audio on Windows XP

Question: I built a new workstation with an Asus P5Q Pro motherboard, using the onboard sound for a soundcard. It is running Windows XP-64bit.
It works fine except when I try to open this WMV stream: http://www.bloomberg.com/streams/video/LiveBTV200.asxx (SFW: Its a business news stream)
The sound is very distorted (kind of pixelated with an echo).
I have taken the following steps to fix/debug this problem:

Tried various media players: VLC,
Windows Media player etc... they all play it with the same distorted sound.
Tried upgrading to the newest driver and downgrading to older driver.
Tried opening other wmv streams and media files... they all play fine.
Ruled out a network issue by using my laptop on the same network to open the stream.
Any ideas what could be causing this problem?
Answer: My thoughts on this would be a problem between the codec, and the driver for the sound card. Unfortuantely windows XP 64bit is renowed for bad driver support. I would suspect that that particular stream uses a codec thats different to anything else you use, for streams that are working, and its having a problem when working with your sound card driver.
Is there any particular reason your using Windows XP 64bit? I know Vista takes alot of bashing, but when it comes to 64bit support its miles ahead of XP. Its a bit drastic for one audio stream I know, but my suggestion would be to change OS's either to Vista x64, or down to xp 32 bit. If it is a driver issue, your unlikely to see any improvement as I doubt there is any further development on most 64bit XP drivers.
Answer: Its pretty much the same for me - As like you I don't have problems with other streams - Its them - Perhaps they have poor encoding or are you using a non standard codec
Answer: For what it's worth to add some details:

The audio codec is Windows Media 9 Voice. On a complete aside it doesn't play with Macs (without an ancient version of Windows Media Player) and sounded okay (but a bit like what you explained - not unbearable but noticeable) when played in a Virtual Machine running Windows XP

Distorted audio on Windows XP


how to call solidity fallback function from react front end client app

Question: In my solidity smart contract there is a fallback function as follow:
contract MyContract {
//rest of contract
...

//**Fallback function**
    function () payable external {}
}

In my react client app , i have following code snippet:
...
const instance = new web3.eth.Contract(
        MyContract.abi,
        deployedNetwork && deployedNetwork.address,
      );
...
await instance.methods.send({from:this.state.accounts[0],value:this.state.chargeValue})
...

in the console log following error
TypeError: this.state.contract.methods.send is not a function
in the contract javascript test script i can call fallback function with following code:
const MyContractInstance = await MyContract.deployed();

await MyContractInstance .sendTransaction({value:"1000000000000000000" });

Answer: Instead of creating the Contract instance and using its helper methods (there is no helper method to execute the fallback function), you can build a tx with missing data field.
await web3.eth.sendTransaction({
    to: deployedNetwork.address,
    from: this.state.accounts[0],
    value: this.state.chargeValue
});

If you don't specify the data field, it's going to be empty, which results in executing the contract fallback function.
Docs: https://web3js.readthedocs.io/en/v1.3.4/web3-eth.html#sendtransaction
Comment: Many thanks for your answer , just one more thing , how can I call fallback function from solidity test script. I could call it from  javascript test script but I don't know how to call it from solidity test script.
Comment: @MohammadMomtaz In Solidity test, you can use the low-level `.call()` member of `address` type. Example: `externalContractAddress.call("")` (the empty string is the empty data field) ...  Docs: https://docs.soliditylang.org/en/v0.8.6/types.html#members-of-addresses


Hooking up my Avlex PA-200 or Fender PX-22080 mixing console to two Passive studio Monitors with RCA inputs. will it work?

Question: I got myself in a bit of a pickle trying to figure out how to set up studio monitors so I could stop running my music I make through guitar cabs and my TV. Ideally, I'd run my interface (scarlett 2i2) into my mixing console (PX-22080 - super old, I know.). and then output to daisy chained RCA studio monitors.
I didn't notice the Rokit KRK monitor speakers only have RCA inputs on them. Would I have better luck just buying powered studio monitors?
Comment: Are you sure your KRK's are not powered? It's unusual for passive speakers to have RCA terminals, they tend to have some kind of screw or clip speaker terminals. The Rokit passives I have seen look like they have screw speakers terminals rather than RCA's. Still, you would know if they have a power socket on them! The PX-22080 also often shipped with a power amp. I'm a bit lost in product numbers having a look around, but if you DO have the passive rokits and you DO have the desk that has a power amp as part of it then you should be fine just using those, as long as everything is working!
Answer: I wasn't able to find any details on any KRK passive monitors that would have RCA inputs, so here is some general information about setting up passive monitors:
Before using the speaker outputs of a powered amp such as the Px-2208 you want to check the specifications of the speakers and make sure the the impedance matches the output of your amp. For example, the output on the Fender mixer requires a 4 ohm speaker array. Mismatching your power amp to the wrong impedance can damage your amp.
One of the advantages of powered speakers is that the amp in the speaker is specifically matched to the speaker.  If you do decide to get powered monitors then you could either go directly from the 2i2 into the monitors, or use your mixer and send through the line outputs from the board.
Usually passive speakers have wire terminals of some sort for the inputs. I have mostly seen screw down, spring clip, banana plugs, and 1/4inch TS jack inputs. In general there will be a positive and a negative input. In some cases such as passive stage monitors there is a "through" jack that lets you chain the monitors together.  I think it is unusual to see RCA jacks for passive speaker input, although I think I remember some bookshelf stereo systems using them.  If the KRKs have them they may have had a power amp that was paired with them.
Either way, I wouldn't daisy chain your speakers since that would only give you a mono output. Your mixer has two amp outputs, so you should use the outputs to set up left and right sides so you can use stereo pan mixing. You can put the left and right outputs of the 2i2 into separate channels on your mixer and pan them to either side.


Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Question: Necessito abrir um arquivo txt e armazenar as informações dele em um ArrayList e depois fazer uma comparação entre o que foi digitado e o que tem no mau ArrayList para ver se o login esta certo ou não.
Segue o meu código:
public void actionPerformed(ActionEvent evento)
{
  if( evento.getSource( ) == bENTRAR )
  {
     openFile();
     //Gravando records = new Gravando();
     int i = 0;
     System.out.println(grava.getListaMateria().size());
     while( i <= grava.getListaMateria().size())
     {
        System.out.println(grava.getListaMateria().get(2).getLogin());
        if(grava.getListaMateria().get(i).getLogin().equals(l) && grava.getListaMateria().get(i).getSenha().equals(s))
           {
              JOptionPane.showMessageDialog(null,"Login feito com sucesso","Bem vindo",1);
              dispose();
              MenuGUI oples = new MenuGUI();
           }
           System.out.println(grava2.getListaMateria().get(i).getLogin()+"\n"+grava2.getListaMateria().get(i).getSenha());
       i++;
       }
      JOptionPane.showMessageDialog(null,"Login ou senha incorretos","Desculpe",1);

   }
 }

public void openFile()
{
  l = tLogin.getText();
  s = Senha.getText();
  try
  {
     input = new Scanner(new File( "login.txt" ));
  } // end try
  catch( FileNotFoundException fileNotFoundException )
  {
     System.err.println( "Error opening file." );
     System.exit( 1 );
    } // end catch

  ArrayList<Gravando> lp = new ArrayList<Gravando>();
  try // read records from file using Scanner object
  {
     while(input.hasNext())
     {
        grava.setLogin( input.next() ); // read account number
        grava.setSenha( input.next() ); // read first name

        lp.add(grava);
     } // end try

  }
  catch ( NoSuchElementException elementException )
  {
     System.err.println( "File improperly formed." );
     input.close();
     System.exit( 1 );
  } // end catch
  catch ( IllegalStateException stateException )
  {
     System.err.println( "Error reading from file." );
     System.exit( 1 );
  } // end catch

  grava.setListaMaterias(lp);
  input.close();
} // end method openFile

Porém quando rodo dá o erro:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.rangeCheck(ArrayList.java:653)
        at java.util.ArrayList.get(ArrayList.java:429)
    at LoginGUI.actionPerformed(LoginGUI.java:309)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6535)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6300)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4891)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
.

Comment: Como eu já disse, você deve estar acessando um indice inexistente do arrayList. Talvez adicionando um [mcve] seja possivel localizar o erro.
Comment: Pode adicionar a pilha completa do erro? Esse erro está relacionado ao acesso de indices inexistentes num array ou vetor.
Comment: Claro, editei a minha pergunta e adicionei o erro completo  @diegofm
Comment: Onde é a linha 309?
Comment: A inha 309 é: System.out.println(grava2.getListaMateria().get(i).getLogin()+"\n"+grava2.getListaMateria().get(i).getSenha());
Comment: Outro detalhe, o array está vazio, cheque seu método que preenche-lo com o TXT, provavelmente nada está sendo copiado.
Comment: Consegui resolver a situação,@ diegofm
Answer: Seu problema está aqui:
while( i <= grava.getListaMateria().size()

A comparação do valor do i deve ser < e não <=. O correto seria:
while( i < grava.getListaMateria().size()

Os índices do array começam em 0, por isso eles só vão até o tamanho do array - 1. Por exemplo, se o tamanho de um array é 2, os índices acessíveis seriam 0, e 1.
Comment: muito obrigado pela a sua ajuda, fiz o que voce falou e funcionou
Comment: Show! Marca como respondido pra ajudar outras pessoas :)


Odds ratio and likelihood of A given B

Question: I've observed 500 nurses touching different surfaces during 500 episodes of patient care.
I've also recorded whether they wash their hands after they finish.
I'd like to find out if touching the patient makes it more likely (or has no influence) on hand hygiene. Is an Odds ratio the right statistical measure to use? And if so could you please point me in the right direction in calculating it?
Regards,
MF
Comment: There are two issues: interpretation and estimation. These data do not allow you to support any conclusion that touching the patient "affects" hygiene. All you can possibly conclude is that the events are associated. (For instance, perhaps hygiene and touching are related because they stem from some innate quality in each nurse, not because the act of touching caused the nurse to wash hands.) Estimation amounts to computing the hand washing rates within each group: touched and did not touch. Confidence intervals are most readily obtained using @Kjetil's approach of logistic regression.
Comment: The hypothesis to check would be that touching is independent of handwashing; the correct alternative to use is that touching and handwashing are dependent--*without specifying whether the dependency is a negative or positive one.* This places you in the simple, classical situation of analyzing a $2\times 2$ [contingency table.](http://stats.stackexchange.com/search?q=contingency+table+chi)
Comment: @whuber This seems logical. And then how does one deduce by how much patient contact affects or doesn't affect hygiene?
Answer: You could use a logistic regression, then you are implicitely using oddsratios as the measure.  The parameter $\beta$ in a logistic regression is the log odds ratio.
To add some detail: let the index $i$ index the observations, so the covariable $x_i$  is the type of contact $i$, being a categorical variable, and $y_i=1$ if washing hands after contact $i$, zero contrarywise. Then logistic regression is the model:
$$
P(y_i=1 | x_i) = \frac{e^{\alpha+\beta x_i}}{1+e^{\alpha+\beta x_i}}
$$
Note that the equation must be read symbolically, the exact interpretation of the $\beta$s depend on the coding of $x$.  The most usual (recommended) coding:  If there are $k$ possible categories for $x$, then it is coded with $k-1$ dummys. The one category "left out" is the "reference category", and the $k-1$ $\beta$s express comparison with that left-out category. So each of those $\beta$s is an estimate of the log-oddsratio for the comparison of that category to the left-out one.
Comment: Could you clarify a little please? I've looked up the logistic regression so only just familiar with it. What will it really tell me? More than a simple probability P(Hand hygiene | Patient contact) ?
Comment: That sounds really good, thank you. I'm not sure how to categorise my $x$. I.e. I have for each observation: Patient contact= Yes or No, then Hand hygiene: Yes or No.
Comment: So you have only $k=2$ categories? Then you only need one dummy, so you can code patient contact yes=1, no=0.  If you usr software like R, the software will take care of construction of dummys.
Comment: I dont really understand how categories can be coded into this regression model. E.g. Imagine instead i have 5 surface groups: near patient, far from patient, patient, hygiene products, equipment. They are not like age groups of patients with or without a disease, which are sequential. I dont see how this fits.. Could you clarify please?

Odds ratio and likelihood of A given B


with Catalyst framework, how to check the uri path in wrapper.tt

Question: I like to check the path in wrapper.tt, so I can dynamically include links based on the path.  But I can't figure out the way to get the path in the tt file after extensive online search.  For example, I can check if a user has signed in and, if yes, show the user's name as the following.  Thanks.
[% IF c.user_exists %]

[% c.user.username %] logout

[% ELSE %]

login

[% END %]

Answer: I got the answer.  c.req.path is the uri path.


Como ler os comentários dos campos da tabela MySQL?

Question: Esse comando

SHOW COLUMNS FROM [nome da tabela];

Mostra os campos de uma tabela e os detalhes mais importantes deles
Eu preciso ler os comentários do campo, exemplo:

COLUMN cod_id INT(10) UNSIGNED NOT NULL COMMENT 'CÓDIGO DE
  CLIENTE'

Essa parte eu peguei no codigo de create da tabela
Precisaria ler com conteudo de "COMMENT"
Comment: Olhe essa resposta: [Link](https://pt.stackoverflow.com/a/185269/92908)
Answer: Existe um banco de dados chamado information_schema, esse banco de dados é responsável por armazenar as estruturas de todos os bancos de dados.
Para você pegar o comentário de uma coluna pode selecionar a tabela COLUMNS:
SELECT a.`COLUMN_COMMENT`
FROM `information_schema`.`COLUMNS` a
WHERE a.`TABLE_SCHEMA` = 'seu_banco' AND a.`TABLE_NAME` = 'sua_tabela' AND a.`COLUMN_NAME` = 'sua_coluna';

Aliás, essa tabela armazena todas as informações de uma coluna, não só o comentário. Esse banco de dados também é útil para outras coisas, como por exemplo pegar todas as informações das tabelas de um banco específico:
SELECT * FROM `information_schema`.`TABLES` a
WHERE a.`TABLE_SCHEMA` = 'seu_banco'

Comment: A fonte seria essa: [FONTE](https://forum.zwame.pt/threads/obter-comment-do-field-de-1-tabela-mysql.189876/)? Caso sim, põe na resposta. ✌
Comment: Então Roberto no mesmo momento que vc estava colocando sua resposta acabei achando um comando bem simples: SHOW FULL COLUMNS FROM TABELA;
O FULL traz todos os pormenores da tabela, agradeço pela resposta
Comment: @rbz, a fonte não foi essa, inclusive montei o `SELECT` manualmente no meu `menangement`.
Comment: @Marcelo, o importante é ter o problema resolvido.
Answer: já achei o comando

SHOW FULL COLUMNS FROM [TABLE];

A fonte: https://stackoverflow.com/questions/5404051/show-comment-of-fields-from-mysql-table


How to Set external variable or program for Rstudio

Question: I know that this question is available in this page, but I have tried most of them, and I just can't make it works. How can I set an external program as blast permanently using Sys.setenv  for my personal functions in R
I'm using a MacOS with R4.1.1 and RStudio 2021.09.0.
The common way that I usually call an external program, in this case BLAST (ncbi-blast-2.2.29+) is just copy and paste the line in RStudio console, something like:
Sys.setenv(PATH = paste(Sys.getenv("PATH"), "/Users/myname/myprograms/ncbi-blast-2.2.29+/bin/", sep= .Platform$path.sep))

And then I just run my personal functions that use blast, and I have no problem with that.  But I just want to set blast permanently in RStudio, and don't need to copy and paste that line every time that I start RStudio. So I tried to paste that line in .Renviron, and then start up Rstudio and tried to run blast functions, and it didn't work !!!
So I tried different, add the path in .zshrc (I'm using /bin/zsh), using nano or sublime text:
nano ~/.zshrc
export BLAST_PATH=$PATH:~/genetools/ncbi-blast-2.2.29+/bin/

And then just add the BLAST_PATH to Sys.setenv in .Renviron
nano .Renviron

Sys.setenv(PATH = paste(Sys.getenv("PATH"), "BLAST_PATH", sep= .Platform$path.sep))

or
Sys.setenv(PATH = paste(Sys.getenv("PATH"), BLAST_PATH, sep= .Platform$path.sep))

And restart RStudio and just it didn't work when I use my personal functions !!!
Any way to set it permanently in RStudio ?
By the way, My .Renviron is located at home (~/.Renviron) and my working directory (R sessions ) in RStudio is located in ~/R !!!
Thanks
Comment: Environment variables for a user has nothing to do with R. You need to set the variables in your pc. check https://unix.stackexchange.com/questions/117467/how-to-permanently-set-environmental-variables for example on how to do it in linux, and https://phoenixnap.com/kb/windows-set-environment-variable on windows
Comment: @Onyambu Except that these solutions categorically do not work for RStudio (or any other GUI applications) on macOS.
Comment: @KonradRudolph I specified that you do not necessarily need to use R. Setting environment variable has nothing to do with R. I am not sure about macOs. As far as I know, in windows, one cam simply use `setx` command, or just search for environment variables from the search button and set them the way they want
Comment: @Onyambu But as my answer shows *there is no good non-R way to do this on macOS*. You need R (specifically, `.Renviron`). So the question, for better or for worse, *does* have to do with R.
Answer: .Renviron does not accept "R code". You can check what's happening for example with calling readRenviron("~/.Renviron").
You could follow this route inside .Renviron or just put your code (above) in an .Rprofile file either in your $R_USER or project directory, depending on your requirements, ie if you want to have those ENV variables "project specific" or not.
Details on the startup process can be found in the R manual or for example in the startup package documentation, [startup package] also adds some nice functionality in case you need to handle passwords or other things along the "way" [ie. the startup process].
Answer: As mentioned, .Renviron does not expect R code but rather shell-like variable assignments. So you could add the following to your .Renviron:
PATH=~/genetools/ncbi-blast-2.2.29+/bin/:$PATH

You could also adjust your PATH inside .zshrc, but unfortunately RStudio will not see these values! Unless, that is, you are actually starting RStudio from inside your zsh, for instance via open -a RStudio. Only then will it work.
In general, applications only inherit the shell environment when they are launched from the shell, and .zshrc is only sourced by your zsh. This means that it cannot be used to set global configuration for applications on macOS. In earlier versions of macOS it was possible to configure the launch daemon (which is the background application that is launching all GUI applications on macOS). However, this no longer works because Apple disabled the mechanism.
Unfortunately, as far as I can tell, there is no way to configure the global environment for GUI applications on macOS any more. All the different hacks that are documented on Stack Overflow fail. The only way is via running launchctl setenv … at every startup.
Comment: thanks so much to all, it just didn't work for me, but I  will try again, thanks so much anyway !!!!


how to load retrieve form value from custom element

Question: i just done build a custom element based on this tutorial: https://docs.acquia.com/articles/drupal-8-creating-elements-theming-elements-and-managing-frontend-libraries
so let say my element type is "location"
so i have:
$form["location"] = [
      '#type' => 'location',
      '#label' => $this->t('Supplier Location'),
      '#theme' => 'supplier_location',
];

so inside type location there are a couple fields (e.g. textfield, select, etc.)
the problem here is: when i submit my form, i couldn't get those value:
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
        drupal_set_message($key . ': ' . $value); // i cant catch my custom element value here T_T why?
    }
  }

so apparently my custom element field value is not catched in submitform during submit, any idea why?
here is my custom element class code:
actually, below is the sample working code after discussion with @clive
<?php
/**
 * @file
 * Contains \Drupal\module\Element\Location.
 */

namespace Drupal\module\Element;

use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a location element.
 * @FormElement("location")
 */
class Location extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#element_validate' => [[$class, 'validateLocation']],
      '#process' => [[$class, 'processLocation'],[$class, 'processGroup']],
      '#pre_render' => [[$class, 'preRenderGroup']],
      '#theme' => 'location',
      //'#theme_wrappers' => ???, //what is theme wrappers?
    ];
  }

  /**
   * Prepare the render array for the template.
   */
  public static function processLocation(&$element, FormStateInterface $form_state, &$complete_form) {

    $countries = \Drupal::service('country_manager')->getList();
    $element['address'] = [
        '#type' => 'textfield',
        '#title' => t('Address: '),
        '#description' => t('Your Address'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your address here',
        ]
    ];

    $element['zip'] = [
        '#type' => 'textfield',
        '#title' => t('Zip: '),
        '#description' => t('Zip Code'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your Zip Code here',
        ]
    ];

    $element['city'] = [
        '#type' => 'textfield',
        '#title' => t('City: '),
        '#description' => t('Select City'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your city here',
        ]
    ];

    $element['state'] = [
        '#type' => 'textfield',
        '#title' => t('State: '),
        '#description' => t('Select State'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your State here',
        ]
    ];

    $element['country'] = [
        '#type' => 'select',
        '#title' => t('Country: '),
        '#options' => $countries,
        '#default_value' => '',
        '#required' => TRUE,
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    $element['latitude'] = [
        '#type' => 'hidden',
        '#title' => t('latitude: '),
        '#default_value' => "",
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    $element['longitude'] = [
        '#type' => 'hidden',
        '#title' => t('longitude: '),
        '#default_value' => "",
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    $element['zoom'] = [
        '#type' => 'hidden',
        '#title' => t('zoom: '),
        '#default_value' => "",
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    // Add the library
    $element['#attached'] = ['library' => ['module/arm_location_field_library']];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
      //what should i do here?
      return $input;
  }

  /**
   * Validation callback for a location element.
   *
   * @param array $element
   *   The form element whose value is being validated.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   */
  public static function validateLocation(&$element, FormStateInterface $form_state, &$complete_form) {
    //what should i do here?
  }

}

Comment: Without seeing your code it's difficult to say - what does your `valueCallback()` method look like for the custom element type?
Comment: I update the code in question
Comment: i dont have valueCallback() method, where should i put it?
Comment: It goes in the form element class, you're overriding [`FormElement::valueCallback()`](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!FormElement.php/function/FormElement%3A%3AvalueCallback/8.2.x). Pretty sure that's what you're missing
Comment: hmm thanks, let me explore that, do you have any reference, if i may? on how to override this?
Comment: Looking at that again I think I might have been wrong. Don't have time to double-check right now, but see what the [`Datetime`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Datetime%21Element%21Datetime.php/class/Datetime/8.2.x) element does for the `valueCallback` method. That element also has multiple fields, and returns an array for the value. Might be worth trying to at least `return $input;` from your own implementation of that method to see if it has an effect
Comment: thank you, still not success :( my element is extending from RenderElement, should i extend it from formElement? i tried to extend it from formElement but it said formElement class is not found...
Answer: Your form element needs to extend the FormElement class, rather than RenderElement.
Because of these few lines of code in ElementInfoManager::buildInfo:
// If this is element is to be used exclusively in a form, denote that it
// will receive input, and assign the value callback.
if ($element instanceof FormElementInterface) {
  $element_info['#input'] = TRUE;
  $element_info['#value_callback'] = array($definition['class'], 'valueCallback');
}

along with these in FormBuilder::doBuildForm:
// Handle input elements.
if (!empty($element['#input'])) {
  $this->handleInputElement($form_id, $element, $form_state);
}

more generic render elements won't be considered capable of providing input, and their values won't make it into the form state.
To fix (untested):

Replace use Drupal\Core\Render\Element\RenderElement with use Drupal\Core\Render\Element\FormElement
Replace @RenderElement("location") with @FormElement("location") in the annotation
Change your class to extend FormElement: class Location extends FormElement
Rebuild the cache
Comment: Thanks,

I changed it into FormElement without valueCallback() and add #input => True in getInfo();

when i try to print, it detect the variable "location" but the value is empty
Comment: I mark you as an answer - thank you for the help, i have update my code in question for anyone who like to see it. in general it is worked, i got the value passed down. just a minor thing: if you see in my buildForm(), i use $form['location'] with type 'location', ideally you should receive the value under/inside ['location'] from $form_state->getValues(); however, what i receive is: ['location'] = empty, ['address'] = correct, ['zip'] = correct, ['city'] = correct, etc. as an individual array (not inside ['location'] array) - how to make it inside ['location']? just to make it tidy.
Comment: Adding `'#tree' => TRUE` to the element definition in `getInfo` makes sure that element values are properly wrapped inside the main element.


Name for descending semitones under a repeating musical phrase?

Question: In much contemporary music, especially instrumental guitar music, there is a particular device employed. It involves a musical phrase in which usually one note, often a bass note, descends in one semitone intervals, while a(n often repeating) phrase is played.
Examples are in L'Amour Manque by Adrian Legg, the start of The Mystery and Footprints by Tommy Emmanuel, and the start of Stairway to Heaven by Led Zeppelin.
Given that this is so common, I wonder whether it's a recognised named musical device.
Comment: The answers already provided for this question are great, I just wanted to point out that Alex Ross talks about this "Lamento" motive throughout the second chapter of his book *Listen to This*. It's an interesting look at the figure throughout musical history.
Comment: Looks like he has a discussion of it here as well (with aduio samples!): http://www.therestisnoise.com/chacona/
Answer: As Bob mentions, this can be described as a descending chromatic bass line. If descending a fourth, from tonic to dominant, this can also be called a "Lament Bass". As a technique, it dates back at least to the early Baroque Era (famously used in Dido's Lament, that character's dying aria from Henry Purcell's Dido and Aeneas, and also in Bach's Crucifixus from his Mass in B-minor). The figure is often used to convey extreme grief, sorrow, and death.
In general, a repeating bass line with other music played over it is called a Ground Bass, or Ostinato Bass. The lament bass (descending chromatic bass line) is commonly employed as a ground bass (as in Dido's Lament). A popular example of a ground bass that isn't a lament bass would be the bass line to Pachelbel's Canon in D, being a continuosly repeated pattern of eight notes.
Comment: So, this figure in the melody would be the same as, for instance, Dowland's *Lachrimae*, right?
Comment: *When I am laid in earth*, a.k.a. Dido's Lament, is often cited as an example of a **passacaglia**. I think what the OP describes would be a passacaglia, but that wouldn't specifically mean a chromatically descending bass.
Comment: A Passacaglia (as well as the closely-related "Chaconne") is a specific form that uses an ostinato bass technique (as well as, usually, a triple meter, and a 'serious' mood); *Dido's Lament* fits this description. But neither a Passacaglia/Chaconne, nor an Ostinato Bass in general, is required to use a descending chromatic bass line (which, as a technique, can also be used outside those forms), and there are Ostinatos that are not Passacaglias/Chaconnes (e.g. Canon in D). Nevertheless, the Lament Bass was a popular choice for the Ostinato in Passacaglias/Chaconnes.
Answer: In popular music, this device is usually called Line Cliché. It is a chromatic line over a static chord creating the illusion of harmonic motion. Line chlichés are most often found in a minor key. The line usually moves near the 7th of the chord. A very common descending line (over a minor triad) is: root -> maj 7th -> min 7th -> maj 6th. This is exactly what you hear in Stairway to Heaven.
Comment: Interesting...does *Line Cliché* refer only to this particular chromatic line in the bass or is it a more general term indicating chromatisms giving the illusion of harmonic change?
Comment: @Bordaigorl: It's more general, it just needs to move chromatically, but it can either ascend or descend, and it can start on different notes. However, as mentioned in my answer, it's always in the area of the 7th of the chord. Also, it's not necessarily in the bass.
Answer: A series of pitches which move down by semitones is a descending chromatic scale. If this line is in the bass you could call it a descending chromatic bassline.
If the harmony above this bassline remains unchanged, the resulting chords can be described as a series of inversions. In popular music terminology this is most easily achieved using "slash-chords". For instance, if a full C Major triad is played or held continuously over a descending chromatic bassline starting on the note C, the resulting chords could be described as:
C  C/B  C/Bb  C/A  C/Ab etc.
You could also take account of the interval added by the bass note:
C  Cmaj7/B  C7/Bb  C6/A
This is particularly useful if you want to "allow" musicians playing the full chords to include the bass note in the chords/lines they play.
Also, it is worth noting that some of the resulting chords can be described differently. For instance, a C/A or C6/A chord can also be named Am7. The choice of chord name is probably best decided by context. If you want to make it clear that the harmony is static above a changing bassline, it would be best to keep the chord name the same (i.e. use C/x in the examples above).


Linear Programming Constraint Percentages

Question: I have a homework about linear programming. I have to formulate the constraint of the following:

A company produces two products, Deluxe and Special. The company decided that the Special must comprise at least 40 percent of the production total.

I have attached my solution. Do you thing my solution is correct already? I just want to be sure if my answer is correct. I hope you can help me thank you.
Answer: Your solution seems fine.
Divide by $0.2$, it can be simplified to
$$-2x_1+3x_2 \ge 0$$
Comment: Thank you so much for your help!


Fundamental group of a compact space with compact universal covering space

Question: I have this problem for Riemannian manifold, but think that it is just a topological problem. I know that this is probably a silly question, but it is since a while that I don't study general topology and algebraic topology..
Let $X$ be a compact topological space and assume that its universal covering space $\tilde{X}$ is also compact.  How can I prove that the fundamental group of $X$ is finite?
Thanks!
Answer: Consider the covering map $\pi \colon \tilde{X} \rightarrow X$. Above any $p \in X$, the fiber $\pi^{-1}(p)$ is a discrete closed subset of a compact space $\tilde{X}$ and so must be finite. By the general theory of covering spaces, if we fix some $\tilde{p} \in \tilde{X}$ with $\pi(\tilde{p}) = p$ then we obtain a bijection between $\pi_1(X,p)$ and $\pi^{-1}(p)$ given by sending (the homotopy class of) a based loop $\gamma \colon [0,1] \rightarrow X$ at $p$ to $\tilde{\gamma}(1)$ where $\tilde{\gamma} \colon [0,1] \rightarrow X$ is the unique lift of $\gamma$ to $\tilde{X}$ satisfying $\tilde{\gamma}(0) = \tilde{p}$. Thus, $\pi_1(X,p)$ is finite.
Answer: The action of $\pi_1(X)$ on $\tilde X$ is proper and free. Suppose that $\pi_1(X)$ is infinite, consider $(f_n)$ pairwise distinct elements of $\pi_1(X)$, for $x\in \tilde X$ the sequence $f_n(x)$ has an accumulation point. Contradiction since the action of $\pi_1(X)$ on $\tilde X$ is proper.


Prove that if $p$ is a prime and $a$ and $b$ are nonzero integers such that $a\equiv b$ (mod $p^2-p$), then $a^a \equiv b^b$ (mod $p$)

Question: Prove that if $p$ is a prime and $a$ and $b$ are nonzero integers such that $a\equiv b$ (mod $p^2-p$), then $a^a \equiv b^b$ (mod $p$). I know
$$p^2-p \vert (a-b)\iff p(p-1) \vert (a-b) \iff p \vert \frac{a-b}{p-1}$$
I don't know any more though. A hint would be much appreciated.
Comment: Hint: Fermat's Little Theorem
Comment: Technically, you want positive integers, since $a^a\equiv b^b\pmod p$ is problematic if one of them is negative.
Answer: Hint: $a\equiv b \bmod p^2-p$ implies $a\equiv b \bmod p$  and $a\equiv b \bmod p-1$. Also, $m\equiv n \bmod p-1$ implies $a^m \equiv b^n \bmod p$.
Comment: You have to deal with the (easy) special case when $p\mid a$ (and hence $p\mid b,$ too.)
Comment: @ThomasAndrews, sure, yes.
Answer: We know $p(p-1)|a - b$ so $a \equiv b \mod p$ and $a\equiv b \mod p-1$.
So if $p|a$ this is trivial $a \equiv b \equiv 0 \mod p$ so $a^k \equiv b^j \equiv 0 \mod p$.
If $\gcd(a,p)=1$ then $\gcd(a,p) = 1$.  By Fermat's little Theorem.  $a^{p-1} \equiv 1\mod p$.
Now $a\equiv b \mod p-1$ so $b = a + k(p-1)$ for some integer $k$.
So  $b^b \equiv a^b \equiv a^{a + k(p-1)} \equiv a^a*(a^{p-1})^k \equiv a^a\mod p$.
Answer: Whatever the approach, everything here boils down to the Chinese remainder theorem and Fermat's little theorem. By the CRT, the initial congruence is equivalent to $a \equiv b$ mod $p$ and $a \equiv b$ mod $(p-1)$. Since the question is obvious if $a \equiv b \equiv 0$ mod $p$, we can assume $\bar a = \bar b$ in $(\mathbf Z/p)^*$ (with obvious notations), so that the desired result is equivalent to ${\bar a}^{a-b}=\bar 1$ in $(\mathbf Z/p)^*$. But $a \equiv b$ mod $(p-1)$, and FLT allows to conclude.


add hyphen after every fourth character in a string seperated by comma

Question: I have a string as 1111111111,2222222222,333333333,....
I want to modify it as 1111-111111,2222-222222,3333-33333,....
the regex I am using is this..
var num = '1111111111,2222222222,333333333,....';
var newNum = num.toString().match(/.{4}/g).join('-');

this add hyphen after every fourth character but I am unable to reset when comma is found.
Comment: `.replace(/\b(\d{4})/g, '$&-')`
Answer: You can use the following regex:
\b\d{4}

with replacement $&-
demo

var num = '1111111111,2222222222,333333333,....';
console.log(num.replace(/\b\d{4}/g, "$&-"));
Comment: There is no point wrapping the whole pattern with a capturing group if you need to refer to it from the replacement pattern. In JS, there is a `$&` replacement backreference right for this purpose (edited the post to show how to use it).
Comment: Yes, same as `&` in sed or vim, and as `$0` in Java, PHP. `$&` also works in .NET and Boost. In Python `re`, `\g<0>` can only be used.
Comment: @WiktorStribiżew: Thanks a lot I didn't know that ;-) so it is very similar to the `\&` in `sed s/.../.../` search and replace command right?
Comment: @WiktorStribiżew: Thanks! `\g<0>` looks really like a backreference to a named capturing group!
Answer: Try following

let str = '1111111111,2222222222,333333333';

let res = str.split(",").map(s => s.slice(0,4) + "-" + s.slice(4, s.length-1)).join(",");

console.log(res);
Answer: You can also use split() and substr() to get that:

var str = '1111111111,2222222222,333333333';
var res =[];
str.split(',').forEach((item)=>{
   res.push(item.substr(0,4)+'-'+item.substr(4,item.length));
});
console.log(res);


Understanding a question in combinatorics

Question: I need help to understand a question in combinatorics.

One corner square in a $3 \times 3$ grid is painted black, the other
squares are white. In one move you can change color in all squares in
a row or in a column. Can you get all the squares black after a number
of such moves?
Hint: Study the number of black squares among the four corner squares

Does this regard a Rubiks cube?  I cannot see other option that that, given the expression "in one move".
If not, any hints appreciated!
[[ Not looking for Solutions , only want Clarification on the Question ]]
Comment: This is the definition of a "move". A "move" is changing the color of one row or one column. And then it is asking if you can achieve something by performing such moves. It could be called a "step" or "operation" instead of "move". It has nothing to do with any Rubik cube, it is about a square.
Comment: Yes that would be right.
Comment: A reminder that this should be also tagged as contest-math
Comment: Talking about Rubik's cubes, if you perform a permutation, like R, do those squares get black?
Comment: @MichalAdamaszek thanks, so if I change the colors of that row with the black square, it turns white and all the others in the row turn black.
Answer: It is a Planar Puzzle , not a Cubic Puzzle (Definitely not Rubic)
Putting in other words & Using Images may aid here , hence I will try that :
We have a 3×3 grid like given below
One Corner Square in that is Initially painted Black.
The other Squares are left White.
Playing a game , you have 2 Possible moves :
- you can change the colour in all Squares in a Selected row.
- you can change the colour in all Squares in a Selected column.

Aim of the game is to make the grid all Black.
You can use these 2 moves in Succession.
Can you get all the Squares Black after a number of such moves ?
What is the Sequence of moves ?

Hint: Study the number of Black Squares among the four corner Squares

No Colouring :

Starting Position :

Playing with the move to the top row :

Ending Position :

Solution :
Not Posting the Puzzle Solution.
OP wants Puzzle Explanation , not Puzzle Solution.

When OP responds , I may include that here.

My HINT : There is Some Invariant which we can try to Identify.
That Invariant will not change when making the moves.
That Invariant is not there in the Ending Position.

Comment: Nice to know that it was useful , @Luthier415Hz , I was sure that you will not want the Solution & may want to think about it yourself !
Comment: Great illustration Prem. Thanks. I got a NO on this as answer.
Answer: Starting sequence:
[X][][]
[][][]
[][][]
...
Target sequence:
[X][X][X]
[X][X][X]
[X][X][X]
Solution:
I think it is unsolvable as the starting position is already in a non-solvable state. It represents a planar graph.

Prem's hint: Study the number of Black Squares among the four corner Squares

There is only 1 black square as a corner, it isn't solvable because of this principle.

Prem's hint 2: There is Some Invariant which we can try to Identify.

Prem's hint 3: That Invariant will not change when making the moves.

Prem's hint 4: That Invariant is not there in the Ending Position.

The upper left square is what is invariant, it will inevitably transform into a white square.
Comment: Thanks for your suggestion, but I think the answer to this question is No. PS: I didnt downvote your answer.
Comment: @Luthier415Hz No problem! Understood, the question was simply to answer if it regarded a Rubik's cube.


Listing usernames that are actually computers in Debian

Question: I have inherited about 6 servers (all Debian based), and part of my project over the next year is consolidate everything into one server. There are 6 "domains" running from Samba3 installations, and I'd like to merge them all into the one new server once I get everything sorted out. What I would like is to know if there is a way to load the /etc/passwd file to show just usernames that end in a $, so I know they are a computer name. Once I can get this, I can (hopefully) make a script to add all the machines to the new master, but that's for another question later
Answer: cat /etc/passwd | grep \$\: | cut -d : -f 1

would be my first attempt.
Answer: Here's how I'd do it:
awk -F: '{print $1}' /etc/passwd | grep '\$$'

Answer: I think
grep -P '^[^:]+?\$:' /etc/passwd

Is the most concise way to do this.
Edit: Found a more concise way. This will not confuse stray "$:" that exist in GECOS fields, for example.


How to do factorial analysis for a non-normal and heteroscedastic data?

Question: I designed a field experiment with 4 independent factors but data is not normal and heteroscedastic.  Friedman test (agricolae package) from R only fits for rbd.  Can anybody suggest how to analyze my data please?
Answer: Package vegan implements some permutation testing procedures using a distance based approach.  For factor analysis, you should take a look at section 5 of the documentation.  There's also more information in the paper:

On distance-based permutation tests for between-group comparisons (Reiss et al, 2010)

You might also be interested in skimming this table:

Choosing the Correct Statistical Test
Answer: The Skillings-Mack test  is a general Friedman-type test that can be used in almost any block design with an arbitrary missing-data structure. It's part of the asbio package for R, and there's a user-written package skilmack for Stata.
Skillings, J. H., and G. A. Mack. 1981. On the use of a Friedman-type statistic in balanced and unbalanced block designs. Technometrics 23: 171-177.
Aho, K. asbio: A collection of statistical tools for biologists. Version 0.3-24. 2010-9-18. Comprehensive R Archive Network (CRAN) 2010-09-19.
Chatfield, M. and Mander, A. The Skillings–Mack test (Friedman test when there are missing data). Stata Journal 9(2):299-305.
Answer: As you suggest you "designed" an experiment, it would be better if can you give a description of your design and data set. Even if the data is heteroscedastic and non-normal, probably some variable transformations might help and you may be able to take advantage of the design. The t-test is fairly robust to the normality assumptions.
Comment: hi S.  yes we did transformed the data, then we standardize against the largest value, then transformed the standardized value
Comment: but was your design a Randomized Complete Block Design?