Customized User Registration form with Profile fields

Question: I'm missing something core to how user registration forms are customized and the data is added to the database and I'm hoping to get a workflow.
I have created about a dozen Profile fields, textareas, radio buttons, select lists, etc.
I have written a module to do a form_alter, and in that module I have laid out fieldsets and containers so that everything is neat and orderly.  For example, for Home Information I have this:
$form['hi'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => t('Home Information'),
    );

    $form['hi']['hic'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',

    );

    $form['hi']['hic']['left'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',

    );

    $form['hi']['hic']['right'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'container',

    );

and then I have this to display Profile fields that are relevent to Home Information:
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone'] = $form['profile_memberlist']['field_home_phone'];
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#maxlength'] = 16;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#size'] = 13;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#title'] = t('Phone');
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#description'] = t('Enter your phone number');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name'] = $form['profile_memberlist']['field_first_name'];
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#maxlength'] = 16;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#size'] = 13;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#title'] = t('First Name YO');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#description'] = 'HEY THERE';

Now when I view the registration form, I see first all my generic Profile fields, PLUS the elements created from the above. I thought that unsetting the profile_memberlist was the way to go, but it turns out that while the user is created the Profile fields do not get saved this way.
My Submit is something like this:
$form['#submit'][] ='all_data_form_submit';

the actual function:
function all_data_form_submit($form, &$form_state) {
drupal_set_message('
' . print_r($form_state['values'],TRUE) . '
');

$new_user = array(
'name' => $form_state['values']['name'],
'pass' => user_password(),
'mail' => $form_state['values']['mail'],
'init' => $form_state['values']['mail'],
'status' => 0,
'access' => REQUEST_TIME,
  'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
  'field_last_name' =>  array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_last_name']))),

);

$form_state['redirect'] = array(
'node/31890',

array(
  'query' => array(
    'foo' => 'bar',
  ),
  'fragment' => 'baz',
 ),
);

$account = user_save(null,$new_user);

}

But that ends with a DATA INTEGRITY error on submit, because apparently user_save is being called twice?  I remove the user_save and the user is created, but none of the Profile fields get added to the database.
What has worked for me is when both the unstyled and the styled form elements are shown, and I don't use a custom submit handler, the Profile data is saved.
My question: how do I display the styled and neatly organized form elements only, and have the data entered through them get saved to the database?
Answer: I believe you're looking for hook_user_presave().
This hook is called directly before the user is saved and the $edit arg will contain all of your form values.
As an alernative, you may look at the Profile2 module
Comment: hook_user_presave() looks like it saves the data serialized in the user object.  So if I removed $account = user_save(null,$new_user); changed $new_user to $edit, it should then automatically save the extra field entries in their respective Profile fields?  I am already using Profile2.
Comment: hook_user_presave would replace hook_form_submit and you wouldn't need to call user_save at all.
Comment: Thanks for the pointers but I must be missing the big picture here.  Nothing I try gets the data from the extra form elements into a profile field or the data column of the user object.
Comment: Have you implemented MODULE_user_presave(&$edit, $account, $category) and drupal_set_message(print_r($edit,true)) inside the hook?
Comment: Okay that provided output.  The second part of my initial question though, is how do I have these:

    $form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#size'] = 13;

    $form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#title'] = t('Phone');

    $form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#description'] = t('Enter your phone number');

 fields only show up in the form AND have their data saved?

If I unset or hide the profile_memberlist $form array data is not saved at all.
Comment: You are trying to hide fields in the registration form?
Comment: In my module I have fieldsets and containters setup to provide a nice clean look for all of the Profile fields I need data collected for. Perhaps the way I built those is wrong, as the FAPI seems to need the Profile fields to be shown on the User Reg. page/not hidden/not unset.

So right now I have on my User Reg page two sets of the same Profile fields.  One set no styling, the other styled like I want. I need to 1) not show the unstyled. 2) get the data from the styled.
Comment: Try #access = FALSE, so $form['hi']['hic']['right']['profile_memberlist']['field_home_phone']["#access"] = FALSE;
Comment: That hides the field I need to show.  So I tried setting #access to FALSE for the field I want to have hidden and it hides it.  Alas the data from the not hidden field is not saved anywhere.  It all boils down to how do I get a styled and neat looking registration form with data entered saved to the proper Profile fields.  I keep thinking that use case must be doable but maybe it's not?


How to group multiple rows of multiple columns in a joint table with grouping by 1 column

Question: I have a joint table from 3 different tables like this.
Select DoctorTable.Doctor, NurseTable.Nurse , PatientTable.Patents

FROM PatientTable

LEFT JOIN DoctorTable on DoctorTable.DoctorCode = PatientTable.DoctorCode

LEFT JOIN NurseTable on DoctorTable.DoctorCode = NurseTable.DoctorCode

Patient     Doctor        Nurse
John        Peter         Mary
John        Peter         Amy
Kate        Terry         Mary
Kate        Leo           Ivy
Paul        NULL          NULL
Emily       NULL          NULL

And I want to join the rows which has the same value with a comma in 'Doctor' Column to have the result below
Patient     Doctor        Nurse
John        Peter         Mary, Amy
Kate        Terry, Leo    Mary, Ivy
Paul        Null          Null
Emily       NULL          NULL

As I still have some columns to join with this table and also need to group the rows with ',', using FOR XML PATH('') to group each column will be very slow. So how can I group this table efficiently?
Answer: I think the answer is using an aggregation function which concatenates rows in the group. Too bad TSQL does not have one (how hard is that?), but if you don't mind using SQLCLR, here is how to create a user defined aggregate concatenation function with .NET in MSDN:
MSDN String Utility Functions Sample
<Serializable(), Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Microsoft.SqlServer.Server.Format.UserDefined, IsInvariantToNulls:=True, IsInvariantToDuplicates:=False, IsInvariantToOrder:=False, MaxByteSize:=8000)> _
Public Class Concatenate : Implements Microsoft.SqlServer.Server.IBinarySerialize

    Private Builder As StringBuilder

    Public Sub Init()
        Builder = New StringBuilder
    End Sub

    Public Sub Accumulate(ByVal value As SqlString)
        If value.IsNull Then Return
        Builder.Append(",").Append(value.Value)
    End Sub

    Public Sub Merge(ByVal other As Concatenate)
        Builder.Append(other.Builder)
    End Sub

    Public Function Terminate() As SqlString
        If Builder Is Nothing Then Return New SqlString("")
        Return New SqlString(Builder.ToString.Substring(1))
    End Function

    Public Sub Read(ByVal r As BinaryReader) Implements Microsoft.SqlServer.Server.IBinarySerialize.Read
        If r Is Nothing Then Throw New ArgumentNullException("r")
        Builder = New StringBuilder(r.ReadString())
    End Sub

    Public Sub Write(ByVal w As BinaryWriter) Implements Microsoft.SqlServer.Server.IBinarySerialize.Write
        If w Is Nothing Then Throw New ArgumentNullException("w")
        w.Write(Builder.ToString())
    End Sub

End Class

Then, you can do something like:
SELECT PatientCode, Patient, dbo.Concatenate(Doctor), dbo.Concatenate(Nurse)
FROM PatientTable
LEFT JOIN DoctorTable on DoctorTable.DoctorCode = PatientTable.DoctorCode
LEFT JOIN NurseTable on DoctorTable.DoctorCode = NurseTable.DoctorCode
GROUP BY PatientCode, Patient


Why does my Poisson GLM with identity link converge, but a Negative Binomial GLM with identity link NOT converge?

Question: I am trying to fit a GLM to count data, with a single feature (also a count), and intercept term. Both the feature and response are nonnegative (but may be 0). I need to use identity link because I want to test the hypothesis that the coefficient in the linear model is 1.
I can fit a Poisson regression to the data no problem. However, as my data is definitely over-dispersed, I would like to fit a Negative Binomial regression instead. Yet when I do this, the optimization algorithm often fails to converge. I have noticed this behavior both in the glm.nb function from the MASS package in R, the vglm function from VGAM in R, as well as in the statsmodels package in Python, so this behavior seems unrelated to any particular software.
I have a number of datasets that I wish to fit these models on in sequence, and the same behavior is observed for most of them.
So my question is: Why would Poisson regression converge but Negative Binomial not? Given the nature of my data and the chosen link function, I understand the intercept and the coefficient both must be positive for the model to make any sense. However, I would think this would be a problem for both Poisson and Negative Binomial, but one works and the other does not.
My suspicion is that this is an issue related to whatever optimization algorithm these packages are using under the hood. But the fact that this happens across three packages in two different languages makes me doubt that this is the case. But if it is, is there anything I can do to rectify these issues, say, alter starting values or pass a different optimization method?
Editing to add a minimum reproducible example. The raw data is unavailable to share but I have taken a small sample. This converges with Poisson, but not with Negative Binomial, when using the statsmodels package in Python. Note the data point with an x value of 0 and a very large y.
import statsmodels.api as sm
import numpy as np

X = np.array([60, 16, 32, 0, 1148, 96, 16, 32, 208, 2, 23, 30, 60, 340, 16, 132, 51, 350, 4, 0])
X = np.vstack((X, [1]*X.shape[0])).T # add intercept
y = np.array([48, 14, 21, 1, 2779, 96, 16, 24, 79, 1, 12, 30, 1, 135, 16, 223, 37, 154, 4, 3279])

poiReg = sm.GLM(y, X, family = sm.families.Poisson(link = sm.families.links.identity)).fit()
poiReg.summary()

nbReg = sm.GLM(y, X, family = sm.families.NegativeBinomial(link = sm.families.links.identity)).fit()
nbReg.summary()

Also note that while this model fails to converge with statsmodels, it actually does with glm.nb in R. However, the full dataset does not, and I do not have the time to continue trying sample permutations until I find one that fails in all cases.
Comment: Can you provide a minimal reproducible example, esp. since you seem to have come across this behavior more than once?
Comment: You might consider using a package that allows more complicated restrictions on the parameters such as *Mathematica*.  Also, is that last data point a typo?  That has the highest count associated with the smallest predictor value and the 2nd largest count is associated with the largest predictor value.
Answer: The linear link function does not impose non-negativity constraints on the prediction, i.e. conditional mean of the distribution.
It is possible that for some values of the explanatory variables, the predicted mean is negative even if the optimization has converged. This could be the case for example if we use OLS to estimate the model.
In this case some parameters of the distribution, loglikelihood, implied variance function or similar, will not be in a valid range and the evaluation of those functions will break or raise an exception.
Then, the family-link combination cannot be estimated.
In other cases, it is possible that the nonnegativity constraints are not binding at the optimum, i.e. the maximum likelihood estimate. In those cases improving starting values can help in achieving convergence.
Specifially, in GLM families different from gaussian, the implied variance is a function of the mean, negative predicted mean implies therefore a negative variance which will in most cases cause numerical problems.
Comment: Thanks, but I don't believe this answers my question. Both Poisson and Negative Binomial require that the conditional mean is positive, and have the variance as a linear function of the mean. Yet one always works, and the other usually fails.


find columns present in vector and replace values that equal 1

Question: I have a binary data set which looks like
     a    b    c   d
 r1  1    1    0   0
 r2  0    1    1   0
 r3  1    0    0   1

And a vector
 V <- c("a", "c")

I want to a command to search colnames and change values in these columns. for example change 1 to A. So the output would be:
     a    b    c   d
 r1  A    1    0   0
 r2  0    1    A   0
 r3  A    0    0   1

Comment: Please, note that this might be changing the type of data as well. If the columns were of type numeric or integer before the replacement the whole columns `a` and `c` will be of type character after replacement. Even the digits 0 and 1 although this cannot be judged from the print out.
Answer: Here is a vectorized way to do it,
df[names(df) %in% V] <- replace(df[names(df) %in% V], df[names(df) %in% V] == 1, 'A')

#or avoid calling the %in% part 3 times by assigning it, i.e.

i1 <- names(df) %in% V
df[i1] <- replace(df[i1], df[i1] == 1, 'A')

#or a more simplified syntax, compliments of @Cath,

df[, V][df[, V]==1] <- "A"

which gives,

   a b c d
r1 A 1 0 0
r2 0 1 A 0
r3 A 0 0 1

Comment: @Cath ahh...that's the syntax. My very first try - which fails -  was `df[names(df) %in% V][df == 1] <- 'A'` :p
Comment: well V are the names so no need for `%in%` (+ a bit of well-used code-golfing can never be bad ;-p )
Comment: Could not agree more! ;) - From now on Thursday is the "Overthinking stuff" day :p
Answer: A solution with dplyr:
library(dplyr)

V <- c("a", "c")
df %>%
  mutate_at(V, ~replace(.x, .x == 1, 'A'))

#    a b c d
# r1 A 1 0 0
# r2 0 1 A 0
# r3 A 0 0 1

mutate_at takes a a data.frame and a vector of column names and applys the specified function to each of the columns.
DATA
df <- structure(list(a = c(1L, 0L, 1L), b = c(1L, 1L, 0L),
                     c = c(0L, 1L, 0L), d = c(0L, 0L, 1L)),
                .Names = c("a", "b", "c", "d"),
                class = "data.frame", row.names = c("r1", "r2", "r3"))

Answer: If left hand side (LHS) and right hand side (RHS) or of the same type, then data.table can be used to update only the selected "cells" in place, i.e., without copying the whole column:
library(data.table)
setDT(df)
for (s in V) df[get(s) == 1L, (s) := 99L]  # replacement value is of type integer
df[]

    a b  c d
1: 99 1  0 0
2:  0 1 99 0
3: 99 0  0 1

To verify that only selected rows in each column are updated, we can check the addresses of each column before and after the update using:
df[, lapply(.SD, address), .SDcols = V]

(In addition, the verbose mode can be switched on by options(datatable.verbose = TRUE).)

In case LHS and RHS are of different type, a type conversion is required anyway. Therefore, the whole column needs to be replaced:
df[, (V) := lapply(.SD, function(x) replace(x, x == 1L, "A")), .SDcols = V]
df

   a b c d
1: A 1 0 0
2: 0 1 A 0
3: A 0 0 1

Using address() shows that each of the affected columns has been copied. But only the affected columns are copied, the other columns haven't been touched. This is different to the other answers posted so far where the whole data frame is copied.


import cv2 dll load failed

Question: When I passed on win7 (python3)
pip install opencv-python

pip install opecncv-contrib-python

Can be correct import CV2
But when I installed opencv on window server 2008 R2 enterprise, this was the following error:
In [2]: import cv2
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-c8ec22b3e787> in <module>()
----> 1 import cv2

c:\python36\lib\site-packages\cv2\__init__.py in <module>()
      1 import importlib
      2
----> 3 from .cv2 import *
      4 from .data import *
      5

ImportError: DLL load failed: The specified module could not be found.

I tried installing C++ Redistributable Package (all versions) and downloading WHL files still can't solve the error.
C:\Users\Administrator\Desktop>ipython
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD6
4)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import cv2
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-c8ec22b3e787> in <module>()
----> 1 import cv2
ImportError: DLL load failed: The specified module could not be found.

My guess is definitely a system problem, but I checked the data and found that the prototype of the server 2008 R2 system is Win7, and I've installed what I can hold, and still can't solve the problem.
So I wanted to know what the real reason for this mistake was, and if I could figure it out and fix it.
So what should I do to ask for help
Comment: What was the error? What have you tried?
Comment: Please update your post with the error message. If you are installing opencv for python 3 than that's a bit different different and trickier.
Comment: @littlecat:It's all Python 3, and it's all right to install the import on a Windows 7 system.
Comment: @jianyi as the error says you have a dll issue try this video if this helps https://www.youtube.com/watch?v=izN-NLpS5t8
Comment: @littlecat But there is no solution
Answer: This can happen if you are using windows 10 N distribution, the N distributions does not come pre installed with windows media feature pack, which is required after OpenCV version 3.4 and onwards.
The preferred solution is to install the feature pack at : https://www.microsoft.com/en-us/software-download/mediafeaturepack
Be careful to choose the version that works with your current version of windows.
If that is not an option, fall back to an earlier version of OpenCV that does not have dll dependencies, you can do that by:pip install opencv-python=220.127.116.11
Since windows rolled out it's N version this problem has been seen at many places, and has many impacts across the windows environment, the fastest way to identify if you have this problem is open youtube in Edge browser, if it says HTML5 media plugin not found, this is the problem.
Neither conda nor any other virtual manager running python natively on windows will solve this unless you install the feature pack. However WSLbash and VMWare will run cv2 without feature pack.
Answer: Try first installing Anaconda, then install opencv with conda. For example opening Conda Prompt in windows and type conda install opencv, instead of using pip. That did the trick for me.

import cv2 dll load failed


Why is it possible to write any string in the hash salt

Question: I have researched a bit, but I couldn't find a precise answer to why it's possible to write any string in <code>$settings['hash_salt']</code>.
For me it doesn't make sense that the site chashes if no hash salt has been set and if I then go to settings.php and write,
<code>$settings['hash_salt'] = 'x';
</code>
the site works just fine.
Why does the site work just because hash salt have any value?
Answer: You can read about it in the default.settings.php file:

Salt for one-time login links, cancel links, form tokens, etc.
This variable will be set to a random value by the installer. All one-time
  login links will be invalidated if the value is changed. Note that if your
  site is deployed on a cluster of web servers, you must ensure that this
  variable has the same value on each server.
For enhanced security, you may set this variable to the contents of a file
  outside your document root; you should also ensure that this file is not
  stored with backups of your database.

This value is used by Drupal as salt for some cryptographic operations. It should be a random value. It adds more security to those cryptographic operations (as long as the value is not known by an attacker).
As far as I know Drupal uses a auto-generated salt value based on Database credentials when no salt is set, so Drupal should work without a salt value.
Answer: Drupal requires a settings key called hash_salt to secure transient hashes.
It will be generated during Drupal install and added to settings.php. If you use a different settings.php in different environments (for example, a settings.local.php), you may have forgotten to set this variable.
Add a line to your local settings.php like:
$settings['hash_salt'] = 'whatever you like';


Is there a module that can list all the views on a system?

Question: Is there a module that can list all the views installed on a system and their pages as well? If it can specify whether the Views are installed by modules or enduser created that will be helpful.
I am looking for something that create a list along this lines.
Name | Type of View | Page Name | Type of Page | Path
Comment: Views module lists views already, via Views UI. What's wrong with their native implementation?
Comment: That's a very unusual request, I'd be quite surprised if anyone has written such a module (I can't imagine how it would be useful). Probably something you're going to have to write yourself to be honest
Comment: @Mołot I need to export the information into a content type or a database, and adjust it and export it as I see fit. I'd prefer a module that has such a view, like Views System which can be cloned and extended
Answer: I don't think a module already exists for that.
To build it yourself, you'll need to implement hook_views_data(), and describe the views_view, and views_display tables.
These are the columns you'll have available from the views_view table:

name
description
tag
base_table
human_name
core

And from views_display:

vid (view id)
id
display_title
display_plugin
position
display_options

display_options is a serialised PHP array of data (containing the path and other specific information), so unless you implement some pretty advanced field/filters/etc handlers you won't be able to filter on those specific elements, or use them as fields.
Comment: The displays themselves are each a row in the `views_display` table, but yeah, most of the useful data in there is in a serialised column (path, row style used, filters, etc)
Comment: Make sure you get the [Advanced Help](https://drupal.org/project/advanced_help) module installed for that; it's not exactly obvious, but there's a bunch of sample code for developing custom handlers buried in the Views section of that module. It's really useful, I'm not sure why they try so hard to hide it
Comment: Does this mean the info for the separate pages of a view are stored in the display_options field rather than in separate database rows?
Comment: I will accept it as it is as near an answer I'll get. I will delve into the Views module code later to see how the serialized info can be extracted


How to run a method after a specific time interval?

Question: It's clear: For example, imagine a button in my form. When a user clicks on the button, some void method should run after 30 seconds.
There would be a void method DoAfterDelay that takes two input parameter. The first one is the method to do (using delegates), and the other one is the time interval. So I'll have:
public delegate void IVoidDelegate();
static void DoAfterDelay(IVoidDelegate TheMethod, TimeSpan Interval)
    {
        // *** Some code that will pause the process for "Interval".
        TheMethod();
    }

So, I just need a piece of code to pause the process for a specific time interval. Heretofore, I used this code to do that:
System.Threading.Thread.Sleep(Interval);

But this code is no good for me, because it stops the whole process and freezes the program. I don't want the program to get stuck in the DoAfterDelay method. That's why the Thread.Sleep is useless.
So could anyone suggest a better way? Of course I've searched about that, but most of the solutions I've found were based on using a timer (like here for example). But using a timer is my last opinion, because the method should run once and using timers makes the program confusing to read. So I'm looking for a better solution if there is. Or maybe I have to use timers?
I guess I have to play with threads, but not sure. So I wonder if anyone could guide me to a solution. Thanks in advance.
Answer: Can you use a task?
Task.Factory.StartNew(() =>
{
    System.Threading.Thread.Sleep(Interval);
    TheMethod();
});

Comment: @MostafaFarzán It's extremely inefficient/wasteful to have a thread sitting there doing nothing just so that you can execute some code after a period of time.
Comment: Thanks for the answer. So actually playing with threads is the solution.
Comment: It was in a scenario when a user clicks a button, hence not a big overhead as it's not going to happen frequently. Otherwise I'd suggest writing a task scheduler.
Comment: System.Threading.Tasks.Task, but still get an error: Cross-thread operation not valid: Control 'panel1' accessed from a thread other than the thread it was created on.
Comment: On the task's thread you can't modify the control's properties. For that you have to use the dispatcher to update the properties on the UI Thread.
Comment: using this you will have thread in a pool doing almost nothing, taking resources.
Answer: This is where you can use the async await functionality of .Net 4.5
You can use Task.Delay an give the delay in miliseconds.
This is a very clean way. ex:
private async void button1_Click(object sender, EventArgs e)
{
    await Task.Delay(5000);

    TheMethod();
}

Answer: There are several methods of creating thread but of course, it depends on what you are doing.
You can create a thread on the fly like this:
Thread aNewThread = new Thread(
    () => OnGoingFunction()
);
aNewThread.Start();

This thread will be running in the background. The function you want to do should have a sleep method to sleep when its done processing. So something like this:
private void OnGoingFunction()
{
   //Code....
   Thread.Sleep(100); //100 ms, this is in the thead so it will not stop your winForm
   //More code....
}

I hope that helps.
Another option is to create the thread whenever you need to process it and not worry about the sleep option. Just create a new thread every time to load the process
Answer: You should create a Coroutine
public IEnumerator waitAndRun()
{
    // WAIT FOR 3 SEC
    yield return new WaitForSeconds(3);
    // RUN YOUR CODE HERE ...
}

And call it with:
StartCoroutine(waitAndRun());

Answer: DoAfterDelay starts a timer that just runs once,  that when it expires it calls your void 'TheMethod'function.
Why would this be messy?
Answer: Here's what you want:
public static void Example1c()
{
    Action action = DoSomethingCool;
    TimeSpan span = new TimeSpan(0, 0, 0, 5);

    ThreadStart start = delegate { RunAfterTimespan(action, span); };
    Thread t4 = new Thread(start);
    t4.Start();

    MessageBox.Show("Thread has been launched");
}

public static void RunAfterTimespan(Action action, TimeSpan span)
{
    Thread.Sleep(span);
    action();
}

private static void DoSomethingCool()
{
    MessageBox.Show("I'm doing something cool");
}

One of the benefits of using Action is that it can be easily modified to pass in parameters.  Say you want to be able to pass an integer to DoSomethingCool.  Just modify thusly:
public static void Example1c()
{
    Action<int> action = DoSomethingCool;
    TimeSpan span = new TimeSpan(0, 0, 0, 5);
    int number = 10;

    ThreadStart start = delegate { RunAfterTimespan(action, span, number); };
    Thread t4 = new Thread(start);
    t4.Start();

    MessageBox.Show("Thread has been launched");
}

public static void RunAfterTimespan(Action<int> action, TimeSpan span, int number)
{
    Thread.Sleep(span);
    action(number);
}

private static void DoSomethingCool(int number)
{
    MessageBox.Show("I'm doing something cool");
}

Very flexible...
Answer: You can specify the exact seconds by using
DateTime runTime = new DateTime();
double waitSeconds = (runTime - DateTime.Now).TotalSeconds;

Task.Factory.StartNew(() =>
{
    Thread.Sleep(TimeSpan.FromSeconds(waitSeconds));
    YourMethod();
});

runTime => When you want to execute the method.
Answer: Here's a simple extension against Dispatcher that you can use in a non-blocking way.
public static void InvokeAfter(this Dispatcher dispatcher, int milliseconds, Action delayedAction) {

    Task.Factory.StartNew(() => {
        System.Threading.Thread.Sleep(milliseconds);
        dispatcher.Invoke(delayedAction);
    });
}

And here's how you use it with a Lambda:
SomeLabel.Dispatcher.InvokeAfter(3000, () => {
    SomeLabel.Text = "Hello World";
});

You can also use it with anything that matches Action. Here's an example using a local function...
void doLater(){
    SomeLabel.Text = "Hello World";
}

// Pass the action itself, not the result of the action (i.e. don't use parentheses with 'doLater'.)
SomeLabel.Dispatcher.InvokeAfter(3000, doLater);

Note: You can then call it against any dispatcher object where you would normally call Invoke. For safety, I like to invoke it using the dispatcher handling the control I'm updating.


Producer/Consumer in Java. Why do we need two conditions?

Question: I've read about the problem on https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html.
This is what the documentation says about the two conditions:

We would like to keep waiting put threads and take threads in separate
  wait-sets so that we can use the optimization of only notifying a
  single thread at a time when items or spaces become available in the
  buffer. This can be achieved using two Condition instances.

I could notify a single thread using one condition since signal() wakes up one thread:
class BoundedBuffer2 {
    final Lock lock = new ReentrantLock();
    final Condition condition  = lock.newCondition();

    final Object[] items = new Object[100];
    int putptr, takeptr, count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length)
                condition.await();
            items[putptr] = x;
            if (++putptr == items.length) putptr = 0;
            ++count;
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0)
                condition.await();
            Object x = items[takeptr];
            if (++takeptr == items.length) takeptr = 0;
            --count;
            condition.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }
}

Why do we need two conditions?
Answer: Say your buffer was empty and two threads were waiting on take, blocked on
condition.await();

Then a thread calls put. This will signal the Condition and wake up one of the take threads. That take thread will subsequently also signal the Condition, waking up the other take thread which will loop back in blocking state since there is nothing for it to take.
That last signal was unnecessary. That second take thread should never have been woken up since nothing was available.
The two condition algorithm allows you to notify only those threads that are relevant.
Comment: Why doesn't the example in documentation use `signalAll()` instead of `signal()`, are they equivalent here since only one type of threads are waiting on one condition? signalAll is only required in case using the same condition for both producer/consumer?
Comment: @SumitJain No, it's not really a question of how many conditions there are. It's more about how many threads can make progress once they're woken up. In this example, there can be multiple threads waiting in `put` on `notFull.await()`, but only one can make progress once it's woken up (because there will only be one spot in the queue to add to).
Comment: Agreed, but if we used one condition then we will have to use signalAll otherwise with signal it can also just wakeup the same type of thread, e.g. if called from take(), it can wake up another thread which calls take()
Comment: @SumitJain In that sense, sure. The `take` thread wouldn't be able to proceed (because of the loop condition check), but there would be no more signals to wake up the put threads.
Answer: The reason for two conditions is to differentiate between threads which are producing items into the buffer and threads which are consuming items from the buffer.

ProducingThread is bothered about notFull condition and is responsible for notEmpty condition, meaning that once it produces something, it has to raise the flag and say, 'hey, i have produced something, so it is not empty now.'
ConsumingThread is bothered about notEmpty condition and is responsible for notFull condition , meaning that once it consumes something, it has to raise the flag and say, 'hey, i have consumed something, so it is not full now.'

By having this kind of separation of threads into two different wait-sets, we can alert one thread at a time - either a producer thread from producerThread set or a consumer thread from consumerThread set. By having a single condition, we might have a producer thread to alert another producer thread, which is not necessary or relevant.
If we have a single condition, which is used by both threads, we will not be able to differentiate which threads to give chance logically, for example, 3 producer threads & 2 consumer threads are waiting for their chance - either to add/remove item. If one of the consuming thread finishes its work, suppose it signals, then it is possible that another consuming thread might get woken up, which would not be our objective.
We might have different usecases of Producer/Consumer problem-

Interleaving of Tasks - We can have tasks interleaving - for example - one consume, one produce, one consume, one produce etc.
Execute only relevant tasks - Producing threads need to be woken up only if producing task is necessary/possible and similarly Consuming threads need to be woken up only if consuming task is necessary/possible, otherwise the logic would become irrelevant/broken.
Comment: Suppose you had 4 producer threads & 2 consumer threads and for instance, buffer is used by 1 producer thread, then the remaining threads are waiting for their chance to use the buffer.
Comment: How can 3 producer threads & 2 consumer threads be waiting for their chance at the same time?
Comment: @MaksimDmitriev, it is possible, in a bursty application, for one or more producers to completely fill up a queue before one of the consumers has had its turn to take something.  Likewise, it is possible for one or more consumers to completely drain the queue before one producer has had a chance to put something.  Either way, you _can_ have producers and consumers waiting at the same time.


Linux server failover

Question: I have two Linux servers (CentOS6) - both are identically configured connected to the same switch with a direct link between them. I only have one external IP that is assigned to eth0 on both servers (connected to the internet switch) with the interface shutdown on server 2.
How can I failover to server 2 if server 1 dies - as stated they are linked directly so they can check for availability of each other via ping/tcp/udp. I toyed with Heartbeat but the documentation seems to be non-existent - not sure how to bring up an interface and start some services if the other server dies.
Answer: I would use Heartbeat.  The problem with the docs is that Heartbeat is now a component of Pacemaker:
http://www.clusterlabs.org/wiki/Documentation
Heartbeat is sufficient to failover an IP address, but will not detect service failures (e.g., your httpd process dies).  You don't have to set up the full Pacemaker configuration if you only care about IP addresses; in that case, you can use the version 1 (Heartbeat) configuration that uses /etc/ha.d/haresources as the resource list.
Comment: I have Monit watching individual services so hopefully that takes care of that. I will look at that documentation and see if I can make it work.
Answer: It is also possible to use Keepalived which is a VRRP implementation that sends multicast checks between the servers and if a timeout is reached it will fail over to the other server.
The configuration is pretty straight-forward and it can check for services and be used as load balancer.
Improving Network Reliability with Keepalived from linux devcenter provides some more information about the VRRP part of Keepalived.
Failover and loadbalancer using keepalived (LVS) on two machines describes more of the loadbalancer part of Keepalived and is very good for understanding a bit more of the components and usage cases.
Last but not least the manual provides some information about how to run it.
The best way to get to know Keepalived is to read the documentation on the project site.

Linux server failover


Nservicebus Sequence

Question: We have a requirement for all our messages to be processed in the order of arrival to MSMQ.
We will be exposing a WCF service to the clients, and this WCF service will post the messages using NServiceBus (Sendonly Bus) to MSMQ.
We are going to develop a windows service(MessageHandler), which will use Nservicebus to read the message from MSMQ and save it to the database. Our database will not be available for few hours everyday.
During the db downtime we expect that the process to retry the first message in MSMQ and halt processing other messages until the database is up. Once the database is up we want NServicebus to process in the order the message is sent.
Will setting up  MaximumConcurrencyLevel="1" MaximumMessageThroughputPerSecond="1" helps in this scenario?
What is the best way using NServiceBus to handle this scenario?
Answer:
We have a requirement for all our messages to be processed in the
  order of arrival to MSMQ.

See the answer to this question How to handle message order in nservicebus?, and also this post here.
I am in agreement that while in-order delivery is possible, it is much better to design your system such that order does not matter. The linked article outlines the following soltuion:

Add a sequence number to all messages
in the receiver check the sequence number is the last seen number + 1 if not throw an out of sequence exception
Enable second level retries (so if they are out of order they will try again later hopefully after the correct message was received)

However, in the interest of anwering your specific question:

Will setting up MaximumConcurrencyLevel="1"
  MaximumMessageThroughputPerSecond="1" helps in this scenario?

Not really.
Whenever you have a requirement for ordered delivery, the fundamental laws of logic dictate that somewhere along your message processing pipeline you must have a single-threaded process in order to guarantee in-order delivery.
Where this happens is up to you (check out the resequencer pattern), but you could certainly throttle the NserviceBus handler to a single thread (I don't think you need to set the MaximumMessageThroughputPerSecond to make it single threaded though).
However, even if you did this, and even if you used transactional queues, you could still not guarantee that each message would be dequeued and processed to the database in order, because if there are any permanent failures on any of the messages they will be removed from the queue and the next message processed.

During the db downtime we expect that the process to retry the first
  message in MSMQ and halt processing other messages until the database
  is up. Once the database is up we want NServicebus to process in the
  order the message is sent.

This is not recommended. The second level retry functionality in NServiceBus is designed to handle unexpected and short-term outages, not planned and long-term outages.
For starters, when your NServiceBus message handler endpoint tries to process a message in it's input queue and finds the database unavailable, it will implement it's 2nd level retry policy, which by default will attempt the dequeue 5 times with increasing infrequency, and then fail permanently, sticking the failed message in it's error queue. It will then move onto the next message in the input queue.
While this doesn't violate your in-order delivery requirement on its own, it will make life very difficult for two reasons:

The permanently failed messages will need to be re-processed with priority once the database becomes available again, and
there will be a ton of unwanted failure logging, which will obfuscate any genuine handling errors.

If you have a regular planned outages which you know about in advance, then the simplest way to deal with them is to implement a service window, which another term for a schedule.
However, Windows services manager does not support the concept of service windows, so you would have to use a scheduled task to stop then start your service, or look at other options such as hangfire, quartz.net or some other cron-type library.
Comment: Thanks a lot Tom. This was really useful.
Answer: It kinds of depends why you need the messages to arrive in order. If it's like you first receive an Order message and then various OrderLine messages that all belong to a certain order, there are multiple possibilities.
One is to just accept that there can be OrderLine messages without an Order. The Order will come in later anyway. Eventual Consistency.
Another one is to collect messages (and possible state) in an NServiceBus Saga. When normally MessageA needs to arrive first, only to receive MessageB and MessageC later, give all three messages the ability to start the saga. All three messages need to have something that ties them together, like a unique GUID. Then the saga will make sure it collects them properly and when all messages have arrived, perhaps store its final state and mark the saga as completed.
Another option is to just persist all messages directly into the database and have something else figure out what belongs to what. This is a scenario useful for a data warehouse where the data just needs to be collected, no matter what. Some data might not be 100% accurate (or consistent) but that's okay.
Asynchronous messaging makes it hard to process them 100% in order, especially when the client calling the WCF is making mistakes and/or sending them out of order. It wouldn't be the first time I had such a requirement and out-of-order messages.

Nservicebus Sequence


How can I remove a button from a Screen using Ruby Motion

Question: I can manage to remove an image
def remove_image
    @button_image.removeFromSuperview
end

But what script works in order to remove a button?
Answer: A button is a subclass of a UIView so you can remove it the same way:
@button.removeFromSuperview

Alternatively, you can just hide the button:
@button.hidden = true

Comment: Thanks a lot, I did not think it would be that easy.


Proof of $E[XY|\mathscr{H}]=XE[Y|\mathscr{H}]$ for $\mathscr{H}$-measurable $X$

Question: I reckon this is a pretty trivial result in the context of elementary probability, but how would one show it in the context of measure-theoretic probability theory?
That is, that $E[XY|\mathscr{H}]=XE[Y|\mathscr{H}]$ for $\mathscr{H}$-measurable $X$ where $X$ and $Y$ are random variables.
Answer: When $X=I_A$ for some measurable set $A$ (w.r.t. $\mathcal H$) this follows from definition of conditional expectation. Now go to simple functions and then take limits. This gives the result for $X$ non-negative. Now write $X$ as $X^{+}-X^{-}$. You have to assume that $E|XY| <\infty$ for the result to be true.
Comment: I see, it should follow in that first step from, for $S \in \mathscr{H}$, $E[\mathbb{I}_{S}(\mathbb{I}_{A}E[Y|\mathscr{H}])]=E[\mathbb{I}_{S \cap A}E[Y|\mathscr{H}]]=E[\mathbb{I}_{S \cap A}Y]$ and uniqueness.
Comment: *That is, because the last term in that expression is equivalent to $E[\mathbb{I}_{S} \mathbb{I}_{A} Y] = E[E[\mathbb{I}_{A} Y | \mathscr{H}] \mathbb{I}_{S}]$ and then by uniqueness.
Answer: Let
$$
Z=E[XY\mid \mathscr{H}]-XE[Y\mid \mathscr{H}]=E[XY\mid \mathscr{H}]-XY+X[Y-E[Y\mid \mathscr{H}]]
$$
and note that $Z$ is a $\mathscr{H}$ measurable function. Further for $H\in \mathscr{H}$, we have that
$$
EZI_H=E(E[XY\mid \mathscr{H}]-XY)I_H+E(Y-E[Y\mid \mathscr{H}])XI_H=0
$$
by the definition of conditional expectation where we use the fact that $XI_{H}$ is $\mathscr{H}$ measurable. Taking $H=I(Z>0)$ and $H=I(Z<0)$ it follows that
$$
Z=0
$$
with probability one from which the claim follows.


How do you plot two different y-axes using a loop with twinx?

Question: I have a pandas data frame, region, containing the prices of flats (Flat) and detached properties (Detached) in areas of the UK over time (the column Month). I'm trying to obtain plots of the change in price over time of both flats and detached properties, so that the plots have two different y axes - both of the average price but in different scales.
I've achieved this by using twinx(), however using the code below I get obviously get two figures. The first of these figures is exactly what I want, but I then get a second figure of blank plots. I have attached a screenshot of the kind of plot I want below.
When removing the second fig line fig, ax2 = ..., I get the error NameError: name 'ax2' is not defined. Also bringing the line ax2 = ax.twinx() outside of the loop gives the error AttributeError: 'numpy.ndarray' object has no attribute 'twinx'. I can't seem to figure out how to get this plot to work without having the duplicate blank figure, any help is much appreciated.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

region_list = sorted(region['Area'].unique().tolist())

fig, ax = plt.subplots(nrows=len(region_list), figsize=(13.8,len(region_list)*7))
fig, ax2 = plt.subplots(nrows=len(region_list), figsize=(13.8,len(region_list)*7))

for i in region_list:
    ind = region_list.index(i)
    filt = region['Area'] == i
    ax2[ind] = ax[ind].twinx()
    ax[ind].plot(region.loc[filt]['Month'],region.loc[filt]['Flat'], color='red', marker='o')
    ax[ind].set_ylabel('Average price of flats', color='red', fontsize=14)
    ax2[ind].plot(region.loc[filt]['Month'],region.loc[filt]['Detached'],color='blue',marker='o')
    ax2[ind].set_ylabel('Average price of detached properties',color='blue',fontsize=14)
    ax[ind].set_title(i, size=14)
    ax[ind].xaxis.set_tick_params(labelsize=10)
    ax[ind].yaxis.set_tick_params(labelsize=10)

plt.tight_layout()

Answer: When creating a secondary axis for a subplot, the result is a new object, and can't be referenced using array indices like the subplot axes (unless you specifically add the new twin axes to an array).
You've probably seen the following:
# with one axis
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax2.plot(...)

But with multiple subplots, the same logic applies:
# with one axis
fig, axes = plt.subplots(1, 2)

ax2 = axes[0].twinx()
ax2.plot(...) # secondary axis on subplot 0

ax2 = axes[1].twinx()
ax2.plot(...) # secondary axis on subplot 1

In your case:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

region_list = sorted(region['Area'].unique().tolist())

fig, ax = plt.subplots(nrows=len(region_list), figsize=(13.8,len(region_list)*7))

# don't add a second plot - this would be blank
# fig, ax2 = plt.subplots(nrows=len(region_list), figsize=(13.8,len(region_list)*7))

for i in region_list:
    ind = region_list.index(i)
    filt = region['Area'] == i

    # don't index into ax2
    # ax2[ind] = ax[ind].twinx()

    # instead, create a local variable ax2 which is the secondary axis
    # on the subplot ax[ind]
    ax2 = ax[ind].twinx()

    ax[ind].plot(region.loc[filt]['Month'],region.loc[filt]['Flat'], color='red', marker='o')
    ax[ind].set_ylabel('Average price of flats', color='red', fontsize=14)
    ax2.plot(region.loc[filt]['Month'],region.loc[filt]['Detached'],color='blue',marker='o')
    ax2.set_ylabel('Average price of detached properties',color='blue',fontsize=14)
    ax[ind].set_title(i, size=14)
    ax[ind].xaxis.set_tick_params(labelsize=10)
    ax[ind].yaxis.set_tick_params(labelsize=10)

plt.tight_layout()


Leading tone for strings harmony

Question: how to write a seventh leading tone chord for 4  part harmony for strings?.
Thank you
Comment: In what context?
Answer: You can do this in many different ways.  The simplest way is to put the root in the cello, the third in the viola, the fifth in second violin, and then double the root in the first violin. You could also put the seventh (which would be the sixth note of the scale) in the first violin part.
So much depends on what is going on around the chord that it's difficult to answer the question with any degree of precision.
Comment: @Tim, wouldn't the seventh of viio7 be LA - or LE in minor?
Comment: How does the 'seventh' become the sixth note of the scale?
Comment: @Tim: well, I wouldn't call it that. In classical theory, chords without roots are pretty avant-garde. I'd call it a vii half diminished chord, because that's what I was taught in school. vii half diminished 7th is an alternative to a V7 chord, both resolving to the tonic. (Now, if you're in a minor key, a ii dim7 resolves to the tonic. For example, in A minor, B-D-F-Ab is a ii dim7.  I like to use that as an alternative harmony to the V7 in blues progressions.)
Comment: @Tim Imagine the key of C. vii is B. So, the root is B, the third is D, the fifth is F, and the seventh is A (this is a "half-diminished 7th" chord; a fully diminished 7th chord would use Ab). A is the sixth note of the scale in C. So, the note that is a 7th from the root is a 6th from the Tonic, if you are using the Leading Tone as the root.
Comment: Thanks, Bob. I had the wrong start point! That chord is basically V9 with no root, I think
Comment: In modern theory, though, (in C maj) B,D,F,A can be seen as Bm7b5 (B half-dim) , and if it is played, say, on gtr, the bass could put a G note under it - making G9. Probably not used much in Classical music, as you say.
Comment: Actually, that's exactly the way that 9th chords were thought of when they first came into vogue in the 18th century. Rameau first proposed a "supposed" bass a third below the fundamental. It didn't take long for theorists to decide that the "supposed" bass was easier to treat as the fundamental and the 9th as a transient or non-chord tone. That led to the idea of a 9th chord, although it really wasn't considered a chord in its own right until beginning of the 20th century. In the 19th century, 9th chords were typically treated as appoggiaturas, with the 9th moving down stepwise.
Comment: But this would never be without the root. I don't know of any circumstance of classical music theory that analyzes a chord without the root.
Comment: @BobRodes Piston's *Harmony* calls this chord the "incomplete dominant 9th"
Comment: @DeanRansevycz Thanks for that. I guess I could stand to brush up a bit. :)

Leading tone for strings harmony


let $a_1,a_2,. . . ,a_n \in \mathbb{R^+} $ then prove that :

Question:
Let $a_1,a_2,. . . ,a_n \in \mathbb{R^+} $. Prove that :
  $$\frac{ a_{1} }{ a_{2} ^{2}+ a_{3} ^{2}+\cdots+ a_{n} ^{2}}
+\frac{ a_{2} }{ a_{1} ^{2}+ a_{3} ^{2}+\cdots+ a_{n} ^{2}}
+\cdots+\frac{ a_{n} }{ a_{1} ^{2}+ a_{2} ^{2}+\cdots+ a_{n-1} ^{2}}
 \geq \frac{ 4}{ a_{1}+ a_{2} + a_{3}+\cdots+ a_{n}}$$

I do not know where to start. please help me .
Comment: Is the last fraction on the left-hand side supposed to be $\frac{ a_{n} }{ a_{1} ^{2}+ a_{2} ^{2}+\cdots+ a_{n-1} ^{2}}$?
Comment: prove this in the case $n=2$
Comment: Induction on $n=2$ base case should work.
Comment: I have a proof for $n=3$ and $n=4$
Comment: @MichaelRozenberg . please write .
Answer: I think we can start by C-S:
$$\sum_{k=1}^n\frac{a_k}{\sum\limits_{i\neq k}a_i^2}=\sum_{k=1}^n\frac{a_k^2}{a_k\sum\limits_{i\neq k}a_i^2}\geq\frac{\left(\sum\limits_{k=1}a_k\right)^2}{\sum\limits_{k=1}^na_k\sum\limits_{i\neq k}a_i^2}.$$
Thus, it remains to prove that
$$\left(\sum\limits_{k=1}a_k\right)^3\geq4\sum\limits_{k=1}^n\left(a_k\sum\limits_{i\neq k}a_i^2\right)$$ or
$$\left(\sum\limits_{k=1}a_k\right)^3\geq4\sum\limits_{k=1}^n\left(a_k^2\sum\limits_{i\neq k}a_i\right).$$
Now, let $\sum\limits_{k=1}^na_k=1$.
Hence, we need to prove that $$\sum\limits_{k=1}^nf(a_k)\leq\frac{1}{4},$$
where $f(x)=x^2-x^3$.
But $f''(x)=2-6x$, which says that $f$ has an unique inflection point on $(0,1)$.
Thus, by Vasc's HCF Theorem it's enough to prove our inequality for
$a_1=a_2=...=a_{n-1}=x$ and $a_n=1-(n-1)x$, where $0<x<\frac{1}{n-1}$.
Thus, it's enough to prove that $g(x)\geq0,$ where
$$g(x)=\frac{1}{4}-(n-1)(x^2-x^3)-(1-(n-1)x)^2+(1-(n-1)x)^3.$$
We have
$$g'(x)=(n-1)(1-nx)(3(n-2)x-1).$$
We see that $0<\frac{1}{3(n-2)}<\frac{1}{n}<\frac{1}{n-1}$, $x_{min}=\frac{1}{3(n-2)}$ and $x_{max}=\frac{1}{n}$, which says
$$g(x)\geq\min\left\{g\left(\frac{1}{3(n-2)}\right),g\left(\frac{1}{n-1}\right)\right\}=\min\left\{\frac{11n^2-56n+72}{108(n-2)^2},\frac{(n-3)^2}{4(n-1)^2}\right\}\geq0.$$
Done!
For the proof we can use also the Vasc's EV Method.
Answer: Notice that $$\left( \frac{a_1}{a_2^2 + a_3^2 + ... + a_n^2} + \frac{a_2}{a_1^2 + a_3^2 + ... + a_n^2} + \ ... \ \frac{a_n}{a_1^2 + a_2^2+... + a_{n-1}^2}\right)(a_1 + a_2 + ... + a_n) \ge \left( \sqrt{\frac{a_1^2}{a_2^2 + a_3^2 + ... + a_n^2}} + \sqrt{\frac{a_2^2}{a_1^2 + a_3^2 + ... + a_n^2}} + \ ... \ \sqrt{\frac{a_n^2}{a_1^2 + a_2^2... + a_{n-1}^2}}\right)^2$$ by Cauchy-Schwarz inequality. WLOG, take $a_1^2 + a_2^2 + ... + a_n^2 = 1$ (because of homogenity). Thus it remains to prove that $$\frac{a_1}{\sqrt{1-a_1^2}} + \frac{a_2}{\sqrt{1-a_2^2}}+ \ ... \ +\frac{a_n}{\sqrt{1-a_n^2}} \ge 2$$Now take $x_m = \frac{a_m}{\sqrt{1-a_m^2}} \ \forall \ 1 \le m \le n$. Then it remains to prove that $$x_1 + x_2 + ... + x_n \ge 2$$ Now since $a_m^2 =\frac{x_m^2}{1+x_m^2}$, we have $$\frac{x_1^2}{1+x_1^2} + \ ... \ + \frac{x_n^2}{1+x_n^2} = 1$$ But $\frac{x_m^2}{1+x_m^2} = x_m \left( \frac{x_m}{1+x_m^2} \right) \le x_m \left( \frac 12\right)$ since $x_m \ge 0$ and it follows that $$1 = x_1 \left( \frac{x_1}{1+x_1^2} \right) + ... + x_n \left( \frac{x_n}{1+x_n^2} \right) \le \frac{x_1}2 + ... + \frac{x_n}2 = \frac 12 \left(x_1 + ... + x_n \right)$$  i.e. $$x_1 + x_2 + ... + x_n \ge 2$$ Done.
Note that $2$ is the minimum attainable value of $$\frac{a_1}{\sqrt{1-a_1^2}} + \frac{a_2}{\sqrt{1-a_2^2}}+ \ ... \ +\frac{a_n}{\sqrt{1-a_n^2}} \ge 2$$ (take $a_1 = a_2 =\frac 1{\sqrt 2}$ and all other $a_i $s equal to $0$).


Android - modify adapter from the UI thread and not from background thread

Question: I have a ListView populated from json and using custom adapter.
This is my shortened code in ZoznamActivity:
 public class Zoznam extends AppCompatActivity{

    private ArrayList<Actors> actorsList;
    private ActorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

   setContentView(R.layout.search_filter);
        final ListView lv = findViewById(R.id.listView1);

        actorsList = new ArrayList<>();
        adapter = new ActorAdapter(this, "Zoznam", actorsList);

        lv.setAdapter(adapter);adapter.notifyDataSetChanged();

        new GetContacts(Zoznam.this).execute("all","all");

   private static class GetContacts extends AsyncTask<String, Void, String> {
        ProgressDialog dialog;
        private final WeakReference<Zoznam> activityReference;

        GetContacts(Zoznam context) {
            activityReference = new WeakReference<>(context);
        }

        @Override
        protected void onPreExecute() {
            Zoznam activity = activityReference.get();
            if (activity == null || activity.isFinishing()) return;
            super.onPreExecute();
            dialog = new ProgressDialog(activity);
            dialog.setMessage(activity.getResources().getString(R.string.Loading));
            dialog.setTitle(activity.getResources().getString(R.string.connecting));
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected String doInBackground(String... sText1) {final Zoznam activity = activityReference.get();

            HttpHandler sh = new HttpHandler();
            String url = "URL";
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONArray actors = jsonObj.getJSONArray("result");

                    for (int i = 0; i < actors.length(); i++) {
                        JSONObject c = actors.getJSONObject(i);

                        Actors actor = new Actors();

                        actor.setLetter(c.getString("letter"));
                        actor.setNazov(c.getString("nazov"));
                        actor.setThumb(c.getString("thumb"));

                        activityReference.get().actorsList.add(actor);

                    }

                }  catch (final JSONException e) {

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(activity,
                                    R.string.Nodata,
                                    Toast.LENGTH_LONG).show();
                        }
                    }); }

return jsonStr;

            } else {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity,
                                R.string.Network,
                                Toast.LENGTH_LONG).show();
                    }
                });
                return null;
            }
        }

        protected void onPostExecute(String result) {
            Zoznam activity = activityReference.get();
            if (activity == null || activity.isFinishing()) return;
            dialog.dismiss();
            activity.adapter.notifyDataSetChanged();
            super.onPostExecute(result);

        }

    }

    protected void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }

The problem is, in crash reports I have found this error:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes.
However it happened only once for one device yet, but I'd like to fix this.
I have read more threads about this, but I still don't have a solution. As you can see in my code, I am calling notifyDataSetChanged() also onPostExecute, so not sure where is the problem.
Comment: Not sure will this fix the issue but you are calling `activity.adapter.notifyDataSetChanged();` before calling `super.onPostExecute(result);` Also you don't need UIThread calls `activity.runOnUiThread` inside `doInBackground` you can do all of that inside `onPostExecute`
Comment: yes, I switched the order in onPostExecute to test it, but it works also like it is now. I can't reproduce the issue, on my device it is always working. The exception appeared only once on one device. So what else should I do in onPostExecute?
Answer: You probably got the exception because you updated the adapter list on the background thread.
activityReference.get().actorsList.add(actor); This line in doInBackground method is updating the actual list you've passed to the adapter. All this calculation in doInBackground must be happening pretty fast and notifyDataSetChanged from onPostExecute is getting called. I'm not sure how, but this one time your onPostExecute wasn't called in time hence your list was updated but your ListView didn't receive the notification.
You can create a local list in your AsyncTask and update the activity's list in onPostExecute. Sample code -
private static class GetContacts extends AsyncTask<String, Void, String> {
    ProgressDialog dialog;
    ArrayList<Actors> actors = new ArrayList<>();
    ...
    @Override
    protected String doInBackground(String... sText1) {
        ...
        for (int i = 0; i < actors.length(); i++) {
            ...
            // activityReference.get().actorsList.add(actor); <-- remove this.
            actors.add(actor);
        }
        ...
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Zoznam activity = activityReference.get();
        if (activity == null || activity.isFinishing()) return;
        dialog.dismiss();
        activityReference.get().actorsList.add(actors); <-- add this
        activity.adapter.notifyDataSetChanged();
    }
}

This should work, but you can further improve your code by using callbacks. That way you won't have to keep a reference of the activity inside the asyncTask and you can move all the logic out of the asyncTask. This answer should be helpful https://stackoverflow.com/a/15693380/6168272.
Comment: Don't do this, it will be an un-optimized code. By a local list, I meant to create a new ArrayList inside your AsyncTask. I'll add some sample code.
Comment: I am not sure how to create a custom list there, but what if I do it this way inside the for cycle:             activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                activityReference.get().actorsList.add(actor);
                                activity.adapter.notifyDataSetChanged();
                            }
                        });
Comment: when I added to the for cycle this: actors.add(actor); then it says can't resolve method add. And in postexecute I added  activityReference.get().actorsList.add(actors); and it says can't resolve actors.
Answer: Change your AsyncTask so that you compute the list inside doInBackground() and then return it to onPostExecute(), and then do all of your updates there:
// change the type parameters to return a List
private static class GetContacts extends AsyncTask<Void, Void, List<Actors>> {

    @Override
    protected List<Actors> doInBackground(Void... ignored) {
        // add this at the top
        List<Actors> actors = new ArrayList<>();

                    // inside your loop, replace this line:
                    // activityReference.get().actorsList.add(actor);
                    // with this instead
                    actors.add(actor);

        // and at the end, return the list
        return actors;
    }

    // the list you returned from doInBackground() is passed here
    protected void onPostExecute(List<Actors> result) {
        // update your activity all at once in this method
        activity.actorsList.clear();
        activity.actorsList.addAll(result);
        activity.adapter.notifyDataSetChanged();
    }
}

I've trimmed out a bunch of code to make things easier to read, but the general idea is there.
Comment: thank you, I forgot to change last parameter to List in Getcontacts before. In your code I think we should change also protected String doInBackground to protected List doInBackground and this way it is working. I will check in future release if the issue will appear after this change, but hopefully not.
Comment: Whoops, yes, you're absolutely right, `doInBackground()` must return `List`


How can I store and retrieve audio files to and from CloudKit?

Question: I am attempting to record voice messages and store them as CKAssets on CloudKit. I convert them into an AVAudioFile and save them to CloudKit as one of several properties on a Post record.
var recordedMessage: AVAudioFile?

var recordedMessageURL: URL? {
    didSet {
        if let recordedMessageURL = recordedMessageURL {
            recordedMessage = try? AVAudioFile(forReading: recordedMessageURL)
        }
    }
}

This part of the process seems to work, although I'm unable to play back the audio when I access the file through my CloudKit dashboard. (Double-clicking on it opens iTunes, but it won't play)
I've created a fetchPosts function that successfully brings down the image tied to the record, but when I attempt to play the audio, it gives me the following error:
ExtAudioFile.cpp:192:Open: about to throw -43: open audio file
I believe it has to do with my being unable to properly convert the asset into an AVAudioFile. It doesn't seem to be as clean-cut as converting image assets.
    var foundAudio: AVAudioFile?
    if let audioAsset = ckRecord[PostStrings.audioAssetKey] as? CKAsset {
        do {
            let audioData = try Data(contentsOf: audioAsset.fileURL!)
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            guard let destinationPath = NSURL(fileURLWithPath: documentsPath).appendingPathComponent("filename.m4a", isDirectory: false) else {return nil}

            FileManager.default.createFile(atPath: destinationPath.path, contents: audioData, attributes: nil)

            foundAudio = try AVAudioFile(forReading: destinationPath)
        } catch {
            print("Could not transform asset into data")
        }
    }

Can anyone tell me where I'm going wrong?
Comment: When you download the `CKAsset` from the CloudKit Dashboard, and you have a raw file, does adding the file extension back to the file allow you to play it on your Mac?
Comment: I appreciate the comment, but I worked around the issue today. It is sufficiently different that I can no longer test your theory. Thanks for reaching out!
Answer: It took many days of changing things around, but I've got a working solution that doesn't involve directly manipulating the data as Data. Instead I use a URL. I initialized the audioAsset as a URL:
var opComment: URL?
var audioAsset: CKAsset? {
  get {
    guard let audioURL = opComment else { return nil }
    return CKAsset(fileURL: audioURL)
    }
    set {
      opComment = newValue?.fileURL
    }
  }

I pulled the ckRecord back down with a convenience initializer:
var opCommentURL: URL?
    if let audioAsset = ckRecord[PostStrings.audioAssetKey] as? CKAsset {
            opCommentURL = audioAsset.fileURL
    }

And I fed it into my AVAudioPlayer as a URL:
        guard let audioURL = post.opComment else {return}

    if !isTimerRunning {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
            audioPlayer.play()
        } catch {
            print("Error in \(#function) : \(error.localizedDescription) /n---/n \(error)")
        }
    } else {
        audioPlayer.pause()
        isTimerRunning = false
    }

(If you're reading this, Sam. Thanks for the gentle push in the right direction!)


What is the difference between summary() and loadings() for princomp() object in R?

Question: Example code:
(pc.cr <- princomp(USArrests))
summary(pc.cr)
loadings(pc.cr)  ## note that blank entries are small but not zero

I am getting different outputs from each, and I am not sure I understand what the difference is.
Here is the output:
> summary(pc.cr)
Importance of components:
                           Comp.1      Comp.2      Comp.3       Comp.4
Standard deviation     82.8908472 14.06956001 6.424204055 2.4578367034
Proportion of Variance  0.9655342  0.02781734 0.005799535 0.0008489079
Cumulative Proportion   0.9655342  0.99335156 0.999151092 1.0000000000

> loadings(pc.cr)  ## note that blank entries are small but not zero

...

               Comp.1 Comp.2 Comp.3 Comp.4
SS loadings      1.00   1.00   1.00   1.00
Proportion Var   0.25   0.25   0.25   0.25
Cumulative Var   0.25   0.50   0.75   1.00

P.S: how can I get access to the table created by summary(pc.cr)?? (I can't seem to find it in str.)
Comment: For the 2nd question, you mean the eigenvectors or the component loadings summary?
Comment: Hi chl - I mean the output from "summary(pc.cr)" - for some reason, I can't find it. (doing something like summary(pc.cr)[[1]] will get me only part of the table)
Comment: Why do you have `# inappropriate` comment in the first line?
Comment: @amoeba -  I honestly don't remember. I removed it. :)
Answer: The first output is the correct and most useful one. Calling loadings() on your object just returns a summary where the SS are always equal to 1, hence the % variance is just the SS loadings divided by the number of variables. It makes sense only when using Factor Analysis (like in factanal). I never use princomp or its SVD-based alternative (prcomp), and I prefer the FactoMineR or ade4 package which are by far more powerful!
About your second question, the summary() function just returns the SD for each component (pc.cr$sdev in your case), and the rest of the table seems to be computed afterwards (through the print or show method, I didn't investigate this in details).
> getS3method("summary","princomp")
function (object, loadings = FALSE, cutoff = 0.1, ...)
{
    object$cutoff <- cutoff
    object$print.loadings <- loadings
    class(object) <- "summary.princomp"
    object
}
<environment: namespace:stats>

What princomp() itself does may be viewed using getAnywhere("princomp.default").
Comment: +1 I also use FactoMineR but I remember that when I tried it's PCA method on a really large dataset, I never got results.
Comment: @gd047 It failed for me too, though it is based on an SVD (might be optimized to handle large data set :)


Upper bound for sum of powers

Question: I have a sequence of positive real numbers $\{x_i\}_{i=1}^{N}$ and $k \in \mathbb{N}$. I was wondering if one can find an upper bound of the type
$$ \sum_{i=1}^{N}{x_i^k} \leq f\left(\sum_{i=1}^{N}{x_i} \right)$$
where $f$ is a smooth function.
Thanks.
Answer: $f(y)=y^k$ works.  If you expand the $k^{\text{th}}$ power of the sum on the right, you get all the terms on the left plus a bunch of positive cross terms.

Upper bound for sum of powers


Certificação de Processo de Qualidade: como obter?

Question: Tenho um sistema e quero certificá-lo. Minha ideia é o ISO 9001.
O que é preciso fazer? Quais são os requisitos para se obter esta certificação?
Devo procurar uma empresa para obter a certificação ou há outros meios de certificar a aplicação, como por exemplo pagar apenas pela homologação?
Answer: A norma ISO 9001 normalmente é usada para a gestão de qualidade em empresas e organizações, mas pode ser perfeitamente usada para a gestão de qualidade do desenvolvimento de um sistema, em teoria.
Para que seja satisfeita a implementação da norma, a parte interessada deve se atentar a uma série de requisitos, como a produção de documentação sobre os processos adotados e as respectivas premissas de qualidade usadas nesse controle de qualidade, como o uso de um software só para isso, por exemplo.
Não é comum haver a aplicação da norma no desenvolvimento do software porque a norma não traz agilidade ao desenvolvimento, além de encarecer todo o processo. O que é mais comum é termos disponíveis no mercado sistemas que façam este controle de qualidade e consequente aplicação correta da norma.
Implementação e certificação pela norma ISO são duas etapas em separado, normalmente feitas por empresas de consultoria, que visitam o negócio com a função de encontrar e mitigar problemas processuais. No seu contexto, duas coisas podem ser homologadas:

O processo de desenvolvimento do seu software;
O seu software, que pode ter sido feito para atender à gestão da qualidade numa empresa e ao consequente cumprimento da norma.


How does a key influence pitch?

Question: I'm trying to figure out how a key influences a song's pitch.
Let's say I have a song in C major. If I transpose it to D major does this necessarily mean that my song will have a higher pitch? Or is this assumption wrong because we could have been playing it one octave lower in D major. In other words, when someone tells you they're playing in one key versus another key, you can't make any assumption if the pitch will go up or down (?)
Answer: I think it might make more sense to ask how transposition affects the pitches of a piece.
Usually a piece is transposed for a specific reason. The two most common reasons are to make it more comfortable for a singer or singers and to make it possible or easier to play with different instruments. In either of those cases, whether the piece is transposed up or down depends on exactly which instruments are going to be used and/or the ranges of the singers.
For example, it's not uncommon for a person with a high voice to sing a part an octave higher than the original, while a person with a low voice may sing an octave lower than the original.
When pieces are played on different instruments, it's usually called a transcription, because more than just a straight transposition is necessary. For example, the classical guitar version of "Leyenda" (often called "Asturias") by Isaac Albeniz involves transposition to a different key from the original as well as moving the lowest notes up or omitting them and moving the highest notes down. Also, the chords are arpeggiated. These changes are necessary because of the major differences between the guitar and the piano (the original instrument).
So in the end, a transposition to a different key might simultaneously involve some instruments playing higher and others playing lower than the original piece, or even some notes being played higher and other notes played lower on the same instrument, when compared to the original.
Answer: 'Transpose from C major to D major' doesn't tell us whether to go one up or seven down.  Or nine up - which might well be the requirement if a song for bass voice was being transposed for soprano!
As anyone who has bought a song copy from one of the online music publishers will have discovered, the ability to have it 'in your key' can be a mixed blessing.  Even without octave shifts, a piano accompaniment can become clunky surprisingly easily when transposed more than a few semitones.   And where other instruments are involved, it's easy to fall foul of the absolute possible range, not just the most effective one.   A piano part transposed down may sound muddy.  A flute asked to play below middle C just can't.  (OK, maybe B, as we're such a lot of pedants here.)
Answer: I think of pitch as the rate at which something vibrates. So a D note a whole step above a C will be higher in pitch. C can be higher, lower or the same as another C.
Transpose means you are playing it in a different key. If everything else was the same, like I am literally just shifting everything up a whole step all the pitches will be higher and you will go from the key of C to D. If you shift everything down from C to a lower D all the pitches will be lower and you will transpose to the key of D.
Comment: "I am literally just shifting everything up a whole step" -- you don't have to shift everything up a whole step (lots of people do, especially guitarists it seems). Play some pattern in a single octave in C major. Now stop, and don't move your hands. Play the same pattern, but this time play C♯ instead of C and F♯ instead of F, whenever one of those notes occurs in the pattern. Now you have modulated up a whole step to D major without raising all of the pitches a whole step. Some would say that D major sounds "brighter" than C major because of the two sharped notes.

How does a key influence pitch?


Paginação PDO - Problemas com prepare(); select();

Question: Olá, estou tendo os problemas para imprimir dados de uma tabela.
Atualização: Inseri as seguinte linhas no arquivo conexao.php:
public function select(){
  $sth = $this->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
  $this->execute();
  $result = $sth->fetchAll();
  return $result;
}

conexao.php
// conexao banco de dados
<?php
    class Conexao {
        private $data = array();
        //variavel da classe Base
        protected $pdo = null;

        public function __set($name, $value){
            $this->data[$name] = $value;
        }

        public function __get($name){
            if (array_key_exists($name, $this->data)) {
                return $this->data[$name];
            }

            $trace = debug_backtrace();
            trigger_error(
                'Undefined property via __get(): ' . $name .
                ' in ' . $trace[0]['file'] .
                ' on line ' . $trace[0]['line'],
                E_USER_NOTICE);
            return null;
        }

        //método que retorna a variável $pdo
        public function getPdo() {
            return $this->pdo;
        }

        //método construtor da classe
        function __construct($pdo = null) {
            $this->pdo = $pdo;
            if ($this->pdo == null)
                $this->conectar();
        }

        //método que conecta com o banco de dados
        public function conectar() {
            $local = "localhost";
            $user = "root";
            $pass = "";
            $basename = "diner";

            try {
                $this->pdo = new PDO("mysql:host=$local;dbname=$basename",
                                "$user",
                                "$pass",
                                array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            } catch (PDOException $e) {
                print "Error!: " . $e->getMessage() . "
";
                die();
            }
        }

        //método que desconecta
        public function desconectar() {
            $this->pdo = null;
        }

        public function select(){
            $pdo = $this->getPdo();
            $sth = $pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
            $sth->execute();
            $result = $sth->fetchAll();
            return $result;
        }
    }
?>

lista-prato.php
//onde será imprimido os dados
<?php
    //inclui as bibliotecas
    require_once('conexao.php');
    //faz a canexão
    $pdo = new Conexao();

    // determina o numero de registros que serão visualisados
    $maximo = 20;
    // armazenamos o valor da pagina atual
    $pagina = isset($_GET['pagina']) ? ($_GET['pagina']) : '1';
    // subtraimos 1, por que os registros sempre começam do 0
    $inicio = $pagina - 1;
    //multiplicamos a quantidade de registros pelo valor da pagina atual
    $inicio = $maximo * $inicio;

    $strCount = $pdo->select("SELECT COUNT(*) AS 'prato_id' FROM prato");
    $total = 0;
    if(count($strCount)){
        foreach ($strCoun as $row)  {
            // armazeno total de registros da tabela para fazer paginação
            $total = $row["id_prato"];
        }
?>

<!DOCTYPE HTML>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width" />
        <title>Paginação com PHP</title>
        <link rel="stylesheet" type="text/css" href="css/estilo.css" />
        <link rel="stylesheet" type="text/css" href="css/reset.css" />

            <colgroup>
                <col class="coluna1"/>
                <col class="coluna2"/>
                <col class="coluna3"/>
            </colgroup>

Paginação com PHP

                    Codigo
                    Municipio
                    UF

            <?php
                //se a tabela nao estiver vazia, percorremos linha por linha pegando os valores
                if(count($result)){
                    foreach ($result as $res) {
                        echo "
";
                        echo "  ".$res['titulo']."	";
                        echo "  ".$res['descricao']."	";
                        echo "  ".$res['preco']."	";
                        echo "
";

                    }
                }
            ?>

            <?
                //determina quantos links serão adicionados e removidos
            $max_links = 6;
            // dados para os botões
            $previous = $pagina - 1;
            $next = $pagina + 1;
            // usa função "ceil" para arredondar o numero
            $pgs = ceil($total / $maximo);
            //se a tabela nao for vazia, adicionar botões
            if($pgs > 1){
                echo "
";
                //botao anterior
                if($previous > 0){
                    echo "
<input type='submit' name='bt-enviar' id='bt-enviar' value='Anterior' class='button' />
";
                }else{
                    echo "
<input type='submit'  name='bt-enviar' id='bt-enviar' value='Anterior' class='button' disabled='disabled'/>
";
                }
            }
            echo "div id='numpag'>";
                for($i=$pagina-$max_links; $i <= $pgs-1; $i++) {
                    if ($i <= 0){
                        //enquanto for negativo, não faz nada
                    }else{
                        //senão adiciona o link para a outra página
                        if($i == $pgs){
                        //se for o final da pagina, coloca ...
                            echo "$i ...";
                        }
                    }
                }

            ?>

Página interna onde será exibido o resultado interno.php:
<?php
require_once 'usuario.php';
require_once 'sessao.php';
require_once 'autenticador.php';

$aut = Autenticador::instanciar();

$usuario = null;
if ($aut->esta_logado()) {
    $usuario = $aut->pegar_usuario();
}
else {
    $aut->expulsar();
}

?>

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Pagina interna</title>

Página interna do sistema

Você está logado como
            <?php print $usuario->getNome(); ?>.

Sair

<?php include 'form-insert.php' ?>

<?php include 'lista-prato.php' ?>

</form>

Erro (já solucionado nas respostas):

Parse error: syntax error, unexpected end of file in C:\wamp\www\login\lista-prato.php on line 1021

Atualização 2: Ele está retornando o seguinte erro (já solucionado nos comentários):

( ! ) Fatal error: Call to undefined method Conexao::prepare() in C:\wamp\www\login\conexao.php on line 58

Atualização 3:
Notice: Undefined variable: result in C:\wamp\www\PROJETOS\210DINER\site-definitivo\newdiner\login\lista-prato.php on line 54
Call Stack
#   Time    Memory  Function    Location
1   0.0529  245376  {main}( )   ..\interno.php:0
2   0.0597  315008  include( 'C:\wamp\www\login\lista-prato.php' )  ..\interno.php:34

Alguém ai sabe onde estou errando e como devo proceder? Tenho que criar o método prepare()? em uma function? como fiz com select? ou não precisa de prepare, posso executar o select de uma vez?
Comment: [`Prepare`](http://php.net/manual/pt_BR/pdo.prepare.php) é um método do PDO. Na linha *58* deixe assim: `$sth = $this->$pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");  $this->$pdo->execute();` e não somente `$this`. Outra coisa, no arquivo *lista-prato.php* você chama esse método assim: `$pdo->select("SELECT COUNT(*) AS 'prato_id0' FROM prato");`, tem certeza que é isso mesmo?
Comment: realmente, tinha um 0 que não deveria. alterei o código para o que sugeriu.
`public function select(){
      $sth = $this->pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
      $this->pdo->execute();
      $result = $sth->fetchAll();
      return $result; }
` se for isso, deu erro.
**( ! ) Fatal error: Call to undefined method PDO::execute() in C:\wamp\www\login\conexao.php on line 59**
Comment: Ops, deixe essa função assim: http://pastebin.com/TVnECSg3 repare também que no arquivo *lista-prato.php* você chama o método `select` com argumentos, sendo que no *conexao.php* ela não recebe.
Comment: errors:

**( ! ) Notice: Undefined variable: pdo in C:\wamp\www\login\conexao.php on line 58**
______________________
**Notice: Undefined property via __get(): in C:\wamp\www\login\conexao.php on line 58 in C:\wamp\www\login\conexao.php on line 21**
_______________________
**Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\login\conexao.php on line 58**
Comment: Está falando do COUNT ? então, fiquei bem confuso..
Comment: Isso, repare que você chama ela com argumentos, mas você não usa parâmetros na função. Sobre o erro, você tem um método que já retorna a variável `pdo`, a função `getPdo` use ela. http://pastebin.com/kCQmHn8z
Comment: Beleza, atualizei a pergunta. Retornou o erro:
`( ! ) Notice: Undefined variable: resultado in C:\wamp\www\PROJETOS\210DINER\site-definitivo\newdiner\login\lista-prato.php on line 54`
Comment: Essa variável não está definida, não era para ser `strCount`?
Comment: Beleza, pararam os erros. mas não está imprimindo os dados do banco!
Comment: deixei assim ó: http://pastebin.com/Pd0rczsK
ele imprime:  **Notice: Array to string conversion in C:\wamp\www\PROJETOS\210DINER\site-definitivo\newdiner\login\lista-prato.php on line 27** e embaixo um do erro imprime na tela **'Array'**
Comment: Faça assim: `echo "" . print_r($resultados, 1) . "";`
Comment: imprimiu: **Array
(
)**
Comment: Independentemente de como você chamar o método `select`, a *query* que vai executar sempre será `SELECT id_prato, titulo, descricao, preco FROM prato` que está definida no corpo da função.
Comment: Então.. ele imprime um Array vazio, alterei no corpo da função todos os select do código chamam os dados.
`("SELECT id_prato, titulo, descricao, preco FROM prato");  `
http://pastebin.com/K4eeQsGg
Answer: Além dos erros de sintaxe no if, há também um erro na tua função select:
public function select(){
  $sth = $this->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
  $this->execute();
  $result = $sth->fetchAll();
  return $result;
}

Você está chamando o método PDO::prepare a partir do $this, o que causa o erro Call to undefined method, é necessário chamar este método a partir do objeto PDO, no teu código ele é retornado na função getPdo(). Portanto, a função select deve ficar assim:
public function select($statement){
  $pdo = $this->getPdo();
  $sth = $pdo->prepare($statement);
  $sth->execute();
  $result = $sth->fetchAll();
  return $result;
}

Comment: `$statement` aí seria: `("SELECT id_prato, titulo, descricao, preco FROM prato");`  quando for chamar eu declaro `$statement = ("SELECT id_prato, titulo, descricao, preco FROM prato");`   ?
Comment: @manzetti.denis Não.. deixe o *conexao.php* assim: **http://pastebin.com/kXK2zTwW** e o *lista-prato.php*: **http://pastebin.com/EFdjnBny**. Não testei.
Comment: Acho que consegui. http://pastebin.com/QudNWmXA - porem ele imprime os valores da seguinte forma: http://pastebin.com/4jqNyxzx . Como eu faço para tratar esses dados e imprimir os campos separando por linhas? devo abrir uma nova pergunta?
Comment: @manzetti.denis Que bom que conseguiu. Acho que seria melhor abrir uma nova pergunta sim, porque essa já está bem extensa com tantos "updates". =) se possível marque uma das respostas também.
Answer: É um erro de sintaxe, falou fechar uma chave em if(count($strCount)){, mude seu código para:
if(count($strCount)){
    foreach ($strCoun as $row)  {
        // armazeno total de registros da tabela para fazer paginação
        $total = $row["id_prato"];
    }
}// <---- chave que faltava.

Comment: Fiz o que você falou e deu:
`Fatal error: Call to undefined method Conexao::select() in C:\wamp\www\login\lista-prato.php on line 17;`
Comment: Na classe conexão não existe esse método select, deve ser em outra, ou vc deve adicionar esse método. @manzetti.denis
Comment: como eu faria isso?
`public function select();{
$pdo = $pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
$pdo->execute();
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
}`

estou iniciando php, não peguei bem as funções.
Comment: Mais ou menos esse o código, no final adicione um `return $result;`, em qual classe ele estava? @manzetti.denis
Comment: eu acabei de criar..  vou adiciona-lo dentro de `class Conexão()`
Comment: O código é esse: `public function select(){
 $sth = $pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
 $pdo->execute();
 $result = $sth->fetchAll();
 return $result;
}` @manzetti.denis
Comment: certo @rray, editei a pergunta com o novo erro.. ele retornou agora para o prepare(); tenho que criar como o select? como eu faria? na verade.. é necessario o prepare?
Answer: Você não fechou corretamente este if
if(count($strCount)){
    foreach ($strCoun as $row  {
        // armazeno total de registros da tabela para fazer paginação
        $total = $row["id_prato"]
    });

deve ser desta forma:
if(count($strCount)){
    foreach ($strCoun as $row) {
        // armazeno total de registros da tabela para fazer paginação
        $total = $row["id_prato"]
    };
}


Horizontal spacing of notes with multiple staves

Question: I created this minimal example :
\version "2.21.0"

\include "italiano.ly"

soprano_notes = \relative do' {
  fad fad16 sold8 la16 re4 re16 re8 re16
  re4 re16 dod8 si16 dod2
}

alto_notes = \relative do' {
  re2 re mi2. mi4
}

tenor_notes = \relative do {
  \clef "G_8"
  la2 fad sol2. ( fad4 ~ fad2)
}

bass_notes = \relative do {
  \clef bass
  re4 dod si lad
  si2 lad
}

\score {
  \new ChoirStaff <<
    \new Staff
    <<
      \new Voice = "soprano" {
        \soprano_notes
      }
    >>
    \new Staff
    <<
      \new Voice = "alto" {
        \alto_notes
      }
    >>
    \new Staff
    <<
      \new Voice = "bass" {
        \bass_notes
      }
    >>
  >>
}

And here is the result I have :

As you can see in the third stave, the 4 notes have the same duration but the spacing is incorrect (and the same kind of problem appears in the second measure). I want to have all the notes with the same duration to take the same horizontal space, is that possible?
Comment: What you want _is_ possible, but is frowned upon IMHO. It does not increase the legibility of the score.
Comment: @yo' to me it is tremendously helpful when I see a score like this since it provides a second visual cue about where the notes fall in respect to one another. If I was to take your argument to the extreme, we wouldn't need to align bars either since the notes would provide the duration anyways
Comment: Right. Horizontal space is _not_ supposed to represent the exact duration of notes, that is indicated by the notes themselves!
Comment: Well, I can count to four quite well :) But counting to 800 in a 200-bar piece would be tougher :) And also, the point is that simultaneous notes _are_ vertically aligned either way!
Answer: LilyPond calls this "proportional duration," and you can find it in the manual here.
Within your score block, you'll want to add a layout block:
\layout {
  \context {
    \Score
      proportionalNotationDuration = #(ly:make-moment 1/20)
  }
}

You can adjust the ly:make-moment 1/20 to be 1/16, 1/8, etc. That number tells LilyPond "use this fraction of a whole note as the unit of spacing." It can be any fraction, so experiment to see what works best for you.
The entire code would thus be:
\version "2.21.0"

\include "italiano.ly"

soprano_notes = \relative do' {
  fad fad16 sold8 la16 re4 re16 re8 re16
  re4 re16 dod8 si16 dod2
}

alto_notes = \relative do' {
  re2 re mi2. mi4
}

tenor_notes = \relative do {
  \clef "G_8"
  la2 fad sol2. ( fad4 ~ fad2)
}

bass_notes = \relative do {
  \clef bass
  re4 dod si lad
  si2 lad
}

\score {
  \new ChoirStaff <<
    \new Staff
    <<
      \new Voice = "soprano" {
        \soprano_notes
      }
    >>
    \new Staff
    <<
      \new Voice = "alto" {
        \alto_notes
      }
    >>
    \new Staff
    <<
      \new Voice = "bass" {
        \bass_notes
      }
    >>
  >>
  \layout {
    \context {
      \Score
        proportionalNotationDuration = #(ly:make-moment 1/20)
    }
  }
}

Which creates:
Comment: Thanks a lot. If I want a small spacing between notes I will always have this strange spacing when different durations are involved but now I have something to play with ;-)

And I don't know how I didn't see it in the manual... :-(


GWT Framework Enable console logs

Question: Im new to the GWT framework which my project is using now. I wanted to trace the code flow and hence thought I could put System.out logs or debug logs. But nothing worked. Then I came accross this page and saw its tottaly differnet for logging. I added,
Debug.Java
public class Debug {
private static boolean isEnabled_ = false;
public static void enable() { isEnabled_ = true; }
public static void setEnabled( final boolean isEnabled )
{ isEnabled_ = isEnabled; }

public static void log( final String s )
{ if( isEnabled_ ) nativeConsoleLog( s ); }

private static native void nativeConsoleLog( String s )
/*-{ console.log( s ); }-*/;
}

and called inside my class
Frame.java
public void onModuleLoad() {

    logSC("@@@@ onModuleLoad");

     Debug.enable();

    Debug.log("&&&&&&&INSIDE BICC******DEBUG LOGGERRRRRRRRR**************************");
}

But I didnt get the debug logs. Could you please advise me what should i do to enable logs and get printed in my console window.
Regards,
Saranya Chandrasekaran
Comment: Try GWT.log("message); This will work in SDM.
Comment: @ElHoss: GWT.log also doesnt work:(. I dont see any logs in my console. Could you please help me out
Answer: The console.log call in your JSNI needs a $wnd. prefix so that it runs on the correct window (gwt defaults to sandboxing its code in an iframe).
private static native void nativeConsoleLog( String s ) /*-{
    $wnd.console.log( s );
}-*/;

Note that using JsInterop will not have this issue - add elemental2-core to your project, and call DomGlobal.console.log() and it will already work in the main window.
Answer: That is not the right way to do logging in GWT, GWT already enables you to use the java logging on the browser, so to enable java logging you need to follow these steps :
1- inherits the java logging module by adding<inherits name="com.google.gwt.logging.Logging"/> to your XXX.gwt.xml file, this will enable logging.
2- enable the console logger by adding:
<set-property name="gwt.logging.logLevel" value="INFO"/>
<set-property name="gwt.logging.enabled" value="TRUE"/>
<set-property name="gwt.logging.consoleHandler" value="ENABLED"/>
-this is the default.
then you can define normal java logger like this
public static final Logger LOGGER = Logger.getLogger(MyClass.getName());
//use the logger
LOGGER.log(Level.info, "my log message");

this kind of logging will work even in the production mode and result in a larger javascript file after compilation. any log statements that does not match the log level defined in the XXX.gwt.xml will be removed from the compilation final result.
another way to do logging for development mode or Super dev mode is to use GWT.log this type of logging will only work for development modes but will be removed in production compilation.
for more readings about this topic you can refer to the gwtproject web site
you can also ask in the gwt-users google group
or you can ask in gwt gitter channel for a live interactive chat
Answer: You need to add the in gwt.xml to enable it
< set-prop name="gwt.logging.logLevel" value="ALL" />
<set-property name="gwt.logging.enabled" value="TRUE" />

Comment: That's not all. The code needs also to utilize jul-logging.
Answer: See here a solution for using the gwt log framework:
gwt logging not working
It uses java.util.log

GWT Framework Enable console logs


Scaling images to window size while keeping relative position to each other

Question: I want to have a container element on my site that holds 9 images (like this) that scale responsively to window size and keep their aspect ratio (1:1, sorry for the image) while staying in the same relative position to each other.
So far my best attempts got me to where the image height would flow out of the container element and made the window show a vertical scroll bar or the third image of a row would get pushed down to the next row.
This is what I am currently stuck with:
https://jsfiddle.net/5xdznc4e/
#img11 {
  position: relative;
  width: 30vmin;
  height: auto;
}

#img12 {
  position: relative;
  width: 30vmin;
  height: auto;
}

#img13 {
  position: relative;
  width: 30vmin;
  height: auto;
}

On resizing the window it doesn't behave nicely at all.
Comment: If it all stays quadratic all the time, then you're probably best off using media queries to check whether you're in portrait or landscape mode - and then set _either_ the width or height, accordingly.
Comment: flexbox is the answer, look at my code snippet in the answer below.
Answer: You need to use flexbox, it's an awesome css3 feature.

.container {
  display: flex;
  flex-direction: row;
  width: 100%;
  justify-content: space-around;
  flex-wrap: wrap;
}
.container img {
  width: 28%;
  padding: 2%;

}

Answer: Between the image you have space because the new line.
If you use html code like this, you don't have problem:

See this fiddle: https://jsfiddle.net/Lujqcovo/1/
Answer: try below code this should work

.container {
  width: 90%;
  margin: 0 auto;
}

.container img {
  position: relative;
  width: 32%;
  height: auto;
  margin:0;
  padding:0;
}

@media (max-width: 768px) {
  .container img {
    width: 49%;
  }
}

Answer:
Remove those BR tags and add the below class and rule.

HTML

CSS
.wdth{
  max-width:400px
}