C# converter string dinâmica em xml com TAG

Question: Gostaria de saber como converter um string com XML inline para um XML com tags, estou utilizando o XmlDocument, tenho o seguinte código:
var MihaString="<MeuXML Info01="teste 0121245" Info02="2020-01-14" Info03="2019-12-30"/>";

a variável MihaString é dinâmica, não sei qual a estrutura do XML, só
sei que vai vir inline, e preciso sempre converter para XML com TAG

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(MihaString);
var result = xmlDocument.OuterXml;

Porem mesmo utilizando o OuterXml ele mantem a mesma estrutura do xml de entrada.
Resultado esperado seria algo assim:
<MeuXMLPai>
 <MeuXML>
  <Info01> teste 0121245 </Info01>
  <Info02> 2020-01-14 </Info02>
  <Info03> 2019-12-30 </Info03>
 </MeuXML>
</MeuXMLPai>

Comment: você além de um exemplo tem vários outros?
Comment: Pode vir qualquer xml, por exemplo assim:

, o objetivo é tirar tudo que esta inline e virar TAG
Comment: complicado, porque parece uma operação mais complicada do que está no exemplo. Geralmente isso já deveria vir pronto, corretamente, agora você poderia escrever um texto explicando o assunto, se for desse jeito é só fazer um processo recursivo e gerar o nodes com a resposta que eu te dei anteriormente
Comment: Consegui resolver, postei a resposta aqui.
Answer: Existem várias formas de fazer o que vc quer, tenho um projeto que manipula strings do xml diretamente, mas no seu caso, pode usar o XmlDocument para fazer a conversão necessária.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("seu xml");

XmlNode selectedNode = xmlDoc.SelectSingleNode("./<XPath>");
selectdeNode = changeNodeAttributesToElements(selectdeNode,xmlDoc);

private XmlNode changeNodeAttributesToElements(XmlNode node,XmlDocument xmlDoc)
{

    foreach (XmlAttribute att in node.Attributes)
    {
        XmlNode newNode = xmlDoc.CreateElement(att.Name);
        newNode.InnerText = att.Value;
        node.Append(newNode);
    }

node.Attributes.RemoveAll();
}

Answer: Utilizando a referencia das respostas 30166183 e 29426107, adaptei e consegui gerar o XML dinamicamente, convertendo os atributos para TAG.
Codigo:
Main
  XmlDocument document = new XmlDocument();
  document.LoadXml(stringXml);
  var dictionary = document.ToObject();
  var xmlElement = XmlDocumentExtension.ToXML(dictionary, document.LastChild.Name);
  var xmldoc = new XmlDocument();
  xmldoc.Load(xmlElement.CreateReader());
  var xmlResult = xmldoc.OuterXml;

XmlDocumentExtension
  public static XElement ToXML(this IDictionary<string, object> dic, string firstNode)
  {
        IList<XElement> xElements = new List<XElement>();
        foreach (var item in dic)
        {
              xElements.Add(new XElement(item.Key.Contains("XX_XX") ? item.Key.Split(new string[] { "XX_XX" }, StringSplitOptions.None)[0] : item.Key, GetXElement(item.Value))); ;
        }
        XElement root = new XElement(firstNode, xElements.ToArray());
        return root;
  }

  private static object GetXElement(dynamic item)
  {
        if (item != null && item.GetType() != typeof(String))
        {
              IList<XElement> xElements = new List<XElement>();
              foreach (var item2 in item as IDictionary<string, object>)
              {
                    var dic = (item2.Value as IDictionary<string, object>);
                    var key = item2.Key;

                    if (item2.Key?.Contains("XX_XX") == true)
                    {
                          key = key.Split(new string[] { "XX_XX" }, StringSplitOptions.None)[0];
                    }

                    if (dic?.Keys.Count == 1 && dic.Keys.First() == "XXvalueXX")
                    {
                          xElements.Add(new XElement(key, GetXElement(dic.Values.First())));
                    }
                    else
                    {
                        xElements.Add(new XElement(key, GetXElement(item2.Value)));
                    }
              }
              return xElements.ToArray();
        }
        return item;
  }

  public static IDictionary<string, object> ToObject(this XmlDocument document)
  {
        XmlElement root = document.DocumentElement;
        return ToObject(root, new ExpandoObject());
  }

  private static IDictionary<string, object> ToObject(XmlNode node, ExpandoObject config, int count = 1)
  {
        var parent = config as IDictionary<string, object>;
        foreach (XmlAttribute nodeAttribute in node.Attributes)
        {
              var nodeAttrName = nodeAttribute.Name.ToString();
              parent[nodeAttrName] = nodeAttribute.Value;
        }
        foreach (XmlNode nodeChild in node.ChildNodes)
        {
              if (IsTextOrCDataSection(nodeChild))
              {
                    parent["XXvalueXX"] = nodeChild.Value;
              }
              else
              {
                    string nodeChildName = nodeChild.Name.ToString();
                    if (parent.ContainsKey(nodeChildName))
                    {
                          parent[nodeChildName + "XX_XX" + count] = ToObject(nodeChild, new ExpandoObject(), count++);
                    }
                    else
                    {
                          parent[nodeChildName] = ToObject(nodeChild, new ExpandoObject());
                    }
              }
        }
        return config;
  }

  private static bool IsTextOrCDataSection(XmlNode node)
  {
        return node.Name == "#text" || node.Name == "#cdata-section";
  }


Pivot table pandas with column prefix

Question: I am trying to reshape dataframe as shown in the images. I want to create a wide dataframe  with the values in asset as new columns with the prefix asset_. In the new asset_ columns the corresponding value from the value column should be stored. See attached images. This is some sort of pivot operation but I can't figure out following:

How to dynamically add the prefix asset_ to the new columns.
How to keep the ser_num and day column that have the same values for each row.

I tried to do this with pandas.pivot but there are no prefix parameter and I do not want to create any multilevel indexes:
Import pandas as pd
data  = {"rowkey":["2017:P7W", "2017:P7W", "2017:P7W"],
            "ser_num":[467, 467, 467],
            "asset": ["A", "B", "C"],
            "value": [123,456, 789],
           "day":[1,1,1]}
df = pd.DataFrame(data)
df.pivot(index="rowkey", columns="asset", values="value").reset_index()

In my problem I have 200+ unique assets so the result will be a very wide dataframe. See images:
Dataframe before manipulation
Dataframe after manipulation
Answer: You can use the add_prefix() method as shown below:
# Create pandas dataframe
import pandas as pd
data  = {
  "rowkey": ["2017:P7W", "2017:P7W", "2017:P7W"],
  "ser_num": [467, 467, 467], "asset": ["A", "B", "C"],
  "value": [123,456,789],"day":[1,1,1]
}
df = pd.DataFrame(data)

# Pivot data and add prefix
df.pivot(index="rowkey",columns="asset",values="value").reset_index().add_prefix('asset_')

here an output after manipulation:

Best,
Abakar
Comment: This is a great answer, only a small adjustment that the function is `add_prefix()` with two d's
Comment: I fixed now the missing d. Thanks @HaplessEcologist
Comment: Here we prefix also rowkey, which is not ideal I think :) For those looking how to change that, see https://stackoverflow.com/questions/70311932/how-to-add-prefix-to-column-names-except-some-columns

Pivot table pandas with column prefix


I enter a specific step in cucumber - a click on a button is simulated, without me triggering it

Question: I use selenium to detect 2 buttons in a webpage.
My test is using cucumber.
Unfortunately, when I enter a specific step in cucumber -
a click on a button is simulated, without me triggering it.
Is this a known issue?
my steps:
Feature: app inbox
  Scenario: app nav inbox
    Given There exists an admin logged in client
    And I navigate to offer "app_navigable" inbox page
    Then text should be as follows:
      | name         | visibility | text                               |
      | inbox_title1 | true       | Here's the link to the app nav app |
      | inbox_title2 | true       | app nav mail title                 |

in the first line of this method the button is clicked:
@And("^text should be as follows:$")
public void text_should_be_as_follows(List<Map<String,
        String>> previewPropList) throws Throwable {
    Map<String, String> previewProps;
    for (int i = 0; i < previewPropList.size(); i++) {

any more data I can add to figure it out?
Comment: cucumber doesn't have anything to do with button click. Do you have any `Background` step? Is there any 'similar' step in any other step definition?  What happens in the step before?
Comment: I don't know what `Background step` is. How do a similar step look like? Nothing special happens in the previous step. no click btw
Comment: Is your code available to check? I'm 100% sure this has nothing to do with cucumber
Answer: This is quite late answer but I ran into a similar issue yesterday and maybe it can be useful for someone.
Did you have a .sendkeys() method somewhere in your code, which takes input data from string list or an external source? Because if there's a "\n" newline or other escape sequence at the end of the input string, it will trigger an "enter" key press, this can be triggering the button (not actually a click).


Change focus to next textfield in flutter

Question: I have a code for making Text Fields as shown below
 ...Column(
   children: <Widget>[
                      textField(text: 'User Name'),
                      SizedBox(height: 20),
                      textField(text: 'Password'), ])...

textField is a class that I made that has the following code to make a textfield. I did this to avoid code duplication,since I use textfields a lot in my applicatin.
...TextField(
    textInputAction: TextInputAction.next,
    obscureText: text == 'Password' ? true : false,
    textCapitalization: TextCapitalization.words,
    cursorColor: primaryColor,
    textAlign: TextAlign.center,
    decoration: InputDecoration(
      labelText: text,
      labelStyle: TextStyle(color: primaryColor, fontFamily: 'Bellotta'),
      filled: true,
      fillColor: Colors.white,
      border: OutlineInputBorder(...

Since I use this function to create the text field I cant use focusNode to change focus.
How can I solve this issue??
Answer: u can specify two more parameter one for focusNode of current textfield & another one for focus u want to change e.g.
textField(
    text: 'User Name',
    focusNode: // your focus node,
    nextFocusNode: // your next field focus node
),

now u can use :
FocusScope.of(context).requestFocus(nextFocus);

tip: if u want to decrease code duplication then instead of creating textfield method u should store ur InputDecoration in var/ method.
Comment: Duh that was so obvious. Cant believe I overlooked that. Thanks


Align buttons side by side - bootstrap 3

Question: Take a look at the below example.
Link to Bootply
I want the  tag to be besides Button 2.
Answer: Bootstrap uses 12 column grid. Right now two buttons take the whole available space (both 6-column width) leaving no space for the third. You can layout your buttons as 5+5+2 columns. For example:

    <button type="submit" class="btn btn-default btn-md col-md-5">Button 1</button>
    <button type="reset" class="btn btn-default btn-md col-md-5">Button 2</button>

Demo: http://www.bootply.com/RAqyEiTp1i
You want to place the third button outside the row container, you can position it absolutely relatively to the col group:

CSS:
.btn-beside {
    position: absolute;
    left: 100%;
    top: 0;
    margin-left: -10px;
}

Demo: http://www.bootply.com/5n3y1uZDng
Comment: that could have worked had i wanted all the 3 buttons to be within the size of the above textbox. I want the `` tag to be besides the current button 2.
Comment: one of the issues is tht, in mobile mode the button 3 appears displaced.


Why is $gN = N$ for $g \in N$?

Question: Suppose we have a homomorphism defined as $\phi: \mathbb{Z}\to \mathbb{Z_3}$, where $\mathbb{Z_3}$ is a group under addition. Then $\ker{\phi}$ will be the set $3\mathbb{Z}=\{0, 3, 6, ..., 27, ...\}$. Now let's take some element in the kernel of $\phi$ (say, $3$) and take the product with the kernel of $\phi$. We will then have $3+\ker{\phi} = \{3, 6, 9, ...,\}$. Basically, this operation appears to eliminate all elements of the kernel, which precede $3$.
I'm wondering what I'm not seeing here, to be able to be satisfied that all cosets of the kernel of some homomorphism must be the kernel of the homomoprhism?
Answer: $3\mathbb Z=\{\dots, -9,-6,-3,0,3,6,9,\dots\}$. The integers wouldn't be a group under addition if they didn't have negative numbers.
Answer: Note that $3\mathbb{Z}=\{...,-9,-6,-3,0,3,6,9,...\}$, so $3+\ker(\phi)=\{...,-6,-3,0,3,6,...\}$.

Why is $gN = N$ for $g \in N$?


Best method to analyse multiple 2x2 contingency tables of a small sample?

Question: I already looked around quite a bit but didn't find answers (I understood), so I apologise if this question should be a duplicate.
I'm analysing a small cohort (n=15) of people with some observed difference/outcome X, which is either positive or negative.
I want to check whether the number of positive X is different between one or many of three binary categories: Older than Y?, Born in Country Z?, and Previous Children?.
My naive approach was to construct three 2x2 contingency tables, do a Fisher's Exact test on each, and apply Bonferroni correction by multiplying the p-values times 3 (since I tested X vs Age, X vs Country, X vs Children).
So my question, as I'm not super statistically fluid: Is this correct? Are there better ways which also might take into account that the variables might be dependent on another (e.g. age and previous children)? I can't really combine the three variables into one since my sample is so small.
Answer: Because of the discreteness of the Fisher exact test, especially for such a small sample size, a simple Bonferroni correction will be too conservative. While accounting for dependence structure will reduce this conservativeness a little, it is hard to implement in your case. In any event, you can get much more power by applying the discrete Bonferroni correction in your example, so that is my recommendation.
See
Westfall, P.H. and Wolfinger, R.D.(1997). Multiple Tests with Discrete Distributions,
The American Statistician 51, 3–8.
Also, in Chapter 17 of
Westfall,P., Tobias, R. and Wolfinger, R. (2011), Multiple Comparisons and Multiple
Tests Using SAS (2nd Ed.), SAS® Press, Cary, NC
there are several worked out examples.
Comment: Thank's a lot! I will have a look at your suggestions and forward them to the coauthors. Will mark as solved afterwards :)
Comment: Great! See also:   Westfall, P.H. (2011).  Improving Power by Dichotomizing (Even Under Normality), Statistics in Biopharmaceutical Research 3, 353–362.


Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Question: I have just downloaded and installed Visual Studio 2012 Ultimate RC, but I'm having an issue with the intellisense: it does not work until I press Ctrl+Space. Code suggestions are disabled also (method parameters for example).
I think the problem is with the VS installation, because at the end of the process the following message is shown: "The event log file is full".
Why do I have this problem, and what can I do to fix it?
Comment: I've had the same problem. I think this is becouse I've had vs2010 with resharper, and vs2012 imported settings from it. You can make everething to work as expected by Tools->Import and export settins->Reset all settings
Comment: I just restarted VS2012 and Intellisense worked again
Comment: Found it under `TOOLS` -> `Settings` -> `Import and Export Settings...`. Doing a reset brought Intellisense back for me.
Comment: I have resharper installed too, but it seems it's not the problem in my case. in the end, it seems VS12 doesn't activate intellisense by default (you need to use CTRL+Space to get autocomplete and code suggestions). I had to enable it from the Tools->Options configuration menu.
Comment: it's Tools -> Options -> Text Editor -> C# -> Intellisense. check "Show Completion list after a character is typed" and the underlying checkboxes
Comment: this doesn't seem limited to the RC version, i had the same issue with the RTM version
Comment: Resetting settings did not work for me, only restarting VS2012
Comment: WHERE in the Tools->Options configuration menu?  Can you please post the complete path?
Comment: Its broken I think... it is not working with Express Web 2012 either
Comment: I get the same issue with VS 2012 premium, and nothing work
Comment: Confirmed... Resetting the settings in "Import and Export Settings..." worked.
Comment: Tools>Options>Text Editor> I would suggest using All Languages here, instead of just a single language like C#, because you will encounter the same frustration again if you forget to set it for the other languages you use.  Hamzad_cne's answer above is correct and will avoid resetting all of your other settings.
Comment: I'm using F# and intellisense pops up then dissapears after half a second making it unusable. Resetting the settings doesn't help
Comment: user1831021's answer below works without having to lose all of your settings just to re-enable one thing.
Comment: can someone explain to me why "Display Line Numbers" is not a default setting after I reset.. *sigh*
Comment: I have been having this problem, but sometimes (not all the time) it is my own foolishness, for trying to get Intellisense to work on a value that is not accessible. Double check the Intellisense behaviour on other known values to make sure that you are having a true problem before trying more drastic solutions.
Comment: When I try that, I get this: Error 1:  Task List Display Settings: The tasklist format has changed.

Which led me to this: http://stackoverflow.com/questions/28189563/the-tasklist-format-has-changed-error-while-reseting-all-settings-in-visual-stud

ie. Just have to make sure you don't have a project open. If you do and got that error, restart and try again.
Answer: Go to
Tools->Options->Text Editor->C# (or All Languages)->General
and enable Auto List Members and Parameter Information in right hand side pane.
Comment: This is fairly common when you're on a trial version of resharper and the trial runs out. I assume R# turns these settings off and replaces it with the R# version, so when R# goes away, so does any kind of code completion.
Comment: I followed these steps, and no dice. the Auto list members is checked, but I am still not getting any intellisense. what's up?
Comment: I had this happen with R# and the trial version. Make sure you go through and reenable it for *each type individually*, along with 'All Languages'.
Comment: best option restart visual studio
Comment: This worked for me after disabling and re-enabling for All Languages. I had also installed the Resharper trial and had it expire.
Comment: Tried alot closing and opening the visual studio..this one works good for me...thanks
Answer: Restarting VS2012 should fix the problem.
Comment: Came her to answer this! Nothing else worked, but hey! This is windows! Just restart VS! (I would go for a rebbot next if it didn't work).
Comment: I just reopen the file I am using. No need to restart whole vs.
Comment: I wish there was a better solution to this problem, but this is the only thing that seems to work.  There seems to be no reason that the intellisense stops working and it seems to happen at the most inconvenient times for me.  Would love an update if someone finds a permanent fix.
Comment: the default solution for all microsoft's product installed in microsoft's OS
Comment: worked for me four! My Intellisense stopped working as I was writing some very simple textbook C# code and a restart fixed it. Not sure why...
Comment: Sometimes it really is that simple... I thought I accidentally had pressed a hot key to disable it or something. Worked in VS2013.
Comment: Bill Gates gates just called from the 90's. He wants his answer back! (this answer worked for me!).
Comment: Worked for me. Thanks.
Comment: hah, hah!  :-)  Yes, this also helped me with some weird failures...  Intellisense seemed to be deliberately hiding all but primitive types.  I did happen to just change some class and file names.....  not sure if that was part of it.  But just close all and restart seems to help :-D
Answer: Look at this post here.
This worked for me:
Delete the files in this folder. vs2010:
 %AppData%\Microsoft\VisualStudio\10.0\ReflectedSchemas

vs2012;
%AppData%\Microsoft\VisualStudio\11.0\ReflectedSchemas

VS Ultimate 2013;
%AppData%\Microsoft\VisualStudio\12.0\ReflectedSchemas

VS Professional 2015;
%AppData%\Microsoft\VisualStudio\14.0\ReflectedSchemas

Comment: To me, the correct path was "%AppData%\Microsoft\VisualStudio\12.0\ReflectedSchemas" since %AppData% included Roaming
Comment: This was the only fix that worked for me! Thanks so much! Its 12.0 now
Comment: \Microsoft\VisualStudio\14.0 for Visual Studio 2015
Comment: The only fix that help me. Thanks.
Comment: Worked! You might need a restart
Answer: Another possible solution is to completely reset the settings. This is what fixed it for me:
Tools->Import and Export settings->Reset all settings.
Comment: Worked perfectly for me.  I'd only lost some intellisense (eg argument signatures for VB methods).  Didn't like the idea of deleting files in some folder when I didn't know what it did.
Comment: Worked great for me. I had to restart the IDE after the reset to get it working.
Comment: When I try that, I get this: Error 1:  Task List Display Settings: The tasklist format has changed.

Which led me to this: http://stackoverflow.com/questions/28189563/the-tasklist-format-has-changed-error-while-reseting-all-settings-in-visual-stud

ie. Just have to make sure you don't have a project open. If you do and got that error, restart and try again.
Answer: A. Save or export out your Import/Export settings:
Tools->Import and Export settings
B. Do the Import/ Export reset:
Tools->Import and Export settings->Reset all settings.
C. Go back and reload your original settings again! Intellisense works and you have your original settings back!
Comment: Worked for me on VS 2012 (though I also had to completely exit VS and start it up again for the changes to take effect). Thanks!
Answer: I use this to solve it, go to cmd line
devenv.exe /setup /resetuserdata /resetsettings

Comment: this one is worked for VS 2013. There is no problem for now :)
Comment: Alas, this didn't help for me. Now at startup I get a lot of error messages (compatibilitychecker not found, something with PHP, etc). Messages I didn't get before. Besides it didn't help: intellisense still works, but after event += I still don't get the tab character for autocomplete that ought to fill in the code for the event handler
Comment: This is not safe. My VS now has error and would not run anymore, needs repair/reinstallation. Use the Reset All Settings instead from Tools
Answer: The basic idea here is to force a resync of the database Intellisense is using.
If the reference is to a project within your solution. Remove the project. Then add the reference using browse option from the exact path of the project you just removed. Do a quick build and check to ensure reference is picked up correctly. Now add the old project back to the solution and remove the old reference and add it as part of the solution.
This idea of forcing the resync of the database could also be done in other ways too. For example by using an absolute folder path.
Comment: Thanks! Was jumping around header files all day because intellisense wasn't working in a single file which had no errors!
Answer:

Go to tools->options.
Make sure the above check boxes are checked.
Answer: Resharper->Options->IntelliSense->General
Set to 'Visual Studio native IntelliSense...'
Answer: It got frustrating for me as well but I figured out my own answer.  Restarting did help but I found why I ran into trouble: I'd copied and pasted an ASP Panel with controls I'd need to re-use.  I only had those in the first Div tag working.  All others needed to be set up, so I said "Aha ... let me comment out the remaining Div Tags that aren't set up ..." and sure enough, intellisense came right back on.
So not only will it fail to work if the cursor is below a code error but it can fail to work if you're a copy / paste type like me.
Answer: My solution (VS 2013) was to run as an administrator
Answer: Its very Simple,

Close visual studio (Having Solution)(Remember Configuration and Solution type and start up project)
Go to solution path
Delete SolutionName.suo
Open Solution again
set Configuration and Solution type and start up project (if it is changed)
Build and check

Reason why it happend
In my case i have changed the references of some project
Answer: My quick solution was to close all opened files in text editor area and then reopen them again from Solution Explorer.
Answer: None of the solutions worked for me. I noticed that the problem was only occuring in one xaml file, and not in other xaml or c# files.
I had an extension called QuickConverter that allows to create custom bindings with in-line converters. This was messing up with Intellisense and this was not detected as an error while building or running the app.
My advice is:

Check if Intellisense stops working in all files or just a particular one
If it's just one file, look for red or blue squiggly lines and you will find the culprit
Answer: I occasionally encountered the same problem as the OP.
Unfortunately, none of the above solutions works for me. -- I also searched from internet for other possible solutions, including Microsoft's VS/windows forum, and did not find an answer.
But when I closed the VS solution, there was a message asking me to download and install "Microsoft SQL Server Compact 4.0"; per this hint I finally fixed the problem.
I hope this finding is of any help to others who may get the same issue.
Answer: One solution is to disable the resharper, or spell checker extension and restart.
Granted this is not ideal.
Answer: In my case .csproj file got corrupted and Visual Studio excluded some class files from the solution (But they were still visible in Visual Studio so the issue wasn't obvious at first sight). In these files intellisense was not available. So the fix was to add the files back to the solution.
Answer: I had been facing this problems since 2 weeks, finally figured it out using a Sysinternal tool called Process monitor (ProcMon.exe). The problem has to do with the automatic updates settings. I applied the below solution and got it working
Solution: Tools -> Options -> Environment -> Extensions and Updates -> (uncheck) Automatically check for updates->OK
Answer: Sometime your code syntax has error, like you use " in ", it must be " ...'...."
For help you quickly detect problems, you click Design button, vs try to render, and it will show the line of error
Answer: I've just had this happen to me - and (while it was not instantly obvious) it was due to Resharper (R#) being disabled during a licensing issue.
Enabling Resharper fixed this for me!
Answer: Generally I face the same problem when I copy some snippets from internet with some special chars that breaks the Intellisense.
It happened a few times with me, I discovered the problem after deleting the file and creating a new one, now when I face the same problem, fist I restart the Visual Studio, if this doesn't resolve the problem, I remove the last snippet I copied from internet and do it by hand, them the problem is gone.


How are PQL, REML, ML, Laplace, Gauss-Hermite related to each other?

Question: While learning about the Generalized Linear Mixed Models, I often see the above terms. Sometimes it seems to me these are separate methods of estimation of (fixed? random? both?) effects, but when I read the literature, I see the terms mixed. For example PQL under REML. Some write, that the Penalized Qusi Likelihood works well for non-normal conditional response, like log-normal, but is biased in classic binomial or Poisson case, so I should use REML or ML for that. In other articles I can see that REML or ML is used only in linear models, while another articles say that REML is now available also for GLMM (glmmTMB in R, for example). So I understand the PQL is a separate method from REML. But then I see a book, where they compare various estimation methods, including PQL via REML. So, is REML a special case of the PQL? And then, where the Laplace or Gauss-Hermitte comes into play? I am totally lost.
Let's consider it using the examples from R: glmmPQL, nlme, lme4, glmmTMB. I know, that glmmPQL uses PQL, nlme uses Laplace, lme4 uses LMER or ML, glmmTMB uses LMER for GLM. I also saw both Laplace and Gauss-Hermitte Quadrature term related to all of them except PQL.
Is there a way to organize these methods?
Answer: Generalized Linear Mixed Models (GLMMs) have the following general representation:
$$\left\{
\begin{array}{l}
Y_i \mid b_i \sim \mathcal F_\psi,\\\\
b_i \sim \mathcal N(0, D),
\end{array}
\right.$$
where $Y_i$ is the response for the $i$-th sample unit and $b_i$ is the vector of random effects for this unit. The response $Y_i$ conditional on the random effects has a distribution $\mathcal F$ parameterized by the vector $\psi$, and the random effects are typically assumed to follow a multivariate normal distribution with mean 0 and variance-covariance matrix $D$. Some standard GLMMs assume that the distribution $\mathcal F_\psi$ is the binomial, Poisson, negative binomial, Beta or Gamma distribution.
The likelihood function of theses models has the following general form $$L(\theta) = \prod_{i = 1}^n \int p(y_i \mid b_i; \psi) \, p(b_i; D) \, db_i,$$
in which the first term is the probability mass or probability density function of $\mathcal F_\psi$, and the second term is the probability density function of the multivariate normal distribution for the random effects. Also, $\theta = (\psi, \mbox{vech}(D))$.
The problem is that the integral in the definition of this likelihood function does not have a closed-form solution. Hence, to estimate the parameters in these models under maximum likelihood, you need to somehow approximate this integral. In the literature, two main types of approximation have been proposed.

Approximation of the integrand: These methods entail approximating the product of the two terms $p(y_i \mid b_i; \psi) \times p(b_i; D)$ by a multivariate normal distribution because for this distribution we can solve the integral. The PQL and Laplace approximation methods fall into this category.
Approximation of the integral: These methods entail approximation of the whole integral by a (weighted) sum, i.e.,
$$\int p(y_i \mid b_i; \psi) \, p(b_i; D) \, db_i \approx \sum_k \varpi_k \, p(y_i \mid b_k; \psi) \, p(b_k; D).$$
Some methods that fall into this category are the Monte Carlo and adaptive Gaussian quarature approximations.

Merits & Flaws

The Approximation of the integrand methods are in general faster than then Approximation of the integral ones. However, they do not provide any control of the approximation error. For this reason, these methods work better when the product of the two terms can be well approximated by a multivariate normal distribution. This is when the data are more continuous. That is, in Binomial data with large number of trials and Poisson data with large expected counts.
The Approximation of the integral methods are slower, but they do provide control of the approximation error by using more terms in the summation. That is, by considering a larger Monte Carlo sample or more quadrature points. Hence, these methods will work better in binary data or Poisson data with low expected counts.
Just to mention that there are some links between the two classes of methods. For example, the Laplace approximation is equivalent to the adaptive Gaussian quadrature rule with one quadrature point.
Finally, the REML method is more relevant in the estimation of linear mixed models for which the integral does have a closed-form solution, but the point is how to estimate the variance components, i.e., the unique elements in the specification of the $D$ covariance matrix. The classic maximum likelihood procedure is known to produce biased results for estimating these parameters, especially in small samples, because it does not account for the fact that to estimate the variance parameters, you first need to estimate the mean parameters. The REML approach does account for that and is a generalization of the idea why in the sample variance we need to divide by $n - 1$ to get an unbiased estimate of the population variance instead of $n$, which is the maximum likelihood estimator, with $n$ being the sample size.

EDIT: PQL in Combination with REML
The approximation performed by the PQL method results in a new response vector $Y_i^*$, which is a transformation of the original data $Y_i$ that attempts to make $Y_i^*$ normally distributed. Hence, fitting a GLMM is equivalent to fitting a linear mixed model for $Y_i^*$, and as mentioned above, in the linear mixed model you may select to estimate the variance components either with maximum likelihood (ML) or restricted maximum likelihood (REML).
Comment: +1 great answer @DimitrisRizopoulos
Comment: Thank you very much, Sir. This is beautifully organized answer. Please, tell me, is PQL related to REML? I sometimes see "REML under PQL" in publications. I thought these two are separate methods. Yet I also saw, that PQL calls ML in the algorithm. Now I'm lost in this chain: REML "under PQL", PQL "uses" ML, so REML -> PQL -> ML. How to distinct the REML from PQL and ML (which of course differs from REML). I'm sorry for a probably naive or stupid question, but as a beginner, I'm totally lost.
Comment: Ah! I got it! So, the glmmPQL routine in R uses PQL to approximate of the integrands and then uses ML to estimate the variance components. lme4, which uses the Gauss-Hermite quadrature (as far as I recall), uses then REML (or ML, depending on switch) to calculate the variance components. I have to check, if lmer set to Laplace and REML=FALSE will give the same results as PQL. Thank you a lot! So much reading of complicated articles, to complex to me, explained by you so simply. I'm sorry, I cannot upvote your beautiful answer yet, having only 12 points.
Comment: @humbleasker Now you have more points and should be able to upvote :) (+1 from me too)
Comment: I made an edit above.


How to create certain number of turtles on the road shapefile and specific area?

Question: I have imported the road shapefile and polygon shapefile and already intersected with patches. I want to create a certain number of turtles in a specific polygon and turtles allow moving only on the road shapefile.
For example, In polygon A have turtles 20, polygon B have turtles 30 and I want to let the number of these to show up on its own polygon.
What I have done is I have intersected the road and the polygon by using (I mean 2 foreach for road and polygon)
foreach gis:feature-list-of x
  [ vector-feature ->
    ask patches gis:intersecting vector-feature
      [blah blah blah...]
  ]

Then, I created turtles using this code
to setup
  create-walkers Population
  ask walkers
  [
    set wlocation one-of patches with [pcolor = red]
    ;I have assigned the road shapefile to red color.
    move-to wlocation
end

With only patches is RED, it's work,
BUT when I tried to set wlocation one-of patches with [pcolor = red and pcolor = ;another color which is the color of polygon]
Netlogo got an error that

move-to expected input to be an agent but got nobody instead

How could I solve this problem?
Thank you in advance.
Answer: You appear to have a basic misunderstanding about patches. In NetLogo, a patch is an area of the world and is a single unit. What that means is that the patch can ONLY have one colour. Try running this code (as a new model)
to testme
  ask patches
  [ set pcolor random 256
  ]
end

You can see the patches, each with a randomly allocated colour. Now type inspect one-of patches in the command centre and an inspect window will open for a randomly selected patch. You will see that one of the listed variables is pcolor.
Short answer - a patch can only have one colour, so your request for patches with colour A and colour B is meaningless.


How to show that the bipolar co-ordinates are othogonal

Question:
How to show that the bipolar co-ordinates are othogonal
where $x=\dfrac{\sin hv}{\cos hv-\cos u},y=\dfrac{\sin u}{\cos hv-\cos u},z=z$
where $u\in [0,2\pi]$ and $y,z\in (-\infty,\infty)$.

How to show a system is orthogonal?
Do I need to compute the angle between them?If yes how to do it?
Answer: Hint.
Given $x(u,v), y(u,v)$ find
$t_x = (x_u,x_v), \, t_y = (y_u, y_v)$
and then verify that
$t_x\cdot t_y = 0$
Comment: what is $t_x,t_y$,i dont get that
Comment: $t_x =\left( \frac{\partial x}{\partial u},\frac{\partial x}{\partial v}\right)$ etc.


If $G_X$ is a Probability Generating Function of $X$, what does it mean by $G_X(0)=\mathbb P(X=0)$ and $G_X(1)=1$?

Question: Let $G_X$ is a Probability Generating Function of $X$.
What does it mean by

$G_X(0)=\mathbb P(X=0)$ ?
$G_X(1)=1$ ?

Why are these identities important?
Answer: The probability generating function (PGF) of a discrete non-negative random variable $X$ is defined to be $G_X(t) = E(t^X)$.
For your first question, suppose $G_X(0) = E(0^X)$. If we take $0^0=1$ then $$E(0^x) = \sum \limits_{x=0}^\infty 0^x f(x) = f(0) = P(X=0)$$ where $f$ is the pmf of $X$.
The second one is easier: $G_X(1) = E(1^X) = E(1) = 1$
As for why these are important, we can recover the pmf of $X$ via derivatives of $G_X$. In the wikipedia article that I linked to they state that
$$
P(X = k) = \frac{G_X^{(k)}(0)}{k!}
$$
so if we want to know $P(X=k)$ for all $k$ then we need to know $G_X^{(k)}(0)$ for each $k \in \mathbb N$, and so $G_X(0) = G_X^{(0)}(0) / 0!$ gets that started. Thus the fact that $P(X=0) = G_X(0)$ is the first step in how we can get the pmf $f$ out of $G_X$.
The result that $E(1^X) = 1$ means that $\sum_x 1^x f(x) = \sum_x f(x) = 1$ so this is equivalent to $f$ being normalized to sum to 1 which is a necessary property for any pmf.


changing the color of scroll bar?

Question: In a div I gave overflow auto to have a scroll bar to display the content that exceeds the limit
My scroll bar appears in blue color that doesn't suit my layout how can i change the color
<code>div#navigation{background:#efe9b9; overflow:auto}
</code>
This is the css i am using ... I want brown colored scrll bar
How to get it
Answer: (except in IE)You can't change Scrollbars with CSS only, check out the JScrollPane for a Cross browser compatible scrollbar changer.
Comment: @Andy's Oh, cute. Now I can detest two browsers for messing with standard UI elements. ;)
Comment: @udaya: Did you look at the link I gave you? That's a jQuery plugin to enable you to change the appearance of scrollbars in a cross brwoser compatible way..
Comment: Actually, you can, but only in IE.
Comment: Oh yes. I forgot about IE, conveniently.
Comment: @deceze: [webkit supports scrollbar styling](http://trac.webkit.org/export/41842/trunk/LayoutTests/scrollbars/overflow-scrollbar-combinations.html) (view in Chrome/Safari), too, although in a much better manner than IE.
Comment: It is cross browser compatible, so yes, it will work.

@Andy E's Head: I didn't know that.
Comment: @Kyle whats the solution
Answer: You can in IE, but I think it's been deprecated (or removed in IE8).
You can also do it in Safari.
Be warned that it will affect usability negatively.
Comment: @udaya I am saying that a typical user may be confused by the scrollbar if it is a different colour than standard.
Comment: are you  saying  that some time it work wrong

changing the color of scroll bar?


Há como especificar uma hash, versão ou assinatura ao executar o `npx` (do npm)?

Question: Estou criando um gerador para gerar algumas páginas estáticas em HTML. Porém, me deparei com a situação de ter que utilizar o NPX para utilizar o AMP Optimizer.
Eu posso executar o comando da seguinte forma:
exec.Command("npx", "@ampproject/toolbox-cli", "optimize", "nome_do_arquivo.html")

Existem outras formas que posso fazer isso, mas de qualquer maneira o problema parece persistir em todos os casos.

O problema é que isso obtem o @ampproject/toolbox-cli que pode ser qualquer arquivo. Não há qualquer tipo de assinatura, hash ou versão especifica. O Golang, por exemplo, inclui um go.sum que permite verificar as hashes, dessa forma se o conteúdo baixado for diferente ele irá falhar. Isso é, ao executar o go run cmd/generate.go ele baixará exatamente aquilo que quero, ou falhará se a hash/timestamp for distinto.

Existe alguma forma de verificar a integridade do @ampproject/toolbox-cli e só executar se a hash for igual à uma especifica, por exemplo?!
Answer: Existe a possibilidade de se fornecer uma versão específica do pacote a ser instalado pelo npx.
Da documentação, você pode utilizar assim:
npx [options] <command>[@version] [command-arg]...

Quanto ao hash de integridade ou algum tipo de assinatura, não achei nenhum tipo de referência que indicasse suporte pelo npx.

Por exemplo:
$ npx firstname.lastname@example.com --version
4.0.3

Mas se eu especificar uma versão diferente:
$ npx firstname.lastname@example.com --version
2.1.8

Como, uma vez que publicados ao npm, pacotes podem somente ser apagados (e não modificados), penso que especificar a versão, de modo hard-coded, já sirva como uma barreira de segurança adicional. Decerto o tipo de preocupação demonstrado na pergunta é importante.
Claro, ainda há a possibilidade de invasão aos servidores do npm, mas ignoremos isso pelo nosso próprio bem. ;)
Comment: Continuo achando estranho não haver como especificar a hash do arquivo, acho que é confiar demais no NPM. :|


How do I store the results of my select statement in a variable?

Question: My code so far is this. The last line gives me a compile error: "expected end of statement".
Dim strSql As String
Dim groupId As String

strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
groupId = CurrentProject.Connection.Execute strSql

Comment: make sure your ListO.Value returns a correct value.
Answer: You are looking at something kinda like this
Dim strSql As String
Dim groupId As String

strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"

Dim rec As Recordset
set rec= CurrentProject.Connection.Execute strSql

groupId = rec(0)

You need to set the results of the query to a recordset and then pull the first value from its results.  Without all the defined variable, I cannot get this to fully compile but this should be a good template to start from.
Comment: It is generally better to use DAO with Accesss, so:  Set rec=CurrentDB.OpenRecordset(strSQL). You may need to Dim rec As DAO.Recordset


Erro ao usar o método sendMessage() da classe Handler. "A mensagem não foi postada ou já foi removida"

Question: Estou estudando sobre Threads e Services e sei que para rodar um processo mais longo, como procurar sinal de internet ou fazer download, devo colocá-lo para ser executado em um Background Thread e não no UI (User Interface) Thread. No app abaixo fiz um exemplo de código sendo executado no background e, conforme esse processo progride, há atualizações na barra de progresso, porém quando executo o aplicativo, levo um erro dizendo o seguinte:

java.lang.IllegalStateException: The specified message queue synchronization  barrier token has not been posted or has already been removed.

Abaixo está o código:
package com.gabrielm.myapplication;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    Handler mHandler;
    Button mButton;
    ProgressBar mProgressBar;

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

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mButton = (Button) findViewById(R.id.button);

        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                mProgressBar.setProgress(msg.arg1);
            }
        };

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        Message msg = Message.obtain();
                        for (int i = 0; i < 100; i++) {

                            msg.arg1 = i;
                            mHandler.sendMessage(msg);

                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });
    }
}

Procurando na internet por uma possível solução para o problema, descobri que o método sendMessage(msg) tem que enviar sempre um novo objeto do tipo Message para a fila de mensagens cada vez que eu quero enviar uma nova mensagem. Ou seja, não posso reutilizar o mesmo objeto, tenho que sempre criar um novo cada vez que quero enviar um dado para o handleMessage(Message msg);. Então o que eu fiz foi retirar a linha de código Message msg = Message.obtains(); do lugar onde estava e colocar dentro do bloco for, porque assim cada vez que o for executa, ele cria um novo objeto do tipo Message.
Essa pequena mudança no código fez com o programa funcionasse, porém não tenho certeza se o que eu fiz foi a forma mais correta de realizar o processo. Assim, gostaria de saber se a lógica que desenvolvi aqui está certa.
Answer: Gabriel, sua pesquisa lhe trouxe informações corretas. Não é possível enviar o mesmo objeto Message várias vezes, então, temos sempre que criar uma nova instância. Ou melhor, ao invés de criarmos uma instância usando new Message(), podemos usar Message.obtain() que retornará uma instância de Message vinda de um pool de objetos reciclados, o que é menos custoso que a primeira opção.

While the constructor of Message is public, the best way to get one of
  these is to call Message.obtain() or one of the
  Handler.obtainMessage() methods, which will pull them from a pool of
  recycled objects.
Comment: Obrigado pelo feedback, é bom saber que estou no caminho certo. Demorei algumas horas para entender bem isso, mas acho que agora finalmente consegui diluir esse conteúdo. A propósito, eu estava com dúvida se deveria usar Message msg = Message.obtains() ou Message msg = new Message(), mas agora entedi que o melhor é o Message.obtains(), já que ele está reutilizando um objeto reciclado e não criando um novo. Enfim, obrigado por sua resposta, foi de grande ajuda.
Answer: Executar códigos em background no Android utilizando Handlers e Threads é uma tarefa muitas vezes complicada e suscetível a erros, por conta disso, foi criada uma classe especial para facilitar a execução de tarefas assíncronas: a Async Task.
A AsynTask fornece os seguintes métodos:

onPreExecute : Método chamado antes que a tarefa de longa duração seja executada. Geralmente é utilizada para preparar e começar a mostrar um progress bar ( ainda vazio ).
doInBackground : Realiza uma tarefa de longa duração ( acesso ao BD, download de um documento, etc. ).
Atenção: Dentro deste método não devem ser feitos acessos a elementos da view, caso isso seja feito, você receberá um erro do tipo java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()"
Se você quiser manipular a view, você deve usar os métodos  onPreExecute() e onPostExecute()
Porém, se realmente for necessário acessar a view dentro do método doInBackground() coloque o método de acesso a view dentro do método runOnUiThread() e coloque-o dentro do doInBackground():
@Override
protected String doInBackground(String... parametros) {

    // Realiza tarefa de longa duração ...

    // Acessa a view
    runOnUiThread(new Runnable() {

        public void run() {

            // faça o acesso a view aqui
        }
    });
}

onProgressUpdate : Utilizada para atualizar o status da tarefa de longa duração ( e.g. incrementar um progress bar). Esse método é chamado toda vez que for feita uma chamada ao método publishProgress()
onPostExecute : Chamado assim que a tarefa de longa duração é concluída. É utilizada para acessar e tratar a variável de retorno da tarefa de longa duração

É importante saber que, como a AsyncTask é uma classe abstrata, ela só pode ser estendida, e não instanciada, além disso, por possuir parâmetros genéricos no seu construtor ( AsyncTask <Params, Progress, Result> ), ao estender a classe AsyncTask você deve fornecer o tipo destes parâmetros genéricos, onde:

Params: É o tipo do parâmetro de entrada do método doInBackground()
Progress: É o tipo do parâmetro de entrada do método onProgressUpdate()
Result: É o tipo do parâmetro de entrada do método onPostExecute()

Assim, para criar uma AsyncTask que faça downloads de um arquivo, por exemplo, você poderia fazer:
// A classe vai receber um conjuntos de URLs como entrada,
// vai enviar um Integer a cada chamada ao método publishProgress()
// e vai enviar um Integer quando a tarefa for finalizada
private class DownloadArquivos extends AsyncTask<URL, Integer, Integer> {

    protected Long doInBackground(URL... urls) {

     // numero de downloads executados
     int downloads = 0;

     for (int i = 0; i < urls.lenght ; i++) {

         downloads += downloadFile(urls[i]);
         // downloadFile() é o seu método de longa duração

         // Atualiza o progresso enviando a porcentagem de arquivos
         // baixados até o momento
         publishProgress( (int) ((i / (float) urls.lenght) * 100) );
     }

     return downloads;
 }

 protected void onProgressUpdate(Integer... progress) {

      // método da sua view que atualiza o progress bar
      setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Int result) {

     // método da sua view que mostra uma mensagem
    // após todos os downloads serem efetuados
     showDialog( result + " arquivos baixados com sucesso!" );
 }
 }

Obs.: Código retirado e adaptado de: http://developer.android.com/intl/pt-br/reference/android/os/AsyncTask.html
Comment: Sim, concordo. A classe abstrata AsyncTask é a mais recomendada para esse tipo de processo que utiliza UI Thread e Background Thread, porém o que estava com dúvida era sobre a classe Handler. Uma dúvida que me surgiu é que com o Handler eu posso manusear um processo que usa dois Threads quaisquer, seja UI Thread e um Background Thread ou dois em Background. Já o AsyncTask é só para um Background Thread e UI Thread. Isso está correto ou tem como trabalhar com dois Threads quaisquer  usando o AsyncTask?
Comment: Outra coisa, pesquisando mais sobre o assunto, percebi que no método doInBackground() eu não preciso criar um Thread, por que o código dentro desse método já está sendo executado no segundo plano. Isso era algo que estava fazendo errado, porém estava funcionando. Oque eu estava fazendo era criar um Thread dentro do doInBackground(), o que é desnecessário.
Comment: @GabrielM.Linassi é possível sim executar duas threads em paralelo e na background task, mas para isso vc vai precisar utilizar o método `executeOnExecutor()` ( dê uma olhada na [documentação oficial](http://developer.android.com/intl/pt-br/reference/android/os/AsyncTask.html#executeOnExecutor) ). Quanto a segunda pergunta: Sim, o doInBackground já é executado em background ( como diz o nome :D ) , portanto você pode executar diretamente seu método dentro dele sem criar uma thread nova


ng-repeat get length of array and bind last value of array

Question: $scope.GetDetails={
  Student:[
      {"id":1,"Name":"Apple","Price":3500}
    ],
  Student:[
      {"id":2,"Name":"Samsung","Price":4000}
     ],
  Student:[
    {"id":3,"Name":"Nokia","Price":1500},
    {"id":3,"Name":"Nokia","Price";7000}
   ]
 }

Am binding data using ng-repeat

        {{A.Name}} - {{A.Price}}

Result is
    Apple - 3500
Samsung - 4000
Nokia - 1500
Nokia - 7000
Here every thing Ok.But what i want mean , Nokia have two array ,so i have to get name from first array and price from 2nd array Like,
Nokia - 7000,
And Also i need the length of student array.
Comment: you have to change the json format, the code you have given will not work with your HTML
Answer: First, You should change your JSON to achieve your result.
Change JSON to below:
$scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]

Please run below code

<!DOCTYPE html>

        {{A.Name}} - {{A.Price}}

I used ng-if="$last" to take the last value from array
Here is a working DEMO
Comment: @Vediyappan.V, checked it?
Comment: Thanks for  Reply its working well..I have one more doubt , How can find length of array. Ex student - Apple - Length 1,student - Samsung- Length 1,student - Nokia- Length 2. Just i need t bind length on ng-repeat.
Comment: @Vediyappan.V, you can use `{{GetDetails.length}}`, check the https://plnkr.co/edit/LSg6fkOK4exuoT2FDdQq?p=preview
Comment: @Vediyappan.V, anything else needed in this answer?
Comment: Thanks agian.J have one more doubt . While using JQuery library it cannot support all the function. EX.     Its for calender control and  this other .I Want use both . Have any solution for this.
Comment: did not get you. could you elaborate?
Comment: you want to use two jquery versions?
Comment: Yes i want use two jQuery verision
Comment: [check this link, this might be useful](http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/). But I dont prefer using both the versions. Use the latest one.
Answer: If you want this only for Name: Nokia, then do it like;

 {{A.Name}}-{{A.Price}}
 {{A.Name}}-{{A.Price}}

and it you want  only last element from every array :
then:

        {{A.Name}} - {{A.Price}}


What's wrong with my taxonomy links or my taxonomy view and contextual filter?

Question: I have a D7 view displaying all items tagged "food" at
mysite.com/industry/term/food

But my taxonomy terms for "industries" link to e.g. mysite.com/industry/food
(i.e. without /term/)
I thought I could update the view to make the page path: /industry/%
instead of: industry/term/%
but that breaks the view
so I thought I might be able to update my Taxonomy url aliasing pattern to be:
[term:vocabulary]/term/[term:name]

instead of [term:vocabulary]/[term:name]
but that doesn't work either :( or at least, it doesn't update all pre-written aliases...
I read this:
http://www.webbykat.com/2012/04/overriding-default-taxonomy-page-view-drupal-7
which pointed to a solution from 2009 here
https://www.drupal.org/node/394062#comment-1953504
but if I use Name or ID (rather than "name converted to ID") in my contextual filter it breaks the view
What am i doing wrong - I'm sure it's something simple and I'm just being blind!?
Answer: You mentioned that changing the alias doesn't update all pre-written aliases. Could you pick one term, edit it, and hit "Automatic alias" under URL aliases so that it updates, then post whether that resolved the issue for that individual term?
If so, all you need is to bulk update aliases for that vocabulary, which can be done with a VBO - I'll detail how if that's the issue.
Comment: thanks @webbykat - I tried what you suggested and edited the taxonomy term "food" in the "industry" taxonomy to make its url alias industry/term/food rather than just industry/food but strangely that didn't work either. I now don't get the view at mysite.com/industry/term/food or mysite.com/industry/food :(
Answer: This method of overriding the taxonomy listing page with a view allows you to design a view which replaces the taxonomy listing page for all taxonomies.
It is important to note that this method only allows you to design one view which overrides all of the taxonomy term listings pages for items in any taxonomy.
As you have discovered, you can do this by creating or enabling a view which uses the special system path with exactly this text: 'taxonomy/term/%'.  The views module provides an example, which by default which is disabled.
To understand what is happening, look at the addresses for each  item when you edit the term.  You will see these when you click 'edit' on any taxonomy term.  eg. 'industry/food' the system edits this as 'taxonomy/term/15'.
You can edit the path settings for each term item individually,  but it is useful to assign the pattern using  Path auto from 'Configuration' -> 'URL aliases' under the Patterns' tab.   You mention trying '[term:vocabulary]/[term:name]', but that this didn't change the path for existing items.
Then next step would be to either edit each old term item separately to assign a path for each one.  Or you could use the 'delete aliases' tab in URL aliases admin to delete all existing aliases for taxonomy terms, and then 'bulk update' for taxonomy terms to apply the new pattern.
Comment: Thanks @digitalsean. As mentioned in the comment above in reply to webbykat I tried what you suggested, by adding 'term' in-between [term:vocabulary]/[term:name] for the "food" tag but it didn't help. Not really sure why as your logic makes sense to me. Any other ideas?


JQuery AJAX synchronous request behavior

Question: I have an ajax address validation function that I am trying to call synchronously, like this:
function validate_address(address, city, state, zip) {
    return $.ajax({
        type: 'POST',
        url: '/ajax/address',
        data: {
            address: address,
            city: city,
            state: state,
            zip: zip
        },
        dataType: "json",
        cache: false,
        async: false
    }).responseText;
}

Before I call the function, I display a spinning gif and hide it after the function:
$('#spinner').show();
var res = validate_address(address, city, state, zip);
$('#spinner').hide();

The issue is that the show() and hide() functions both get called AFTER the ajax call is completed.
I verified this by adding a 5 second delay to the ajax call, server-side. show() and hide() were both called immediately after each other 5 seconds after I triggered this sequence.
Before you call me out, I know that synchronous requests are not encouraged. In this case, I do have to use a synchronous call. I'm just trying what's going on here and how to fix it.
Comment: "This is not the Ajax you are looking for", you should be using asynchronous requests, no matter what excuse you may have for locking the browser?
Comment: Why do you think you had to do a synchronous call? Imo this is the reason for the DOM not getting rendered between the show and hide calls (and yes, it *is executed before* the ajax call)
Comment: @nathancahill: Yes, it seems you will need to make the call asynchronous. What prevents you from doing that?
Comment: ^ Now that I read that, it sounds stupid. Just refactored all of my code around callbacks and everything works. Thanks for the help @Bergi and adeneo, much appreciated.
Comment: jQuery animation's does not wait for other functions. Take a look at this: http://api.jquery.com/ajaxComplete/
Comment: @Bergi That's kind of what I'm thinking. Executed but not rendered until the call is done, at that point they get rendered right after each other
Comment: should also note in docs that `async: false` is deprecated.
Comment: I have a series of views with forms that I'm stepping through. If the view doesn't validate, it shouldn't show the next view.
Answer: You're already returning the deferred from the ajax function, so just use done() :
$('#spinner').show();
validate_address(address, city, state, zip).done(function(data) {
    res = data;
    $('#spinner').hide();
});

This would even work with an asynchronous request ?
If the showing of the spinner is still to slow, and you'd like to degrade user experience even more, you can always use a callback:
$('#spinner').show(1000, function() {
    validate_address(address, city, state, zip).done(function(data) {
        res = data;
        $('#spinner').hide();
    });
});

Comment: No, he does return the `responseText`
Comment: I added a number of console.log calls. The code above works fine in Firefox. Safari doesn't animate or log anything until the ajax call is finished. Chrome logs before and after the request, but doesn't animate anything.
Comment: @nathancahill - what Bergi said above. Remove the responseText line!
Answer: what about ajaxStart and ajaxEnd
Take a look at this post : How can I create a "Please Wait, Loading..." animation using jQuery?
$("body").on({
    // When ajaxStart is fired, add 'loading' to body class
    ajaxStart: function() {
        $(this).addClass("loading");  // or do what you need here
    },
    // When ajaxStop is fired, rmeove 'loading' from body class
    ajaxStop: function() {
        $(this).removeClass("loading"); // or do what you need here
    }
});


Drupal function to convert node into Json object

Question: I would like to know if any drupal function is readily available which converts the node object into Json object so that i can return it in the menu callback function in Ajax call.
thanks,
Ahmad
Answer: To return on menu callback function in Ajax call you can use drupal_json_output(), you can use this function as an example.
On that exampe you can see that you only need to call drupal_json_output() function with the object as the parameter, there's no need to return anything from your callback function.
If you need to convert the Drupal node object into JSON object to be returned on a function, you could consider to use drupal_json_encode()
Answer: Try: drupal_json_output($var = NULL)
Comment: I tried but it only returns "False" as a return value
Comment: Because you'd need `drupal_json_output($node);` or other similar var to output.


Exercises or understanding to unlock my highest notes (I'm a man)

Question: I've been taking singing lessons for a few months now and one notable thing is gaining confidence with my head voice. Previously I probably never used it, now as well as my chest voice being able to go much higher (A2 - E4/F4) I can confidently sing some fairly powerful head voice notes in the range D4 - Bb4, and can reach B4, in a relaxed manner that doesn't strain my voice and feels quite natural.
However above B4 I notice I have to switch to a much more forced technique, and have far less control. I sort of have to "throw" my voice and hope it hits the right note. I've tested with a vocal app and I can reach C5-E5, sometimes as high as G5, and hold the notes in pitch, but it's really just a squeak not something useful. And it tires my throat out very quickly. And I feel stupid doing it which is a big factor for me personally.
I believe this is me switching from head voice to falsetto and wondered if there are specific techniques and exercises I can use to develop this part of my range... and if I should be using this technique or instead trying to expand my natural voice higher rather than trying to sing these very high notes at all in this style.
Answer: [Note; I'm an untrained rock/pop singer with 40+ years' experience, so my opinions on the subject are from my own experience rather than academia/classical training]
There are points at which your voice needs to 'swap modes'. As you rise towards to the swap point you need more control to hold the lower mode without having to switch to the higher. These points are unlikely to change much over time, except they will drop lower after many years.
In the meantime, all you can do is strengthen those 'weak points' by repetition - just below the switch point is always going to be the most tiring area. Working on songs that reach or even exceed it will help - but don't go all out & expect you will gain the strength in a week or two; you'll really tire that switch point very quickly to start with.
Think of it like doing 50 sit-ups after not having exercised for a year - you won't really find out how much it hurts until 2 days later, & then you'll have trouble getting out of a chair for a week... so take it steady & build up.
As a singer who has schedules with little or no work for months, then a month of sustained effort [I'm pretty much retired these days so I take a lot of time off in between] I find I need to work gradually up to it over 2 ~ 4 weeks, the more the better. Start slow, work up to it.
As far as I know, based on my own experience, you will never get rid of the 'switch points' but you will eventually learn to live with them & make the most of how they work for you.
Answer: I sing in the Grace Cathedral Choir and have learned a few things about strengthening my falsetto / switch into falsetto. I am a bass, so my falsetto was not very strong either. This is what I did:

Relax

First of all, to successfully sing in head voice, you need to relax. Your thinner, stretched-out vocal cords won't work if the body around them is tense. Find a mirror and look at yourself as you talk in your Mickey Mouse voice. The more relaxed your body is, the easier it will be for you to produce sound in head voice.
Here are some specific areas to check and relax as you make sound in your head voice range:

Tongue
Jaw
Neck
Shoulders

The Concert Woooo

Have you ever been to a concert and heard someone yelling "Wooooo!" in a really high voice? This exercise comes from that concept. Take in a good breath and do some of these "woo" noises while maintaining your relaxed body. Open your mouth as you go up in pitch. Make sure that you are not pushing; you should feel as though your voice is finding its way up rather than being forced.

Ghostly Singing

This last exercise borrows from that spooky "oOoOOOooOO" high voice that all of us are familiar with. Using your breath, practice doing this in your head voice. Remember to stay relaxed!


How to store a static DateFormatter in a struct?

Question: When using a DateFormatter in the initialization of a struct like below, what's the cleanest way of caching that formatter?
struct Entry {
    let date: Date
    // ...

    init?(string: String) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
        if let date = dateFormatter.date(from: string) {
            self.date = date
        } else {
            return nil
        }
        // ...
    }
}

Comment: Related:https://stackoverflow.com/questions/28504589/creating-an-nsdateformatter-in-swift.
Answer: Just assign it to a property:
struct Entry {
    let dateFormatter: DateFormatter
    // ...

    init?(string: String) {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd hh:mm:ss"
        dateFormatter = df
        // ...
    }
}

However, because date formatters are somewhat expensive to create, it is very common to make these a static property so there is only one for the type rather than one for each instance.
struct Entry {
    private static let dateFormatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd hh:mm:ss"
        return df
    }()
 }

Comment: Beware: prior to iOS 7 and macOS 10.9, `DateFormatter` is not threadsafe, so you can run into nasty bugs if you used a shared instance like this in a threaded context
Comment: Ah, perfect. This feature to initialize a static property with a closure is what I forgot about.
Comment: Another risk of this is race conditions.  Let's say you create two instances of Entry, the second one writes to the dateformatter, and then the first reads it but alas it is different from before...


Number of numbers need to check before finding a prime

Question: I am interested in (roughly estimating) how many random integers do I have to check before I find a prime of size say $100$ digits.
I was thinking like so:
Let the number of primes up to $X$ be denoted by $\pi(X)$. The famous Prime Number Theorem says that
$$
\lim_{X\to\infty}\frac{\pi(X)}{X/\ln(X)}=1
$$
so a randomly chosen number $N$ has probability
$$
P(N \ being \ prime)=\frac{1}{\ln(N)}
$$
of being prime.
Now I need numbers of size $10^{100}$ which means I have
$$
\frac{1}{\ln(10^{100})}=\frac{1}{100}\cdot \frac{1}{\ln(10)}\approx 0,02305
$$
so the chance of picking a prime is roughly $2,3\%$ therefore I need (in theory) to check at least $50$ numbers before I hit a prime.
Is my reasoning correct?
Thank you!
Edit:
I made a silly calculator mistake the correct value is:
$$
\frac{1}{230}\approx 0,00434
$$
so I need to check a  bit over $200$ numbers say $250$.
Comment: The numerical value is not correct. It is about $\frac{1}{230}$. Of course, with trial division (lets say upto $100$) , you can speed up the search and you increase the chance to find a prime by a factor of $8.3$ if you try large numbers.. Basically , your approach is correct however.
Comment: You are not going to bother checking even numbers, are you?
Comment: No definitely not, in a realistic case (further non ending with 5 etc) :)
But the question said "random integers" so I assume they mean actually a randomly picked integer
Comment: @Peter thank you. I corrected the question. I made a silly calculator mistake
Comment: I have recently read that this approach (probability $\frac{1}{\ln(N)}$) has been refuted, but this should not be critical. I do not think that the error is big.
Comment: Your calculation is correct. However, as is pointed out above, picking and testing random numbers is a very inefficient way of finding primes.
Answer: There was a Polymath Project (see link here) to come up with an efficient deterministic algorithm to find a prime larger than a given number $N$ (equivalent to a prime of size at least $\lceil \log_2 N \rceil$ bits in your notation). Terence Tao led this effort and a paper (see abstract here) was published at the end of the project.
See also Terence Tao's blog here for a discussion of the results of the project.
I quote from the introduction of the paper, which confirms your guess of the randomized complexity, as being essentially $O(\log^{O(1)}N)$:

Note that if one allows probabilistic algorithms [..] one can accomplish this in time
  polynomial in the length of $N$ (i.e. in time at most $\log^{O(1)} N$); indeed, one can select
  integers in [N, 2N] at random and test each one for primality. [..] Using algorithms such as the AKS algorithm,
  each such integer can be tested in time at most $\log^{O(1)} N$, and by the prime number
  theorem one has about a $1/ \log N$ chance of success with each attempt, so the algorithm
  will succeed with (say) 99% certainty after at most $\log^{O(1)} N$ units of time

Note: The notation $\log^c N$ is used for $(\log N)^c$ here. AKS (Agarwal-Kayal-Saxena) algorithm which is used in the paper is a deterministic primality test with original complexity $O(\log^6 N)$ for a number of bitsize $N$, and it's since been improved to $O(\log^3 N)$ later. If this algorithm states that a number is prime, the number is indeed a prime, not subject to errors.


Is it a good idea to use HTML5 now?

Question: I know it will be 'finalized/made official' in 2012 (and something to do with it being given 'Recommendation status' in 2022), but I'm wondering if it's a good idea to make a site using HTML5 now.
A simple portfolio sorta site? Given that most users (most people using IE) won't have support for it, although IE9 (shock) will be shipping with support.
Comment: @Crusader: HTML5 is fairly stable; what's left is basically minor issues. Most of the draft is unlikely to change, at least not significantly (which is why it is already being implemented by many vendors). The fact that W3C is an extremely slow beureaucratic organization has very little to do with anything — CSS2.1 wasn't made a recommendation until 2007, and by then it had been used and implemented for several years.
Comment: Silverlight and Flash/Flex don't run on the most interesting part of the market (that where people are spending lots of money): iPhone/iPad.
Comment: @Crusader: good for you, but I'd keep the trolling off SO. This is a Q&A site, not an imageboard. Regarding assumptions on future browsers; it's pretty much given that all major browsers will support large parts of HTML5 within a few years, since non-IE browsers are almost there already and Microsoft has promised support in IE9. And I'll bet it'll run more smoothly than Flash on Linux, too.
Comment: Ah, now you see, if I say a specific part, there's bound to be a browser out there that doesn't support that current feature.
Comment: Bottom line is, jumping into it now, you're an early adopter. Some may claim otherwise but the truth is that these committees work **very** slow and they need the backing of a large number of competitive browser vendors. Why take on the risk for a fraction of the features you want when you can use Silverlight or Flash/Flex and develop on a mature, backwards compatible platform now?
Comment: So, the vibe I'm basically getting is....no?
Comment: @You You're making broad assumptions regarding future browsers as well as a number of other shortcomings which it does nothing to address, some of which have been elaborated on down below, but okay. I love pissing off HTML5 evangelists. :) Sorry, but HTML5 is mostly hype right now. We'll see where it stands a few years from now.
Comment: It's not trolling, it's just stating opinions--some of which are the same as Gartner researchers--and I find it hiliarous when some people react so defensively. HTML5 is mostly hype now. How certain are you that "support" translates to a complete lack of differences? You can't be certain, so there's still a risk, it's that simple.
Comment: Of course "support" isn't *guaranteed* to mean complete lack of differences (case in point: IE), that's bound to happen when several different vendors implement a standard. But hey, at least I have choice. (And there's not a complete lack of differences in Flash either; the Linux port of Flash is horrible compared to the Windows version, for example.)
Comment: Flash doesn't solve the cross platform issue 100% (although I suspect part of that is lack of cooperation from those user communities), but my main point is that it DOES solve the issue of cross browser differences--a much more common and annoying issue.
Comment: True, Apple's closed/proprietary operating system is intentionally crippled in this way. But you really think that'll last long with an open OS alternative like ALL the various droid phones out there? Apple is one company with some good marketing--against the **entire** mobile market, the odds are against them over time.
Comment: Update - actually allegedly Android overtook iOS in market share, so I've heard. So intentionally crippled iJunk isn't so much the "most interesting" anymore, I guess. I don't know why HTML5ers always run to the mobile OS debate though. Desktop is still the primary market for making money, and it's most certainly the primary platform for business applications, which is where a VM-based Silverlight/Flex/JavaFX strategy really does great.
Comment: This is a really late comment, but I'd like to point out the fact that Silverlight is all but dead now, but sadly HTML5 still isn't fully ratified.
Answer: There is no one monolithic HTML5. HTML5 is being developed as a single large (oh so very large) document, yes, but that doesn't reflect reality(*).
That is to say, HTML5 is a collection of loosely related incremental improvements to HTML4. Some of those new features are widely implemented already. Some of them you can safely use knowing that they'll degrade usefully for old browsers. Some of them you can use as long as you add explicit fallback code. Some of them will be shutting out some browsers for the foreseeable future. Some of them will only ever have minority support. Some of them may never be implemented at all, or may yet be edited out of the standard. And many new features that are often regarded as being "HTML5" aren't in HTML5 at all, but other standards (CSS3, ECMA262-5, DOM extensions, WebSocket...).
You will have to pick and choose which the features of the New Web you want individually, judging by current and apparent future support. There's not a switch for 'using' vs 'not using' HTML5, other than merely the doctype itself (which doesn't get you any new behaviour).
*: This was a big mistake, in my opinion. It would have been better to quickly standardise the bits that were already supported by everyone—like HTML3.2 did after the HTML3.0 fiasco (XHTML2, anyone?)—and then add new features in a more modular fashion. But that's not what happened, and it's too late to do much about it now.
Comment: @Crusader: Silverlight and Flash is consistent? You must be in a dreamworld somewhere.
Comment: No disagreement here, but personally I can't see why you'd want to remain subjected to such a rapidly evolving, chaotic, and non-standard environment when we have **consistent** platforms like Silverlight and Flex/Flash with which to build once and not have to worry about future compatibility problems.  HTML5 needs to unify a historically competitive and non-cooperative group (browser vendors) when what we probably should be doing is using virtualization technologies to give developers standardized, stable development platforms to work within. Standardized plugin platforms fit the bill.
Comment: I just wish the OSS community could develop an "OSS Flash" (and have it not fragment into 10 different incompatible branches) so people stop complaining about proprietary control over platforms that are freely given away.
Comment: @Lie They're much, **much** more consistent than 5 different browsers running on 3 very different operating systems. They're the only consistent platforms available on the Internet (well, Java). Write an app to Flash and you'll never have to rewrite it again--THAT is the point.
Comment: @Crusader: really? I have only seen Flash/Java applets that run on Windows crashing the browser in Linux or vice versa, or taking gigantic amount of unwarranted memory. Faulty Javascript/HTML may cause the page to show incorrectly, but at least it doesn't crash the browser.
Comment: Yes, Java destroys my browser on Ubuntu.
Comment: One man's consistent is another man's stagnant, I suppose! ;-) And yeah, personally I'm not a fan of plugins. I'm glad applets and media-player embedding are dying, replaced by Flash, and I'm glad HTML5 `` is starting to muscle in on Flash video. The "OSS Flash" in terms of the vector animation Flash was originally designed for is arguably SVG plus scripting, but we've got a way to go yet on support and speed (IE9 is doing great work here) and authoring tools.
Comment: WOW now thats what I call an answer!
Comment: Why assume this is a Flash problem and not an issue with the browser/OS? It could be either. Most problems with Flash tend to be poor support from things wrapped around it or interacting with it. Now at least I see where you're coming from. Perhaps Adobe needs Linux people to actually report such issues (if they are indeed widespread) rather than simply complain about them not getting fixed? They can only do so much with in-house testing.
Comment: For what it's worth, the new Flash Player Square beta on Ubuntu has been by far the most stable Flash I've ever used on any platform. Which isn't saying a great deal, but still. Also Flash is often affected by, and receives the blame for, bugs in graphics card video acceleration drivers.
Comment: That's good to hear, and I expect that by 2022 (when HTML5 might be 'complete'), cross platform issues should be gone. If not, I'll be glad to dump any inferior platform for a stable, consistent one.
Answer: It is a good idea to prepare your website for HTML5, but please be backwards compatible to allow users with a browser that is not yet "ready" for HTML5 to be able to view your site, event if that means limited functionality. That way, users with the latest browsers will reap full benefits, but those of us who are not on the bleeding edge will still be able to view content. As you can see, I feel somewhat strongly about this topic, but hey, I'm a realist.
Also, keep in mind that there are technologies like Silverlight and Flash, today, that can support rich functionality, if you want to allows non-HTML5 compatible browsers to also view such content.
Comment: As I've said, **perfect** cross platform support is in the future on all fronts (RIA and HTML5), but on the Flex/Flash front you're at least partially incorrect: http://www.howtoforge.com/native_linux_flash_player9_in_ubuntu  I do understand that even a one-time-process like this is a pain to have to do at all, but I attribute this to the Linux ecosystem more than anything else. It's been awhile since I've used Linux but if installs are still a *fraction* of how painful they used to be, it's not yet worth the hassle when Winblows can install stuff like this with one click (or already has it).
Comment: +1, it will be a gradual shift so keep older browsers on hand for testing -- but you do indeed want to be ready
Comment: True say, I know there are workarounds for IE.. but I'm wondering is it worth the hassle just yet-- just more coding isn't it?
Comment: It's NOT worth the hassle yet. Trust me, you will not like having to fix bugs and issues that **will** arise eventually when some browser (or new version of a browser) breaks something. Browser vendors haven't been able to cooperate in the past, and that was only with two major competitors, so there's no reason to believe that even more competitors controlled by very different groups can cooperate in the future. HTML5 is a gamble.
Comment: http://www.modernizr.com/ << This is quite cool, found it just now. If anyone does decide to use HTML5 use this.. It does most of what you've said above ^^.
Comment: That brings up another of my complaints with the HTML5 deal - a very fragmented and rapidly changing set of dev libraries, tools, and so on. I do some amount of research on all these "JavaScript frameworks" (for lack of better terms) and I've yet to see that one. At least if you hire a Silverlight or a Flex developer, you *know* they've used the same exact APIs you're using.
Comment: I see your point, but neither Flex nor Silverlight provide native support for Linux... and I hate sites that tell me to download Silverlight to view.
Answer: Certain bits of HTML5, sure. Almost all new elements introduced in HTML5 can be used already, thanks to the html5shiv, and if you provide a suitable fallback you could be using <video> and <audio> as well. Those, along with the more advanced scripting features (local storage, etc.) are the features that will take time to implement.
Also, while Mark Pilgrim's Dive into HTML5 mostly discusses features that won't be available for some time (at least not in IE, i.e. the majority of web users), the chapter on semantics is both interesting and applicable.
Also keep in mind what your target audience is; if most of your visitors are from the designer community (or whatever), most of them probably have a browser with HTML5 capabilities. WebKit browsers already support much of the HTML5 draft.
Comment: Yeah, it's more sitepoint.com than 4chan.org (please dont hurt me)
Comment: Anyone care to elaborate on their downvote?
Answer: The thing you should understand is that html5 is not ONE big thing, it is a lot of bits and parts that you will start to use envtually here is a extract from Dive into HTML5

It's not one big thing

You may well ask: "How can I start
  using HTML5 if older browsers don't
  support it?" But the question itself
  is misleading. HTML5 is not one big
  thing; it is a collection of
  individual features. So you can't
  detect "HTML5 support," because that
  doesn't make any sense. But you can
  detect support for individual
  features, like canvas, video, or
  geolocation.
You may think of HTML as tags and
  angle brackets. That's an important
  part of it, but it's not the whole
  story. The HTML5 specification also
  defines how those angle brackets
  interact with JavaScript, through the
  Document Object Model (DOM). HTML5
  doesn't just define a  tag;
  there is also a corresponding DOM API
  for video objects in the DOM. You can
  use this API to detect support for
  different video formats, play a video,
  pause, mute audio, track how much of
  the video has been downloaded, and
  everything else you need to build a
  rich user experience around the
   tag itself.

If you are really interested you will find this very interesting!
Answer: There are people that wanna be progressive, those are the ones that bring the change, and I figure your one of them. So my advice would be, sure, cool, use it, just with care that users whose browsers don't support it also have decent experience.
Things that might help:
http://code.google.com/p/html5shiv/
("Public repo for the latest HTML5 JavaScript shiv for IE to recognise and style the HTML5 elements. ")
Also, as new user i can't post more than one link, but look for css3pie:
("PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.")
Answer: Once IE 9 is released, all major browsers vendors will support a large subset of HTML5. http://caniuse.com is a very useful site for answering the question "Which HTML5 related feature can I use now (or in the near future)?"
Updated (to address @Crusader's comment):
By some measures the market share of browsers without at least some HTML5 support (i.e. IE 6,7,8) is now lower than 50%. In other words, the era of HTML5 has already arrived.
With the arrival of IE 9 soon, I predict the share of browsers with no-HTML5 support will fall to less than 25% in the next 12 months. And for those who refuse to upgrade (or can't because of corporate policy), Chrome Frame allows easy use of HTML5 in IE 6,7, and 8 for sites that need to support those browsers.
Or consider: the only reason MS is implementing HTML5 features in IE 9 (instead of continuing to put all its eggs in the Silverlight basket) is because they know HTML5 has already arrived and they are late to the party.
Comment: But, meanwhile, look at how many people are still using less than IE 8. It'll still be awhile until decent support is common, even after IE 9--and it's yet to be seen how well 9 will perform. It could be "a Vista" or "an ME", for all we know.
Answer: Realize that html5 is a blanket term.  Using the doctype is just the start.  I wouldn't start including advanced webkit animations in all your sites, but using border-radius and box-shadow will work with most(minus ie) browsers and degrade gracefully.
Comment: You know what, I did slightly misread that initially - apologies.
Comment: But how can we say such features "work" if 50%+ of Internet users use IE where it doesn't exactly work?  Do you mean to say these "work" or "won't completely break the page"?
Comment: i mean work, and I excluded ie. please read before flaming
Comment: Wasn't a flame, just asking the question. :) It's just that to me for it to "work" IE has to support it, and it sounds like you excluded it because it lacks support, right?
Comment: @crusader "will work with most(minus ie) browsers"
Comment: border-radius and box-shadow have nothing whatsoever to do with HTML5. They're part of CSS3. People really need to stop lumping CSS3 in with HTML5, they're completely separate.
Comment: Thanks for that clarification, this was pointed out in another answer but we didn't connect that fact here.

Is it a good idea to use HTML5 now?


Adding a custom subject field to the Revision Information Drupal 7

Question: I would like to be able to add a subject field to the Revision Information along with the log message. Is there any way I could do that?
Answer: No - because revisions are not Drupal entities themselves but metadata associated with entities. You can expose an entity to the revisioning system but not the other way around, its a core part of Drupal.
Best way I could think of to come close to this functionality is to have a special fieldset / field collection of fields that allow for what you want (ex. log message, subject) and then use field permissions to hide that from the end user. You would then have your team use these fields for recording their updates rather than the log field.
Answer: I would suggest a different approach:
You could extend the node_revision table with a new column that holds the revision log's title and modify the node edit form to capture the value for this field. Below is a little module example that does the trick. If you need some more help, let me know, cheers!
<?php

/*
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function raks_form_node_form_alter(&$form, &$form_state, $form_id){
  if( isset($form['revision_information']) ){

    // Check the revision log checkbox when the log subject or textarea is filled in.
    // This must not happen if "Create new revision" is enabled by default, since
    // the state would auto-disable the checkbox otherwise.
    if (isset($form_state['node']) && !$form_state['node']->revision) {
      $form['revision_information']['revision']['#states'] = array(
        'checked' => array(
          array('input[name="log_subject"]' => array('empty' => FALSE)),
          array('textarea[name="log"]' => array('empty' => FALSE)),
        ),
      );
    }

    $form['revision_information']['log_subject'] = array(
      '#type' => 'textfield',
      '#title' => 'Revision log subject',
      '#weight' => -15,
      '#description' => t('Provide an subject for the changes you are making.'),
    );

    // Reorder / Move the checkbox above the new form field
    $form['revision_information']['revision']['#weight'] = $form['revision_information']['log_subject']['#weight'] - 1;
  }
}

/*
 * Implements hook_schema_alter().
 */
function raks_schema_alter(&$schema) {
  $schema['node_revision']['fields']['log_subject'] = array(
    'type' => 'varchar',
    'default' => null,
    'description' => "The subject of the revision log's description",
    'length' => 255,
    'not null' => FALSE,
  );
}

/*
 * Implements hook_install().
 */
function raks_install() {
  if (!db_field_exists('node_revision', 'log_subject')) {
    $schema = drupal_get_schema('node_revision');
    db_add_field('node_revision', 'log_subject', $schema['fields']['log_subject']);
  }
}

/*
 * Implements hook_uninstall().
 */
function raks_uninstall() {
  if (db_field_exists('node_revision', 'log_subject')) {
    $schema = drupal_get_schema('node_revision');
    db_drop_field('node_revision', 'log_subject');
  }
}

/**
 * Implements hook_views_api().
 */
function raks_views_api()
{
    return array(
        'api' => 3
    );
}

You would also need a separate *.views.inc file, e.g. raks.views.inc, with the following code inside:
<?php

/**
 * Implements hook_views_data_alter().
 */
function raks_views_data_alter(&$data)
{

  $data['node_revision']['log_subject'] = array(
    'title' => "Subject of the revision's log",
    'help' => "Subject of the revision's log",
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    )
  );

}

Once this file is in place (and following a clear-cache if needed), you should have access to the log_subject as a field in your Content Revisions view.
Let me know if this works all the way, I am curious :-)
May even submit it as a contrib module on D.O., what do you think?
Comment: Thank you! This worked. I am also trying to display the revisions via the views module. Do you know how I can pull in that newly created field, and display it on the page?
Comment: Welcome! I updated the answer with infos about how to get this working with Views. Cheers
Comment: I think its a good idea. This definitely helped with my project. Thanks a ton!


On the definition of positive and negative crossings

Question: In the definition of the Kauffman bracket, we have to resolve a crossing in two ways.
The way to resolve these crossings involve distinguishing whether the crossings are positive or negative. But without orientation, I do not see why the sign of a crossing can be uniquely defined.
For example, should I apply the rule $$<T> = a <A> + a^{-1}<B>$$ or $$<T> = a <B> + a^{-1}<A>$$ to obtain the Kauffman bracket for T?
The reason I asked is because if you rotate the picture by 90 degrees clockwise you will apply a different rule and get a different answer but I don't think that could be the case for a knot invariant...

Do I miss anything?
Comment: I get what you're asking, and I think the answer is in the paper I linked to. But Najib's answer amounts to the same thing.
Comment: The definition at http://en.wikipedia.org/wiki/Bracket_polynomial makes no mention of positive & negative crossings.
Comment: Maybe the explanation at http://www.maths.ed.ac.uk/~aar/papers/kauffmanjones.pdf will be useful.
Comment: I edited the question. Hope you get what I'm asking.
Answer: Orientation doesn't matter in the Kauffman bracket. In the definition, you can smooth out crossings that have the form:

And then depending on how you resolve you get either a 0-smoothing or a 1-smoothing:
                     and
If you rotate the figure 90°, you get something like this:

And you cannot apply the rule to crossings like that. If you rotate it 180°, you get the original picture; but then 0- and 1-smoothings are the same as for the original picture. All in all, you can see that orientation doesn't matter. It's not a question of positive and negative crossings.

In fact if the diagram were oriented, you wouldn't be able to do both smoothings! For example consider the following knot diagram (obviously it's the unknot, but it's just for the example -- you could envision a more complicated diagram):

The crossing is a positive crossing. But you see that if you want to keep an oriented link diagram, only one smoothing is allowed namely . The other one welds the two parts in such a way that the orientations conflict.


O textBox Search multiplica os valores de busca

Question: <code> Private Sub txtSearchByDish_TextChanged(sender As Object, e As EventArgs) Handles txtSearchByDish.TextChanged
    Try
        con = New OleDbConnection(cs)
        con.Open()
        cmd = New OleDbCommand("SELECT  DishName, I.Rate, SUM([Qty]) as ItemQuantity, BillDate, ( I.Rate * SUM([Qty])) As TotalAmount FROM Dish as I, RestaurantBillingInfo as P, RestaurantBillingItems as PD WHERE DishName like '" & txtSearchByDish.Text & "%' Group By DishName, I.Rate, [Qty], BillDate ORder By DishName", con)
        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgw.Rows.Clear()
        While (rdr.Read() = True)
            dgw.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3), rdr(4))
        End While
        con.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub
</code>
Comment: Por favor ,explique o que está querendo fazer o seu problema, não ficou muito claro apenas com o título e o trecho de código. Pelo que entendi a cada caracter digitado no textbox você vai ao banco, abre conexão e faz uma query? é Windows forms? Ou Web? Não esqueça de dar dispose nos objetos, ou utilize o Using
Comment: Windows forms; É um form que exibe o relatorio de vendas, e contem la uma textbox para buscar ou mostrar somente alguns items. Ex: se digito PEIXE, irá mostrar apenas a lista com items de nome PEIXE. Espero ter esclarecido....E o meu problema é: ao digitar PEIXE ele multiplica o mesmo Item 9 vezes.....
Comment: Onde ele multiplica? isso que eu nao entendi, ele multiplica na hora que faz o While e adicionar no Seu DataGridview ?
Comment: Exatamente ...PS: o textbox buscar funciona como um filtro de busca.
Comment: Só com estas informações não temos como ajudar. Este código está cheio de erros. Curiosamente você sabe fazer certo (https://pt.stackoverflow.com/q/261141/101), mas não o fez.
Answer: Consegui resolver o problema modificando o meu codigo para:
<code>Private Sub txtSearchByDish_TextChanged(sender As Object, e As EventArgs) Handles txtSearchByDish.TextChanged
    Dim totalAmount As Double
    Dim totalQuantity As Integer
    Try
        con = New OleDbConnection(cs)
        con.Open()
        Dim cb As String = "SELECT DishName, I.Rate, SUM([Qty]) as ItemQuantity, BillDate, ( I.Rate * SUM([Qty])) As TotalAmount FROM Dish as I, RestaurantBillingInfo as P, RestaurantBillingItems as PD WHERE I.ItemID = PD.Item_ID AND PD.B_ID=P.BillId AND DishName like '" & txtSearchByDish.Text & "%' Group By DishName, I.Rate, [Qty], BillDate ORder By DishName"
        cmd = New OleDbCommand(cb, con)
        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgw.Rows.Clear()
        Do While (rdr.Read() = True)
            dgw.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3), rdr(4))
            dgw.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(4))
            totalAmount += rdr(4)
            totalQuantity += rdr(2)
        Loop

        lblQuantity.Text = totalQuantity
        lblTotal.Text = Format(totalAmount, "#,##0.00")
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        cmd.Dispose()
        con.Close()
    End Try
End Sub
</code>
Comment: Ele ainda está cheio de problemas, você só não está vendo.
Comment: E porque não dizes onde está o problema???
Comment: Porque são muitos e eu já disse que você sabe fazer certo.
Comment: ok obrigado pela sua GRANDE contribuição.


Stop reduce_while with tuple

Question: I want to stop reduce_while when my function get {:error,reason} instead of false
my code is:
Enum.reduce_while(
      [1,2,3,4],
      0,
      fn filename, _foo ->
        if carica() do
          IO.puts "OK"
          {:cont, carica()}
        else
          IO.puts "KO"
          {:halt, carica()}
        end
      end
    )

  def carica() do
    {:error,"ERROR!!!!!"}
  end

I want a output like
"KO"
{:error,"ERROR"}

because in this way I have
OK
OK
OK
OK
{:error, "ERROR!!!!!"}

Answer: If you want to pattern match the response from your function, use case:
case response = carica() do
  {:error, reason} ->
    IO.puts "KO"
    {:halt, response}
  _ ->
    IO.puts "OK"
    {:cont, response}
end

Stop reduce_while with tuple