Shibboleth SP - Signing and Encryption Key

Question: I have a Shibboleth SP installed on Server 2012 R2. I tried to submit the metadata to be imported into the IDP and was told that without having the signing or encryption key, they won't be able to send the SP any assertions.
From what I've found on this, Shibboleth SP has the key to use included in the default installation. I believe that is the sp-cert.pem and the sp-key.pem included in the C:\opt\shibboleth-sp\etc\shibboleth folder.
I'm not sure how to reference it in the Shibboleth2.xml file either.
Here is my shibboleth2.xml as of right now:
<SPConfig xmlns="urn:mace:shibboleth:2.0:native:sp:config"
xmlns:conf="urn:mace:shibboleth:2.0:native:sp:config"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
logger="syslog.logger" clockSkew="180">

<OutOfProcess logger="shibd.logger">

</OutOfProcess>

<InProcess logger="native.logger">
    <ISAPI normalizeRequest="true">

        <Site id="1" name="sp-example.com"/>
    </ISAPI>
</InProcess>

<StorageService type="Memory" id="mem" cleanupInterval="900"/>
<SessionCache type="StorageService" StorageService="mem" cacheTimeout="3600" inprocTimeout="900" cleanupInterval="900"/>
<ReplayCache StorageService="mem"/>
<ArtifactMap artifactTTL="180"/>

<RequestMapper type="Native">
    <RequestMap applicationId="default">
        <Host name="sp-example.com" authType="shibboleth" requireSession="true"/>

    </RequestMap>
</RequestMapper>

<ApplicationDefaults id="default" policyId="default"
    entityID="urn:mace:university.edu:shibboleth:test:sp:university:administrative:cscn:sp-example.com"
    homeURL="https://sp-example.com"
    REMOTE_USER="eppn persistent-id targeted-id"
    signing="false" encryption="false"
    >

    <Sessions lifetime="28800" timeout="3600" checkAddress="false"
        handlerURL="/Shibboleth.sso" handlerSSL="true"
        exportLocation="http://sp-example.com/Shibboleth.sso/GetAssertion" exportACL="220.127.116.11"
        idpHistory="false" idpHistoryDays="7" cookieProps="https" >

        <SessionInitiator type="Chaining" Location="/Login" isDefault="true" id="Intranet"
                relayState="cookie" entityID="urn:mace:university.edu:shibboleth:test:idp:university:administrative:cscn:idp-test.university.edu">
            <SessionInitiator type="SAML2" defaultACSIndex="1" acsByIndex="false" template="bindingTemplate.html"/>
            <SessionInitiator type="Shib1" defaultACSIndex="5"/>
        </SessionInitiator>

        <md:AssertionConsumerService Location="/SAML2/POST" index="1"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"/>
        <md:AssertionConsumerService Location="/SAML2/POST-SimpleSign" index="2"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign"/>
        <md:AssertionConsumerService Location="/SAML2/Artifact" index="3"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"/>
        <md:AssertionConsumerService Location="/SAML2/ECP" index="4"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:PAOS"/>
        <md:AssertionConsumerService Location="/SAML/POST" index="5"
            Binding="urn:oasis:names:tc:SAML:1.0:profiles:browser-post"/>
        <md:AssertionConsumerService Location="/SAML/Artifact" index="6"
            Binding="urn:oasis:names:tc:SAML:1.0:profiles:artifact-01"/>

        <LogoutInitiator type="Chaining" Location="/Logout" relayState="cookie">
            <LogoutInitiator type="SAML2" template="bindingTemplate.html"/>
            <LogoutInitiator type="Local"/>
        </LogoutInitiator>

        <md:SingleLogoutService Location="/SLO/SOAP"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"/>
        <md:SingleLogoutService Location="/SLO/Redirect" conf:template="bindingTemplate.html"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"/>
        <md:SingleLogoutService Location="/SLO/POST" conf:template="bindingTemplate.html"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"/>
        <md:SingleLogoutService Location="/SLO/Artifact" conf:template="bindingTemplate.html"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"/>

        <md:ManageNameIDService Location="/NIM/SOAP"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"/>
        <md:ManageNameIDService Location="/NIM/Redirect" conf:template="bindingTemplate.html"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"/>
        <md:ManageNameIDService Location="/NIM/POST" conf:template="bindingTemplate.html"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"/>
        <md:ManageNameIDService Location="/NIM/Artifact" conf:template="bindingTemplate.html"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"/>

        <md:ArtifactResolutionService Location="/Artifact/SOAP" index="1"
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"/>

        <Handler type="MetadataGenerator" Location="/Metadata" signing="false"/>

        <Handler type="Status" Location="/Status" acl="127.0.0.1"/>

        <Handler type="Session" Location="/Session" showAttributeValues="false"/>

    </Sessions>

    <Errors session="sessionError.html"
        metadata="metadataError.html"
        access="accessError.html"
        ssl="sslError.html"
        localLogout="localLogout.html"
        globalLogout="globalLogout.html"
        supportContact="root@localhost"
        logoLocation="/shibboleth-sp/logo.jpg"
        styleSheet="/shibboleth-sp/main.css"/>

    <MetadataProvider type="Chaining">

        <MetadataProvider type="XML" uri="https://idp-test.university.edu/universityfed-test-metadata-signed.xml"
             backingFilePath="C:\opt\shibboleth-sp\etc\shibboleth\universityfed-test-metadata-signed.xml" reloadInterval="7200">
        </MetadataProvider>
    </MetadataProvider>

    <TrustEngine type="Chaining">
        <TrustEngine type="ExplicitKey"/>
        <TrustEngine type="PKIX"/>
    </TrustEngine>

    <AttributeExtractor type="XML" path="attribute-map.xml"/>

    <AttributeResolver type="Query"/>

    <AttributeFilter type="XML" path="attribute-policy.xml"/>

</ApplicationDefaults>

<SecurityPolicies>

    <Policy id="default" validate="false">
        <Rule type="MessageFlow" checkReplay="true" expires="60"/>
        <Rule type="ClientCertAuth" errorFatal="true"/>
        <Rule type="XMLSigning" errorFatal="true"/>
        <Rule type="SimpleSigning" errorFatal="true"/>
    </Policy>
</SecurityPolicies>

According to an email I recieved, I need to include <md:KeyDescriptor use="encryption"> and <md:KeyDescriptor use="signing">
From what I found online, it should be something similar to:
<md:SPSSODescriptor>
<md:KeyDescriptor>
    <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:X509Data>
            <ds:X509Certificate>
                hash found in sp-cert.pem file
            </ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</md:KeyDescriptor>

I don't know where I should be putting this in the Shibboleth.xml file.
Can anybody help to get me on the right track? I have been through a decent amount of documentation and guides from different institutions, but haven't found any direction.
Answer: The answer was to add the following line to the Shibboleth2.xml (in the ApplicationDefaults section):
<CredentialResolver type="File" key="sp-key.pem" certificate="sp-cert.pem"/>

sp-key.pem and sp-cert.pem are included in the Shibboleth installation.  They are located in the same folder as the Shibboleth2.xml file.
I also changed the line:
<ApplicationDefaults id="default" policyId="default" entityID="urn:mace:university.edu:shibboleth:test:sp:university:administrative:cscn:sp-example.com"
    homeURL="https://sp-example.com"
    REMOTE_USER="eppn persistent-id targeted-id"
    signing="false" encryption="false"
    >

To:
<ApplicationDefaults id="default" policyId="default"
 entityID="urn:mace:university.edu:shibboleth:test:sp:university:administrative:cscn:sp-example.com"
    homeURL="https://sp-example.com"
    REMOTE_USER="eppn persistent-id targeted-id"
    signing="true" encryption="true"
    >

When the line is added, the Metadata has entries for for the certs and needs to be reimported to the IDP.


How to add background color for ODD and EVEN rows in PHP?

Question: I want to add background color for each odd rows(#e5e8e8) and even rows (#b9b8bb) in CSS.
for ($i = 2; $i <= $arrayCount; $i++) {

        $_SESSION["a"] = trim($allDataInSheet[$i]["A"]);

        $_SESSION["b"] = trim($allDataInSheet[$i]["B"]);

        $_SESSION["c"] = trim($allDataInSheet[$i]["C"]);

        $_SESSION["d"] = trim($allDataInSheet[$i]["D"]);

        $_SESSION["e"] = trim($allDataInSheet[$i]["E"]);

        $_SESSION["f"] = trim($allDataInSheet[$i]["F"]);

        $_SESSION["g"] = trim($allDataInSheet[$i]["G"]);

                       echo ' ';
                       echo ' ';
                        echo '
';
                            echo '';
                                echo '';
                           echo ' 	';

                            echo '';
                                echo '
';
                                    echo '
';
                                        echo '	';
                                   echo '
';
                                    echo '
';

                                        echo '';
                                            echo '';

                                                 echo $_SESSION["a"];
                                            echo '';
                                       echo ' 	';

                                       echo ' ';

                                        echo '	';
                                    echo '
';
                                    echo '
';
                                        echo '	';
                                   echo '
';
                                echo '
';
                            echo '	';

                           echo ' ';
                                echo '';
                            echo '	';
                            echo '';
                                echo '';
                            echo '	';
                            echo '';
                                echo '
';
                                    echo '
';
                                        echo '	';
                                   echo '
';
                                    echo '
';
                                        echo '';
                                            echo '';
                                              echo $_SESSION["b"];

                                            echo '';
                                        echo '	';
                                        echo '';
                                            echo '';
                                              echo $_SESSION["c"];
                                            echo '';
                                        echo '	';
                                   echo '
';
                                    echo '
';
                                        echo '	';
                                    echo '
';
                                echo '
';
                            echo '	';
                            echo '';
                                echo '';
                            echo '	';
                            echo '';
                                echo '';
                            echo '	';
                            echo '';
                                echo '
';
                                    echo '
';
                                        echo '	';
                                   echo '
';
                                    echo '
';
                                        echo '';
                                            echo '';
                                            echo $_SESSION["d"];

                                            echo '';
                                       echo '	';
                                        echo '';
                                            echo '';
                                             echo $_SESSION["e"];
                                           echo '';
                                        echo '	';
                                    echo '
';
                                    echo '
';
                                        echo '	';
                                    echo '
';
                                echo '
';
                            echo '	';
                            echo '';
                                echo '';
                            echo '	';

                            echo '';
                                echo '';
                            echo '	';
                            echo '';
                                echo '
';
                                    echo '
';
                                        echo '	';
                                    echo '
';
                                    echo '
';
                                        echo '';
                                            echo '';
                                             echo $_SESSION["f"];

                                            echo '';
                                       echo ' 	';
                                        echo '';
                                            echo '';
                                               echo $_SESSION["g"];
                                           echo ' ';
                                        echo '	';
                                   echo '
';
                                   echo '
';
                                        echo '	';
                                   echo '
';
                                echo '
';
                           echo ' 	';
                            echo '';
                                echo '';
                            echo '	';

                        echo '
';

                        echo '';

   }

Here I want to add background color for each odd rows(#e5e8e8) and even rows (#b9b8bb) in PHP dynamically to this row which I wrote inside the for loop.My above given table code was created for Email template.So it has lot of  and s.so ODD and EVEN options not working properly.Any suggestions.Thanks in advance
Comment: Where's your code?
Comment: I just edited my post..Please help.thanks in advance
Comment: Crikey! Why so many `echos`?
Comment: My above given table code was created for Email template.So it has lot of  and s.Thats why I used more echos
Answer: So without delving into your code to correct it here's a general example as it is a CSS question realistically.. So to do this you need to use nth-child(). Here's an example:

tr:nth-child(odd)  { background-color:#e5e8e8; }
tr:nth-child(even)  { background-color:#b9b8bb; }

         Row 1

            Row 2

Comment: How to use the following code inside PHP:                                                    tr:nth-child(odd)  { background-color:#e5e8e8; }
tr:nth-child(even)  { background-color:#b9b8bb; }
Comment: My above given table code was created for Email template.So it has lot of  and s.so ODD and EVEN options not working properly.Any suggestions.Thanks in advance


Data props undefined on calling child component

Question: I am facing problem in passing data to my child component.
import React, { Component } from 'react'
import { Text, View, ScrollView } from 'react-native'
import axios from 'axios'
import ClaimStatus from '../table/ClaimStatus'

export class ClaimsEW extends Component{

    render(){
        console.log(this.props.claim_approval_summary)
        return(
            <ScrollView>

                <View style={{elevation:5, backgroundColor:'#fff', margin:15}}>
                    <ClaimStatus newprops={this.props.claim_approval_summary} />
                </View>
            </ScrollView>
        )
    }
}

class ClaimsAMC extends Component{
    render(){
        return(
            <View>
                <Text>
                    class two
                </Text>
            </View>
        )
    }
}

export default class ClaimsLevelTwo extends Component {

    constructor(props) {
        super(props)

        this.state = {
            id: '',
            param_oem: '',
            dropdown_arg: '',
            claim_approval_regions: [],
            claim_approval_summary: [],
        }
    }

    async componentDidMount(){

        const param_oem = this.props.navigation.getParam('value');
        const auth_id = this.props.navigation.getParam('auth_token');
        const dropdown_arg = this.props.navigation.getParam('arg');

        await this.setState({
            param_oem,
            id: auth_id,
            dropdown_arg,
            fetched: true
        });

        var headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Headers': 'x-access-token',
            'x-access-token': this.state.id
        }

                axios.post('http://bi.servassure.net/api/ClaimApprovalSummary', {
                oem: this.state.param_oem,
            }, {headers:headers})
            .then(res => {

                let claim_approval_regions = res.data.region;
                let claim_approval_summary = res.data.data[0];

                this.setState({
                    claim_approval_regions :claim_approval_regions,
                    claim_approval_summary : claim_approval_summary
                });

                console.log(this.state.claim_approval_regions)
            }).catch(err => console.log(err));

    }
    render() {
        const state_values = this.state;
        console.log(state_values)
        return (
            (this.state.dropdown_arg === 'ew' ? (Object.keys(state_values).length > 0 ? <ClaimsEW {...state_values} /> : null) : <ClaimsAMC/>)
        )
    }
}

When I call ClaimStatus newprops={this.props.claim_approval_summary} /> component inside the class ClaimsEW, the props gets undefined. I even tried printing the values without the new child component, giving just a  but still gives same result.
If I don't pass any new Component or View inside the class ClaimsEW, console.log(this.props.claim_approval_summary) prints the props value in console. On calling ClaimStatus newprops={this.props.claim_approval_summary} />, prints undefined props in following component.
The data I am receiving is in the object form hence I am converting it into array to map it further in the <ClaimStatus/> component.
Please help to resolve this.
Answer: Quick solution: You need to call this.props.newprops like console.log(this.props.newprops) if you do <ClaimStatus newprops={this.props.claim_approval_summary} />
Explanation:
When you do this <ClaimsEW {...state_values} /> you are basically sending each of the state values as a separate prop key. so this becomes <ClaimsEW claim_approval_regions={[]} and so on... /> that's why console.log(this.props.claim_approval_summary) works when you do <ClaimsEW {...state_values} /> . To understand this better I recommend you take a deep look at object destructuring feature of javascript.
One of the basic rule of sending prop is <AnyComponent propOne={valueOne} propTwo={valueTwo} and so on.../> and they become available in AnyComponent as this.props.propOne, this.props.propTwo and so on ...
Hope that helps. Cheers!
Comment: No luck. Still the same problem. As soon as `` is called, `newprops` become undefined.
Comment: Resolved it. I have to again apply object length condition for passing data props into child component. Thanks for help!
Answer: i think cleaner code will solve your problems, i have cleaned out few parts of it maybe this will help
import React, { Component } from 'react'
import { Text, View, ScrollView } from 'react-native'
import axios from 'axios'
import ClaimStatus from '../table/ClaimStatus'

export class ClaimsEW extends Component{
 render(){
    console.log(this.props.claim_approval_summary)
    return(
        <ScrollView>
            <View style={{elevation:5, backgroundColor:'#fff', margin:15}}>
                <ClaimStatus newprops={this.props.claim_approval_summary} />
            </View>
        </ScrollView>
    )
 }
}

class ClaimsAMC extends Component{
 render(){
    return(
        <View>
            <Text>
                class two
            </Text>
        </View>
    )
 }
}

export default class ClaimsLevelTwo extends Component {
 constructor(props) {
    super(props);
    this.state = {
        id: '',
        param_oem: '',
        dropdown_arg: '',
        claim_approval_regions: [],
        claim_approval_summary: [],
    }
 }

 async componentDidMount(){
  const { getParam } = this.props.navigation;
  const param_oem = getParam('value');
  const auth_id = getParam('auth_token');
  const dropdown_arg = getParam('arg');

  const headers = {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Headers': 'x-access-token',
        'x-access-token': auth_id
    };

    const result   =  await  axios.post('http://bi.servassure.net/api/ClaimApprovalSummary', {
            oem: param_oem,
        }, {headers:headers});

     const claim_approval_regions = res.data.region;
     const claim_approval_summary = res.data.data[0];

     this.setState({
          param_oem,
         id: auth_id,
            dropdown_arg,
            fetched: true,
             claim_approval_regions,
             claim_approval_summary,
        });

 }

 render() {
    const state_values = this.state;
   const { dropdown_arg } = state_values;
    return (
        // having dropdown_arg means the length is always > 0
        (dropdown_arg === 'ew' ? <ClaimsEW {...state_values} />) : <ClaimsAMC/>)
    )
 }
}

Comment: No luck. Still the same problem. As soon as `` is called, `newprops` become undefined.
Comment: Resolved it. I have to again apply object length condition for passing data props into child component. Thanks for help!


Alterar a posição de uma  para a primeira posição

Question: Tenho a seguinte
:

Escolha a opção abaixo

1

1

3

Tem como alterar a posição de uma
 para a primeira posição da
 em jQuery ao clicar sobre a dada
?
Answer: Basicamente

$('li').click(function(){ $($(this).closest('ul')).prepend($(this)); })

Escolha a opção abaixo

1

1

3

Comment: isso mesmo, obrigado.
Answer: Criei um exemplo baseado no que entendi sobre o seu questionamento, veja se o código abaixo corresponde a sua necessidade.

$(document).ready(function(){
  let opcoes = $('.opcoes');
  let opcoesItems = opcoes.find('li');

  opcoesItems.each(function(i){
   $(this).click(function(e){
     opcoes.prepend($(this));
    });
  });
});

Selecione uma opção

1

1

3

Tive que adaptar seu código HTML para que a lógica funcionasse corretamente.
Answer: Esse tem efeito na transição

$(document).ready(function() {
$('li').click(function() {
  // the clicked LI
  var clicked = $(this);

  // all the LIs above the clicked one
  var previousAll = clicked.prevAll();

  // only proceed if it's not already on top (no previous siblings)
  if(previousAll.length > 0) {
    // top LI
    var top = $(previousAll[previousAll.length - 1]);

    // immediately previous LI
    var previous = $(previousAll[0]);

    // how far up do we need to move the clicked LI?
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');

    // how far down do we need to move the previous siblings?
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());

    // let's move stuff
    clicked.css('position', 'relative');
    previousAll.css('position', 'relative');
    clicked.animate({'top': -moveUp});
    previousAll.animate({'top': moveDown}, {complete: function() {
      // rearrange the DOM and restore positioning when we're done moving
      clicked.parent().prepend(clicked);
      clicked.css({'position': 'static', 'top': 0});
      previousAll.css({'position': 'static', 'top': 0});
    }});
  }
});
  });
a,a:hover{text-decoration:none;}
ul{list-style:none;}

Escolha a opção abaixo

1

2

3

Fonte:  brother
Comment: Esse com um efeito ... kkk !!! #massa
Answer: Forma usando .prependTo() e respeitando a hierarquia dos elementos:
$('.opcoes li').on("click",function(){ $(this).prependTo($(".opcoes")); });

$('.opcoes li').on("click",function(){ $(this).prependTo($(".opcoes")); });

Escolha a opção abaixo

1

1

3


Metronome with built-in microphone

Question: I play drums for a church. I was wondering if there is a kind of metronome that has a microphone built into it so that it can give me the tempo from hearing other people play music so that I don't get lost
Comment: Have you tried just listening to the other people's playing?
Comment: The easiest way to determine the bpm tempo of music that you're hearing is a metronome with a "tap" feature: you tap a button repeatedly on the beats and it tells you the tempo.
Comment: Right now the question is off topic here because we won't recommend equipment for you. But if you want to edit your question to ask how to follow a tempo set by others then we can give you good advice there.
Comment: Hi! I strongly recommend that you use the "edit" button to change this question. Right now I'll vote to close, since [the topics covered here](https://music.stackexchange.com/help/on-topic) don't include "help me find a ___" types of questions. But I think you, or the others you play with, are having a tempo problem that needs to be fixed in some other way. Please edit to tell us more about the problem so you can get the best answer, and I can retract my close-vote.
Comment: @AndyBonner - I don't find those tap buttons that easy. One can be several bpm out with no trouble at all. And I've been playing for many years! A beginner would be even more inaccurate.
Comment: If I can't hear the beat, I need either to train that, or stop making music. As a drummer you need to become a master of time, which includes subdivisions of time.
Comment: @AndyBonner And that doesn't need a specialised device: there are many smartphone apps with tap-to-tempo.
Comment: You are the drummer. It's on them to not get lost on the tempo.
Answer: There is some amazing music technology available in this day and age. There is actually computer software that can analyze and detect a tempo in recorded music but that is after the fact. There is no such thing as a stand alone metronome that extracts and generates a click by listening to what people are playing in real time. Even if there were, it would probably not be much help to you.
You actually have it backwards, you as a drummer are one of the instruments that are responsible for establishing and dictating the tempo in music along with the bass and to a slightly lesser extent, guitar and piano. You should be focused on listening to and playing with these other rhythm section instruments and between you provide the steady time for the singers, horns, etc. not the other way around.
One of the issues you might have is that maybe there is poor monitoring that doesn't allow you to hear the other instruments well enough. That would make it hard for you to know what is going on and lock in with them. If that is the case, consider adding a monitor speaker to your setup or position yourself or others in a way that you can hear them better. As a drummer you have a responsibility to provide a steady beat with the rhythm section and know the song structures so you can provide a solid base for the rest of the band.
It IS possible to play to a metronome in a live situation and some groups actually do but that has to be set up in a particular way. The drummer or preferably the entire rhythm section can have a click in earbuds that is not audible to the audience and then they all play along to that. Whether or not a band plays to a click is a matter of preference and the powers that be would make the choice.
Answer: As John says, the band should be following you, not you trying to follow the rest of the band.
However, churches were never built acoustically for drums, which does make playing in time difficult in any case, due to echoes coming at you from many directions. And, drums in church can often come across as too loud.
Given that the pieces are at a constant tempo, you could use a metronome which has a visible readout - a nice big needle that swings across the screen in time, as well as giving you the click track that is so necessary, in an earpiece. Or a couple of flashing leds, red - green - green - green in each bar, for example.
Not recommending equipment (out of bounds on this site), there are plenty of drum machines which can be set to merely a click track, with earpiece facility, some pre-programmable for the entire set. One of those seems a possibility.
A lot of church bands will have a conductor, so talking to and working with them will solve a lot of problems.
If the pieces do fluctuate, due to poor players, then it's your job to keep them in time. If the pieces fluctuate on purpose, then again, it's your job. That's why there's a drummer in the band!
Answer: Yes, there are ways to get a computer to 'listen' to music and display a tempo.   But this isn't generally available in a neat stand-alone box, probably because it would be absolutely useless!  You're playing, you see a readout 'q=144'.   So what do you do with this information?   Maybe it even outputs a click or flashes a light at the detected tempo.  So you can follow a click but you can't listen to the music directly?
YOU must listen to the other musicians.  THEY must listen to you.  If it all comes to pieces, someone isn't listening, and quite likely that person (or everyone) is playing too loudly!
It's simplistic to say the drummer should lay down the beat and everyone else should follow.   Music, even in a church band, should be more subtle and flexible than that.

Metronome with built-in microphone


htaccess: remove subdirectory form URL while serving up original content

Question: I have a URL structure like this
http://domain.com/page/thing1
http://domain.com/page/thing2
http://domain.com/page/thing3

I want to:

remove /page/ from the URL
serve up content from /page/thing1

I am using ExpressionEngine, so here's what I do to remove index.php from the URL
<IfModule mod_rewrite.c>
        RewriteEngine On

        # Removes index.php
        RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

Comment: You don't necessarily have to do this via ModRewrite, depending on how you're accessing this data in EE. Are these URLs created via the Pages module? Or is `page` a template group and `thing1` a template? Or are `thing1`, `thing2` etc, all entry URL titles?
Comment: Here are two posts which may help http://stackoverflow.com/questions/2402140/use-a-subdirectory-as-root-with-htaccess-in-apache-1-3 and http://stackoverflow.com/questions/990392/htaccess-rewrite-to-redirect-root-url-to-subdirectory
Comment: @DerekHogue right now I have it set up where page is a template group and thing1 and thing 2 are entries.
Comment: In that case, [see rjb's answer](http://stackoverflow.com/a/8890130/174299) - the Pages module is the way to go here. Accessing individual entries by their URL title via the first segment is not a good route to take.
Answer: What are the gains to be had from these new URLs?
Simply removing the /page URL segment (i.e. template group) from your URIs creates a lot of additional overhead and complexity, as illustrated in the following ExpressionEngine URL Schematic:

The native ExpressionEngine Pages Module or the third-party Structure Module is the simplest method and won't require adding any RewriteRules rules to your .htaccess file.
However, this will require you to create a page URL for each entry, which may be less than ideal.
Answer: If you change all your urls to be http://domain.com/thing1 and http://domain.com/thing2 etc, couldn't you just add the page/ back in when you rewrite to the index.php file?
RewriteRule ^(.*)$ /index.php/page/$1 [L]

Comment: This would assume *all requests* would be routed thru the `/pages` template group, which would break many URIs — including many core ExpressionEngine URLs. At a minimum, you'd have to combine the `RewriteRule` with a `RewriteCond`.
Answer: Append these lines below your existing Rewrite rule in IfModule block:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?!page/)(.*)$ /page/$1 [L,NC]


Show the integral equality $\int_0^\infty\frac{1}{\sqrt{x^3+1}}\mathrm dx = 2 \int_0^\infty\frac{1}{\sqrt{x^6+1}}\mathrm dx$ without evaluating

Question: Without evaluating the integrals directly, how can I prove that : $$\int_0^\infty\frac{1}{\sqrt{x^3+1}}\mathrm dx = 2 \int_0^\infty\frac{1}{\sqrt{x^6+1}}\mathrm dx$$
For the second integral, I tried the change of variable $x^2 \to x$ to get :
$$\int_0^\infty\frac{1}{\sqrt{x^6+1}}\mathrm dx=\int_0^\infty\frac{1}{2\sqrt{x}\sqrt{x^3+1}}\mathrm dx$$
However, I cannot relate it with the first one as there is an extra $\sqrt{x}$ term in the denominator.
How can I proceed further or are there better methods to solve it ?
Answer: Hint It's not much more effort to look for a $1$-parameter family of such identities. Substituting $$x = \frac{1}{u^b}, \qquad dx = -\frac{b\,du}{u^{b + 1}}$$ in
$$\int_0^\infty \frac{dx}{\sqrt{1 + x^{2 + a}}}, \qquad a > 0 ,$$ gives
$$\int_0^\infty \frac{dx}{\sqrt{1 + x^{2 + a}}} = b \int_0^\infty \frac{du}{\sqrt{u^{2 - a b} + u^{2 + 2 b}}},$$
so choosing $b = \frac{2}{a}$ and renaming $u$ as $x$ on the r.h.s. gives
$$\int_0^\infty \frac{dx}{\sqrt{1 + x^{2 + a}}} = \frac{2}{a} \int_0^\infty \frac{dx}{\sqrt{1 + x^{2 + \frac{4}{a}}}} .$$
Taking $a = 1$ (or $a = 4$) gives our case.
Incidentally, $$\int_0^\infty \frac{dx}{\sqrt{1 + x^{2 + a}}} = \frac{\Gamma\left(\frac{a}{4 + 2 a}\right) \Gamma\left(\frac{1}{2 + a}\right)}{\sqrt{\pi} (a + 2)} .$$
Comment: You're welcome. That question is perhaps worthy of its own post, but substituting $x^{2 + a} = \tan^2 \theta$ transforms the integral to $\frac{2}{2 + a} \int_0^\frac{\pi}{2} \sin^l \theta \cos^m \theta \,d\theta$ for some $l, m$, but the latter integral can immediately be expressed in terms of the beta function, hence the gamma function; see https://en.wikipedia.org/wiki/Beta_function#Other_identities_and_formulas.
Comment: Wow thanks ! Can you tell how the general integral in the last is evaluated ?
Comment: Thanks once more for the hinted substitution. Yes, I'm aware of the latter one which is related Wallis integrals.
Answer: Proof by Gamma function
We consider the general integral
$$
I(a)=\int_0^{\infty} \frac{1}{\sqrt{x^a+1}} d x
$$
$$
\begin{aligned}
I(a) & =\int_0^1 y^{-\frac{3}{2}}\cdot\frac{1}{a}\left(\frac{1}{y}-1\right)^{\frac{1}{a}-1} d y \\
& =\frac{2}{a} \int_0^1 y^{-\frac{1}{2}-\frac{1}{a}}(1-y)^{\frac{1}{a}-1} d y \\
& =\frac{2}{a} B\left(\frac{1}{2}-\frac{1}{a}, \frac{1}{a}\right) \\
& =\frac{2}{a} \frac{\Gamma\left(\frac{1}{2}-\frac{1}{a}\right) \Gamma\left(\frac{1}{a}\right)}{\Gamma\left(\frac{1}{2}\right)} \\
& =\frac{2}{a \sqrt{\pi}} \Gamma\left(\frac{1}{2}-\frac{1}{a}\right) \Gamma\left(\frac{1}{a}\right)
\end{aligned}
$$
Putting $a=3$ and $a=6$ respectively gives
$$
I(3)=\frac{2}{3 \sqrt{\pi}} \Gamma\left(\frac{1}{6}\right) \Gamma\left(\frac{1}{3}\right)=2I(6)
$$
Comment: Even though I didn't asked by directly evaluating the integral, thanks for it.


How to Separate Months by Their Years in SQL

Question: I am trying to see the profit by each month in SQL. However, I have multiple "Julys" and can't seem to separate them into different years. This is the query I am trying.
select
    concat(datename(year, o.orderdate), ' ', datename(month, o.OrderDate)) [Month],
    sum((t.StandardPrice - t.TotMaterialCost) * ol.OrderedQuantity) [Total Profit]
from
    Temp_V t, OrderLine_T ol, Order_T o
where
    t.ProductID = ol.ProductID
    and ol.OrderID = o.OrderID
group by
    o.OrderDate

I am getting the correct output, but for instance, it says July 2017 in two different rows instead of July 2017 and then July 2018. (Which is what I want it to say). I think it is an error with Concat().
Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was replaced with the *proper* ANSI `JOIN` syntax in the ANSI-**92** SQL Standard (**more than 25 years** ago) and its use is discouraged
Answer: You want, I believe, this use of EOMONTH():
SELECT EOMONTH(o.orderDate) month_ending,
       sum(<whatever>) [Total Profit]
  FROM <whatever>
 GROUP BY  EOMONTH(o.orderDate)

The EOMONTH function takes any date or date/time value and truncates it to the start of the last day of the month.  So, it's an ideal way to take a whole mess of orderDate values and group them into the months when they happened.
Comment: I didn't know EOMONTH existed until now. After reading, it came as a surprise that it had been there since sql 2012 and I didn't come across it. I had been using my very own user defined function for such operations. Glad I visited SO today.
Comment: Yes. I make a point of reviewing, once every couple of months, the date/time functions of whatever DBMS I'm working with. It's worth every second of the time I spend on it. Less bugs, clearer code. Let a vast company with lots of testers worry about calendars, time zones, day rollovers, and all that stuff. Better them than me!
Comment: Well it will be my new habit from now on too. Would be grateful if you could share some insights on your methods of doing so or some useful links that are updated as per new standards (other than w3school). Won't be able to post responses here in comments to avoid spamming so thank you in advance. oh yes learning is fun...
Answer: I believe what you are missing is a correct "group by" clause which should be :
group by concat(datename(year, o.orderdate), datename(month, o.OrderDate))


(How) can two words differ in fewer places than the minimum distance?

Question: I'm working on an unassessed course problem (which I paraphrase for conciseness),

Let $C$ be the code over $\mathbb{F}_5$ with generator and parity-check matrices
$$G=\begin{pmatrix}2&3&4&1\end{pmatrix}, \hspace{1em} H=\begin{pmatrix}1&0&0&3\\2&1&0&3\\0&1&1&3\end{pmatrix}.$$
Determine the minimum distance $d(C)$ and the error-correcting index $t$,
and find the codeword of $C$ closest to $\underline{w}=1123$.

The solution booklet gives $$d=4, \hspace{1em} t=1, \hspace{1em} \underline{c}=1423 \text{ with } d(\underline{w},\underline{c})=1.$$
How can two words differ in fewer places than the minimum distance?
I'm guessing there's something basic I haven't understood.
Comment: The minimum distance of a code is the minimum distance between two codewords.  Which need not be the distance between a codeword and a non-codeword.
Comment: @kimchilover OK, thanks, that makes sense. It didn't occur to me that $\underline{w}\notin C$. The comment is enough for me, but if you want to make it an answer I'll be happy to accept.
Comment: @kimchilover is right. also what makes a code able to correct errors is that non-codewords $w$ which are at most distance $t$ from a codeword, where $d=2t+1$ or $d=2t+2$ can be decoded to the nearest codeword.
Answer: Here is my intuitive way to see what is going on here.
Let us say , we have some way to put the Code Points in some linear order (which is not generally true : the "order" will be in some non-linear graph , but that is enough to see the intuition behind the Issue here)

Here the Integer Code Points are the Blue Marks , which may be something like $1423$.
The other Integer Points on the line are invalid Code Patterns. Eg the Purple Mark & the Green Mark , which may be like $1123$.
Over-all , the Minimum Distance is between 2 Blue Marks which is highlighted with the Arrows.
Now , we are given 2 invalid Integer Points , the Purple Mark & the Green Mark.
We want to know which valid Code Point got transmitted with errors , hence we chose the left Code Point for Purple Mark & the right Code Point for the Green Mark , because these are the closest valid Code Points to those invalid Points.
It might happen that the errors are too large & the transmitted Purple Point was actually the left-most & the transmitted Green Point was actually the right-most , though we will not know that : We will always select the nearest unique Blue Mark.
Now , we see that :
(1) the Distance between Valid Code Points is very large
(2) these Distances between Valid Code Points have a Minimum (larger is better)
(3) the Distance between valid Mark & Invalid Mark might be less (smaller is better)
(4) In fact , Distance between valid Mark & Invalid Mark SHOULD BE less than Minimum Distance between valid Code Points , to allow selecting the Correct Code Point when receiving invalid Core Points with errors
In text  book Exercise , we received $1123$ which is invalid.
We calculate that the Original Code Point must have been $1423$ because that is the nearest , with Distance $1$.
Luckily , the error during transmission did not exceed $4$ , which is the Minimum Distance between 2 valid Code Points.
In Case , the error Distance had been 2 , we might have 2 or more valid Code Points to select (something like left-nearest , right-nearest , upper-nearest or lower-nearest) : we will not know which was the Original Code Point.


Pass arguments to hook_form_alter()

Question: I have two login boxes on the same page and, I would like to integrate different behaviors to those based on some arguments.
I'm calling myself the forms with drupal_get_form('user_login');. I would like to pass a variable to the form:
drupal_get_form('user_login', $myvar);

And then be able to get it from a hook_form_alter():
function mymodule_form_alter($form, $form_state, $form_id, $myvar) {
  // some code here
}

But i can't find a way to do this.
Comment: hook_form() is something completely else, I assume you mean hook_form_alter().
Answer: The passed arguments are kept in $form_state['build_info']['args']. You can find a documentation of the $form_state structure here: drupal_build_form().
Comment: My question was for D6, anyway thanks a lot, the answer you gave helped me finding the right solution for D6:

The arguments are in $form['#parameters'][argument];
Comment: Search about one day to find this one here. Works great. Just giving the register form a string and reading it out via the build_info. Cool.

Pass arguments to hook_form_alter()


Accessing members of a class within a vector of vectors

Question: class item
{
private:
    std::string name;
    double price;
    int quantity;

public:
    void item();
    void setName(string itemName);
    std::string getName();
    void setPrice(double itemPrice);
    double getPrice();
    void setQuantity(int itemQuantity);
    int getQuantity();
};

class list
{
private:
    std::vector<std::vector<item>> notepad;

public:
    bool isEmpty();
    void addList();
    void printLists(bool printTotalPrice);
    void addItem();
    void removeItem();
    void editItem();
    void importList(ifstream& iFile);
    void exportList(ofstream& oFile);
};

Here is where I am having trouble.  For my function list::addItem() I want the user to enter a string in order to search the notepad vector's first row elements ONLY in order to find a match.
Something like this...
          for (int i = 0; i < notepad.size(); ++i)
             if (user's entered string) == first element of 'i'th vector.getName()

... match found
Any ideas on how I could do this?
Answer: if ( user_entered_string == notepad[i][0].getName() )

[i] gets the 'i'th vector from notepad.
[0] gets the first item from that result.
.getName() is called on that result.


Prove using the formal definition of limit that $\lim\limits_{x\to\infty}(\cos x)$ does not exist.

Question: My attempt: Let $\epsilon=1$ then the inequality $|\cos x-L|<1$ should hold for $x>M$,where $M>0$. Suppose that $\exists$ an $M>0$ such that the inequality holds. Then $$|\cos x-L|\leq|\cos x|+|L|\leq 1+|L|<1$$ However this implies that $|L|<0$ which is contradiction. Hence the limit does not exist.
I would like to know whether this approach is correct or not. Any inputs will be highly appreciated.
Comment: It is wrong: you cannot deduce $|\cos x|+|L|\leq 1$  starting from $ |\cos x-L|<1$ and from $|\cos x-L|\leq|\cos x|+|L|$! The proof goes in a different way: the point is that the function $f(x)$ assumes values -1 and +1 for $x$ bigger than an arbitrary large number $M$ and whatever is $L$, $L$ has distance greater than 1 from $+1$ or from $-1$.
Answer: You have a mistake because you might have $1\le |\cos x|+|L|$. Pick $a,b\in \Bbb R$ such that $|\cos a-\cos b|:=c\ne0$. Let $\epsilon =\frac c2$. Notice that we can find $n\in\Bbb N$ such that $a+2n\pi, b+2n\pi\ge M$ so we get
$$|\cos a-L|< \epsilon$$
and $$|\cos b-L|<\epsilon$$
hence using triangular inequality
$$c=|\cos a-\cos b|\le |\cos a-L|+|\cos b-L|<c$$
which is a contradiction.


How to make Google Map Label Clickable in Android

Question:
By default on google map app it shows all the transport label and other poi label which are clickable. How can i make them clickable in code, I tried groundoverlay listener and that doesnt work. Also in my app, these poi is not clickable, i want to make it clickable and display the description. How can i do it?
Comment: why not to make the click on the marker ?
Comment: No, by default in google map without searching anything, there are some poi overlaid on the map. but they are not clickable. I wonder any google api to do it.
Comment: Also, I have seen google places picker, I want the ui to be something like that, that i can click on the overlaid icon and retrieve information. but i want this to be integrated into my own map
Answer: @user6491664 yeah by default the map POI's are not clickable. Make them clickable by implementing the GoogleMap.OnPoiClickListener in your class and set the OnPoiClickListener on the map by calling GoogleMap.setOnPoiClickListener(OnPoiClickListener).
see example below;
<code>class MapPOIDemo extends AppCompatActivity implements
    OnMapReadyCallback, GoogleMap.OnPoiClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mappoidemo);
        SupportMapFragment mapFragment;
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.setOnPoiClickListener(this);
    }

    @Override
    public void onPoiClick(PointOfInterest poi) {
        //set TODO
    }
}
</code>


How to statistically account for the different length of time patients were on the different drugs, as to compare the two groups in R?

Question: Conducting a statistical analysis of two groups of subjects being on different drugs. One group has stayed on drug A, while the other group switched to drug B from drug B at around the middle of the individual experiment time - for some subjects it would be 200 days, while for the others it is 1000.
In general, the subjects who stayed on drug A were on the drug longer than the group which switched.
I already know that there is a significant difference between the two lengths of specific drugs. Is there to predict the changes in the switch group prior to the comparison, and then analyse it? Possibly, introduce it into the ANCOVA or the regression analysis?
Is it possible to do in R?
Comment: Could you please proofread your question.
Answer: You can do Independent Sample T-test. I am not sure what the codes are in R, but you can google it.
Comment: This post was improperly migrated from stats.stackexchange.com just because the author put R in the title by mistake.  Statistically speaking, the question cannot be answered without using highly complex methods with more assumptions because medication switching is a **dependent** variable.


Stars & Bars Question: Identical Balls in Distinct Boxes

Question: I am terrible at combinatorics so any and all help would be appreciated.
20 identical balls are put into 10 distinct boxes so that at most 3 boxes are empty. In how many ways can this be done?
Thanks
Comment: Sorry to shatter your illusion and knock you off your high horse but it just so happens that there are people who are so unfamiliar with a topic that they cannot solve a problem without another person's aid despite how long they attempt the problem. But thanks for your incredibly useful underhanded condescension.
Comment: Starting a question with "I am terrible at xxx..." is just shorthand for "I haven't tried to solve this problem". How many ways are there of placing 20 balls into 10 boxes with no boxes empty? If one is empty, this is placing 20 balls into 9 boxes with no boxes empty. Etc.
Comment: Anyway, I wanted to solve this problem by breaking it up into several cases: 0 boxes empty, 1 empty, 2 empty, and 3 empty. In the case with 0 boxes empty, would it be 19 choose 9?
Comment: Yes, that's the right approach. You have to remember to take into account how many ways there are of selecting nine boxes of 10, and so forth.
Comment: If there are zero boxes empty, then you must put one ball in each box, and then distribute the remaining ten freely among all ten boxes.
Comment: @user155812:  For $0$ boxes empty, yes, your $\binom{19}{9}$ is correct. For $1$ box empty, the empty box can be chosen in $\binom{10}{1}$ ways. For each of these ways, the balls can be put in the $9$ boxes that are supposed to be non-empty in $\binom{19}{8}$ ways, for a total of $\binom{10}{1}\binom{19}{8}$. Do something similar for $2$ empty, $3$ empty and add up the $4$ cases.
Answer: We can split this into $4$ cases based on the number of empty boxes, and use stars and bars for each case.

Case 1: No empty boxes.
We place $1$ ball in each box, and we imagine $9$ dividers and the remaining $10$ balls, so the number of possible ways to arrange the $19$ objects is $$\binom{19}{9}$$
Case 2: One empty box.
There are $10$ ways to choose the empty box. We place $1$ ball in each of $9$ boxes, and imagine $8$ dividers with the remaining $11$ balls, so the number of ways to arrange the $19$ objects is $$10\binom{19}{8}$$
Case 3: Two empty boxes.
There are $\binom{10}{2}=45$ ways to choose which boxes are empty. We place $1$ ball in each of $8$ boxes, and imagine $7$ dividers with the remaining $12$ balls, which gives $$45\binom{19}{7}$$
Case 4: Three empty boxes.
There are $\binom{10}{3}=120$ ways to choose which boxes are empty. We place $1$ ball in each of $7$ boxes, and imagine $6$ dividers with the remaining $13$ balls, which gives $$120\binom{19}{6}$$

Our final answer is
$$120\binom{19}{6}+45\binom{19}{7}+10\binom{19}{8}+\binom{19}{9}=\boxed{6371498}$$
Comment: For each case where there IS an empty box, shouldn't you multiply by $\dbinom{10}{n}$, where $n$ is the number of boxes you want to be empty? So for example, if there is one box empty, there would be $\dbinom{10}{1}$$\dbinom{19}{8}$ because there the boxes are distinct, so it matters which ones are selected to be empty.
Comment: @user155812 You're right, I've fixed it :)
Comment: @user155812 in fact, it may help to understand the generalization to correct it to "for each case you multiply by $\binom{10}{n}$ where $n$ is the number of boxes you want to be empty" since we could have multiplied by $\binom{10}{0}=1$ in the case of zero empty boxes.
Comment: Yes, thank you for your response Zubin. This is the answer I had gotten initially, but my lack of confidence combined with the fact that my classmates had gotten another answer made me unsure.
Answer: Hint:  Can you do the case where no boxes are empty?  That is a standard stars and bars.  Then pick $9,8,7$ of the boxes (how many ways each?) and do the case where no boxes are empty.  Add them up.
Comment: Yes $19 \choose 9$ is the case where you do not allow any empty boxes.  Your second is correct as well-$10 \choose 1$ picks the empty box and $19\choose 8$ puts the balls in the rest with no empties.
Comment: In the case with no empty boxes, would it be 19 choose 9? If it is, then I think I'm on the right track.
Comment: Furthermore, would the case with 1 box empty be $\dbinom{10}{1}$$\dbinom{19}{8}$?


Componente primefaces não renderizou como esperado

Question: Como podem ver na imagem abaixo, o campo de digitar o texto não está no layout do primefaces. Alguém sabe como posso resolver?

Abaixo agora segue o meu arquivo .xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <h:panelGroup id="cadastro">
            <h:form id="cad">

                    <h:outputText value="Cadastro de Habilidades"
                        style="font-size:18px;fontweight:bold" />

            </h:form>
        </h:panelGroup>

O driver está nas dependências do Maven.
Answer: Douglas,
Sua página XHTML começa com o componente h:panelGroup antes do form:
<h:panelGroup id="cadastro">

Sugiro que você coloque o formulário como primeiro elemento e utilize apenas componentes nativos do Primefaces, no seu caso eu mudaria seu código para algo assim:
<h:form id="formCadastro">

</h:form>

O que faz a classe de estilo ui-noborder do código abaixo?

Tome cuidado pois dependendo do que há nessa classe há possibilidades do estilo do seu campo texto ser sobrescrito por outras regras que tenham maior prioridade.
Você utiliza tema? Está funcionando com outros componentes?
Envie mais detalhes para que as pessoas possam entender melhor seu problema e quem sabe melhor ajudá-lo.
Espero que isso ajude...
Boa sorte!
Comment: Obrigado, rsrs....Nem lembrava desta pergunta mais... :)
Comment: kkkkkkkkkkkkkk pior que vi agora quer era de Maio. Valeu!  :)


$(\Bbb R, \tau)$ with $\tau$ defined as:
$U\in \tau \iff U=\emptyset \vee 0 \in U$ is not second-countable.

Question: Let $(\Bbb R,\tau)$ be a topological space with $tau$ is defined as:
$$U\in \tau \iff U=\emptyset \vee 0 \in U.$$
Show that $\tau$ is not second-countable.
Attempt:
The goal is to show that for any basis $\mathcal{B}$ for a topology $\tau$, then $\mathcal{B}$ is uncountable.
Let $\mathcal{B}$ be any basis for topology $\tau$. By definition, for any $U \in \tau$ and for all $x \in U$, there is $B \in \mathcal{B}$ such that $x \in B \subseteq U$.
But then, how to construct $U$ for which the cardinality of $\mathcal{B}$ and $\Bbb R$ are the same?
Thanks in advanced.
Answer: Hint:
Let $x\in \mathbb{R}$, show that any basis of $\mathbb{R}$ with this topology must contain $\{0,x\}$.
Comment: If it has proved, then since $x \in \Bbb R$ was arbitrary, we have that the basis is uncountable. Like this?
Comment: Does the proof of your hint goes as follows? Let $\mathcal{B}$ be any basis for $\tau$ of $\Bbb R$. By definition, for any $U\in \tau$ and for all $x\in U$, there is $B=\{0,x\} \in \mathcal{B}$ such that $x\in B\subseteq U$. Thus, any basis for $\tau$ of $\Bbb R$ must contain $\{0,x\}$.
Comment: Thus, since $x \in \Bbb R$  was arbitrary given, we conclude that $|\mathcal{B}|=|\Bbb R|$. Hence, $(\Bbb R,\tau)$ is not second-countable.
Comment: @PitikKepit Yep
Comment: Sorry? What is "Yep"?
Comment: It means yes, you are correct :-)
Comment: Oooh, I see. Pardon Sir :")


Finale no beaming over rests

Question: I am working in a 12/8 time signature and whenever I insert an eighth note, an eighth rest, and another eighth note, Finale automatically extends the beam from the first note to the last, passing over the rest.
I want to deselect this behaviour, keeping at the same time the default beaming of three eighth notes together. So I don't think that changing the time signature would be the right way.
I'm using Finale 2014.5 and also, I know that I could break a beam by pressing the / key, but since I have an Italian keyboard, it doesn't work.
Comment: Select the Simple Note Entry icon, go to the Simple menu / Simple Entry Options,  click Edit Keyboard Shortcuts. If the standard shortcuts don't work on an Italian keyboard, change them to what you want. For a long time Finale didn't even work properly with UK English keyboards, which are different from US English so I'm not surprised it doesn't understand Italian!
Comment: @alephzero makes a great suggestion. Another possibility would be to install a US keyboard, which is pretty straightforward both [on a PC](https://egarc.ku.edu/installing-language-keyboards-windows-7) and [on a Mac](http://www.wikihow.com/Change-the-Keyboard-Language-of-a-Mac). I teach physics, a discipline that uses a lot of Greek letters for variables (θ, μ, α, β, ψ, δ, Δ, ε, φ, γ, Γ, η, κ, λ, π, ρ, σ, τ, ω, Ω...). When writing course materials, I'm switch back and forth between Greek and US keyboards all the time and I find it really easy.
Answer: I checked Document Options and none of the checkboxes seem to do what you are looking for.

Therefore, I think your best bet is to break the unwanted beams using the speedy entry tool. To do this, place the speedy entry cursor over the latter or of the two notes that you want to unbeam and use the key command for Break/Join Beams. In my case the key command is /. You can find the key command using the Speedy menu as seen below.
I agree that changing the time signature so that beams are never formed automatically is not the right way to do this. I think it would be more work to beam the groups of three than to break the groups of two.

As for the problem with an Italian keyboard, assuming macOS, you can use System Preferences -> Keyboard Shortcuts to override Finale's default key command.

I have tested this and verified that the keyboard command override works.
Comment: On Wiindows, without the paid version, I dont see any of those on the top bar

Finale no beaming over rests


StringOverrides doesn't change the text in DCommerce "Add to Cart" Button

Question: Seen a lot of references to the hook_form_alter function on how to apply this, but many of the posts are aimed at more seasoned developers. I know enough to know that I need either a custom module to change these, but I don't know where to find the form id's on the buttons to change.
I was also pointed in the direction of the StringOverrides module, but this doesn't effect the changes I want on the buttons, only where the terms I want appear in plain text, as opposed to what I'm learning is hard-coded into the Commerce Modules.
So...a) how do I find the form ids to make a module to change these buttons? and b) how to get String Overrides to actually change the text on the buttons?
Answer: The fields I was trying to change ended up being hard-coded into drupal commerce, such that string Overrides, and even the Commerce Cart Overrides modules didn't help me get done what I needed to do completely.
So...I applied the hook_form_alter() functions in the bartik theme, because I couldn't get them to work in a stand alone module, although from what I read this would be better practice and then you don't have to remember what you changed where if you want to change themes etc.
So, combination approach got done what I needed in the end. Have to say, overall documentation is pretty opaque for a relatively easy fix and from googling, a relatively around a common problem.
Code snippet that might help:
<code>function bartik_form_alter(&$form, &$form_state, $form_id){
dpm($form_id);
dpm($form);
if (commerce_form_callback($form_id, $form_state) == "commerce_cart_add_to_cart_form"){
$form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value']=t("Add to Inquiry List");
}
if(strpos($form_id, 'views_form_commerce_cart_form_default')===0){
$form['actions']['submit']['#value'] = t("Update List");
$form['actions']['checkout']['#value'] = t("Submit List");
}
if(strpos($form_id, 'commerce_checkout_form_checkout')===0){
    $form['buttons']['continue']['#value'] = t('Proceed to final list submission.');
    }
if(strpos($form_id, 'commerce_checkout_form_review')===0){
    $form['buttons']['continue']['#value'] = t('Submit your inquiry list');
    }
</code>
}


VB.NET Array out of words but only one Index for text in ""

Question: I have no idea how to get an array of words from a string which has words separated by spaces but some "words" are delimited by quotes, e.g:
Dim blablah As String = "This is some \"nice String\""

Should give an array of ["This", "is", "some", "nice String"]
How can I do that?
Answer: You could regard the string as CSV data where the separator is a space and some fields are enclosed in quotes, which means you can use a TextFieldParser to get the array you are looking for:
Imports System.IO
Imports Microsoft.VisualBasic.FileIO

Module Module1

    Sub Main()
        Dim blablah As String = "This is some ""nice String"""
        Dim parts As String()

        Dim strm = New StringReader(blablah)

        Using tfp As New TextFieldParser(strm)
            tfp.Delimiters = {" "}
            tfp.HasFieldsEnclosedInQuotes = True
            parts = tfp.ReadFields()
        End Using

        Console.WriteLine(String.Join(vbCrLf, parts))

        Console.ReadLine()

    End Sub

End Module

Outputs:

This
is
some
nice String

Other CSV parsers are available if you don't want to use methods from Microsoft.VisualBasic.


Let $p=(5,0,-4)$ and $v \in T_{(5,0,-4)}M$. Compute $(F^{*}\omega)_p(v)$.

Question: Let me show my work before presenting the problem itself.
Let $M=\{(x,y,z) \in \mathbb{R}^3 : x+y=5, x+z=cos^2y\}$.
We can easily see that $M$ is a submanifold of $\mathbb{R}^3$ of dimension $1$.
We can also see that we can construct a global atlas for $M$, say $\{(M,\varphi)\}$, where $\varphi:M\rightarrow\mathbb{R}$ is given by $(x,y,z) \mapsto y$.
If $P=(p_1,p_2,p_3) \in M$, then $T_PM=\langle (-1,1,1-2sin(p_2)cos(p_2)) \rangle$. In particular, for $P=(5,0,-4) \in M$, $T_{(5,0,-4)}M = \langle (-1,1,1) \rangle$.
Consider the morphism (smooth map) $F:M \rightarrow S^1$ given by $(x,y,z) \mapsto (\frac{x}{\sqrt{x^2+y^2}},\frac{y}{\sqrt{x^2+y^2}})$.
Remember that $S^1=\{(x,y) \in \mathbb{R}^2 : x^2+y^2=1\}$, so the given morphism is well defined.
Expressing $F$ in the atlas of $M$, we get
$$F(x,y,z)=F(\varphi^{-1}(y))=(\frac{5-y}{\sqrt{2y^2-10y+25}},\frac{y}{\sqrt{2y^2-10y+25}})$$
We can see that $F(5,0,-4)=(1,0)$.
Now we choose a coordinate chart $\psi$ of $S^1$ in a neighborhood of $(1,0)$. For example, $\psi:U=\{(x,y) \in S^1 : x > 0\} \longrightarrow ]-1,1[$ given by $(x,y) \mapsto y$.
We have also that $\omega=-\frac{1}{x}dy$ is one $1$-form which is an orientation of $S^1$ in a neighborhood of the point $(1,0)$.

Let $P=(5,0,-4)$ and $v \in T_{(5,0,-4)}M$.
I want to compute $(F^{*}\omega)_P(v)$.

I'll show my attempt:
We put $x:=\frac{u}{\sqrt{u^2+v^2}}$ and $y:=\frac{v}{\sqrt{u^2+v^2}}$.
So $-\frac{1}{x}dy=\frac{v}{u^2+v^2}du-\frac{u}{u^2+v^2}dv$ (I don't present the calculations because they're somewhat boring).
So $F^*\omega = \frac{y}{x^2+y^2}dx -\frac{x}{x^2+y^2}dy$ and $(F^*\omega)_p=-\frac{1}{5}dy$, so $(F^*\omega)_p(v)=-\frac{1}{5}C$, where $v=(-C,C,C) \in T_{(5,0,-4)}M = \langle (-1,1,1) \rangle$.

Is this right?

Some help would be appreciated. Thanks in advance.
Answer: Your notation is a bit strange. Let's write $F(x,y,z) = (u(x,y,z),v(x,y,z))$. Then you want to calculate $F^*ω$ with $ω = -1/u dv$.
Now, $F^*(1/u) = 1/u(x,y) = \sqrt{x^2 + y^2}/x$ and $F^*dv = \frac{∂v}{∂x} dx + \frac{∂v}{∂y} dy + \frac{∂v}{∂z} dz$. So it seems that you missed a term.
Then you plug you values for $(x,y,z)$ in. Concerning the tangent vector: If you write $v = a∂_x + b∂_y + c∂_z$ then by definition of the dual basis $dx(v) = a, dy(v) = b, dz(v) = c$.
I hope this helps.


How to find the list of 'paths' on my site?

Question: I recently became the administrator of a Drupal site. I am attempting to configure various blocks on the page, and have so far only succeeded in removing them altogether. The configuration menu tells me to enter the 'path' for where I want the block to appear. How do I find the list of path names available for entry? The site has a blog, but entering "blog" or even "blog/*" did not make the block appear on the block.
Answer: To get all the paths you can use, you can use the following code to get all the paths defined from modules:
$items = module_invoke_all('menu');
drupal_alter('menu', $items);
foreach ($items as $path => $info) {
  print preg_replace('/%([a-z0-9_]*)/i', '*', $path);
}

The code will show the path as you enter in the block settings; this means it will change node/%node in node/*, and node/%node/edit in node/*/edit.
About your specific issue, the block could not appear because the block has not been assigned to any theme section, the theme doesn't define the section where the block should appear, or the block is empty. In most cases, modules don't output empty blocks.
Comment: this listing will find paths defined by modules, where `/admin/config/search/path` will only show content aliases.
Comment: You can put the code above on a file, for example `get-paths.php`, and then execute it like this: `drush php-script get-paths.php`
Comment: Wrap the `print` in an `if (!path_is_admin($path)) {` if you don't want admin paths.
Comment: ```$items = module_invoke_all('menu');
drupal_alter('menu', $items);
foreach ($items as $path => $info) {
  if (!path_is_admin($path)) {
    print preg_replace('/%([a-z0-9_]*)/i', '*', $path) . "\n";
  }
}
```
Comment: Hrm, this doesn't actually show all the aliases registered.
Answer: If you have the Path module (core) enabled, there will be a page that lists all URL aliases on the site.
If using Drupal 7: example.com/admin/config/search/path
If using Drupal 6: example.com/admin/build/path
Comment: While helpful, this isn't sufficient, there are others ways to register paths in Drupal that the Path module doesn't display. http://drupal.stackexchange.com/a/14586/6602 has a more robust solution.


What IP addresses to use for monitor the availability of Internet connection?

Question: I would like to check the availability of Internet connectivity by sending ICMP "echo request" messages to some IPv4 addresses. Those IPv4 addresses should be as reachable as possible in stability wise and they should not handle ICMP traffic as low priority. I know that DNS servers of tier-1 ISP's(e.g. Level3) and large content providers(for example Google 126.96.36.199) are a popular choice. Maybe it's wiser to use some service which is using DNS entries(IP addresses in different ISP networks) in round-robin fashion like pool.ntp.org? In a nutshell, which IP addresses do you use for this and why?
Answer: An upstream router at your ISP might be a good choice too.  Typically something one hop up from your local router.
Though a word of caution, the problem with doing this or using Google or L3 would be that it is possible the responders not to work, but the connection still be up and online.  Just make sure you use them as a test and not rely on only one as an automated way to failover a connection... One of those, been there, done that situations...
Comment: best practice for automated failover is probably to use ISP upstream router AND tier-1 ISP DNS server AND Google DNS server? In other words, failover connection to another provider only if all three are not reachable at the same time?
Comment: IMO, that would be a good idea. Perhaps do it in 'stages', e.g., ping every 5 seconds, if fail do 4 pings once every second, then if all 4 pings fail, raise the alarm.
Comment: Agreed, I use Google and the upstream router on each of our connections.  One happens to be line of sight wireless to a nearby hill so I ping the router at that location.  In the case of that circuit, if that fails, it most certainly has an issue.
Answer: As you mention I primarily use googles public DNS.
I have never had an issue with it, however if you feel like that doesn't cover it, you could always check multiple hosts. The chance of 2 major datacenters being down is very little.
For example :

b.resolvers.level3.net - 18.104.22.168
google-public-dns-a.google.com - 188.8.131.52


Why can't I edit "Settings" on rules components in the Rules UI?

Question: When I click to edit a rule in the Rules UI, "Settings" is displayed in blue and upon clicking "Settings" the "Name", "Tags", "Active" and "Weight" options are presented.
However, when I click to edit a rules component, "Settings" is displayed in black and I cannot edit the name of the rule nor the arguments.
Before, I solved this problem by:

clearing the Drupal cache (twice)
clearing the cache in my browser and restarting it
switching to a different browser (e.g., from Firefox to Safari)

However, this time none of the above worked.  How can I edit the settings for rules components?
Answer: I had this problem when using entity-rc1.  Upgrading to entity 1.0 resolved the issue for me.


How to get a functions arguments and values from outside the function?

Question: I have searched a little bit to try to figure this one out but didn't get a solution that I was exactly looking for.
This is my use case:

I would like to evaluate expressions from a functions/methods doc-string against the f/m's parameters and values, but from outside the function (when being called but outside execution of the function
I can't statically change the source code I am evaluating (cant write in new functionality) but dynamically changing (i.e. wrapping the function or adding attributes at run-time) is acceptable
I would prefer to stick with tools in the standard library but am willing to try external libraries if it will make the task a breeze

Here is a simple example of what I am trying to do:
def f1(a,b):
    """a==b"""
    pass

def f2(f):
    f_locals = "get f's args and values before f is executed"
    return eval(f.__doc__,None,f_locals)

>>> f2(f1(2,2))

Comment: Why? You can't pass `f1(2, 2)` as an argument to another function without evaluating it; the value of `f1(2, 2)` is the return value of the f1 called with those parameters.
Comment: Is it acceptable to call it like `f2(func, *args, **kwargs)`, which in your case would be `f2(f1, 2, 2)`? Is this some kind of testing framework?
Comment: You don't get what you want from http://docs.python.org/library/inspect.html for functions and code objects?
Comment: i know, bad example.  the intention is to "execute the function enough" to get the parameters and values without fully executing the function (which could modify the parameters by execution end).  its a academic project on model checking and i am trying to figure out how to evaluate pre-conditions.  i am trying to "intercept" the function call, retrieve the args/values, and evaluate.
Comment: possible duplicate of [Can you list the keyword arguments a Python function receives?](http://stackoverflow.com/questions/196960/can-you-list-the-keyword-arguments-a-python-function-receives)
Answer: While I have no clue why you would want to do this, what you've described can be achieved with the inspect module. This example is as close to your original example that I can come up with.
from inspect import getcallargs
def f1(a,b):
   """a==b"""
   pass

def f2(f, *f_args, **f_kwargs):
    f_callargs = getcallargs(f, *f_args, **f_kwargs)
    return eval(f.__doc__, None, f_callargs)

f2(f1, 2, 2)

This should output True.
Keep in mind that this assumes a great many things about the arguments and docstrings of any such functions passed to f2, not the least of which is that none of the examined functions are malicious or malformed. Why don't you want to call functions normally, and why don't you want to change functions?
Edit: As Pajton pointed out, getcallargs is more appropriate here, and removes the calls to both dict and zip. The above code has been updated to reflect this.
Comment: Of course `getcallargs(func[, *args][, **kwds])` would be better than `getargspec`.
Answer: I'm not sure if this is what you are looking for, but here's an alternative without inspect module.
#!/usr/bin/python
# -*- coding: utf-8-unix -*-
"""
This is a sample implementation of Inline.pm (Perl) in Python.

Using @inline decorator, it is now possible to write any code
in any language in docstring, and let it compile down to executable
Python code at runtime.

For this specific example, it simply evals input docstring, so
code in docstring must be in Python as well.
"""

# Language compiler for MyLang
class MyLang:
    @classmethod
    def compile(self, docstring):
        # For this example, this simply generates code that
        # evals docstring.
        def testfunc(*arg, **kw):
            return eval(docstring, None, kw)
        return testfunc

# @inline decorator
def inline(lang):
    def decorate(func):
        parm = func.__code__.co_varnames[0:func.__code__.co_argcount]
        fgen = lang.compile(func.__doc__)
        def wrap(*arg, **kw):
            # turn all args into keyword-args
            kw.update(dict(zip(parm, arg)))
            return fgen(**kw)
        return wrap
    return decorate

@inline(MyLang)
def myadd(a, b):
    """a + b"""

print(myadd(1, 9))
print(myadd(b = 8, a = 2))
print(myadd(a = 3, b = 7))


Oops, an error occurred! You are not allowed to access the given folder: "" TYPO3 7.6

Question:
I installed TYPO3 v7.6 and i have installed media gallery extension. I followed This TYPO3 extension user manual,
on step 5 -> In Filelist click on the Create new album in "" icon in top toolbar or use Create new album in "" from the context menu in file list
I m getting this error Please help me
Answer: The storage is offline, you need to enable it.
<code>TYPO3 backend -> List -> File storage -> Edit -> Tab: Access > is online
</code>
Comment: Thank you for your answer


Calculating rate of change of a circle's radius w.r.t. time when given it's area and the rate of change of area w.r.t. time

Question: So I've got a question where I'm given the area of a circle: $$a = 12m^2$$ as well as the rate of change of the decrease in the circle's area w.r.t. time: $$ \frac {da}{dt} = -0.5m^2s^{-1}$$ and I'm being asked to calculate the R.o.C. of the radius w.r.t. time.
This is my working and answer:
$$ r = \sqrt {\frac {a}{\pi}} = 1.9544... $$
$$ \frac {dr}{dt}= \frac {dr}{da} * \frac {da}{dt} $$
$$ a = \pi r^2$$
$$ \frac {da}{dr} = 2 \pi r $$
$$ \frac {dr}{da} = \frac {1}{2 \pi r} $$
$$ \frac {dr}{dt} = \frac {1}{2 \pi r} * -0.5 = -0.0407 (3s.f.) $$
So the radius is decreasing at a rate of: $$ 0.0407ms^{-1} $$ to 3 significant figures when the area is: $$ 12m^2 $$
Have I worked this out correctly?
Comment: I assume the value you gave is the INITIAL area, as it is changing?
Comment: Yes, the wording is "What is the rate of change of the radius when the area of the circle is 12m²?"
Comment: Your solution is correct, I will include a way to do a sanity check in my answer.
Answer: To cross-check the answer, we can do a rough estimation about how the area should have changed given a small $\Delta t$, let's say $\Delta t = 1$ s. Then $A_t = A_0 + \frac{dA}{dt} \Delta t = 12 + (-0.5)(1) = 11.5$ m$^2$ s$^{-1}$, and the corresponding radius would be $r_t = \sqrt{\frac{A_t}{\pi}} = 1.9133$ m.
This leads to an estimation of $\frac{dr}{dt}\approx \frac{\Delta r}{\Delta t }= \frac{1.9544-1.9133}{1} \approx 0.0411$ m s$^{-1}$, which is very close to what you get.
Comment: Edited your answer just for better look


Given an angle at a point A and given another segment BC, construct a point D so that the angle DBC equals the given angle at A.

Question: I'm not sure if I understand this question right.
Q. Given an angle at a point A and given another segment BC, construct a point D so that the angle DBC equals the given angle at A.
Figure -
Should I assume one of the sides of the angle a is bc and the end point of the other side is the point d ?
Comment: Not quite. One of the sides of the *reproduced angle* is $bc$, and the endpoint of the other side is $d$.
Comment: @DavidMitra - I might be misinterpreting what you said, but how is that different from what I intended on assuming ?
Comment: I may be misinterpreting you. It seemed you wanted to take angle $a$ and just call one of its sides $bc$. You have to, of course, reproduce the angle on the line segment $bc$ as given. (The reproduced angle has to be called something other than "$a$").
Comment: @DavidMitra - You are right. But I am still confused on how to reproduce the angle a on the line segment bc?
Comment: Hint: 1) Draw an arc, with arbitrary radius, on angle $a$ with center the vertex of $a$. Call the points of intersection of $a$ and the arc $e$ and $d$ .  2) Draw an arc of radius $d$ with center $b$ on the segment $bc$ 3) How could you find the points on the arc drawn in 2) that correspond  to the points $d$ and $e$?
Answer: David Mitra was spot on. Go the the following link it has the proof and a java video to help you understand. Are you in Math430 UMD?
http://www.mathopenref.com/constcopyangle.html


How can I create IF EXIST clause in my BEFORE INSERT trigger to prevent a duplicate record from being inserted?

Question:

<code>
-- Create a trigger to prevent a student from registering for a section that the student is already
-- registered for.
USE College ;

DROP TRIGGER IF EXISTS  Registration_Before_Insert;

DELIMITER $$

        CREATE TRIGGER Registration_Before_Insert
        BEFORE INSERT ON Registration
        FOR EACH ROW

      BEGIN

        DECLARE Studentid INT;

         SELECT COUNT(*) INTO Studentid FROM Registration WHERE StudentID= NEW.StudentID;
         IF NEW.Studentid= 100 AND NEW.SectionID= 16 THEN
     SIGNAL SQLSTATE VALUE '45000'
      SET MESSAGE_TEXT= 'The student is already registered for this section';
  END IF ;

      END $$

DELIMITER ;

INSERT INTO Registration(StudentID, SectionID, Grade)
VALUES(100, 16, 4.2);

INSERT INTO Registration(StudentID, SectionID, Grade)
VALUES(100, 16, 4.2); </code>

I am working on creating a BEFORE UPDATE trigger to prevent a student from registering for a section that the student is already registered, but I am not sure how to use the IF EXISTS clause within my trigger to invoke that trigger when I insert the same record twice. Can anyone help me? Here is my code?
Comment: I think you could also achieve this by placing a unique constraint on `(StudentID, SectionID)`.  But since your requirement is a trigger, I won't post this as an answer.
Comment: @ Tim Biegeleisen Can you give me a hint of why the second INSERT goes ahead and inserts the same record again instead displaying the error message?
Answer: Perhaps you just need to change the defined variable studentid to something else
<code>DROP TABLE IF EXISTS REGISTRATION;
CREATE TABLE REGISTRATION(StudentID INT, SectionID INT, Grade DECIMAL(10,2));

DROP TRIGGER IF EXISTS  Registration_Before_Insert;
DELIMITER $$
       CREATE TRIGGER Registration_Before_Insert
        BEFORE INSERT ON Registration
        FOR EACH ROW
      BEGIN
       DECLARE counter INT;
         SELECT COUNT(*) INTO counter FROM Registration WHERE StudentID= NEW.StudentID
                and new.sectionid = sectionid;
         IF counter > 0 THEN
                 SIGNAL SQLSTATE VALUE '45000'
                  SET MESSAGE_TEXT= 'The student is already registered for this section';
        END IF ;
      END $$

DELIMITER ;

TRUNCATE TABLE REGISTRATION;

INSERT INTO Registration(StudentID, SectionID, Grade)
VALUES(100, 16, 4.2);

INSERT INTO Registration(StudentID, SectionID, Grade)
VALUES(100, 16, 4.2);
</code>
Comment: @PSalmon, Why put the TRUNCATE statement. I am not clear about why you put that? Truncate statement deletes the data in the table not the actual table? Your statement works. Thanks for your help.
Comment: You don't need truncate - I use it out of habit to ensure that table is empty when I test.


Distributing $k$ distinct items among $r$ distinct groups without ordering

Question:
Calculate the number of ways of distributing $k$ distinct items
  among $r$ distinct groups such that each group receives at least
  $a$ and at most $b$ items and internal arrangement of items
  within groups doesn't matter.

For example suppose there are 2 groups and 3 items A, B, C. The distributions (AB, C) and (BA, C) must not be counted twice.
I've read a similar question here. But the solution doesn't satisfy my second condition.
Answer: Let $a,b,r$ be fixed.  For any $k$,  let $f(k)$ be the number of ways of arranging the $k$ distinct items into $r$ distinct groups with the specifications you give.  The exponential generating function for $f(k)$ is
$$
\sum_{k=0}^\infty f(k) \frac{x^k}{k!} = \left( \frac{x^a}{a!} + \frac{x^{a+1}}{(a+1)!} + \cdots + \frac{x^b}{b!} \right)^r
$$
So, for a fixed $k = k_0$, $f(k_0)$ is the coefficient of $\frac{x^k}{k!}$ in the power series above.  An explicit formula is
$$
f(k_0) = \frac{d^k}{dx^k} \left. \left[ \left( \frac{x^a}{a!} + \frac{x^{a+1}}{(a+1)!} + \cdots + \frac{x^b}{b!} \right)^r \right] \right|_{x = 0}
$$
I highly doubt there is any way to simplify this in general with so many parameters involved.  However, if you pose specific conditions on $a$ and $b$ you get some nicer results.  For example if $a = 0$ and $b = \infty$, then
the generating function becomes $(e^x)^r = e^{rx}$, so $f(k) = r^k$.
But you probably already knew that.
Addendum:
If we require that $|b - a| \le 1$, then either $b = a$ or $b = a+1$.

If $b = a$, we want the coefficient of $\frac{x^k}{k!}$ in $\left(\frac{x^a}{a!}\right)^r$, which should be easy.
If $b = a+1$, we want the coefficient of $\frac{x^k}{k!}$ in $\left(\frac{x^a}{a!} + \frac{x^{a+1}}{(a+1)!}\right)^r = \frac{x^{ar}}{(a!)^r} \left(1 + \frac{x}{a+1}\right)^r$.
This ultimately evaluates to
$$
{r \choose k - ar} \cdot \frac { k! } { (a!)^r (a+1)^{k - ar} }
$$
Comment: Thank you very much ... Let me see if I can work out from here :)
Comment: What if I impose one more condition?..... |b-a|<=1 .. Now the problem reduces to:- What is the coefficient of x^m in the expansion of (1 + a*x + b*x^2)^n Can you please help out?
Comment: @AbhinavChauhan I'll edit the answer.


How do I get a field count from an executed query?

Question: I'm sure this exists, but after a few dozen searches, I'm not any closer to an answer.
After I've executed a query in Drupal (for example)
$dbParts = db_select("parts", "p")
    ->fields("p")
    ->execute();

How can I get a count (or list) of fields without pulling this first record? With MySQL I was able to use "mysql_num_fields".
UPDATE
Just to give a little background... I have some old code (using mysql_* functions) that export data to the DBF format. In order to format the header of the DBF, I need to have a field count (and information about the fields) even if the record count is 0 in order to format a "blank" database.
Answer: Drupal uses PDO, whose equivalent function is PDOStatement::columnCount():

Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.

So what you're looking for isn't totally possible these days. I can't see a Drupal equivalent of columnCount(), but you can always grab the PDO connection object with Database::getConnection(), and work with that directly if it'll help you get part of the way there.
To take a different approach, and assuming you've used the schema API to describe your table to Drupal, you can query that instead:
$table = drupal_get_schema_unprocessed('MYMODULE', 'table_name');
$fields = $table['fields'];

Comment: I just tried $dbParts->columnCount() and it actually works. So I guess the Drupal object is some sort of extension of the 'PDOStatement' object (making it's built in functions available). Thanks! =)
Comment: Sweet, didn't know that!
Comment: Didn't know that?? https://api.drupal.org/api/drupal/includes!database!database.inc/class/DatabaseStatementBase/7 `class DatabaseStatementBase extends \PDOStatement implements DatabaseStatementInterface`
Comment: @chx Just never looked, thinking about it I've used PDO methods on a `SelectQuery` before so on _some_ level I guess I knew ;)


Maximum likelihood estimators for gamma distribution

Question: I'm having trouble with an exercise about maximum likelihood estimators.
Specifically, the exercise gives me values of a protein which was found in 50 adults. We assumed that the data follow a gamma distribution:
$X \sim \Gamma(r,\lambda)= \frac {\lambda^{r}}{\Gamma(r)}x^{r-1}e^{-\lambda x} $ if $x\ge0$.
It asks me to find the maximum likelihood estimators of parameters $\lambda$ and $r$.
How can I find those parameters given that from the data I have $E(X),Var(X)$?
Comment: The standard recipe: write down the likelihood function, take the logarithm, take the gradient of that with respect to the parameters, set it equal to zero. Doing that here, you readily get that the expected value of the estimated distribution (whatever that is in your parametrization; there are three in common usage and it is not clear which you are using here) is the sample mean. I do not easily see how to find both parameters, however, because the other equation appears to be transcendental.
Comment: https://math.stackexchange.com/q/1510480/321264
Answer: We know that $\Gamma(r,\lambda)= \frac {1}{\Gamma(r)}\lambda^{r}x^{r-1}e^{-\lambda x} $ if $x\ge0$.
In this case the likelihood function $L$ is $$\prod_i \Gamma(r,\lambda)_{x_i}=\frac{1}{\Gamma(r)^{n}}\lambda^{nr}x_1^{r-1}x_2^{r-1}...x_n^{r-1}e^{-\lambda T}$$
where $T=x_1+...+x_n$;
By apllying the logaritmic function to $L$ we semplificate the problem so
$$logL=(r-1)\sum_ilogx_i-\lambda T +(nr)log\lambda -nlog(\Gamma(r))$$
and now we must find the point of  max of $logL$, so $\frac{\partial L}{\partial\lambda}= -T+\frac{nr}{\lambda}=0$ which have as solution $\hat\lambda = \frac{nr}{T}$.
With the same method you can obtain the extimation for $r$. (Find $\frac {\partial L}{\partial r}$ and put it equal to $0$).
Comment: yes i agree with you but from the one equation i find that λ=\frac{\widehat{r}}{\widetilde{x}} and from the other  lnr-Γ'(r)/Γ(r)=lnx-x . i have to find numbers not equations...I imagine in this stage i have to use newton-raphson method to find r estimator to find r1 r2 r3 .... until |r4-r3|<10^-4 for example ....i dony know which  r to put in the first equation....sorry for my equations i have to get used latex more....if you have question about the equations i wrote ask me
Comment: the one equation is:  \widehat{ \lambda }=  \frac{r}{ \bar{x} } and the other equation is: \ln( \hat{r} )-\frac{ \Gamma '(r)}{\Gamma (r)} =\ln \bar{x}- \bar{x}
Comment: Maybe you must stimate T with the expected value, the problem give you any information to the the values that each X_i assume?
Comment: no nothing...i can compute μ and σ from the given data but only those....i know that i have to use newton-raphson method for the second equation and after a couple results i have to put r in the first equation but why? and also the first equation has \widehat{r} not r1,r2,....,rn
Comment: In this case i don't know how i can help you, i'm sorry.
Comment: Indeed $\frac{\partial L}{\partial r}$ gives a transcendental equation, even if you know the data $x_i$. One first approximation is to set the variance equal to the sample variance, which would give $r=(\lambda S^{-2})^{1/2}$. This is just the "method of moments" estimator. It is probably not the MLE but it is a place to start your numerical method.
Comment: From the method of moments I have ${{r}_{0}}=\frac{{{\overline{x}}^{2}}}{{{s}^{2}}}$ .Even If I run the newton-rapson method until $\left| {{r}_{n+1}}-{{r}_{n}} \right|<{{10}^{-4}}$ how can I use the ${{r}_{n+1}}$ in my 1st equation which is$\hat{\lambda }=\frac{{\hat{r}}}{{\bar{x}}}$ ?
Comment: To be more certain we have from the method of moments that $\mu =\bar{x}=\frac{{\hat{r}}}{{\hat{\lambda }}}$ and ${{s}^{2}}=\frac{1}{n-1}\sum\limits_{i=1}^{50}{({{x}_{i}}-\bar{x}}{{)}^{2}}= \frac{{\hat{r}}}{{{{\hat{\lambda }}}^{2}}}$ . From this 2 equations we have ${{s}^{2}}=\frac{{\bar{x}}}{{\hat{\lambda }}} =>\hat{\lambda }=\frac{{\bar{x}}}{{{s}^{2}}}$and $\hat{r}=\hat{\lambda }\bar{x}=\frac{{{{\bar{x}}}^{2}}}{{{s}^{2}}}$.
Comment: OK, so you have an initial guess for $r$, namely $\frac{\overline{x}^2}{s^2}$, and an initial guess for $\lambda$, namely $\frac{\overline{x}}{s^2}$. If all you have is the sample mean and sample variance then this is the best you can do. If you have the data then you can try to numerically solve the system of two equations using these method of moments values as initial conditions.


How to avoid NullReferenceException

Question: The following line of code:
double? paidAmount = invoices.Value.Where(x => x.Status.Equals(Constants.InvoicePaid)).Sum(x => x.TotalAmount);

Is causing an error when the status is null.:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Can I avoid this exception using null-coalescing? If interested, here I'm checking if the status property is equal to "paid" I want to sum.
Comment: Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) On another note, `Can I avoid this exception using null-coalescing?`  have you tried it, what was the results?
Comment: We need more information. Which property exactly is throwing the exception ?
Comment: Another option, do you have a choice of `Constants.InvoiceNotPaid` or maybe `Constants.InvoiceNew`, it would be helpful as it could be the default for `Status`... unless `null` is a valid value for notpaid/unknown etc...
Comment: @Fabjan the Status property is causing the exception
Answer: You can use the null coalescing operator:
double? paidAmount = invoices.Value.Where(x => x.Status?.Equals(Constants.InvoicePaid)).Sum(x => x.TotalAmount);

This will evaluate to false if the Status is null.
Comment: `x` shouldn't ever be null, so I don't think you need that conditional operator there.
Comment: Noted, I've updated.
Comment: @ekke it doesn't work it cause compiler error: Cannot convert lambda expression to intended delegate type  because some of the return types in the block are not implicitly convertible to the delegate return type

How to avoid NullReferenceException


How to Set up AWS java project in Eclipse?

Question: i am trying to run simple AWS project in Eclipse but not able to do that. I am very new with this. I have already followed all the step given in official site don,t know what i am missing. please if anyone who has already done this guide me.
Thanks a ton....
Sample Code:
https://github.com/naohta/java_hello_dynamodb
Guidlines:
http://aws.amazon.com/eclipse/faqs/#What_is_the_AWS_Toolkit_for_Eclipse &
<code>http://aws.amazon.com/articles/3586?_encoding=UTF8&jiveRedirect=1
</code>
Comment: Please provide more info what you have tried what is your problem etc
Comment: @a paul i just simply want to run AWS project on Eclipse and for that i already have sample source code. I am even not able to create AWS java Project but able to create AWS java Web project.
Comment: Did you installed "AWS Toolkit for Eclipse" ?
Comment: @APaul ya i installed..after that what i need to do..
Answer: Moving to answer from comment.
I will suggest below steps

AWS Toolkit for Eclipse
This is a good tutorial, might help you. http://java.awsblog.com/post/Tx1GZLJAE4RCX4J/Eclipse-New-AWS-Java-Project-Wizard
Comment: @a paul I want to create New AWS java project but i am not able to do this. according to given tutorial I am trying to do...
Comment: Great. Go ahead I am sure you will be able to do that. Let us know if you have any specific question. And if the above answer help you dont forget to mark it as answer :)
Comment: @a paul still same problem i am not able to create New AWS java Project... :-(
Comment: I think some issues with your eclipse. Please download the latest eclipse and try. It should be very easy to config, not sure what is the issue.


Is training loss guaranteed to decrease for stochastic gradient descent?

Question: When performing stochastic gradient descent, it is necessary for the training loss to decrease
a) between iterations in an epoch? (I think the answer is no)
b) between epochs? (I think the answer is yes)
The training loss is always defined using the entire dataset.
Comment: no to both q's.
Answer: In both cases, it is not guaranteed because you're not using the full batch, i.e. stochastic gradient descent only approximates the gradient to be found by the full batch. However, between epochs (b), it's much more likely to decrease compared to between iterations (a), because the entire training dataset have been inputted to the network and weights are updated several times towards a local minimum.


Data ingestion pipeline in Azure Synapse gives BadRequest ERROR

Question: I am relatively new to Azure Analytics area.
I am getting following error while ingesting data in Azure Synapse using pipeline mentioned in this exercise.
However, at the end, when I try to deploy the data ingestion pipeline, it gives me following error.
BadRequest The document creation or update failed because of invalid reference 'adventureworks'

I tried removing the space between the connection name (which it had earlier). Tried changing the name, which I thought might be taking from somewhere else. But, still it gives ERROR. I can also access products.csv when tried accessing directly.
Is there any other way I can troubleshoot this problem?
Or is this documentation missing any important step or something changed after this doc and its not updated accordingly?
Comment: Please check this thread which provides a solution for similar problem: https://stackoverflow.com/questions/72416798/the-document-creation-or-update-failed-because-of-invalid-reference
Answer:
As per the Microsoft documentation,
try to change the step 6 & 9 from Ingest data -> 6th point
Row delimiter as Default (\r,\n, or \r\n) from the above.
As we implemented and followed the same steps and here it is a working solution for the similar SO.
And as per @ChiragMishra's reply here, maybe you have not published the linked service once you created, recheck it after connection modified (space removed) have you hit the publish.


show "My billing information is the same as my shipping information." option when creating order from admin

Question: I am using Drupal version 9.3.14.
Option "My billing information is the same as my shipping information." gets available on checkout page automatically. But when creating order from Admin side this option is not available resulting into filling same address twice in shipping and billing address.
How can I make this option available on admin side also?
Answer: It's roughly supported but not a great experience. Essentially, you would have to create the order without any billing details then create a shipment for the order. After doing so, when you go back to the order edit screen and click the button to add a billing address, it will default to copying the address from the shipment.
Ideally, the shipment add form would have a similar option to copy from the billing address instead, since the order management flow is different from the checkout flow. I'm going to file that as a feature request for the Commerce Shipping module.
Comment: Yes, currently we are following the same steps. Creating an order without billing details, and then edit the order again and click that checkbox to copy the address. But it becomes little bit tedious when there many orders to process in a day.
Comment: I forgot to link to the ticket I created. I think this is fixable. : D https://www.drupal.org/project/commerce_shipping/issues/3316917


Problet to Nested StimulSoft

Question: Field UserName has value in StimulSoft but list OrderLogViewModels nothing any value.. how do i get it?
<code>public class OrderLogsViewModel
{
  public int? Id { get; set; }
  public string UserName { get; set; }

  public List<ViewModel.LogsViewModel> OrderLogViewModels { get; set; }
}
</code>
Comment: where are you initializing OrderLogsViewModel and how are you checking the values
Comment: OrderLogViewModels has values and correctly transmits Stimulus

But the problem is OrderLogViewModels in Stimul, I can't get the nested listing in Business Object
Answer: If you use mrt file you can define new Child Of Business Object;

Add a business object with Model name and add Id, UserName column to it;
Right click on Model and select New Business Object (Child Of Business Object);

Select Child Of Business Object and then name it what you want like OrderLogViewModels and then add your LogsViewModel class properties to it;

Set your data band's Data Source to OrderLogViewModels and use it in your Text component like Model.OrderLogViewModels.OrderId or Model.OrderLogViewModels.Log;

Problet to Nested StimulSoft