Incluir nameSpace Default em XML

Question: Srs(as), bom dia,
Estou gerando um XML a partir da serialização de uma classe.cs(schema) e na saida é criado o xml (primeiro exemplo)
.
Esse será exportado para um sistema externo, porem pediram para deixar o XML igual ao (segundo exemplo).
Pelo que vi, existe um NameSpace Defaut (tns) que precisaria incluir, porem não consigo faze-lo.
O XML está sendo gerado pelo código abaixo.
entitiesList = new extEntitiesList() { entity = tEntity };
                    fileName = string.Format("{0}{1}{2}", sPath, tEntity.idExt, ".xml");
                    serializer = new System.Xml.Serialization.XmlSerializer(typeof(extEntitiesList));

                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, false, encoding))
                    {
                        serializer.Serialize(sw, entitiesList);
                        //sw.Write(xml.InnerXml);
                        sw.Dispose();
                    }

A classe foi gerada pelo comando XSD.exe VS2010.
gerou:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://value.com/model/v2/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://value.com/model/v2/", IsNullable=false)]

(primeiro exemplo)

    <?xml version="1.0" encoding="iso-8859-1"?>
<extEntitiesList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://value.com/model/v2/">
  <entity>
    <idExt>value</idExt>
    <name>value</name>
    <fntsyName>value</fntsyName>
    <personType>value</personType>
    <taxId>value</taxId>
    <inscMun />
    <clientType>
      <name>Ivalue</name>
      <id>
        <value>value</value>
      </id>
    </clientType>
    <platform>
      <platformId />
      <name />
      <email />
    </platform>
    <economicGroup>
      <name>value</name>
      <id>
        <value>value</value>
      </id>
    </economicGroup>
    <obs />
    <obsWithoutPwrImpact />
    <address>
      <state>value</state>
      <city>value</city>
      <publicArea>value</publicArea>
      <comp>value</comp>
      <zip>value</zip>
      <phoneNr>value</phoneNr>
      <faxNr>value</faxNr>
    </address>
    <lob>
      <extId />
      <name />
    </lob>
  </entity>
</extEntitiesList>

(segundo exemplo)

<?xml version="1.0" encoding="UTF-8"?>
<tns:extEntitiesList xmlns:tns="http://value.com/model/v2/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://value.com/model/v2/ value.xsd ">
<tns:entity>
    <tns:idExt>value</tns:idExt>
    <tns:name>value</tns:name>
    <tns:fntsyName>value</tns:fntsyName>
    <tns:personType>value</tns:personType>
    <tns:taxId>value</tns:taxId>
    <tns:inscEst>value</tns:inscEst>
    <tns:inscMun>value</tns:inscMun>
    <tns:clientType>
      <tns:name>value</tns:name>
      <tns:id>
        <tns:value>value</tns:value>
      </tns:id>
    </tns:clientType>
       <tns:responsibleArea>
      <tns:respAreaId>value</tns:respAreaId>
      <tns:name>value</tns:name>
      <tns:email>value</tns:email>
    </tns:responsibleArea>
    <tns:platform>
      <tns:platformId>value</tns:platformId>
      <tns:name>value</tns:name>
      <tns:email>value</tns:email>
    </tns:platform>
    <tns:economicGroup>
      <tns:name>value</tns:name>
      <tns:id>
        <tns:value>value</tns:value>
      </tns:id>
    </tns:economicGroup>
    <tns:expirationDate>value</tns:expirationDate>
    <tns:status>value</tns:status>
    <tns:document>
      <tns:documentExtId>value</tns:documentExtId>
      <tns:documentTypeExtId>value</tns:documentTypeExtId>
      <tns:documentTypeName>value</tns:documentTypeName>
      <tns:formalizationId>value</tns:formalizationId>
      <tns:formalizationName>value</tns:formalizationName>
      <tns:book>value</tns:book>
      <tns:sheet>value</tns:sheet>
      <tns:issueDate>value</tns:issueDate>
      <tns:pubDate>value</tns:pubDate>
      <tns:expirDate>value</tns:expirDate>
      <tns:grantDate>value</tns:grantDate>
      <tns:closeDate>value</tns:closeDate>
      <tns:active>value</tns:active>
    </tns:document>
    <tns:address>
      <tns:addressExtId>value</tns:addressExtId>
      <tns:state>value</tns:state>
      <tns:city>value</tns:city>
      <tns:publicArea>value</tns:publicArea>
      <tns:number>value</tns:number>
      <tns:comp>value</tns:comp>
      <tns:district>value</tns:district>
      <tns:zip>value</tns:zip>
      <tns:phoneNr>value</tns:phoneNr>
      <tns:faxNr>value</tns:faxNr>
    </tns:address>
    <tns:lob>
      <tns:extId>value</tns:extId>
      <tns:name>value</tns:name>
    </tns:lob>
    </tns:entity>
    <tns:entity>
</tns:extEntitiesList>

Comment: É interessante você postar o código que está usando para gerar o xml.
Comment: Incluido...Obrigado!!!
Answer: Luiz,
Tente usar o XmlSerializerNamespaces antes da serialização:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("tns", "http://value.com");
XmlSerializer serializer = new XmlSerializer(typeof(extEntitiesList));
serializer.Serialize(Console.Out, new extEntitiesList(), ns);

Incluir nameSpace Default em XML


Discord.js Bot Command Error: Warn Command

Question: I am a beginner at Node.js Coding and recently coded my bot on repl.it
I know that there is something wrong with this code and cannot understand where should I put '{'
Can you please help me <3
Here is my code:
client.on("message", async (message) => {
 if(message.content.startsWith("!warn"))
 let victim = message.mentions.users.first()
 if(!victim) message.reply("mention someone to warn.")
 else {
 let embed = new Discord.MessageEmbed()
 .setTitle("Warnings")
 .setDescription(`${victim} got warned by ${message.author}!`)
 .setColor("GREEN")
 .setFooter(`Moderator : ${message.author.username}`)
 .setTimestamp()

 message.channel.send(embed)
 }
});

If there are some questions ask it I will really appreciate it if you will help! <3
Can you please send the final version of this code
Comment: After `if(message.content.startsWith("!warn"))` and a closing curly bracket before `});`. Please do make sure to learn some basic JavaScript before hopping into Discord.js Development. It is highly recommended to do so and would help you a lot while debugging your code rather than coming on a support site for such a minor issue (Sorry if I'm being a bit rude).
Comment: I corrected that in my answer to your other question.
Comment: ikr @WorthyAlpaca
Answer: You missed brackets on your opening check for message.content
and as a user suggested, try learn some basic JS before coding. I know making a discord bot you want to go straight into in but spend maybe an hour learning the very basics can solve alot of issues for you. :)
client.on("message", async (message) => {
  if (message.content.startsWith("!warn")) {
    let victim = message.mentions.users.first();
    if (!victim) return message.reply("mention someone to warn.");
    let embed = new Discord.MessageEmbed()
      .setTitle("Warnings")
      .setDescription(`${victim} got warned by ${message.author}!`)
      .setColor("GREEN")
      .setFooter(`Moderator : ${message.author.username}`)
      .setTimestamp();

    message.channel.send(embed);
  }
});


How to get number of rows and columns from a matplotlib plot?

Question: I have a function that dynamically creates figures of different columns and rows:
import random

import matplotlib.pyplot as plt

def build_dynamic_plot():
    """Return a figure with random rows and columns."""
    nrows = random.randrange(1, 10)
    ncols = random.randrange(1, 10)

    fig, ax = plt.subplots(nrows, ncols)

    return fig.tight_layout()

plot = build_dynamic_plot()

Using the matplotlib API, how do I get the number of rows and columns from the figure, which are dynamically generated, e.g. plot.get_rows and plot.get_cols?  I ultimately need to verify that the row by column dimensions are accurate.  Thank you.
Answer: Although HYRY's answer was helpful and it might work sometimes (or worked before), the true solution should be:
fig.axes[0].get_subplotspec().get_topmost_subplotspec().get_gridspec().get_geometry()

Answer: I think there no API for this, but you can get the grid size by:
fig.axes[0].get_subplotspec().get_gridspec().get_geometry()


How do I draw a layer 2 (link layer) network map containing Cisco and *NIX boxes?

Question: I've been tasked with drawing a layer 2 network map of our very small datacenter network.
There is one 1841 cisco router, two 3560 cisco catalyst switches and 4 solaris sunfire T-1000 boxes.
I have logged in to the cisco boxes and downloaded the running configuration files for all 3. I have also gotten the output of ifconfig -a for the 4 solaris boxes.
my question is: what reading/learning should I do now to put it all together? Any tips?
I was looking at tools such as lanmap2 but that is for linux, not SunOS and I don't know if I could recompile it successfully myself.
I understand intermediate networking, but I'm not a routing guy. I know a VLAN is a way to segregate groups of ports in different switches in their own subnetworks and I hear that a trunk is a connection between two routers that conveys VLAN information but that's the extent of my knowledge on those two topics.
Comment: Layer 2 map... so what are you expressing? "Servers A, B, and C are in VLAN X"? This seems more like a dataset for a spreadsheet, unless I'm missing something.
Comment: Something similar to Mike Pennington's drawing [seen here](http://serverfault.com/questions/401758/suggestions-for-transitioning-to-new-gw-private-network/404625#404625)
Answer: This answer includes a simple LAN diagram that could serve as a template for your network; note that the colors (green / pink / orange) indicate different vlans.
Typically you want to include details like switch / router port numbers, vlan information, IP addressing / netmask, hostnames, and the port name of the interface on the server.
If you don't have a copy of Visio, you can use Inkscape to generate drawings.  If you are adventurous, you can even build inkscape-compatible copies of Cisco's networking icons
Comment: That's a really neat drawing! I will use it as my template. I have omnigraffle which is similar to visio.
Answer: Considering the number of devices, you don't need any extra tools for this, just an understanding of how things are wired. Because you're drawing a LAYER 2 map, you're concerned primarily with MAC addresses and potentially VLANs.
First, start by diagramming layer 1, and verify how things are cabled. I suspect that the router is connected to one or both switches, or just to one switch and the switches are daisy-chained.
Then grab the MAC address-table off of the router and the two switches and start to build your adjacencies.
Considering there are 4 servers, 2 switches, and 1 router, you should be able build a complete layer 2 topology in under 15 minutes.


Automorphism of tensor product of Hopf algebras

Question: Let $A$ be a commutative Hopf algebra over the commutative ring $R$, that is we have comultiplication $\Delta:A\to A\otimes_{R}A$, counit $\epsilon: A\to R$ and coinverse (or antipode) $S: A\to A$. I want to prove that the map $a\otimes b\mapsto (a\otimes 1)\cdot \Delta(b)$ is an automorphism of $R$ algebras of $A\otimes_{R}A$.
I found a similar exercise on Milne's notes on affine group schemes, though my context is just that of commutative algebra.
My first idea was to prove directly injectivity and surjectivity, but I'm completely stuck. Can anyone give me some hints on which is the correct way to follow?
Answer: You want to write down an inverse explicitly using the other operations.
Since $A$ is commutative $G = \text{Spec } A$ is an affine group scheme so we can think about this map in terms of the dual map $G \times G \to G \times G$ of affine group schemes, which is easier to think about. Its action on a pair of $S$-points $g, h : A \to S$ of $G(S)$, for any $R$-algebra $S$, sends $(g, h) \in G(S) \times G(S)$ to some other pair of points in $G(S) \times G(S)$, which we can calculate by restricting the given map to the first and then the second copy of $A$. Restricting to the first copy gives
$$a \mapsto (a \otimes 1) \Delta(1) = a \otimes 1$$
which reveals that the first component of our map is $(g, h) \mapsto g$. Restricting to the second copy gives
$$b \mapsto (1 \otimes 1) \Delta(b) = \Delta(b)$$
which reveals that the second component of our map is $(g, h) \mapsto gh$. Altogether, our map is
$$G(S) \times G(S) \ni (g, h) \mapsto (g, gh) \in G(S) \times G(S).$$
This is much easier to think about: its inverse is just $(g, h) \mapsto (g, g^{-1} h)$.
Comment: @Avenavolo: the great thing about working in terms of functors of points is that it suffices to verify that the inverse is really an inverse on all points, so you are just doing basically the same computation you'd do in an ordinary group.
Comment: @Avenavolo: you can translate the map $(g, h) \mapsto (g, g^{-1} h)$ back into a map $A \otimes_R A \to A \otimes_R A$. I didn't do this because it is slightly annoying. It's determined by the property that its restriction to the first copy of $A$ is $a \mapsto a \otimes 1$ and its restriction to the second copy of $A$ is $b \mapsto (S \otimes \text{id}_A) \circ \Delta(b)$ (this is the annoying bit). So in total the map is $a \otimes b \mapsto (a \otimes 1) \left( (S \otimes \text{id}_A) \circ \Delta(b) \right)$. The proof that this is actually the inverse in this language is also annoying.
Comment: Thank you! I had already started going down this road and found the same inverse, though I couldn't actually prove it was in fact the inverse. I'm not used to affine group schemes so I used category theory terminology (natural transformations and so on), but I guess it's the same
Comment: Is it possible to explicitly compute the inverse in the context of morphisms of $R$ algebras? Because while the idea is clear to me, I'm definitely not accustomed to Groups Schemes, so I don't know how to prove the result using only what I know. Thank you very much for the help!


Passar o valor de uma key ao criar ou após criado o array

Question: Eu tenho o seguinte arquivo JSON:

const animais = {"types":[
  {
    "id":100196,
    "animal":"dog",
    "type":"adult",
    "tags":"AA 96 87"
  },{
    "objid":100578,
    "animal":"cat",
    "type":"old",
    "tags":"T2 96 AB"
  },{
    "objid":100643,
    "animal":"parrot",
    "type":"young",
    "tags":"MAN L5 65"
  },{
    "objid":101165,
    "animal":"falcon",
    "type":"teen",
    "tags":"T2 56 AA"
  },{
    "objid":101168,
    "animal":"rabbit",
    "type":"old",
    "tags":"FII R25 75"
  },{
    "objid":164713,
    "animal":"rabbit",
    "type":"teen",
    "tags":"MAN R25 75"
  },{
    "objid":101174,
    "animal":"horse",
    "type":"baby",
    "tags":"MAN R62 75"
  },{
    "objid":101177,
    "animal":"turtle",
    "type":"old",
    "tags":"MAN R4 75"
  },{
    "objid":101180,
    "animal":"tiger",
    "type":"young",
    "tags":"MAN R8 75"
  }
]}

O dado foi tratado para retornar os animais separados dentro de um mesmo array, possuindo somente o nome do animal e as tags que o mesmo carrega.

const types = animais.types.reduce((animal, item) => {
    const val = item.animal;
    animal[val] = animal[val] || [];
    animal[val].push(item);
    return animal;
    },{}
)

threeanimals = Object.entries(types)
    .filter(([key, value]) => value.length < 3)
    .map(([key, value]) => ({ key, tags: value.map(({tags}) => tags) }))

console.log(threeanimals)

A tratativa me retorna uma Array de Objetos com uma key, que carrega o nome do animal e um array de tags, com as tags que o objeto possuia.

[Object {key: "dog", tags: ["AA 96 87"]}, Object {key: "cat", tags: ["T2 96 AB"]}, …]

O que eu poderia fazer para além das tags e o nome do objeto como key, me fosse retornado por exemplo, o primeiro trecho do nome da tag como key da tag e o objid como value? Da seguinte forma:

[Object {key: "dog", tags: ["AA": "100196"]}, Object {key: "cat", tags: ["T2": "100578"]}, …]
Answer: Um exemplo minimo de como criar essa solução utilizando map em vez de reducer:

const animais = {
  "types": [{
    "objid": 100196,
    "animal": "dog",
    "type": "adult",
    "tags": "AA 96 87"
  }, {
    "objid": 100578,
    "animal": "cat",
    "type": "old",
    "tags": "T2 96 AB"
  }, {
    "objid": 100643,
    "animal": "parrot",
    "type": "young",
    "tags": "MAN L5 65"
  }, {
    "objid": 101165,
    "animal": "falcon",
    "type": "teen",
    "tags": "T2 56 AA"
  }, {
    "objid": 101168,
    "animal": "rabbit",
    "type": "old",
    "tags": "FII R25 75"
  }, {
    "objid": 164713,
    "animal": "rabbit",
    "type": "teen",
    "tags": "MAN R25 75"
  }, {
    "objid": 101174,
    "animal": "horse",
    "type": "baby",
    "tags": "MAN R62 75"
  }, {
    "objid": 101177,
    "animal": "turtle",
    "type": "old",
    "tags": "MAN R4 75"
  }, {
    "objid": 101180,
    "animal": "tiger",
    "type": "young",
    "tags": "MAN R8 75"
  }]
}

const types = animais.types.map((obj, index) => {
  const tags = obj.tags.split(' ');
  return {
    key: obj.animal,
    tags: {
      [tags[0]]: obj.objid
    }
  };
}, {})

console.log(types);


ComboBox not showing on Dialog load

Question: I have the following ComboBox declared in a custom Dialog:
    <Control Id="EnvironmentCombobox" Type="ComboBox" Sorted="yes" ComboList="yes" Property="ENVIRONMENT" X="25" Y="110" Width="200" Height="15">
      <ComboBox Property="ENVIRONMENT">
        <ListItem Text="Development" Value="Development" />
        <ListItem Text="SIT" Value="SIT" />
        <ListItem Text="UAT" Value="UAT" />
        <ListItem Text="Production" Value="Production" />
      </ComboBox>
    </Control>

When I run my installer and get to that dialog, the ComboBox doesn't show until I run my mouse over it.  It also appears when if I hit a navigation button.  If I leave and come back to the dialog, it is gone again, until I mouse over it or hit a navigation button.
I've tried setting Hidden="no" and increasing the height, but no luck.

Adding full files, per request in comments.
The above is in the EnvironmentDlg:
    <?xml version="1.0" encoding="UTF-8"?>
    <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
        <Fragment>
        <UI>
          <Dialog Id="EnvironmentDlg" Width="370" Height="270" Title="[ProductName] Setup">

            <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.LicenseAgreementDlgBannerBitmap)" />
            <Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
            <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />

            <Control Id="Title" Type="Text" X="15" Y="15" Width="300" Height="15" Transparent="yes" NoPrefix="yes" Text="{\WixUI_Font_Title}Choose environment for [ProductName]" />
            <Control Id="InstallText" Type="Text" X="25" Y="70" Width="320" Height="80" Text="Choose the environment to which [ProductName] is being installed." />
            <Control Id="EnvironmentCombobox" Type="ComboBox" Sorted="yes" ComboList="yes" Property="ENVIRONMENT" X="25" Y="110" Width="200" Height="15">
              <ComboBox Property="ENVIRONMENT">
                <ListItem Text="Development" Value="Development" />
                <ListItem Text="SIT" Value="SIT" />
                <ListItem Text="UAT" Value="UAT" />
                <ListItem Text="Production" Value="Production" />
              </ComboBox>
            </Control>

            <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)" />
            <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)">

              <Condition Action="disable">ENVIRONMENT = ""</Condition>
              <Condition Action="enable"><![CDATA[ENVIRONMENT <> ""]]></Condition>
            </Control>
            <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)">
              <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish>
            </Control>
          </Dialog>
        </UI>
        </Fragment>
    </Wix>

The sequence is in MyWixUI_Unsecured:
    <?xml version="1.0" encoding="UTF-8"?>
    <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
        <Fragment>
        <UI Id="MyWixUI_Unsecured">
          <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" />
          <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="12" />
          <TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" />

          <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />

          <DialogRef Id="ErrorDlg" />
          <DialogRef Id="FatalError" />
          <DialogRef Id="FilesInUse" />
          <DialogRef Id="MsiRMFilesInUse" />
          <DialogRef Id="PrepareDlg" />
          <DialogRef Id="ProgressDlg" />
          <DialogRef Id="ResumeDlg" />
          <DialogRef Id="UserExit" />

          <Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish>

          <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="EnvironmentDlg">1</Publish>

          <Publish Dialog="EnvironmentDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg">1</Publish>
          <Publish Dialog="EnvironmentDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>

          <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="EnvironmentDlg">1</Publish>
        </UI>

        <UIRef Id="WixUI_Common" />
        </Fragment>
    </Wix>

Comment: Can you post your UserInterface.wxs source
Comment: @CheGueVerra:  Added the full definitions of the Dialog and the flow.
Answer: The issue is regarding the Height of InstallText control in EnvironmentDlg.
Change the Height to 25
<Control Id="InstallText" Type="Text" X="25" Y="70" Width="320" Height="25" Text="Choose the environment to which [ProductName] is being installed." />

Full Code:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <UI>
            <Dialog Id="EnvironmentDlg" Width="370" Height="270" Title="[ProductName] Setup">

                <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.LicenseAgreementDlgBannerBitmap)" />
                <Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
                <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />

                <Control Id="Title" Type="Text" X="15" Y="15" Width="300" Height="15" Transparent="yes" NoPrefix="yes" Text="{\WixUI_Font_Title}Choose environment for [ProductName]" />
                <Control Id="InstallText" Type="Text" X="25" Y="70" Width="320" Height="25" Text="Choose the environment to which [ProductName] is being installed." />
                <Control Id="EnvironmentCombobox" Type="ComboBox" Sorted="yes" ComboList="yes" Property="ENVIRONMENT" X="25" Y="110" Width="200" Height="15">
                    <ComboBox Property="ENVIRONMENT">
                        <ListItem Text="Development" Value="Development" />
                        <ListItem Text="SIT" Value="SIT" />
                        <ListItem Text="UAT" Value="UAT" />
                        <ListItem Text="Production" Value="Production" />
                    </ComboBox>
                </Control>

                <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)" />
                <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)">

                    <Condition Action="disable">ENVIRONMENT = ""</Condition>
                    <Condition Action="enable"><![CDATA[ENVIRONMENT <> ""]]></Condition>
                </Control>
                <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)">
                    <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish>
                </Control>
            </Dialog>
        </UI>
    </Fragment>
</Wix>

I will suggest you using WixEdit control for designing UI

ComboBox not showing on Dialog load


Validação checkbox dinamico com jquery-validator

Question: Estou tentando validar um checkbox utilizando o plugin http://jqueryvalidation.org/.
O problema ocorre que o campo que estou validando ele não existe até que um outro campo pré-determinado seja selecionado. Sendo assim, a validação passa mesmo sem esse campo existir.
Não consegui uma maneira de fazer com que a validação ocorra mesmo o campo não existindo.
Tentei assim:
$('#form_novo').validate({
 rules: {
    'bnd[]': {
        required: true
    },
    'responsavel[]': {
        required: true
    },
    'etapa[]': {
        required: true
    },
}

Esse campo responsável só existe depois de selecionado o campo bnd. Alguém sabe como resolver?
Answer: A única solução que me ocorre é controlares a existência desse campo dinâmico no submitHandler e agires em conformidade:
Exemplo no JSFiddle
$('#form_novo').validate({
    rules: {
        'bnd[]': {
            required: true
        },
        'responsavel[]': {
            required: true
        },
        'etapa[]': {
            required: true
        },
    },
    submitHandler: function(form) {
        // estou a assumir que tem a classe "responsavel"
        if ($(form).find('.responsavel').size()>=1) {
            form.submit();
        } else {
            alert("crap");
        }
    }
});

O que está a ser feito é permitir a submissão do formulário se o elemento dinâmico existir, caso não, fazemos algo como apresentar uma mensagem de erro no local adequado.
Answer: Você poderia fazer com que o campo sempre exista, deixando o mesmo invisível?
display: none;

Se puder, então isso resolveria o seu problema.
Comment: Não posso, é um campo dinâmico que depende da escolha do bnd


How many ways can a drummer with a varying amount of limbs play?

Question: I'm looking at the amount of possible combinations of single stroke rolls using varying amount of limbs.
Let's use these letters for reference

R is right hand.
L is left hand.
r is right foot.
l is left foot.

There is one variation for one limb: R. There are two variations for two limbs: RL
 and LR. There are six variations for three limbs:

RLr
RrL
LRr
LrR
rRL
rLR

I won't list them all, but there are 24 combinations for four limbs. Here is the first one:

RLrl
RLlr
RrLl
RrlR
RlLr
RlrL

That leads to the following ratios: $1:1$, $2:2$, $3:6$ and $4:24$. That would leave me to believe the next pair of numbers to continue the pattern would be $5:120$.
Is there an equation that I can use to solve for number of variations using different numbers of limbs using only one limb once?
Comment: The equation is, $n*(n-1)*(n-2)*.....*3*2*1$.  That is so useful we write it as $n! $.   Now you might hope that there is some shorter expression.  But there isn't really.  $n!=1*2*3*.....*n $  is in and of itself about as basic as the expression gets.
Comment: Do you have $5$ limbs?
Answer: You are trying to count, for each fixed number $n$  the number of ways to arrange the numbers $1, 2, 3, \dots, n$ in a sequence, using each number exactly once.  These are called permutations of $1, 2, 3, \dots, n$.  The number of permutations of $1, 2, 3, \dots, n$ is called "$n$ factorial", written $n!$, and is equal to $n! = (n) (n-1)(n-2) \cdots (2) (1)$. The reason is that you have $n$ choices to fill the  first position, $n-1$ choices to fill the second position, etc.
Answer: The pattern you posted so far matches:
<code>F(1) = 1
F(X) = X * F(X-1)
</code>
Answer: The problem with all of the other answers you've received so far, is that you only have four limbs.  Based on the rules you have implied in your question, I see no reason to assume that there is only one way for the first variation.  You could, for example, do "R", but you could also do "L", or "l", or "r"--so in this case, I count four possibilities, not one.
Similarly, for two limbs, you seem to ignore the feet, but give no reason why.  For three limbs, you ignore the left foot.
In the case of using all four limbs, with the exception of the fourth outcome (which seems to be a typo), all of the outcomes you enumerated use "R", "L", "r", "l" exactly once, but it seems that order is important--at least, it would be if you count 24 outcomes as you claim.
Finally, you ask:

Is there an equation that I can use to solve for number of variations using different numbers of limbs using only one limb once? (emphasis mine)

This is clearly problematic:  if you can use each limb only once, it is impossible to have a variation that uses more than four limbs, unless you are not human, or have extra limbs, or are counting some other appendage as a limb.  So you need to think about what you actually mean by this statement.
For what it's worth, I count 4 variations for a single hit on the drum, 12 variations for two hits, 24 variations for three hits, and 24 variations for using all four limbs.  Variations with five or more hits are not possible--you don't have five limbs to use.
Comment: All of that is true. I just wanted an equation to match that data set.


Scripting engine for Twilio similar to Tropo

Question: Tropo has a scripting engine using which we can write code in scripting language for voice and sms applications. e.g. the python code to answer a call looks like,
<code>answer()
say("thanks for calling")
transfer("tel:+1xxxxxxxxxx")
hangup()
</code>
Is there something similar available for Twilio. I see that they have Python wrapper over their SDK using which one can do something similar. But I need to find out if there is something similar that Twilio has.
Thanks,
gg
Answer: If you need to do anything dynamic (respond in different ways based on who is calling), you'll need to provide Twilio with a URL, and then respond with TwiML at that URL.
You can create TwiML with Python with the helper library: Creating TwiML with twilio-python
If you are responding to every call in the same way (eg a static reply), Twilio has Twimlets you can use to create small snippets of functionality, like say a message and then dial a new number. You can host Twimlets with Twilio, so you don't need your own server.


Asymptotic distribution of exponential order statistics

Question: Let $X_1,...,X_n$ be i.i.d. random variables and $X_{(1)}<...<X_{(n)}$ be the order statistics. Assume $X_i\sim \text{exp}(1)$. Find a sequence of constants $a_n$ such that $X_{(n)}-a_n$ converges in distribution.
CDF of $X_{(n)}-a_n$ is $(1-e^{-(x+a_n)})^n$. What condition should we have over $a_n$ such that $(1-e^{-(x+a_n)})^n$ has a limit?
I think if $a_n=\ln(n)$ then $$(1-e^{-(x+a_n)})^n=(1-\frac{e^{-x}}{n})^n\rightarrow e^{-e^{-x}}$$
Answer: Correct.  For your choice of $a_n$, $$\lim_{n \to \infty} X_{(n)} - a_n$$ has what is called an extreme value distribution, with CDF $e^{-e^{-x}}$ and the convergence is in distribution.
As an exercise, as a function of $n$, what is $\operatorname{E}[X_{(n)}]$?  What happens if we choose $a_n = \operatorname{E}[X_{(n)}]$?  What is the asymptotic variance in each case?


Evaluating $~\int_0^1\sqrt{\frac{1+x^n}{1-x^n}}~dx~$ and $~\int_0^1\sqrt[n]{\frac{1+x^2}{1-x^2}}~dx$

Question: How could we prove that

$$\int_0^1\sqrt{\frac{1+x^n}{1-x^n}}~dx~=~a\cdot2^{a-1}~\bigg[\frac12~B\bigg(\frac a2,~\frac a2\bigg)~+~B\bigg(\dfrac{a+1}2,~\dfrac{a+1}2\bigg)\bigg],$$

where $a=+~\dfrac1n$ , and

$$\int_0^1\sqrt[n]{\frac{1+x^2}{1-x^2}}~dx~=~a\cdot2^{a-1}~\bigg[\frac12~B\bigg(\frac a2,~\frac a2\bigg)~-~B\bigg(\dfrac{a+1}2,~\dfrac{a+1}2\bigg)\bigg],$$

where $a=-~\dfrac1n$ ?

This question arose as a generalization of the fact that the arc length of the $($co$)$sine function over an interval of the form $\bigg(k~\dfrac\pi2,~m~\dfrac\pi2\bigg)$, with $k,~m\in\mathbb Z$, can be expressed in terms of $\Gamma$ functions, which was somewhat surprising, since the evaluation of such arc lengths usually involves elliptic integrals; indeed, it was one of the main historical reasons for defining them in the first place.

I tried substituting $x^n=\cos2t$, and then employing the well-known trigonometric formulas for $1\pm\cos2t$, in the hopes of reducing the original problem to a beta function by means of Wallis' integrals, since $\sqrt{\dfrac{1+x^n}{1-x^n}}~=~\cot(t)$, but this approach ultimately lead me nowhere $($which is not to imply that the same method might not prove fruitful in someone else's skilled hands$)$.
Comment: have you tried $x^n=\cos^2(y)$ in your first integral? after applying the binomial theorem and integration term by term one ends up with a sum witch is easily shown to be of the form $_2F_1(...,-1)$. I suspect that we can finish it of from there by the use of one of the (too many) transformation rules of $_2F_1$ together with Kummers theorem and/or Gauss summation theorem. But i don't have the courage/time to really take care of this at the moment
Comment: To be a little bit more precise, my representation for now is $$
\frac{1}{n}\text{B}(\frac{1}{2},\frac{1}{n})\, _2F_1\left(-\frac{1}{2},\frac{1}{n};\frac{1}{n}+\frac{1}{2};-1\right)
$$
Comment: Rephrasing the question and providing an answer are two different things. Explaining a mystery by means of a riddle wrapped in an enigma is not particularly enlightening. Hence my ever-growing frustration.
Comment: @Lucian do i understand you correctly? you are not interested in a proof containing hypergeometric functions?
Comment: @tired: If that proof also contains a $($link to a$)$ proof or explanation of the afore-mentioned hypergeometric property $($one which my brain can actually understand$)$, then I am *very* interested. Either way, I always upvote correct answers to my questions, even if I personally cannot relate to them that well.
Comment: @Lucian i added something and try to proof the hypergeo. identity tomorrow.
Comment: @Lucian have a look at my edit. i added a paper where a proof is given and it seems to be quite understandable :)
Comment: For the first integral, by long division we have that $$\sqrt{\frac{1+x^n}{1-x^n}}=\sqrt{\frac{2}{1-x^n}-1},$$ now use the substitution $\sec^2 t = \frac{2}{1-x^n}$ and change the limits to be $\pi/4$ to $\pi/2$. The 2nd integral may goes in the same approaches.
Answer: First integral:
Let us multiply the numerator and denominator of the integrand by $\sqrt{1+x^n}$ , so that the initial integral becomes
$$\mathcal{I}=\underbrace{\int_0^1\frac{dx}{\sqrt{1-x^{2n}}}}_{\mathcal{I}_1}+
\underbrace{\int_0^1\frac{x^ndx}{\sqrt{1-x^{2n}}}}_{\mathcal{I}_2}.$$
After the substitution $x=\sin^{\frac1n}\theta$ the integrals $\mathcal{I}_{1,2}$ reduce to integral representations of two beta functions:
$$\mathcal{I}_1=\frac{1}{2n}B\left(\frac12,\frac1{2n}\right),\qquad
\mathcal{I}_2=\frac{1}{2n}B\left(\frac12,\frac{1+n}{2n}\right).$$
It can be easily shown (using duplication formula for gamma function or repeating the computation from this link) that
\begin{align*}
B\left(\frac12,\frac1{2n}\right)&=2^{\frac1n-1}B\left(\frac1{2n},\frac1{2n}\right),\\
B\left(\frac12,\frac{1+n}{2n}\right)&=
2^{\frac1n}B\left(\frac{1+n}{2n},\frac{1+n}{2n}\right),
\end{align*}
which proves the first formula of the question. Hopefully this is not too mysterious.

Second integral:
The change of variables
$$y=\sqrt[n]{\frac{1-x^2}{1+x^2}} \qquad \Longleftrightarrow\qquad x=\sqrt{\frac{1-y^n}{1+y^n}}$$
transforms the integral into
$$\int_0^1\frac{ny^{n-2}dy}{\left(1+y^n\right)\sqrt{1-y^{2n}}}
=\int_0^1\frac{ny^{n-2}\left(1-y^n\right)dy}{\left(1-y^{2n}\right)^{\frac32}}=\int_0^1\frac{\left(1-y^n\right)}{y}d\left(\frac{y^n}{\sqrt{1-y^{2n}}}\right).$$
Now it suffices to integrate by parts and apply exactly the same procedure (two beta functions at the first step and duplication formula at the second one).
Comment: Quite the contrary, I feel like slapping myself silly. :-$)$
Comment: @Lucian I added a derivation of the second identity.
Comment: Or we could just break it up into a difference of two beta functions. This is simply brilliant. I wish I could upvote it twice!  $($And I didn't even notice the relation between the two integrands$)$.
Comment: @Lucian Thank you! Breaking into a difference didn't seem straightforward to me because of $\frac32$ in the denominator. That was the reason to first integrate by parts. But maybe there is a nicer way to handle the divergence.
Answer: Ok maybe not the most elegant solution but nevertheless:
I concentrate on the integral first integral and call it $I_1$. Using a substitution $x^n=\cos^2(y),\,dx=-\frac{2}{n}\sin(x)\cos^{\frac{2}{n}-1}(x)$ we obtain
$$
I_1=\frac{2}{n}\int_{0}^{\pi/2}\cos^{\frac{2}{n}-1}(y)\sqrt{1+\cos^2(y)}
$$
Expanding the square root as a Taylor series allows us to write after exchanging summation and integration:
$$
I_1=\frac{2}{n}\sum_{m=0}^{\infty}\binom{1/2}{m}\int_0^{\pi/2}\cos^{2m+\frac{2}{n}-1}(y)
$$
The integral is now in the form of Beta function and we obtain
$$
I_1=\frac{\sqrt{\pi}}{n}\sum_{m=0}^{\infty}\binom{1/2}{m}\frac{\Gamma \left(m+\frac{1}{n}\right) }{\Gamma \left(m+\frac{1}{n}+\frac{1}{2}\right)}
$$
Remembering $\binom{1/2}{m}=\frac{(-1)^m\Gamma(2m+1)}{\Gamma(m+1)^2}\frac{1}{(1-2m)4^m}$
And using some basic properties of the Gamma function (duplication formula and the reduction formula for $\Gamma(\frac{1}{2}+n)$)this boils down to
$$
I_1=\frac{1}{n}\sum_{m=0}^{\infty}(-1)^m\frac{\Gamma \left(m-\frac{1}{2}\right)}{m!}\frac{\Gamma \left(m+\frac{1}{n}\right) }{\Gamma \left(m+\frac{1}{n}+\frac{1}{2}\right)}
$$
Now using the the defintion of the Hypergeometric function together with the defintion of Pochhammer symbol we may rewrite this as
$$
I_1=\frac{1}{n}B(\frac{1}{2},\frac1n)_2F_1\left(-\frac{1}{2},\frac{1}{n},\frac{1}{2}+\frac{1}{n}\right)
$$
Now using Eulers Transformation this yields
$$
I_1=\frac{1}{2n}B(\frac{1}{2},\frac1n)_2F_1\left(1+\frac{1}{n},\frac{1}{2},\frac{1}{2}+\frac{1}{n},-1\right)
$$
Which may accoording to this site can be evaluated in terms of $\Gamma$-functions yielding the correct result.
Remarks:
I'm not very satisfied with this answer because it contains (what i really hate to be honest) to much Hypergeometric hocus-pocus. I will try to add a proof to the crucial identity tomorrow, but hopefully we find a more elegant way for this problem...
Edit:
For a proof of the above mentioned identity have a look
here,chapter 2
Comment: Two major problems: For starters, he doesn't actually offer a proof of Kummer's formula anywhere. Secondly, I'm at a loss as to how he is magically able to reduce a finite sum of *ratios of binomial coefficients*. Not even Vandermonde's identity can help with that.


PHP MYSQL looking for a way to group rows that have same value in certain column

Question: I have a table named records with the columns: recordid, artist, album, description and coverimg. Some of the albums in the table have the same artist.
On my site I would like to display it like this:
-artist1
  album1
  album2
- artist2
  album3
-artist3
  album4
  album5
If I use GROUP BY it just shows one row per artist. Is there any other way to group them without resorting to relational tables?
Because now I have a form to insert and update the table through my site, and I have no idea how I would have to code the forms to make this work with relational tables.
Comment: I'd recommend you look up CONCAT on the mysql docs. Or wait another 15 minutes for someone to tell you how to do it. I just can't remember the syntax at this instant.
Comment: That's a display problem, not a query problem. a 'viewing' group is not the same as an 'sql' group.
Answer: try this
select artist,group_concat(album) from albums group by artist

gives you
artist1  | album1,album2,album3
artist2  | albumx,albumy

You can split the second column in PHP e.g. using explode(row[1])
That should help you a bit
Answer: You can do it without a group by:
<?php
$query = 'Select artist, album
    FROM records
    ORDER BY artist'
$result = mysql_query($query);

$artist = '';
while ($line = mysql_fetch_assoc($result)){
    // only show artist when it's an other artist then the previous one
    if ($line['artist'] != $artist){
        echo $line['artist'].'
';
        $artist = $line['artist'];
    }
    echo $line['album'].'
';
}
?>

I know I should not be using mysql_* functions anymore, please choose mysqli_* or PDO....
Comment: ...and another application gets created with `mysql_query` as the foundation.


Apache modrewrite for vhost applies to all vhosts

Question: I have three separate dvhost configurations on sites-available and one of them contains:
RewriteEngine On
RewriteRule ^/$ /app/login.axvw [R]

The major problem is that it redirects all other vhost roots to /app/login.axvw too.
Full vhost conf:
Edit. Added full conf of one vhost:
<VirtualHost *:80>
    ServerName sub.domain.com
    ServerAlias sub.domain

        redirect / https://sub.domain.com/app/login.axvw

        ErrorLog ${APACHE_LOG_DIR}/sub.domain_error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/sub.domain_access.log combined

</VirtualHost>

<VirtualHost *:443>
        ServerName sub.domain.com

        SSLEngine on
        SSLCertificateFile    /etc/apache2/ssl.crt/domain.com.crt
        SSLCertificateKeyFile /etc/apache2/ssl.key/domain.com.key
        SSLCertificateChainFile /etc/apache2/ssl.crt/gd_bundle.crt

RewriteEngine On
RewriteRule ^/$ /app/login.axvw [R]

#       redirect / https://sub.domain.com/app/login.axvw
    ProxyRequests Off

    ProxyPass / ajp://sub.domain.com:8009/
    ProxyPassReverse / https://sub.domain.com

    <Location />
        Order allow,deny
        Allow from all
    </Location>

        ErrorLog ${APACHE_LOG_DIR}/sub.domain_error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/sub.domain_access.log combined

</VirtualHost>

Comment: Can you post the complete configuration if convenient?
Comment: I must add that this is name based setup for vhosts. Server has one IP.
Answer: Ditch the rewrite and use Redirectmatch instead; save your sanity for when things get really interesting.
Redirectmatch ^/$ https://sub.domain.com/app/login.axvw

Comment: This causes same problem.
When I have sub2.domain.com then it's root is redirected to /app/login.axvw


Implicit function theorem for $f(x,y,z)$: Can I find a function $g$ such that $y=g(x,z)$?

Question: If I want to use the Implicit function theorem for a function $f:\mathbb{R}^3\rightarrow \mathbb{R}$.
Is the order of the variables important?
What I mean with that is, if I can solve $f(x,y,z)$ for $y$?
*implicit function theorem
Thoughts:
Assuming  $f(a,b,c)=0$ for $(a,b,c)\in\mathbb{R}^3$ and $\frac{\partial f}{\partial y}(a,b)\neq 0 $ then* $f$ is locally solvable for $y$ i.e. there exist a neighborhood $U\subset \mathbb{R}^2$ of $(a,c)$ and a continuous differentiable function $g: U\rightarrow \mathbb{R}$ with $y=g(x,z)$ and $f(x,g(x,z),z)=0$ for every $(x,z)\in U$
But can I use the theorem * like that?
The general form in the theorem is given by: $f:\mathbb{R}^m\times \mathbb{R}^n\rightarrow \mathbb{R}^m$
$f:\mathbb{R}^3\rightarrow \mathbb{R}$ can be written as:
a) $f:\mathbb{R}^m\times \mathbb{R}^n\rightarrow \mathbb{R}^m$ with $m=1,n=2$ if I want to search for a solution $x=g(y,z)$
b)$f:\mathbb{R}^n\times \mathbb{R}^m\rightarrow \mathbb{R}^m$ with $m=1,n=2$ if I want to search for a solution $z=g(x,y)$.
c) How can I write $f:\mathbb{R}\times\mathbb{R}^m\times\mathbb{R}\rightarrow \mathbb{R}^m$ if I want to search for a solution $y=g(x,z)$ with $m=1$? I cannot identify $n$.
I'm having some trouble phrasing my question, hopefully it still makes sense to you.
Answer: The order of the variables doesn't matter. If it helps, you can just define a new function with the variables in the order you want and then apply the implicit function theorem to the new function:
$$ F(x,z,y) := f(x,y,z).$$


Wrap unsigned integer addition/subtraction around a range

Question: I am in need a of a function that computes the sum of unsigned val and signed dX and wraps the result around the range lower and upper
For example:
A value of 5, change of -6, and a range of 0 and 10 would return 10.
< 1  2  3  4  5  6  7  8  9  10 >
A value of 2, change of 3, and range of 1 and 3 would return 2
/*
 * Given a value and a change in that value (dX), find the sum and wrap it between lower and upper.
 */
unsigned int wrap(unsigned int val, const int dX, const unsigned int lower, unsigned int upper)
{

}

I don't really know how to approach the unsigned and signed addition/subtraction to avoid underflow. Nor am I sure exactly how to wrap the lower bound.
Comment: Well that's the assignment, isn't it? To figure that out?
Comment: It's not an assignment. It's for my own personal project. Don't downvote assuming I'm just asking for my homework to be completed. There are [similar questions on stack overflow](http://stackoverflow.com/questions/2061245/how-to-subtract-two-unsigned-ints-with-wrap-around-or-overflow) but they don't directly address underflow along with wrapping
Comment: @BLUEPIXY that won't work because the **sum** you do with `int calc = val + dx;` is `signed`. Meaning if the sum would have been over signed integer max value, it would overflow to negative values. I've already though about that and hence that's why I'm here on stack overflow
Comment: I think that `long long` can be used for calculation in the middle.
Comment: That seems a little bit of a hack-y solution but I think you are correct. Hmmmmm
Comment: Do you have to handle the case where upper - lower is greater than the maximum signed integer value?
Comment: @samgak No that shouldn't happen unless the bounds are ridiculously high.
Answer: First, calculate upper-lower to use as a modulus value and convert to an int (as per your comment, the case where upper - lower is greater than the maximum signed integer value doesn't need to be handled):
int modulus = (int)(upper - lower) + 1;

You can then modulo dX by the modulus, to take into account wrapping around:
dX %= modulus;

dX will now have a value between -(modulus-1) and modulus-1. If it's negative just add the modulus:
if(dX < 0)
    dX += modulus;

dX is now guarantted to be positive and you only have to handle the overflow. You can add the difference between val and lower, and then check against the modulus again. This avoids having to deal with unsigned overflow.
dX += (val - lower);
if(dX >= modulus)
    dX -= modulus;

This gives you a value relative to the lower bound, which you can use to compute the new val:
val = lower + (unsigned int)dX;

Comment: Wow, what an answer. I like the logic of lowering `dX` down to only the part that matters. I think though that you need to add `+ 1` to `(int)(upper - lower)` or else it seems to be one under the upper bound. For example, `wrap(0, -1, 0, 10)` prints `9` instead of `10` which it should have wrapped to.
Comment: Note that `upper - lower` may exceed `INT_MAX` rendering `int modulus = (int)(upper - lower)` problematic.
Comment: @Hatefiend Yes, you're right, I didn't notice that the upper bound was inclusive. I've edited the answer to add 1 to the modulus
Answer: If you are willing to change dx from const int to int, you can do the arithmetic in a loop. This avoids possible problems with upper - lower exceeding INT_MAX.
#include <stdio.h>

unsigned int wrap_add(unsigned int val,
                      int dx,
                      const unsigned int lower,
                      const unsigned int upper);

int main(void)
{
    printf("Range [0, 10]: 5 + (-6) = %u\n", wrap_add(5, -6, 0, 10));
    printf("Range [1, 3]: 2 + 3 = %u\n", wrap_add(2, 3, 1, 3));
    printf("Range [2, 5]: 2 + (-9) = %u\n", wrap_add(2, -9, 2, 5));

    return 0;
}

unsigned int wrap_add(unsigned int val,
                      int dx,
                      const unsigned int lower,
                      const unsigned int upper)
{
    while (dx < 0) {
        if (val == lower) {
            val = upper;
        } else {
            --val;
        }
        ++dx;
    }

    while (dx > 0) {
        if (val == upper) {
            val = lower;
        } else {
            ++val;
        }
        --dx;
    }

    return val;
}

Program output:
Range [0, 10]: 5 + (-6) = 10
Range [1, 3]: 2 + 3 = 2
Range [2, 5]: 2 + (-9) = 5

Comment: I guess looping is the only way to gain true safety from under flowing? Great solution. I'll definitely use this one. Thanks so much.
Comment: I don't know if it is the only way, but it seemed like a nice alternative. If the range is very large, the loops will be large, and this may be too inefficient for large numbers of calculations. I suppose the best solution always depends on the context.


dynamic php xml image files attribute redifined error

Question: I am new to web developing and trying to make xml through php to be used in my flash gallery and getting this error when i am checking my php file:
This page contains the following errors:
error on line 3 at column 84: Attribute THUMB redefined
Below is a rendering of the page up to the first error.
Here is the code:
    <?php
// Set which extensions should be approved in the XML file
$extensions = array
(
  'jpg', 'JPG',
  'png', 'PNG',
  'gif', 'GIF',
  'bmp', 'BMP'
);

// Echo the header (XML)
header("Content-Type: text/xml");

// Prepare the XML file
echo '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\r\n";
echo '<GALLERY COLUMNS="5" XPOSITION="30" YPOSITION="30" WIDTH="100" HEIGHT="100">' . "\r\n";
$gallery = '<IMAGE FULL="';

// Get the files from the current directory
if (file_exists ("full_images/"))
{
  if (is_dir ("full_images/"))
  {
    $dh = opendir ("full_images/") or die (" Directory Open failed !");

    // Prepare the images array
    $imgs = array();
    while ($file = readdir ($dh))
    {
      // Only get the files ending with the correct extension
      if ( in_array( substr($file, -3), $extensions ) )
      {
        array_push($imgs, $file);
      }
    }
  closedir ($dh);
  }

  // Sort the array
  sort($imgs);

  foreach ($imgs as $img)
  {
    // Return all images in XML format
    $gallery.= 'full_image/' .$img . '" ' . 'THUMB="';
  }
}
// Get the files from the current directory
if (file_exists ("thumbs/"))
{
  if (is_dir ("thumbs/"))
  {
    $dh = opendir ("thumbs/") or die (" Directory Open failed !");

    // Prepare the images array
    $thumbs = array();
    while ($file = readdir ($dh))
    {
      // Only get the files ending with the correct extension
      if ( in_array( substr($file, -3), $extensions ) )
      {
        array_push($thumbs, $file);
      }
    }
  closedir ($dh);
  }

  // Sort the array
  sort($thumbs);

  foreach ($thumbs as $thumb)
  {
    // Return all images in XML format
    $gallery.= 'thumbs/' . $thumb;
  }
}
$gallery.= '" />';
$gallery.= "\r\n";
echo $gallery;
echo "</GALLERY>";
?>

where am i going wrong? and what is the solution? Thankyou.
Comment: As you can see with the syntax highlighting in your question, you have not written much code but much string. I would say this is the part you ask for "where am I going wrong." The solution is to fix the little error you did. Close the string instead of keeping it open.
Comment: @M8R-1jmw5r Only the syntax highlighter doesn't work...
Comment: If that is not the case, then the error message pretty precisely tells what is going wrong. The solution is to not add an attribute with the same name twice to the same element. XML does not support that.
Comment: @M8R-1jmw5r Exactly, now explain him where his error in the PHP-Code is.
Comment: The error is because of doing multiple things at once. That's complicated and it results in doing more errors.
Comment: What he wants is jumping from top to bottom... so, see my answer.
Comment: @bwoebi: Yes, certainly, however, your answer does not fix the problem to mix that many things. See http://stackoverflow.com/a/16023809/2261774 for an example that modularizes a little more and aims for more code-reuse.
Answer: foreach ($imgs as $img)
{
    // Return all images in XML format
    $gallery.= 'full_image/' .$img . '" ' . 'THUMB="';
}

This code part adds the attribute THUMB as many times as there are keys in $imgs.
You have to always create a new Image child element.
This would be the right code (supposing that thumb and image have the same name)
<?php
// Set which extensions should be approved in the XML file
$extensions = array
(
  'jpg', 'JPG',
  'png', 'PNG',
  'gif', 'GIF',
  'bmp', 'BMP'
);

// Echo the header (XML)
header("Content-Type: text/xml");

// Prepare the XML file
echo '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\r\n";
echo '<GALLERY COLUMNS="5" XPOSITION="30" YPOSITION="30" WIDTH="100" HEIGHT="100">' . "\r\n";
$gallery = '';

// Get the files from the current directory
if (file_exists ("full_images/"))
{
  if (is_dir ("full_images/"))
  {
    $dh = opendir ("full_images/") or die (" Directory Open failed !");

    // Prepare the images array
    $imgs = array();
    while ($file = readdir ($dh))
    {
      // Only get the files ending with the correct extension
      if ( in_array( substr($file, -3), $extensions ) )
      {
        array_push($imgs, $file);
      }
    }
  closedir ($dh);
  }

  // Sort the array
  sort($imgs);
}
// Get the files from the current directory
if (file_exists ("thumbs/"))
{
  if (is_dir ("thumbs/"))
  {
    $dh = opendir ("thumbs/") or die (" Directory Open failed !");

    // Prepare the images array
    $thumbs = array();
    while ($file = readdir ($dh))
    {
      // Only get the files ending with the correct extension
      if ( in_array( substr($file, -3), $extensions ) )
      {
        array_push($thumbs, $file);
      }
    }
  closedir ($dh);
  }

  // Sort the array
  sort($thumbs);

  for ($i = 0; $i < count($imgs); $i++)
  {
    // Return all images in XML format
    $gallery .= '<IMAGE FULL="full_image/'.$imgs[$i].'" THUMB="thumbs/' . $thumbs[$i].'"/>'."\r\n";
  }
}
echo $gallery;
echo "</GALLERY>";
?>

Comment: Well i tried your code and it is showing  label properly now (thankyou) but not spitting out the . I mean it is not echoing $gallery at all. D:
And yes the thumbs and full images have same names.
Comment: ''
So you see..it is not echoing the $gallery at all..
Comment: @MuhammadAli Oh, there was a typo… (`$images` instead of `$imgs`) Should be fixed now.
Comment: Thankyou very much for your patience. It is working perfectly now :)
Answer: Technically your problem is given in the error message. Practically the problem is doing too many things at once. Instead simplify. For example obtaining files from a directory filtered by the extension has been solved already in large parts, you only need to add some little code:
class ListExtensions extends FilterIterator
{
    private $extensions;

    public function __construct($path, array $extensions = array()) {
        $this->extensions = $extensions;
        parent::__construct(new DirectoryIterator($path));
    }

    /**
     * @link http://php.net/manual/en/filteriterator.accept.php
     * @return bool true if the current element is acceptable, otherwise false.
     */
    public function accept() {
        /* @var $file SplFileInfo */
        $file = $this->getInnerIterator()->current();
        return in_array($file->getExtension(), $this->extensions);
    }
}

This class allows you to easily traverse over the files with the extensions you specify. Because it all is encapsulated, your code is much more module. E.g. only in one part you concentrate on doing the directory listing and filtering, not in one part inside of another.
Similar for generating the XML. A library for that already exists, too. It takes care of creating the document, and as it knows XML you can not do that much wrong or even if, you will get noticed much earlier.
$extensions = array
(
    'jpg', 'JPG',
    'png', 'PNG',
    'gif', 'GIF',
    'bmp', 'BMP'
);

$largeFiles = new ListExtensions($pathFullImages, $extensions);
$thumbFiles = new ListExtensions($pathThumbImages, $extensions);

$pairs = new MultipleIterator();
$pairs->attachIterator($largeFiles);
$pairs->attachIterator($thumbFiles);

$gallery = new SimpleXMLElement('<GALLERY COLUMNS="5" XPOSITION="30" YPOSITION="30" WIDTH="100" HEIGHT="100"/>');

foreach ($pairs as $pair)
{
    $image = $gallery->addChild('IMAGE');

    $image['FULL']  = "full_image/$pair[0]";
    $image['THUMB'] = "thumbs/$pair[1]";
}

// Serve XML incl. header
header("Content-Type: text/xml");
$gallery->asXML('php://output');

Comment: Yes, surely this fixes the problem; but I'm really unsure that the TO will understand what you are doing ;) (my code only fixes the problem without rewriting everything...)
Comment: @bwoebi: Well, at least you could create a function that does the reading of a directory into the array. The orignal code has doubled it, that means, you need to maintain the same code two-times while not doing any difference between the two.
Comment: i am completely out of the circle here, i am sorry. It gives meh this error now:
**Fatal error: Class 'ListExtensions' not found in /..../..../public_html/flash_gallery/backhand.php on line 10**

as i mentioned before i am new to web developing specially to php and xml so i would appreciate if you just give me a link that describes this code more briefly? Thankyou.
Comment: @MuhammadAli you naturally must include the code above too (which starts with `class`...) ;)
Comment: i already did that but then it is showing meh just a big pile of errors :o
Comment: Fatal error: Uncaught exception 'RuntimeException' with message 'Directory name must not be empty.' in /.../..../public_html/flash_gallery/backhand.php:8 Stack trace: #0 /.../.../public_html/flash_gallery/backhand.php(8): DirectoryIterator->__construct('') #1 /.../.../public_html/flash_gallery/backhand.php(30): ListExtensions->__construct(NULL, Array) #2 {main} thrown in /..../..../public_html/flash_gallery/backhand.php on line 8

This is the error that it is showing after adding the class
Comment: @MuhammadAli It'd be an idea to define `$pathFileImages` and `$pathThumbImages`


Por que meu append (jQuery) está duplicando elementos?

Question: Bom dia.
Tenho o seguinte código.
// Inclui novo Container com seus elementos
$(document).on('click', 'ul[class^="inpt_"] li button[name="mais"]', function () {
    var i = 0;
    $('#gado ul[class^="inpt_"]').each(function () {
        var alvo = $(this).attr('class');
        alvo = alvo.replace('inpt_', '');
        alvo = parseInt(alvo, 10);
        if (alvo > i) {
            // Serve apenas para ver qual o elemento com maior número
            i = alvo;
        }
    });
    i++;

    $('#gado').append(
            "
" +
            "
" +
            "
<input name='boi[]' type='text' maxlength='50' placeholder='Num. do animal'>
" +
            "
<select class=\"verificar\" name='fk_boi[]'><option value=''>Aguardando...</option></select>
" +
            "
<input class=\"verificar\" type='number' name='peso[]' placeholder='Peso'>
" +
            "
<input class=\"verificar\" type='date' name='d_peso[]'>
" +
            "
<button type='button' name='mais'>+1</button>
" +
            "
<button type='button' name='inpt_" + i + "'>excluir este</button>
" +
            "
" +
            "

" +
            "
"
            );
});

Inicialmente ele cria um único elemento, mas dobra a quantidade a cada vez que a janela de diálogo a que ele está ligado abre. Na segunda vez ele adiciona dois do mesmo, na terceira vez que a janela abre ele cria três/quatro e assim vai.
Se eu limpo o cache do navegador, volta ao normal, mas não posso ficar pedindo isso pro cliente.
Alguma dica do que pode haver de errado?
Answer: Olá,
De uma lida na documentação do jQuery sobre as funções append e html. A função append() adiciona o conteúdo após o último elemento, já a função html() define o conteúdo do elemento como aquele passado por parâmetro. Veja:
var elemento = "teste";

$("body").append(elemento); // teste
$("body").append(elemento); // testeteste
$("body").append(elemento); // testetesteteste

$("body").html(elemento); // teste

Portanto, oque seu código está fazendo é adicionar uma nova div ao final do conteúdo toda vez que vc executa a função. Troque o append por html e seu código irá funcionar.
Espero ter ajudado, abraço!
Comment: Boa tarde, @Lucas Deano. Obrigado por compartilhar seu conhecimento. No meu caso, eu preciso que seja adicionado aquele elemento ao final. O .html não me resolve. Trata-se de um formulário de venda onde o usuário vai acrescentando produtos conforme a necessidade.


Collecting user and node locations seperate or combined?

Question: In my drupal site i like to have the location of users stored as well as the location of nodes.
To store these locations i am using Geofield in combination with adressfield.
Adressfield collects the postalcode. Geofield codes them in points.
Would it be better to store the locations of nodes and users apart from each other or together:
Meaning storing the user locations in one set of fields:
Geo field A Postal adress A
And the nodes in Geo field B and Postal adress B?
Or should i just collect both the users and nodes with one set of fields:
Postal adress A and Geo field A for both users and nodes?
Answer: Other things being equal, it is better to reuse the fields. This simplifies the schema. Neither a postal address field nor a Geo field are likely to change in the future, never mind change differently for nodes and users.


Bind getActivity().findViewById() using Butterknife

Question: Is that possible to do getActivity().findViewById() using @Bind. I want to bind view in another fragment using this way. But so far it can only be done in standard way :
Button mSubmit = (Button) getActivity().findViewById(R.id.btnSubmit)

Comment: You can achieve this using create ViewHolder class. @Azizi
Comment: try this: `Button mSubmit = Butterknife.findById(getActivity, R.id.btnSubmit)`
Answer: I'm not sure I fully understand the question, but it seems like using the two argument form of ButterKnife.bind would work -- pass getActivity() as the 2nd argument.
(I suspect this may have already been answered -- if someone wants to find an existing answer, please do.)


Creating emails while accounting for two first names when using input()

Question: My code below works as long as all of the student's name consists of only two names - ex. Julie Andrews. But, when generating the student's emails, I'm trying to account for the students who have two first names - ex. Mary Jane Stewart. I want it to output something like firstname.lastname@example.com, vs. what my current code will print, which is firstname.lastname@example.com - totally ignoring the student's last name.
After hours of researching Google, I have tried updating my create_emails fx to change my original variable first_last = name.split(" ") to something like first, middle, last = name.split(" ") or first_last = name.split(" ", 2) while also, respectively, updating the line utilizing the attribute .append from its original to student_emails.append(first_last[0][0] + first_last1 + first_last[2]+ last_three_sid + "@gmail.com") or student_emails.append(first[0] + middle[0] + last + last_three_sid + "@gmail.com"). All attempts have obviously returned some form of an error...
The attached Stack Overflow article is the closest thing I could find whose logic might be applicable to what I'm trying to accomplish here, specifically the comment by Manfred, but in reading it, I don't know how to apply what they've done to my program... because I don't quite understand what it is that I'm reading... since I'm such a newbie at all this. I'd appreciate any help you can offer.
student_names = []

def create_names():
  count = 1
  while count <= 5:
    name = input("Enter student name, please. ")
    student_names.append(name)
    count += 1
create_names()

import random

student_ids = []

def create_ids():
  student_id = random.randint(111111,999999)
  return student_id

def create_id_list():
  for name in student_names:
    student_ids.append(create_ids())
create_id_list()

student_emails = []

def create_emails():
  for name in student_names:
    first_last = name.split(" ")
    sid = str(student_ids[student_names.index(name)])
    len_sid = len(sid)
    last_three_sid = sid[len_sid-3:len_sid]
    student_emails.append(first_last[0][0] + first_last[1] + last_three_sid + "@gmail.com") #ignores last index if one is provided.

create_emails()

def student_info():
  for name in student_names:
    name_pos = student_names.index(name)
    print("\n" + "name: " + name)
    print("id: " + str(student_ids[name_pos]))
    print("email: " + student_emails[name_pos])
student_info()

Finding and first and middle initials in a list of names in python
Comment: Why don't you simply do `names = name.split(" ")` which will result in `names` being a list and then you can simply create email by `"_".join(names) + "_" + str(last_three_sid)`. This should account for however many names they have.
Comment: I'm afraid I don't quite understand your statement "create email by "_".join(names) + "_" + str(last_three_sid)." Where exactly am I putting that?
Comment: It goes in the `create_emails` function where you're appending a new email to the list of emails.
Comment: I updated my ' student_emails.append(first_last[0][0] + first_last[1] + last_three_sid + "@gmail.com"' to be 'student_emails.join(names) + str(last_three_sid) + "@gmail.com"' and got the AttributeError: 'list' object has no attribute 'join.' And, I changed my variable 'first_last' > 'names,' as well.
Answer: You could do it like this I guess:
student_names = []

def create_names():
    count = 1
    while count <= 5:
        name = input("Enter student name, please. ")
        student_names.append(name)
        count += 1
create_names()

import random

student_ids = []

def create_ids():
    student_id = random.randint(111111,999999)
    return student_id

def create_id_list():
    for name in student_names:
        student_ids.append(create_ids())
create_id_list()

student_emails = []

def create_emails():
    for name in student_names:
        email_name = ""
        first_last = name.split(" ")
        for i, v in enumerate(first_last):
            if i > len(first_last)-2:
                break
            email_name+=v[0]
        email_name = email_name+first_last[-1]
        sid = str(student_ids[student_names.index(name)])
        len_sid = len(sid)
        last_three_sid = sid[len_sid-3:len_sid]
        student_emails.append(email_name + last_three_sid + "@gmail.com") #ignores last index if one is provided.

create_emails()

def student_info():
    for name in student_names:
        name_pos = student_names.index(name)
        print("\n" + "name: " + name)
        print("id: " + str(student_ids[name_pos]))
        print("email: " + student_emails[name_pos])
student_info()

Result:
Enter student name, please. Julie Andrews
Enter student name, please. Mary Jane Stewart
Enter student name, please. Jack Hendricks
Enter student name, please. Maria Basset Juliett
Enter student name, please. Marco Hansen

name: Julie Andrews
id: 742536
email: firstname.lastname@example.com

name: Mary Jane Stewart
id: 823274
email: email@example.com

name: Jack Hendricks
id: 590875
email: firstname.lastname@example.com

name: Maria Basset Juliett
id: 982168
email: email@example.com

name: Marco Hansen
id: 671240
email: firstname.lastname@example.com

Comment: LOL. Yes, I'm actually filipino. Trying to get into the Software Coding world.
Comment: Wow! Thank you! It's beautiful. Now I'll have something to study tomorrow, to try to understand what's exactly happening within your new changes. :) "v in enumerate" is new to me, and my brain is questioning what's happening in that if statement you made.... Anyway, thank you so much!
Comment: @RenelynCruz No problem, feel free to accept my answer. Also your name reminds me of someone from the Philippines, my wife is from the Philippines and your names seem a bit the same. :-)
Answer: The code is too redundant and could be implemented with some simpler structures.

name construction can use split combined with join function
storage can also use dictionaries to store multiple information about the same object, compared to multiple lists so more concise and efficient
The code itself is not a big problem, mainly the syntax structure requires more skilled,let's encourage each other in our endeavours
try this:

import random

info = []

# You can use for loop if you already know how many times it will loop
for i in range(5):
    name = input("Enter student name, please:")  # get name
    student_id = random.randint(111111, 999999)  # get id
    name_structure = name.split()
    email = "{firstname.lastname@example.com".format(
        name_abbr="".join([item[0] for item in name_structure[:-1]]),   # Generate initials
        last_name=name_structure[-1],   # Generate the last part of the name
        sid=str(student_id)[-3:]    # Generate the id in the mailbox
    )
    info.append({"name": name, "id": student_id, "email": email})       # Store to the list, or print directly

# Print Information
for item in info:
    print("name:", item["name"])
    print("id:", item["id"])
    print("email:", item["email"])
    print()

Comment: I do agree that this structure is a lot simpler, but as someone who is really new to coding, there are a lot of parts in what you wrote that I would need some help in understanding... But thank you for giving me something new to study. :)
Comment: I'm sorry maybe I didn't write it concisely enough, but actually the contents inside are all basic python modules, including list, dictionary, string, format, join, random, input, split, and I'm also a learner
Comment: I hope we can we friends who learn together! :) Of those, I'm not overly familiar with dictionary & join. I've heard of format... but I've yet to totally grasp exactly how it works.
Comment: Of course, feel free to exchange and learn
Comment: So, with the help of Thonny, I now understand this code better. But, I was hoping you could clarify for me why you chose to use -1 in the variables for name_abbr and last_name, instead of +1. They both accomplish the same result... at least, from what I understand.

Whereas, with the variable sid, I could understand using -3, as I'm seeing that as telling the computer to "drop the first 3 numbers, print from there to the end of the string.
Comment: I don't quite understand the naming style in your country, so I just follow the example of your title to understand the name composition
Comment: for example, the name consists of three parts, like this: Mary Jane Stewart, after using the split method name_structure = ["Mary", "Jane", "Stewart"], I divide the email into three parts: " {firstname.lastname@example.com"
Comment: name_abbr is the abbreviated name with the first letter of the name except the last name, last_name is the last name of the name, sid is the last three digits of student_id
Comment: so in the construction of name_abbr abbr is used when constructing name_abbr[:-1], which means that it does not contain the last item, and [-1] is used when constructing last_name, which means that only the last item is obtained, and ***List Comprehensions*** is used in the content: [item[0] for item in name_structure[:-1]], which can be understood, which means that using name_structure[:-1], which means building a new list with the first element of each data item in name_structure[:-1]


How can I transfer SVN repositories from VisualSVN Server (Windows) to Apache SVN (Linux) correctly?

Question: My goal is to transfer old SVN repositories from a Windows VisualSVN server to a Linux Apache SVN server. The first step was to make a dump of all the repositories with the svnadmin dump command.  After that I loaded those dumps into my Linux server. There were no errors when I imported the repositories. However, for some files I get a 500 internal server error when committing changes in them.
To check what is wrong, I opened some of the files that generated the error into my web browser. I found out that several last lines from these files are corrupted. There is no data lost, but there are strange characters at the end of the file. They are displayed by: "???" in my web browser.
I tried to do multiple exports, but all of the exports will cause the same problem. Is it possible to correct the repository or dump? Do you have any idea how I can prevent this from happening?
Comment: How did you import the repositories? If you run a checkout from them locally without using the web server (use a `file:///` checkout URL), does it work correctly?
Answer:
AFAICR, there was some changes in the repository's structure|data|storage some versions ago: it will be more bullet-proof, if Subversion version under the hood for VisualSVN Server and apache's side will be the same (i.e upgrade VisualSVN Server, if it needed)
From FS-view, repository in VisualSVN Server and Linux's Apache are the same - just directories with files and some not-repository files. Thus, in easiest case, you can just copy tree from RepoRoot into new server (fix owner and permissions according to new OS reqirements), add (old) passwd-file (if needed), placed outside repo-tree and (old) authz-file (if needed), migrate svn-related part from httpd.conf of VisualSVN Server to the new environment (with applying all needed changes, mostly path-related) and have repositories at the new location

PS: I performed such lazy "copy-pase" migrations without big headache

500 internal server error when committing

can have two main reasons: not migrated userbase and|or forgotten ACLs in (probably missing or empty) authz file - dumps of repos doesn't transfer these files


Interpreting SPSS output for mixed linear models - there are zero values in estimates of fixed effect

Question: I need help in interpreting the output for mixed linear model.The estimates of fixed effect shows the parameters of my level 1 predictor variables, but there are some zero values, and i'm not sure why or how to interpret it. Could it be due to lack of data points in ITEM16? Here's a snapshot of the output..

Parameter   Estimate    Std. Error  df  t   Sig.    95% Confidence Interval
                        Lower Bound Upper Bound
Intercept   .184285 .016181 40.209  11.389  .000    .151588 .216982
[ITEM=1]    -.033855    .008585 29812.714   -3.944  .000    -.050681    -.017029
[ITEM=2]    -.020130    .008915 29812.824   -2.258  .024    -.037603    -.002657
[ITEM=3]    -.064286    .008792 29814.834   -7.312  .000    -.081519    -.047053
[ITEM=4]    -.077827    .009920 29817.388   -7.846  .000    -.097270    -.058384
[ITEM=5]    -.040264    .011120 29804.602   -3.621  .000    -.062061    -.018468
[ITEM=6]    -.031131    .008790 29815.299   -3.542  .000    -.048359    -.013903
[ITEM=7]    -.037671    .010160 29809.248   -3.708  .000    -.057585    -.017757
[ITEM=8]    -.023466    .010947 29806.310   -2.143  .032    -.044923    -.002008
[ITEMC=9]   -.025810    .011665 29807.427   -2.213  .027    -.048673    -.002947
[ITEM=10]   -.004509    .011803 29805.702   -.382   .702    -.027643    .018626
[ITEM=11]   -.073471    .009903 29816.904   -7.419  .000    -.092881    -.054061
[ITEM=12]   -.059247    .010095 29806.327   -5.869  .000    -.079033    -.039460
[ITEM=13]   -.038357    .014345 29810.276   -2.674  .008    -.066474    -.010240
[ITEM=14]   -.032134    .013288 29807.876   -2.418  .016    -.058178    -.006089
[ITEM=15]   -.046073    .010736 29808.929   -4.291  .000    -.067116    -.025029
[ITEM=16]   0   0   .   .   .   .   .
[...}.....
...
...

Thanks!
Answer: It looks like ITEM is a categorical factor variable, in which case the model is parameterized with a dummy or indicator variable for each distinct value of it, and if there is a fixed intercept in the model, the last one of these will be redundant or linearly dependent on the prior ones. That gets aliased to 0 in the formation of the generalized inverse formed during estimation. This is to be expected and does not indicate a problem.
If you have additional factor variables you'll see similar situations for them, and for interactions involving factors you'll generally see multiple parameters aliased to 0.


ReadAllLines not working and it won't tell me why

Question: I've finally gotten around to learning Java and I'm trying to write an interpreter for an esolang. I looked up a few tutorials and wrote this code.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class NDBall {
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) {
        String input = scanner.nextLine();
        Path path = Paths.get(input);
        List<String> code = new ArrayList<String>();
        code = Files.readAllLines(path);
    }
}

However, the readAllLines function keeps giving me an error, and I don't know why. It won't tell me what the error is, and everything else seems fine. I'm doing it exactly as the tutorials I looked up told me.
Is there some mistake I made?
Comment: Wrap the call to Files.readAllLines() in a try-catch block and print the error message to the console. This way, you can see the exact error message that Files.readAllLines() is throwing and get a better idea of what the issue might be.
Comment: *keeps giving me an error, and I don't know why. It won't tell me what the error is,* - this just does not make sense.  Is there some output, if so please post it as part of your question.
Comment: @coting So... it works now. It only works if I put it in a try-catch. The mystery error is gone.

I guess I have a lot to learn about Java. Thanks for your help.
Answer: The below code will work for you. have hard coded the path so escape characters are taken care of:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Solution {

    public static Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) {
        String input = scanner.nextLine();
        Path path = Paths.get("C:\\Users\\xyz\\Desktop\\imp.txt");
        List<String> code = new ArrayList<String>();
        try {
            code = Files.readAllLines(path, StandardCharsets.UTF_8);
            code.stream().forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Rule Rewrite Alterando diretórios dos scripts

Question: Estou com o seguinte problema, ao utilizar o rule abaixo meu diretório padrão é alterado e meus scripts js e arquivos css param de funcionar.
<rule name="Produtos Detalhe">
   <match url="^(produto)\/(.*)\/(.*)\/?$"  />
   <action type="Rewrite" url="/Produto/Detalhe?id={R:3}"  />
</rule>

Exemplo, este código:
<link href="@Href("~/Content/Site/css/bootstrap.min.css")" rel="stylesheet">

Está ficando assim depois de renderizado:
<link href="/produto/Content/Site/css/bootstrap.min.css" rel="stylesheet">

Gostaria que ficasse:
<link href="/Content/Site/css/bootstrap.min.css" rel="stylesheet">

Comment: Já tentou tirar o til dessa instrução? `@Href("~/Content/Site/css/bootstrap.min.css")`
Answer: É simples.
Seu rule está como regra geral, na base, o diretório produto.
como você mesmo pode ver, tudo e qualquer url que você usar terá automaticamente sempre isso.
Tenta criar uma regra universal.
E com os dados coletados você tenta saber onde está indo no sistema, se for para produtos você ai sim, usa o dir /produtos e caso contrário /.
Fiz isso no apache mas em asp não sei.
Estou tentado só te dar uma luz.
Tenta de deixar assim: ^(.*)\/(.*)\/?$ e depois você cria regras de código a parte para saber se você está no dir produtos.


Calculate a vector that is perpendicular to Oy axis.

Question: Find a vector perpendicular to $Oy$ axis. Knowing that $v\cdot v_1=8$ and $v\cdot v_2=-3$, where $v_1=(3,1,-2)$ and $v_2=(-1,1,1)$
Comment: Are you aware of the practice of accepting answers to your question? (See [this meta question](http://meta.math.stackexchange.com/questions/3399).)
Comment: Yes, but I don´t understand your commentaire. Was I rude with someone here. If I was, I´m sorry about it.
Answer: ley $v=(x,y,z)$ perpendicular to $OY$ axis means that
   $v*(0,1,0)=0$
$v*v_1=3*x+1*y-2*z=8$
$v*v_2=-1*x+1*y+1*z=-3$
$v*(0,1,0)=0 -->y=0$
so $3*x-2*z=8$
$-x+z=-3$   from second   $z=-3+x$ put into first one
$3*x-2*(-3+x)=8$
 $x=2$  and $z=-1$ so we have
$v=(2,0,-1)$
Comment: my friend i am happy that  could help you,just please consider advices from other people and accept their answers,it is rule of this website  ok?it is friendly advice
Comment: Thanks dato. I will consider this in the future.


How to print some inputs from user in python?

Question: I am learning python. I tried to the following code but it did not work.
How can I print inputs from a user repeatedly in python?
while ( value = input() ):
    print(value)

Thank you very much.
Comment: `=` is an assignment operator which can't be used in `while` loop, it needs a boolean condition
Comment: python is not a C language to assign values to variables in condition
Answer: while true is an infinite loop, therefore it will always take an input and print the output. value stores the value of a user input, and print prints that value after. This will always repeat.
while True:
    value = input()
    print(value)

Answer: Use this code
while 1:
    print(input())

If you want to stop taking inputs, use a break with or without condition.
Answer: Assignments within loops don't fly in python. Unlike other languages like C/Java, the assignment (=) is not an operator with a return value.
You will need something along the lines of:
while True:
    value = input()
    print(value)


Facets rendering on all pages irrespective of value dynamicaaly form contextual filter in views

Question: I m trying to add facets using facets module in drupal 8. i have created listing of all products using views page. on listing page, facets are showing properly as per brand information added from admin panel.
All products listing Page:

but when i go to the detail page of every individual product,facet blcok show only single value of that brand only. check below image for more reference:

Here on detail page , i want to show complete list of facets as shown in first image. how to do that??? any idea??
Answer: I believe, this is the default behaviour, where the facets are filtered based on the result set.
What you want may not be achievable OOB.
But this is not a bug, it is a correctly working behaviour.
Comment: Thanks for your reply..do you know how make that checkbox selectable when we land to details page of a brand as mentioned in second image..
Comment: I would recommend linking to the second page. Making the checkbox checked, wont be easy.
Facets read GET params, and check the checkboxes accordingly.


Change apollo local state whenever a remote mutation is called

Question: I'm studying the usage of Apollo Client Local State Management, and came across this issue: I want to change my local state whenever a specific mutation is called.
From what I could read the only way would be writing to the cache or calling a @client mutation in every place that calls the remote mutation.
Is there a way to do that in one place and only call the remote mutation in all places?
Answer: If anyone gets here I solved by creating a local mutation that calls the server mutation and does whatever it wants as well:
resolver(parent, args, context) {
  // do anything else
  return context.client.mutate(...);
}


How do I print custom user fields?

Question: I am trying to customize the authored by information for all of my nodes that prints the User First and Last Name, which are custom fields on the User Profile.

I copied the node.html.twig template into my theme
I added the following code to load the user information in my preprocess function
function blend_preprocess_node(&$variables) {

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// get field data from that user
$firstname = $user->get('field_first_name')->value;
$lastname = $user->get('field_last_name')->value;

// some default getters include
$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;

}

I added this code to node.html.twig

{{ title_prefix }}   {% if not page %}

  {{ label }}

   {% endif %}   {{ title_suffix }}

{% if display_submitted %}

      {{ content.field_services }}

  {{ author_picture }}

    {% trans %}Submitted by {{ firstname }} {{ lastname }} on {{ date|date("m/d/Y") }}{% endtrans %}
    {{ metadata }}

   {% endif %}
{# We hide the comments and links now so that we can render them later. #}

{{ content|without('comment', 'links', 'field_tags', 'field_services') }}

{% if content.field_tags|length and not is_front %}
{{ content.field_tags }}   {% endif %}
{{ content.links }}   {{ content.comment }}

How do I make variables (mostly fields) from different entities available to print in different template files?
Answer: Assuming this information is from the user profile.
You could do the following
blend.theme
function blend_preprocess_node(&$variables){
    $node = $variables['node'];
    $variables['firstname'] = $node->getOwner()->field_first_name->value;
    $variables['lastname'] = $node->getOwner()->field_last_name->value;
}

From there you can use {{ firstname }} and {{lastname}} anywhere in your template.
Comment: Thanks for the quick reply but your solution just gave me white screen. Is there another example on how I would print information from the node Author?
Comment: Oopss.. the `$node = $variables['node'];` need to be inside of the preprocess function. Sorry, I have fixed in my answer.
Comment: You rock sir!!!

For future reference.  When looking to get access variables from other entities, where would I search in the D8 API for the correct functions?
Comment: "D8 API for the correct functions"... hahaha... I do not know. I know this because I'm working on contrib theme. And I ask a similar question before so I have plenty of examples in my working theme.
Comment: hahah thanks sir!  that is awesome :) Well I just added yours to my Dropbucket.  Its a cool place for Drupal snippets http://dropbucket.org/node/7235
Comment: @kaleemclarkson if you add use type hinting then your IDE will be able to help you guess the available methods on an object.
Comment: @Eyal

I mostly use sublime text 2. Is there a specific plugin that I need to make it work more like an traditional IDE?
Comment: @kaleemclarkson I don't know. I only use sublime for small projects. You should upgrade to an IDE.
Comment: Does someone know how to get the isolated path to th profile? In order to fill an  to wrap around the name. Would $node->getOwner()->link_path->value; do the trick?
Answer: The accepted answer didn't work for me on Drupal version 8.3.4 and more. Actually the $node = $variables['node'] didn't work so I found out the following method to make it work.
On the .theme file (in this example blend.theme), I used the following code.
function blend_preprocess_node(&$variables){
  $node = \Drupal::routeMatch()->getParameter('node');
  $variables['firstname'] = $node->getOwner()->field_first_name->value;
  $variables['lastname'] = $node->getOwner()->field_last_name->value;
}

How do I print custom user fields?


Why $\int_0^{\pi } {\left(\cos \;t\right)}^{3\ldotp 5}\;\mathrm{dt}=2\int_0^{\frac{\pi }{2}} {\left(\cos \;t\right)}^{3\ldotp 5}\;\mathrm{dt}$?

Question: I can't figure out how this definite integral is transformed like this:
$$\int_0^{\pi } {\left(\cos \;t\right)}^{3\ldotp 5} \;\mathrm{dt}=2\int_0^{\frac{\pi }{2}} {\left(\cos \;t\right)}^{3\ldotp 5} \;\mathrm{dt}$$
I've been studying the integration of even or periodic functions, but can't find anything useful about this particular example.
Any clue?
Thanks in advance!
Comment: You can't integrate the left-hand side. You have negative values for $t\in(\pi/2,\pi)$. The result becomes true if the range is instead $-\pi/2$ to $\pi/2$.
Comment: @Clayton, you're right. Thanks.
Comment: That's a weird one all right!  I'm not sure what to do with the square roots in a symmetry argument here.
Comment: $\sin t$ is symmetrical across $t = \pi/2$. $\cos t$ is symmetrical across $t = 0$ or $t = \pi$
Comment: Perhaps its was supposed to be $|\cos t|$ rather than $(\cos t)$
Comment: So, what is the integral on the left really supposed to be?
Answer: Hint
$$\int_0^{2a}f(x)\ dx=\int_0^af(x)\ dx+\int_a^{2a}f(x)\ dx$$
For the last integral, set $2a-x=y$
Can you recognise $f(x), a$ here?
Comment: Thanks. I think I got it: $\int_0^{\pi } {\left(\cos \;t\right)}^{3\ldotp 5} \;\mathrm{dt}=\int_0^{2\left(\frac{\pi }{2}\right)} {\left(\cos \;t\right)}^{3\ldotp 5} \;\mathrm{dt}=2\int_0^{\frac{\pi }{2}} {\left(\cos \;t\right)}^{3\ldotp 5} \;\mathrm{dt}$


How to call jquery function?

Question: i have this jquery function :
<code>$("#settingsNavTabsIntegrationContent").on('change', 'input[type="checkbox"]', function () {
    ...
});
</code>
and then i want to call the function above on my new function as below :
<code>$("#settingsNavTabsIntegrationContent").on('click', '.sourceFieldRecordUL', function () {
   // call the function above
});
</code>
the first function is used when i 'click' the box/text in the choice in dropdown of checkbox options.
the second function is for when i click on the area around the text/checkbox.
how is the correct way to call it? or any suggestion on how to achieve this?
Comment: Use : `$("#settingsNavTabsIntegrationContent input[type="checkbox"]").trigger("change")`
Comment: Assign function in a variable and use anywhere you want
Comment: @Swati thanks for your advice, i will try using it.
Answer: Assign function in a variable and use anywhere you want. Try the below code for example:
<code>const myFunc = function () {
   ...
}

$("#settingsNavTabsIntegrationContent").on('change', 'input[type="checkbox"]', myFunc);

$("#settingsNavTabsIntegrationContent").on('click', '.sourceFieldRecordUL', function () {
   // call the function above
   myFunc();
});
</code>
Checkout this blog for reference: https://dmitripavlutin.com/6-ways-to-declare-javascript-functions
Comment: Alternative syntax is:  `function myFunc() { ... }`  then call it the same way `myFunc()` or directly as event handler as in the examples above
Comment: Yes that's also correct. I'm more of a typescript user so I'm more into arrow functions that's why this syntax.
Comment: @BeshambherChaukhwan thanks for your advice, i will try using it.
Comment: @iqbal does this answer your question?
Comment: @BeshambherChaukhwan yes, more or less. got the idea of the syntax.
Answer: Not sure, what you really want to know, but let me try to give you a possible answers:-

If your question is related to registering an event then the best way to use Jquery 'trigger' method to attach events.
If you question attaching multiple events on the same id, then I would suggest you separate your IDs and events else it could give you a bubble-up events issue.
Answer: There is no issue in both the call, but technically we should use the change for the checkbox. Whenever you will change an event you will get the real value of that input using event object
<code>$("#settingsNavTabsIntegrationContent").on('change', '.sourceFieldRecordUL', function (e)
{
   // call the function above
});
</code>
However, in the above function, you might face an issue if your content is loading after registration of event or dynamic content
Suggested approach is
<code>$(document).on('change', '#settingsNavTabsIntegrationContent', function ()
{
   // call the function above
})
</code>
This function will not fail if your content is loading dynamically or after the script load.
Comment: Hi, the goal is that i want to add a function when i CLICK on the AREA around TEXT/CHECKBOX, so it may appear as the same -or so- function as CLICK at /CHANGEd value of TEXT/CHECKBOX.

How to call jquery function?


Finding the co-efficients of this power series

Question: I am required to find the co-efficients of this power series: $2x\ln(1+2x)$
I approached the problem by considering the $\ln(1+2x)$ part as the integral of $2/(1+2x)$ and applied the geometric series to this. Factoring the $2$ on the numerator outside this expression gives us $4x$ on the outside (after multiplying it with $2x$).
I need to get the first 5 nonzero co-efficients, and what I got is: $0, 4, -8, 16$ and $-32$. Only $0$ is right, according to the online portal.
How do I approach this problem?
Comment: You could also calculate the 2x and ln part separately and than multiply
Comment: You didn't integrate. Your mistake would have been clearer if you had written out what you tried in more detail.
Comment: You should have $ \ \ln (1+2x) \ = \sum_{n=1}^{\infty} \ (-1)^{n-1} \ \frac{(2x)^n}{n} \ $ as an intermediate result.  I think you may also have an excess "2" floating around in there...
Answer: $\log(1+2x)=\sum_{n=1}^{\infty} \frac{(-1)^{n+1}(2x)^n}{n}$ implies that
$$2x\log(1+2x)=\sum_{n=1}^{\infty} \frac{(-2x)^{n+1} }{n}=\sum_{n=2}^{\infty} \frac{(-2x)^{n} }{n-1}$$
Comment: $ =\sum_{n=2}^{\infty} (-2)^n x^n/(n-1)$ to make it explicit.
Comment: @martycohen That is correct also.  I have added that equality per your suggestion.
Answer: I am not sure what you are talking about in the second paragraph. However since you are doing it with geometric series, then you know that $\frac{1}{1+2x} = \sum^{\infty}_{n=1}(-2x)^{n-1}$. Then you just integrate and multiply by $4x$, which gives $2x\ln(1+2x) = 4x \sum^{\infty}_{n=1} \frac{(-2)^{n-1}x^{n}}{n} = \sum^{\infty}_{n=1}\frac{(-2x)^{n+1}}{n}$.
Comment: Thanks, that did help. I had made an error in my calculations, but seeing the summation form helped me do it again correctly.