HTML - Float 3 tables next to each other but have text below

Question: I am floating 3 tables next to each other using
 and this works just fine.  However, I have some text that I want at the very bottom, and I want it to be left justified.  Currently, it is just being wrapped to the right side of the right-most table.  I've confirmed that it is outside of all of my tables.  My html is below.  This creates 3 tables, with nested tables within them.  The 3 main tables line up next to each other, but I want the text to be at the bottom and not shoved off to the left...

td,
th {
  font-family: calibri;
  border: 1px solid black;
  padding: 2px;
}

.tablestyle {
  font-family: calibri;
  border: 1px solid black;
  width: 420px;
}

.wide {
  width: 40%;
}

.thin {
  width: 20%;
}

Weather Summary for $date:

    Temperature
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      Temperature (℉)
      $hTemp
      $aTemp
      $lTemp

      Dewpoint (℉)
      $hDewPnt
      $aDewPnt
      $lDewPnt

      Humidity (%)
      $hHum
      $aHum
      $lHum

      Feels Like (℉)
      $hFeels
      $aFeels
      $lFeels

      Apparent Temperature (℉)
      $hAppTemp
      $aAppTemp
      $lAppTemp

      Heat Index (℉)
      $hHeatInd
      $aHeatInd
      $lHeatInd

      Wind Chill (℉)
      $hWndChl
      $aWndChl
      $lWndChl

    Wind & Pressure
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      Pressure (inHg)
      $mxPress
      $aPress
      $mnPress

      Wind Speed (mph)
      $hWind
      $aWind
      $lWind

      Wind Gust (mph)
      $hWndGst
      $aWndGst
      -

      Wind Direction
      -
      $aWndDir
      -

    Rain & Evaporation
    <col span="1" class="wide">

      Maximum
      Total
      Minimum

      Rainfall (in)
      -
      $totRain
      -

      Rain Rate (in/Hr)
      $rainRate
      -
      -

      Evapotranspiration (in)
      -
      $evapoTrans
      -

    Solar
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      UV Index
      $hUV
      $aUV
      -

      Solar Radiation (W/m²)
      $hSolRad
      $aSolRad
      -</td

    Temperature
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      Temperature (℉)
      $hTemp
      $aTemp
      $lTemp

      Dewpoint (℉)
      $hDewPnt
      $aDewPnt
      $lDewPnt

      Humidity (%)
      $hHum
      $aHum
      $lHum

      Feels Like (℉)
      $hFeels
      $aFeels
      $lFeels

      Apparent Temperature (℉)
      $hAppTemp
      $aAppTemp
      $lAppTemp

      Heat Index (℉)
      $hHeatInd
      $aHeatInd
      $lHeatInd

      Wind Chill (℉)
      $hWndChl
      $aWndChl
      $lWndChl

    Wind & Pressure
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      Pressure (inHg)
      $mxPress
      $aPress
      $mnPress

      Wind Speed (mph)
      $hWind
      $aWind
      $lWind

      Wind Gust (mph)
      $hWndGst
      $aWndGst
      -

      Wind Direction
      -
      $aWndDir
      -

    Rain & Evaporation
    <col span="1" class="wide">

      Maximum
      Total
      Minimum

      Rainfall (in)
      -
      $totRain
      -

      Rain Rate (in/Hr)
      $rainRate
      -
      -

      Evapotranspiration (in)
      -
      $evapoTrans
      -

    Solar
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      UV Index
      $hUV
      $aUV
      -

      Solar Radiation (W/m²)
      $hSolRad
      $aSolRad
      -</td

    Temperature
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      Temperature (℉)
      $hTemp
      $aTemp
      $lTemp

      Dewpoint (℉)
      $hDewPnt
      $aDewPnt
      $lDewPnt

      Humidity (%)
      $hHum
      $aHum
      $lHum

      Feels Like (℉)
      $hFeels
      $aFeels
      $lFeels

      Apparent Temperature (℉)
      $hAppTemp
      $aAppTemp
      $lAppTemp

      Heat Index (℉)
      $hHeatInd
      $aHeatInd
      $lHeatInd

      Wind Chill (℉)
      $hWndChl
      $aWndChl
      $lWndChl

    Wind & Pressure
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      Pressure (inHg)
      $mxPress
      $aPress
      $mnPress

      Wind Speed (mph)
      $hWind
      $aWind
      $lWind

      Wind Gust (mph)
      $hWndGst
      $aWndGst
      -

      Wind Direction
      -
      $aWndDir
      -

    Rain & Evaporation
    <col span="1" class="wide">

      Maximum
      Total
      Minimum

      Rainfall (in)
      -
      $totRain
      -

      Rain Rate (in/Hr)
      $rainRate
      -
      -

      Evapotranspiration (in)
      -
      $evapoTrans
      -

    Solar
    <col span="1" class="wide">

      Maximum
      Average
      Minimum

      UV Index
      $hUV
      $aUV
      -

      Solar Radiation (W/m²)
      $hSolRad
      $aSolRad
      -</td

Definitions:

Feels Like: attempts to quantify what human skin detects as the temperature, taking into account any warming or cooling effect of exposure to different humidity levels, high wind, or shade/sunshine.

Apparent Temperature: the general term for the perceived outdoor temperature, caused by the combined effects of air temperature, relative humidity and wind speed.

Heat Index: an index that combines air temperature and relative humidity in an attempt to determine the human-perceived equivalent temperature - how hot it feels.

Wind Chill: takes into account how the speed of the wind affects our perception of the air temperature. The faster the wind blows, the faster heat from our bodies is carried away and the colder the environment feels.

Evapotranspiration: the process by which water is transferred from the land to the atmosphere by evaporation from the soil and other surfaces and by transpiration from plants.

UV Index: a measure of the intensity of ultraviolet radiation from the sun at the sun's highest point on a particular day in a particular place.

Solar Radiaton: energy radiated from the sun in the form of electromagnetic waves, including visible and ultraviolet light and infrared radiation.

Comment: You have already been answered, but so that you understand what the matter is, I recommend that you familiarize yourself with the concept [float and clear](https://www.w3schools.com/css/css_float.asp) I hope you find it useful
Answer: Wrap everything after the tables in a div and


Do I need to explicity unload an assembly I loaded dynamically?

Question: I am using some .NET assemblies another developer wrote for use from an older VB6 application. They are only used for some of our customers so I am using the Assembly.LoadFrom(file) method and invoking the methods. I am worried about unloading / releasing the objects after I make the calls. Do I need to do something explicitly, or will the garbage collector take care of it automatically?
Answer: You can't unload an assembly.
(The closest you can come to that is loading it into an AppDomain that you then unload.)
Comment: Dynamically loading assemblies into a separate AppDomain is actually the correct design pattern.  That way, if an unhandled exception is thrown in the dynamically loaded assembly, it is isolated from your application which loaded it.  Furthermore, as Steven stated, you can shut down the dynamically loaded AppDomain when needed.


Embed and display PDF viewer

Question: I'm looking for a solution to display some of my PDF files with a viewer.
I found many solutions for Drupal 7 but not yet for Drupal 8.
Is there any module or open source solution to display PDFs in a Viewer ?
Answer: You can use the Embedded Google Docs Viewer module for that

Drupal 8
This module provides a formatter for the File field type. This
  formatter presents the file as a fully rendered object within a web
  page - i.e. it displays the contents of the file as appropriate to its
  filetype (Adobe Acrobat .pdf, Microsoft Word .doc/.docx, Microsoft
  Excel .xls/.xlsx, Microsoft Powerpoint .ppt/.pptx), using the Google
  Docs embedded rendering engine.

There are some other modules but those are in Dev version. Have a look at the Comparison of PDF viewer modules
Comment: Thank you for your help. I will not use any viewer after all

Embed and display PDF viewer


Plugin Facebook - PhoneGap

Question: estou utilizando um plugin do PhoneGap para logar-se com o Facebook, está funcionando perfeitamente, eu consigo obter o email e o id do usuario, agora, eu precisava colocar esses dados num JSON para eu trabalhar com ele via ajax.
segue o codigo:
HTML

Logar com Facebook

Mostrar Dados

Fazer Logout

JS
        var login = function () {
          if (!window.cordova) {
             var appId = '305528339609022';
             facebookConnectPlugin.browserInit(appId);
          }
          facebookConnectPlugin.login( ["email"],
             function (response) { alert(JSON.stringify(response)) },
             function (response) { alert(JSON.stringify(response)) });
        }

        var apiTest = function () {
            facebookConnectPlugin.api( "me/?fields=id,email", ["user_birthday"],
                function (response) { alert(JSON.stringify(response)) },
                function (response) { alert(JSON.stringify(response)) });
        }

        var logout = function () {
            facebookConnectPlugin.logout(
                function (response) { alert(JSON.stringify(response)) },
                function (response) { alert(JSON.stringify(response)) });
        }

podem ver que faço o login() depois clico no mostrar dados, nisso vai aparecer um alert pra mim mostrando os dados. Agora, eu precisava botar ele num array, para pegar via ajax...
vocês podem ver no ar
http://www.petfy.com.br/facebookconnect/www/
CERTO AGORA EU PEGUEI OS DADOS, ELE ESTA EM OBJETO
MEU OBJETO
                var apiTest = function () {
                facebookConnectPlugin.api( "me/?fields=id,email", ["user_birthday"],
                    function (response) {
                      dados = response;
                    });
            }

o objeto chama-se "dados", como eu posso pegar esse objeto e fazer um json_enconde()?
Comment: botar num array para pegar via ajax ? xDD
Comment: na apiTest(), a response que recebes já é um js object, basta guardares numa var qlqer
Comment: @EnoqueDuarte como ficaria? var id = JSON.stringify(response); ?
Comment: podes declarar a var 1º no topo, onde quisers (var dados), e depois entao dentro da função dás o valor (dados = response),,,,, se queres um object não fazes o stringify xd, o stringify é para transformar o jobject numa string json
Comment: vou meter o codigo numa resposta para veres
Comment: @EnoqueDuarte eu entendi, agora, como faço para por exmplo, pegar ela via ajax?

vou editar a pergunta
Comment: o que queres dizer como pegar ela via ajax ? a variavel está definida, é só usa-la :)
Comment: uhm ? esse codigo vai tar no servidor ?? estás a usar node.js ?
Comment: acho que te estás a confundir xd, o javascript corre client-side
Comment: sim @EnoqueDuarte eu quis dizer que o codigo que conecta com o facebook vai estar no server-side, para eu pegar esses dados no server eu vo ta no cliente-side! entende?
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/16255/discussion-between-enoque-duarte-and-furlan).
Answer: Bastante simples, defines uma variavel fora da chamada à api e dentro da chamada guardas a response nessa variavel... como queres um objeto, não fazes o JSON.stringify() , o stringify serve apenas para respresentar o objeto numa string json (para apresentar num alert como ai tens por exemplo)
   var dados;

   var login = function () {
      if (!window.cordova) {
         var appId = '305528339609022';
         facebookConnectPlugin.browserInit(appId);
      }
      facebookConnectPlugin.login( ["email"],
         function (response) { alert(JSON.stringify(response)) },
         function (response) { alert(JSON.stringify(response)) });
    }

    var apiTest = function () {
        facebookConnectPlugin.api( "me/?fields=id,email", ["user_birthday"],
            function (response) {
              dados = response;
              alert("sucesso !!!"+JSON.stringify(response));
            },
            function (response) { alert(JSON.stringify(response)) });
    }

    var logout = function () {
        facebookConnectPlugin.logout(
            function (response) { alert(JSON.stringify(response)) },
            function (response) { alert(JSON.stringify(response)) });
    }

Comment: Olá, bem vindo SO-PT, sua resposta parece ser boa e responder a pergunta, só que não é há muita explicação em torno dela, se possível, comente a sua solução proposta para que possamos entender melhor o que ela propõe.

Plugin Facebook - PhoneGap


Scale SVG image non-proportionally to fit in remaining space

Question: Below arrow is composed out of 3 single  elements. The center part should stretch horizontally so the arrow can fill its surrounding container. But as you can see in the rendered code, the stretching doesn't work. How to enable stretching and making sure, there are no gaps at the junctures. Probably, there should be a small overlap between the parts because of the antialiasing (which is mandatory).

EDIT: Using preserveAspectRatio="none" suggested by @Turnip is stretching the image, but it is producing gaps and jumps on certain widths. See this screenshot:

Can't explain this weird behavior at all!

.arrow {
  display: flex;
  max-width: 200px;
  padding-bottom: 2em;
}

.arrow svg {
  height: 25px;
  shape-rendering: auto;
}

#arrow-1 svg.stretched {}

#arrow-2 svg.stretched {
  width: 100%;
}

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M13 2.5h-1.31A5.21 5.21 0 006.5 7.69v14.62"/>
</svg>

  <svg xmlns="http://www.w3.org/2000/svg" class="mid" viewBox="0 0 3 25"><rect y="1" width="3" height="3"/></svg>

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M5.5 15.84V7.69A5.21 5.21 0 00.31 2.5H0"/>
  <path d="M5.5 24.31l4.88-11.94-4.88 2.84-4.88-2.84L5.5 24.31z"/>
</svg>

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M13 2.5h-1.31A5.21 5.21 0 006.5 7.69v14.62"/>
</svg>

  <svg xmlns="http://www.w3.org/2000/svg" class="stretched" viewBox="0 0 3 25"><rect y="1" width="3" height="3"/></svg>

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M5.5 15.84V7.69A5.21 5.21 0 00.31 2.5H0"/>
  <path d="M5.5 24.31l4.88-11.94-4.88 2.84-4.88-2.84L5.5 24.31z"/>
</svg>

Answer: Instead of using 3 svg elements I'm using only one. I'm putting the start and the end of the "arrow" in a <symbol> element so that I can use those shapes where I need them. Please observe that the <symbol> elements have a tight viewbox (the viewBox is wrapping tight the shape and has the same size as the bounding box of the shape + some extra space for the 1/2 width of the line).
Now I can use those symbols as many times as I need and where I need.
In order to connect the 2 use elements I'm using a line. please observe that the x1 attribute of the line (in the first group) is 18 where 18 = 10 (the x attribute of the first use element) + 8 (the width attribute of the first use element).
The x2 attribute of the line deppends on how long you need it to be and has the same value as the attribute x of the second use element.

<svg viewBox="0 0 130 70">
  <symbol id="start" xmlns="http://www.w3.org/2000/svg" viewBox="5 0 8 22">
    <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M13 2.5h-1.31A5.21 5.21 0 006.5 7.69v14.62" />
  </symbol>

  <symbol id="end" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 25">
    <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M5.5 15.84V7.69A5.21 5.21 0 00.31 2.5H0" />
    <path d="M5.5 24.31l4.88-11.94-4.88 2.84-4.88-2.84L5.5 24.31z" />
  </symbol>

  <g id="g1">
    <use xlink:href="#start" x="10" width="8" height="22" />
    <use xlink:href="#end" x="100" width="11" height="25" />
    <line x1="18" y1="2.5" x2="100" y2="2.5" stroke="black" stroke-width="3" stroke-linecap="round" />
  </g>

  <g id="g2">
    <use xlink:href="#start" x="20" y="35" width="8" height="22" />
    <use xlink:href="#end" x="70" y="35" width="11" height="25" />
    <line x1="28" x2="70" y1="37.5" y2="37.5" stroke="black" stroke-width="3" stroke-linecap="round" />
  </g>
</svg>
Comment: Very elegant solution, I really like it! But unfortunately it scales proportionally instead of horizontally only; stroke width should be fix.
Answer: You can do the biggest part using CSS and it would easier to handle:

.box {
  width: 50%;
  margin: auto;
  height: 50px;
  border: 10px solid;
  border-bottom: 0;
  border-radius: 20px 20px 0 0;
  position: relative;
}

.box::after {
  content: "";
  position: absolute;
  bottom: 0;
  right: -5px;
  width: 45px;
  height: 58px;
  transform: translate(50%, 30%);
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 12 11 13"><path d="M5.5 24.31l4.88-11.94-4.88 2.84-4.88-2.84L5.5 24.31z"></path></svg>') bottom/contain no-repeat;
}

Also like below:

.box {
  width: 50%;
  margin: auto;
  height: 50px;
  border: 10px solid;
  border-bottom: 0;
  border-radius: 20px 20px 0 0;
  position: relative;
}

.box svg {
  position: absolute;
  bottom: 0;
  right: -5px;
  width: 45px;
  transform: translate(50%, 30%);
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 12 11 13"><path d="M5.5 24.31l4.88-11.94-4.88 2.84-4.88-2.84L5.5 24.31z"></path></svg>

Comment: Using background images in CSS is a good approach — but unfortunately I can't use pseudo elements because I am limited to use CSS inline styles!
Answer: Use preserveAspectRatio="none" on the SVG that you want to stretch. This will allow the inner rect to stretch along with the SVG element.

.arrow {
  display: flex;
  max-width: 200px;
  padding-bottom: 2em;
}

.arrow svg {
  height: 25px;
  shape-rendering: auto;
}

#arrow-1 svg.stretched {}

#arrow-2 svg.stretched {
  width: 100%;
}

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M13 2.5h-1.31A5.21 5.21 0 006.5 7.69v14.62"/>
</svg>

  <svg xmlns="http://www.w3.org/2000/svg" class="mid" viewBox="0 0 3 25"><rect y="1" width="3" height="3"/></svg>

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M5.5 15.84V7.69A5.21 5.21 0 00.31 2.5H0"/>
  <path d="M5.5 24.31l4.88-11.94-4.88 2.84-4.88-2.84L5.5 24.31z"/>
</svg>

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M13 2.5h-1.31A5.21 5.21 0 006.5 7.69v14.62"/>
</svg>

  <svg xmlns="http://www.w3.org/2000/svg" class="stretched" viewBox="0 0 3 25" preserveAspectRatio="none"><rect y="2" width="3" height="3"/></svg>

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 25">
  <path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3" d="M5.5 15.84V7.69A5.21 5.21 0 00.31 2.5H0"/>
  <path d="M5.5 24.31l4.88-11.94-4.88 2.84-4.88-2.84L5.5 24.31z"/>
</svg>

Comment: Yes, the stretching works, but somehow the look gets messed up if the middle part is smaller or larger. Just remove max-width and try by making viewport smaller and larger. I'll put an image of the result at the end of my question.


kiwi tcms - Gitlab bug tracker Integration

Question: I have installed kiwi tcms on my machine with docker installation (https://kiwitcms.readthedocs.io/en/latest/installing_docker.html)
I have successfully created User/TestCases/TestPlan/TestRuns ...
But I would like to use GitLab as my issue tracker.
I found this documentation https://kiwitcms.readthedocs.io/en/latest/modules/tcms.issuetracker.types.html but since I´m new as kiwi tcms user, I don´t figure out how to be able to use this.
I have my GitLab repo ready to test.
Thanks for your help.
Answer: See https://kiwitcms.readthedocs.io/en/latest/admin.html#configure-bug-trackers
this should help clear some of the missing pieces.
You have to create a new record in the database which represents your GitLab repository. For that you need the base_url and api_password fields. They are the ones used by the integration code.
Notice that there can be several different products (repositories) on GitLab and for each one you need to create records in the Kiwi database. Otherwise Kiwi TCMS will not know how to link TestCases to issues on GitLab.
Note: GitLab integration was brough to Kiwi TCMS over the weekend by an external contributor and the new version that supports it has been literally released minutes ago. You may have to update your docker image to make use of that.


Information about Mercury hammer blow tenor sax

Question: I bought a very nice playing upper-level saxophone. It says "Mercury Design in USA". The seller told me the parts came from Korea and it was assembled in the USA.
Seller said:

Double arms on all claps in the low registers, just like the Yanagisawa's.

Inscription:

"Mercury musical design USA"

Serial nummer:

JF0117H8.

It plays incredible, but I can't find any information about this peculiar sax. And the hammer blow is really rare. Have you seem hammer blow (does it translate like this: hamerslag) saxes before? Does anybody have any information about this sax?

I've only found this strange website:
http://www.lk-js.com/en/info.asp?id=4
Comment: Checking in w/ my bro the sax repair/restore/performance guy... hope to have an answer soon.
Comment: Also got some info here http://forum.saxontheweb.net/showthread.php?207830-Coolest-sax-ever-Information-about-Mercury-hammer-blow-tenor-sax&p=2168798&posted=1#post2168798
Answer: New and Asian. Basically if you have a few design ideas and a checkbook, you can get an Asian manufacturer to make their standard issue horn with your personal modifications and your brand name. And, yes, they make some good ones. Could be something like a music shop owner in Smalltown, USA who hoped to hit the big time.


Finding rating for individual based on multiple raters

Question: I am trying to find an individual agent's score based on customer scores (raters) while the customer only rates their overall experience.
Context
The customer enters a shop and meets a service agent number one. Then he moves onto service agent two and so on. Generally, a customer meets 4 to 6 agents one after another and once he is done with all the transaction he is asked his overall experience of all the agent interactions on a scale of 1 to 5. It is possible to know which all service agents the customer met and tie the overall score to all those service agents
It is optional for customers to leave feedback. Moreover, there are multiple service agents, with different shift routines, close to 200, that are working in different departments which implies that each customer is unique but service agents are randomly assigned.
Eg - Customer no. 1 meets service agent A,B,C,D and E, while customer no. 2 meets B,D,E,G and H.
Problem

I am trying to ascertain the rating of each service agent based on the overall customer store
Additionally, it would be great if I could somehow compare service agents across departments

Attempt
I have been assuming that each service agent is equally liable for the overall experience score and thus I have been doing the following

Assign the overall experience score to each service agent who met that customer
Find the average of all such customer scores for that service agent

Customer Score Table

Service Agent Score Table
Service Agent ║ Average Score
║  A             ║ 3.67
║
B             ║ 4
║
C             ║ 3
║
D             ║ 5
║
E             ║ 2.5
I have also searched stack exchange and come across terms such as Cronbach's alpha, Cohen's Kappa and Fleiss Kappa but I do not think they apply to my case. I think this way of rating plus ANOVA can do the trick as can be found here which is somewhat similar to my problem.
Your thoughts?
Comment: Seems to me this is not going to work well. A perceived very bad experience with only one agent can spoil a customer's ratings for the whole visit---even if the one agent's behavior is not typical of the group. // Personal anecdote: Dealership where I get my car serviced has one persistently disagreeable agent and several pleasant, efficient ones. Always asked to send in questionnaire. Don't give 'very highly satisfied' rating for whole visit even if outcome satisfactory: that one agent is enough to make me want to stay away. Mgmt must be clueless not to realize they've got a grump.
Comment: @BruceET We had thought about it but couldn't because of teo reasons. First, multiple questions leads to frustration among the responders which will cause lesser response rate. Second, most customers aren't bothered to know the names of all the service agents who they met even if they arr willing to fill a longer survey.
Comment: I wasn't criticizing your survey, just pointing out difficulties of making inferences about specific employees. Even so, it you find a particular store with an unusual mix of good and bad scores, then it may be worthwhile trying to deduce who was on duty for which questionnaires.
Comment: @BruceET Deducing who was on duty is something that is already being monitored. The difficult part is correlating it with the the customer score. Are you aware of any such problem or a way to solve this one with the constraints mentioned?
Answer: I wasn't able to find a satisfactory answer but I suppose statistics like Shapley Values or Wins above replacement levels might be helpful.


java csv multiple data parsing

Question: I have String as:
String cont = "[[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,13.46,\"1682432\"]," +
                    "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-13.46,\"1682432\"]," +
                    "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-14.52,\"1682432\"]," +
                    "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FICA and\",-13.46,0,\"1682432\"]," +
                    "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FEED\",-1.06,0,\"1682432\"]" +
                "]";

I need output as
Account || Date ||        Amount || Description ||          InvoiceNo
1001     2014-07-15       -13.46                            1682432
....some more data
6002     2014-07-15       -1.06    MY desc                  1682432

I am trying to use Apache CSV parser with version 2.3.
<dependency>
    <groupId>net.sf.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>2.3</version>
</dependency>

java code:
CSVReader reader = new CSVReader(new StringReader(cont), ',');
List<String[]> records = reader.readAll();
Iterator<String[]> iterator = records.iterator();
while (iterator.hasNext()) {
    String[] record  =  iterator.next();
    for (String string : record) {
        System.out.println(string);
    }
}

output:
[[START
1001
2014-07-15

...

["START
6002
020
0000000PWO
2014-07-15
MY Comment - FEED
-1.06
0
1682432"]]

1) How do I remove the special character "[" and "]"
2) How do I assign values to above output fields
3) I want to convert above csv to bean object
4) bean to json
Comment: I think you're actually using [opencsv](http://opencsv.sourceforge.net). Yes, it happens to be under Apache license, but there is also [Commons CSV](http://commons.apache.org/proper/commons-csv/) which is the CSV library by The Apache Software Foundation. As a side note, I can warmly recommend Commons CSV.
Answer: You could utilize the open source library uniVocity-parsers to convert csv to bean objects, just as following code shows:
public static void main(String[] args) throws FileNotFoundException {
    /**
     * ---------------------------------------------
     *  Read CSV rows into list of beans you defined
     * ---------------------------------------------
     */
    // 1st, config the CSV reader with row processor attaching the bean definition
    BeanListProcessor<ColumnBean> rowProcessor = new BeanListProcessor<ColumnBean>(ColumnBean.class);
    settings.setRowProcessor(rowProcessor);
    settings.setHeaderExtractionEnabled(true);

    // 2nd, parse all rows from the CSV file into the list of beans you defined
    parser.parse(new StringReader(cont));
    List<ColumnBean> resolvedBeans = rowProcessor.getBeans();

    // 3rd, process the beans with business logic
    // ......
}

With the library, you only need several lines of code, and it also provides significent performance. Find tutorials at its Homepage.
As per the convert from bean object to json, you can check the Google Gson project.
Answer: For 2), use System.out.print, instead of println (this just prints the string without a new line at the end), and concatenate tabs (\t) to your data values.  You will need to break up your string variable into multiple parts to achieve this.  Tabs will allow you to align them in proper rows appropriately.
Once your string is in multiple parts, for 1) you will want to slice the first character from the first "piece" and the last character from the last piece.  This will remove the first [ and the last ].  I suggest using substring.
Answer: To remove the special characters I used a regexp for all special characters except "-" which you strings seems to contain. If more characters are to be kept , refactor that to a special set and just append it to the regexp.
For assigning values I'm not really sure what you want to do, I guess you want a String variable in the code for either a line or a ,ABCXYZ,. If you want to construct a string dynamically from a whole line use a StringBuilder or StringBuffer. I came up with this code for parsing
String cont = "[[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,13.46,\"1682432\"]," +
            "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-13.46,\"1682432\"]," +
            "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-14.52,\"1682432\"]," +
            "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FICA and\",-13.46,0,\"1682432\"]," +
            "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FEED\",-1.06,0,\"1682432\"]" +
            "]";

    CSVReader reader = new CSVReader(new StringReader(cont), ',');
    List<String[]> records = reader.readAll();
    Iterator<String[]> iterator = records.iterator();
    while (iterator.hasNext()) {
        String[] record = iterator.next();

        for (String string : record) {
            string = string.replaceAll("[^\\w\\s\\-]", "");
            if (string.startsWith("START")) {
                System.out.println();
            }
            System.out.print(string);
            System.out.print(",");
        }
    }

Answer: You no need to use any csv parser jars
Just use the below code
public static void main(String arg[]) {
   String cont = "[[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,13.46,\"1682432\"]," +
                "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-13.46,\"1682432\"]," +
                "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-14.52,\"1682432\"]," +
                "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FICA and\",-13.46,0,\"1682432\"]," +
                "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FEED\",-1.06,0,\"1682432\"]" +
            "]";

    String[] csvArry = cont.split(",");
    for (String value : csvArry) {
        value = value.replaceAll("[^\\w\\s\\-]", "");
        System.out.println(value);
    }
}

It will do everything which you want.
Hope this will resolve your issue.
Answer: For transformation of CSV to beans use https://github.com/CyborTronik/fluent-ssv
You are also able to write your line parser(where you will throw unecesary chars) by implementing LineParser and provide it to SsvStreamBuilder.
That's it

java csv multiple data parsing


Probability distribution estimation -- why normalize by bin width?

Question: This is from a typical introduction to kernel density estimation.
Suppose we want to estimate the probability density function $p(x)$ given a set of samples $x_1,x_2 \ldots x_N$. The simplest method that does this is from the histogram of the samples.

Divide the sample space into a number of bins and approximate the
  density at the center of each bin by the fraction of points in the
  training data that fall into the corresponding bin.

Suppose we have divided the sample space into $K$ bins of width $h$. The histogram of the given data is computed as :
$$
H(k) = \# \hspace{1mm} \mbox{of} \hspace{1mm} x^{(i)} \hspace{1mm} \mbox{in bin k }
$$
This can be converted into a probability density as
$$
P(k) = \frac{H(k)}{N}
$$
For a given sample $x$, let $p_k(x)$ be the probability that $x$ falls in bin $k$. From above, we have
$$
p_k(x) = P(k)
$$
Why is it that the above is mentioned further normalized by bin width $h$ as follows ?
$$
p_k(x) = \frac{\# \hspace{1mm} \mbox{of} \hspace{1mm} x^{(k)} \hspace{1mm} \mbox{in same bin as x} }{N h}
$$
Comment: This can be seen on dimensional grounds alone. Probability density is not probability, but a density with units probability per unit used. If the variable is length in mm, it is per mm; if the variable is age in years; it is per year.
Comment: Turns out there are some assumptions on the underlying $p(x)$ that bring in $h$. I found the following useful : http://research.cs.tamu.edu/prism/lectures/pr/pr_l7.pdf
Comment: By definition a *density* is a probability divided by the bin width.  See http://stats.stackexchange.com/questions/4220 for further discussion.  **This question therefore seems to have reversed the concepts of probability and density:** $P(k)$ is the probability and $p_k(x)$ is the density.  It is not valid to equate the two; as Nick Cox pointed out, they don't even have the same units of measurement.
Answer: The expression
$$P(k) = \frac{H(k)}{N}$$
is the empirical relative frequency mass that falls into bin $k$, which we think of as empirical probability mass.
Let bin $k$ be the interval $[x_1, x_2]$, with center $x_k$. Then the estimated density curve $p(x)$  should be such that the area on this interval below the density curve is approximately $P(k)$. This can be approximated by a trapezoid, especially if bin length $h=x_2-x_1$ is "small". Applying the rule for the area of a trapezoid we have
$$ \frac{H(k)}{N}\approx (x_2-x_1)\frac {p(x_2) + p(x_1)}{2} \approx hp(x_k) $$
$$\Rightarrow \hat p(x_k)\approx\frac{H(k)}{Nh}$$
Sine we have started by remarking that $H(k)/N$ is empirical probability, this result also helps seeing why the density does not give probabilities.
Comment: Note that the trapezoid rule is not needed here and therefore invoking it may be an unnecessary distraction from the crux of the matter. Implicitly, KDE assumes the density is continuous. In this case the [Mean Value Theorem](http://en.wikipedia.org/wiki/Mean_value_theorem#First_mean_value_theorem_for_integration) of Calculus asserts the existence of $x_k\in [x_1,x_2]$ for which $$p(x_k)=\frac{1}{x_2-x_1}\int_{x_1}^{x_2}p(x)dx,$$ which is estimated by $\frac{1}{x_2-x_1}H(k)/N=H(k)/(Nh)$. These equalities are *exact*, not approximations (and $h$ need not even be "small").
Comment: So $p_k(x)$ is an estimate of probability distribution. When $h$ is small, it close to probability $P(k)$. $\sum p_k(x) \neq 1$. $\sum P(k) = 1$. $\sum p_k(x) * h = 1$. Right? As the function `hist()` in `R` statisfies $\sum_i f^{(x[i])} (b[i+1]-b[i]) =1$,  where $f^{(x[i])}$ is density in bins, $b[i+1]-b[i]$ is binwidth.


How to handle OAuth2 refreshToken with RestKit 0.20

Question: I know for method
<code>-[[RKObjectManager sharedManager].HTTPClient setAuthorizationHeaderWithToken:]
</code>
and I suppose that this method accepts accessToken. How to handle OAuth2 refreshToken?
Comment: So you're already handling the OAuth login and getting the token, you then just need to set the token? And the token is sent as a header in each request?
Comment: Yes, that's right. I'm also trying to set AFOAuth2Client (extension on AFHTTPClient) to handle access and refresh tokens, but RKObjectManager returns false response. I'll add code example
Answer: Ok, I resolve my problem.
First of all, you have to download AFOAuth2Client from http://goo.gl/zdTdlJ
This is AFHTTPClient extension witch handles OAuth2 authentication and here's snippet how to initialize it and set it into RestKit as HTTPClient.
<code>AFOAuthCredential* credential = [AFOAuthCredential credentialWithOAuthToken:accessToken tokenType:kAFOAuthCodeGrantType];
[credential setRefreshToken:refreshToken expiration:expirationDate];
AFOAuth2Client* oAuth2Client = [AFOAuth2Client clientWithBaseURL:[NSURL URLWithString:baseUrl]
                                                                clientID:clientID
                                                                  secret:secret];
[oAuth2Client setAuthorizationHeaderWithToken:accessToken];

// This line is for environment where you don't have valid certificate.
// For example for development environment
[oAuth2Client setAllowsInvalidSSLCertificate:YES];

[[RKObjectManager sharedManager] setHTTPClient:oAuth2Client];
[[RKObjectManager sharedManager] getObjectsAtPath:path parameters:nil
     success:^(
       RKObjectRequestOperation* operation, RKMappingResult* mappingResult) {
           // Handle success response
     } failure:^(RKObjectRequestOperation* operation, NSError* error) {
          // Handle failure response
}];
</code>


Creating checkboxes in Java Swing application

Question: I am creating this application to communicate the servlet by sending the selected units, if there is any changes in unit master server sends those units in the form of map with null values. From the desktop I need to get data from the server for only selected units. Initially server sends all the units and associated data to the desktop app, after selection at desktop again we need to connect to server to get data. For that I need show the checkboxes with the names which are there in map.
How to create checkboxes in Java Swing application with Map keys as their names. Assume initially from the server
Map<String, String> m1 = new HashMap<String, String>();
    m1.put("091","091");
    m1.put("061","061");
    m1.put("001","001");
    m1.put("032","031");

After selection at desk application, it should be
Map<String, String> m1 = new HashMap<String, String>();
        m1.put("091","091");
        m1.put("061",null);
        m1.put("001",null);
        m1.put("032","031");

With res. to key and value pair of map I want to create the checkboxes where key is the name of the checkbox and value is to select that checkbox. If key contains a value (not null) then while creating that checkbox it should be selected. The map is going to be changed dynamically and creating checkboxes should be added to the JDialog. At the end of the selection I need to construct the map and I want to send that to the server.
Answer: I always start with the examples in the tutorial on Check Boxes. If that's not what you mean, can edit your question?
Comment: Is there any way to transfer the data in the form ["091","ABCD","091"] ["061","einc",null].... here first string for value, second for display name and third for selected/notselected. Does i need objects to represent this kind of data and transfer it with arraylist. class A{string code, string name, string status} .. arraylist.add(new A())
Comment: You can use `String.split()` to break it down. A lot of people here use [`JTable`](http://download.oracle.com/javase/tutorial/uiswing/components/table.html) and keep the data is a `TableModel`. `Boolean` columns get rendered with a check box automatically.
Answer: Create an array of JCheckBoxs, the size of the array should be the size of m1. Iterate over m1 and initialize the JCheckBoxes accordingly, for example if entry is the current entry (in your iteration), cbArr is the array of checkboxes and i initialized to 0 before the start of the loop:
cbArr[i] = new JCheckBox(entry.getKey());
if (entry.getValue() != null)
{
    cbArr[i].setSelected(true);
}
else
{
    cbArr[i].setSelected(false);
}
yourPanel.add(cbArr[i++]);

This is the basic, to create the updated HashMap (to send to server) iterate over the array of CheckBoxes and insert key as current name of the check box, and value depending if the checkbox is selected or not.
Hash<String,String> m2 = new HashMap<String,String>();
for (int i = 0; i < cbArr.length; i++)
{
    m2.put(cbArr[i].getText(), cbArr[i].isSelected() ? cbArr[i].getText() : null);
}


Probability of paired combinations

Question: There are 8 friends: Alfred, Alex, Billy, Barbara, Connie, Chris, David and Donna.
The friends are paired up at random. What is the probability that at least two pairs will share the same first initial?
I believe the probability of having all four pairs share the same first initial is:
$(4/28)*(3/15)*(2/6)$ = .0095
where the numerator is the number of remaining possible pairs who share a first initial, and the denominator is the number of possible pairs left (8/6/4 choose 2).
How can you determine the probability of at least 2 pairs having the same initial?
Comment: By permutation test, it appears the answer is p=.1239, but I would still like to know how this is solved analytically
Answer: Formulation
Because the same question has been asked and answered with "at least 2" replaced by "none," let's obtain the full distribution.  In other words, suppose there are $n$ pairs of objects and all $2n$ of those objects are randomly permuted, creating $n$ pairings.  For any integer $k$, what is the chance exactly $k$ of those new pairings will bring back together some original pair?
One way to tackle this is to think of the random permutation as arising by putting all $2n$ objects in a jar, mixing them up, and drawing them out randomly in groups of two (without replacement).  How many of these draws consist of the original pairs?  Let that count be the random variable $X$.  We seek its probability distribution.
Naturally we would like to consider what happens when we draw out the first group.  Immediately we're confronted with yet a larger generalization of the original problem: unless that first group is a pair, there will be some objects left in the jar that have no pairs at all.  A little thought indicates that the number of such unpaired objects will always be even, so let it be $2m$.
Here, then, is the formal question to be addressed:

What is the probability distribution of the number of pairs obtained when drawing objects without replacement in groups of two from a jar that contains $2n$ objects (forming $n$ pairs) and $2m$ unpaired objects?

Let's remark that for large $n$, the Poisson$(n/(2n-1))$ distribution will give an excellent approximation. The Poisson$(1/2)$ will be almost as good.  That is because there are only $n$ pairs out of $\binom{2n}{2} = n(2n-1)$ possible groups of two objects, whence there is only a $n/(n(2n-1))=1/(2n-1)$ chance, which is rare for large $n$.  This means the total number of pairs can be approximated by a Binomial$(n, 1/(2n-1))$ distribution, which in turn is extremely close to a Poisson$(n/(2n-1))$ distribution.  This heuristic result is interesting because it shows that as the number of pairs in the jar grows, the chances associated with $X=k$ eventually don't change much.  In particular, since there is only a one chance in a million that a Poisson$(1/2)$ variable will exceed $6$, it is highly likely $X \le 6$ no matter what $n$ might be!

Solution
Because this threatens to get complicated--so far there are variables $k, m, n$ to keep track of--let's deal with the entire probability distribution by means of its probability generating function (pgf), $p(m,n)$.  By definition this is a polynomial whose coefficients are the desired probabilities:
$$p(m,n)(t) = \Pr(X=0) + \Pr(X=1)t + \Pr(X=2)t^2 + \cdots + \Pr(X=n)t^n.$$
Here, $t$ is the polynomial variable and I was able to stop the sum at $n$ since obviously no more than $n$ pairs can be drawn.
The question itself can be answered by computing $p(0,n)(t)$, with $n=4$, ignoring the coefficients of $1$ and $t$, and setting $t=1$ to obtain the sum $\Pr(X=2) + \Pr(X=3) + \cdots + \Pr(X=n)$.
If $n=0$, there are no pairs in the jar, making the answer clear: $p(m,0)(t) = 1$ for all $m \ge 0$, indicating there is $100\%$ chance that $X=0$.
So, suppose $n \ge 1$.  This implies there are at least two objects in the jar.  Draw two out at random.  The following things can happen:

You draw a pair.  Since there are $\binom{2(m+n)}{2}$ groups of two objects in the jar, $n$ of them are pairs, and every group has the same chance of being drawn, the chance of this event is $n/\binom{2(m+n)}{2}$.  The jar now has $n-1$ paired objects and it still has $2m$ unpaired ones.
You draw two of the unpaired objects. (This can happen only when $m\ge 1$.)  The chance of this event is $\binom{2m}{2}/\binom{2(n+m)}{2}$.  Since the number of unpaired objects has been reduced by two, the jar still contains $n$ paired objects and $2(m-1)$ unpaired ones.
You draw two of the paired objects, but they do not form a pair.  (This can happen only when $n \ge 2$.)  There are $\binom{2n}{2}$ groups of two such objects, but we already counted $n$ of them in (1): they are the actual pairs.  Therefore the chance of this event is $\left(\binom{2n}{2} - n\right)/\binom{2(m+n)}{2}$.  The number of pairs remaining is only $n-2$, but there are now $2(m+1)$ unpaired objects.
You draw one paired object and one unpaired object. There are $(2n)(2m)$ ways to do this, so the chance is $(2n)(2m)/\binom{2(n+m)}{2}$.  There is one less paired object left, so $n$ is reduced to $n-1$.  You created a new unpaired object when you drew its mate, but you removed on unpaired object, too, so $m$ remains the same.

In case (1) you increased $X$ by $1$: that multiplies the pgf of the jar by $t$.  In the remaining cases $X$ remained the same.  Consequently, by the law of total probability, we may add the four pgfs, each weighted by the corresponding chance.  To clarify the expression I have multiplied both sides by the common denominator, $\binom{2(m+n)}{2}$, which clears out all fractions:
$$\eqalign{
\binom{2(n+m)}{2}p(m,n)(t) &= &n\, t\, p(m,n-1)(t) \\
& &+ \binom{2m}{2}p(m-1,n)(t) \\
& &+ \left(\binom{2n}{2}-n\right) p(m+1,n-2)(t) \\
& &+ (2n)(2m) p(m, n-1)(t).
}$$
This recursion can easily be solved with a dynamic program: start with the case $n=0$, use it to solve for the case $n=1$ by sweeping from $m=0$ upwards, and repeat until you reach the desired value of $n$.  (A Mathematica implementation appears at the end of this post as a working illustration.)  Although storage requirements can be reduced to $O(n^2)$, the computation time is proportional to $O(n^3)$, so it's not terribly efficient--but it will work just fine for values of $n$ into the hundreds.
Here are the first few pgfs:
$$\eqalign{
p(0,1)(t) &= \frac{1}{1}\left(t\right) \\
p(0,2)(t) &= \frac{1}{1\cdot 3}\left(2 + t^2\right) \\
p(0,3)(t) &= \frac{1}{1\cdot 3\cdot 5}\left(8 + 6 t + t^3\right)\\
p(0,4)(t) &= \frac{1}{1\cdot 3\cdot 5\cdot 7}\left(60 + 32 t + 12 t^2 + t^4\right) \\
\cdots}$$
In particular, the chance of two or more pairs when $n=4$ can be read directly from the terms in the last polynomial having powers of two or greater:
$$\frac{1}{1\cdot 3\cdot 5\cdot 7}\left(12 t^2 + t^4\right)\bigg|_{t=1} = \frac{13}{105} \approx 0.12381.$$
As a check, the Poisson$(4/7)$ approximation gives $0.113$, which--even though $n$ cannot be considered large--is quite close.

Addendum: Code
f implements the pgf and ff computes the distribution function.
Clear[f, ff];
f[_, 0] := 1;
f[m_, _] /; m < 0 := 0;
f[_, n_] /; n < 0 := 1;
f[m_, n_] := f[m, n] = Expand[((\[FormalX] n + (2 n) (2 m) ) f[m, n - 1] +
      (Binomial[2 n, 2] - n) f[m + 1, n - 2] +
       Binomial[2 m, 2] f[m - 1, n])/Binomial[2 m + 2 n, 2]];
f[n_] := f[0, n] ; (* PGF *)

ff[k_, n_] /; 0 <= k < n := With[{s = CoefficientList[f[n], \[FormalX]]},
  Total[Take[s, Floor[k] + 1]] / Total[s]] (* CDF *)
ff[k_, _] /; k < 0 := 0;
ff[k_, n_] /; k >= n := 1;
ff[k_, n_] /; n < 0 := HeavisideTheta[k];

This takes about one second to compute all the pgfs up through $n=100$.
As an example of its use, here is a display of some of the pgfs:
Clear[t];
With[{n = 6},
 TableForm[Array[f, n] /. \[FormalX] -> t,
  TableHeadings -> {Array["n=" <> ToString[#] &, n], {}}]
 ]

$$\begin{array}{cc}
 \text{n=1} & t \\
 \text{n=2} & \frac{t^2}{3}+\frac{2}{3} \\
 \text{n=3} & \frac{t^3}{15}+\frac{2 t}{5}+\frac{8}{15} \\
 \text{n=4} & \frac{t^4}{105}+\frac{4 t^2}{35}+\frac{32 t}{105}+\frac{4}{7} \\
 \text{n=5} & \frac{t^5}{945}+\frac{4 t^3}{189}+\frac{16 t^2}{189}+\frac{20 t}{63}+\frac{544}{945} \\
 \text{n=6} & \frac{t^6}{10395}+\frac{2 t^4}{693}+\frac{32 t^3}{2079}+\frac{20 t^2}{231}+\frac{1088
   t}{3465}+\frac{1208}{2079} \\
\end{array}$$
Answer: Here's a less advanced approach than whuber's:
The total number of possible "pairings" (ways to divide the 8 friends into four pairs) is
$$
\frac{\binom{8}{2} \binom{6}{2} \binom{4}{2}}{4!} = 105.
$$
This is because there are $\binom{8}{2}$ ways to choose the first pair, then $\binom{6}{2}$ ways to choose the second pair, then $\binom{4}{2}$ ways to choose the third pair, but because we don't distinguish between the "first pair", "second pair", "third pair" and "fourth pair", we divide by the $4!$ ways of labelling the four pairs as "first", "second", "third" and "fourth".
The number of "pairings" with the same initials in all 4 pairs is clearly 1.
There are no "pairings" with the same initials in exactly 3 pairs, because the last pair would then also have the same initials.
The number of "pairings" with the same initials in exactly 2 pairs is
$$
\binom{4}{2} \times 2 = 12,
$$
because there are $\binom{4}{2}$ ways of choosing the "matched" initials from $\{A,B,C,D\}$, and then 2 possibilities for the unmatched pairs.
The probability that at least two pairs have the same initial is the number of "pairings" in which at least two pairs have the same initial divided by the total number of possible "pairings", which, from the above, is
$$
\frac{1 + 12}{105} = \frac{13}{105} \approx 0.124.
$$

Probability of paired combinations


Setting changed key signature before volta in Lilypond

Question: I'm scoring Mozart's first piece, K1 - Minuet and Trio. The structure is essentially 4 repeats. After the first two repeats, the key signature changes from G Major to C Major.
I've split the right hand into two variables: rh-g and rh-c and am using \key c \major at the beginning of the second variable.
However by default, lilypond (2.23) adds the naturals in the new key signature to the end of the prior repeat.

Is there a way to have the naturals appear at the beginning of the next section where a key signature would normally be?
The code I'm using is:
\version "2.23"

\header {
  title = "Minuet and Trio"
  subtitle = "K1"
  composer = "Wolfgang Amadeus Mozart (1756-1791)"
  style = "Classical"
  license = "Public Domain"
  maintainer = "Tim Burgess"
  maintainerEmail = "firstname.lastname@example.com"
}

global = {
  \time 3/4
  \tempo 4 = 80
}

rh-g =  {
  \key g \major
  \relative g' {
    \repeat volta 2 {
      \partial 4 b'8(\mf g8 b,4)-. c4-. d4-. d4( c4)    a'8( fis8 a,4)-. b4-. c4-. c4( b4) b'8( g8 \break

      e4) g8( e8 cis4)  e8( cis8 a8 g8 fis4)  \tuplet 3/2 { b8( a8 g8 } fis4)-. e4-. | d2 \break
    }

    \repeat volta 2 {
      \partial 4 d'8(\mp b8 gis4)-. f'4-. e4-. d4( c4) c8( a8 fis4)-. e'4-. d4-. c4( b4) e8(\mf c8 \break

      a4) c8( a8 fis4) d8( fis8 a8 c8 b4) \tuplet 3/2 { e8( c8 a8 } g4)-. fis4-. g2 \break
    }
  }
}

rh-c =  {
  \key c \major
  \relative g' {
    % bar 18
    \repeat volta 2 {
      \partial 4 c8( g8 e4)-. e4-. d8( e8) e4( f4) d'8( b8 f4)-. f4-.  e8( d8) d4( e4) e'16( d c b \break

      a4 a'4) d,16( c b a g4 g'4) d16( b a g e'4 d4)-.  fis,4-. a4( g4) s4 \break
    }
  }
}

rh = {
  \clef "treble"
  \rh-g
  \rh-c
  \bar "|."
}

lh =  {
  \clef "bass"
  \relative g {
    \key g \major
    \partial 4 r4
    g4-. a4-. b4-. | b4( a4) r4 |
    fis4-. g4-. a4-. | a4( g4) r4 |
    g2 e4 | cis4 a4 d4 | g4 a4-. a,4-. | d4-. d,4-.

    \partial 4 r4
    e'4-. d'4-. c4-. | b4 a4 a8 fis8 | d4-. c'4-. b4-. | a4 g4 r4 |
    c2 a4 | fis4 d4 g4 | c4 d4-. d,4-. | g2

    \key c \major
    \partial 4 c,8 e8
    R2.*8

  }
}

Comment: As a clarification, LilyPond is doing things according to standard practice. Is there some reason you need your score to deviate from that?
Comment: The naturals cancelling the previous key signature make the change very obvious; without them, it'd be very easy to miss the lack of sharps at the start of the next line.
Comment: Just personal preference. I have seen non-public scores which have been annotated this way.
Comment: Just like @Aaron I am puzzled about this. It makes life so much easier for the musician if the standard notation is kept when there is no nonstandard things going on. The picture you posted has the change written at the end of the G major section which is good. Then on the next line where a key signature would normally be you do in fact have the key signature, because the key signature for C major is nothing, no sharps no flats, just nothing. And nothing is exactly what you have written. Thus you do have the key signature completely correctly written in that image.
Answer: Line 475 at ./usr/share/lilypond/current/scm/define-grobs.scm shows where break-align-orders is defined. Essentially, it controls the order in which certain elements will appear. In your layout, add this:
\layout {
  \context {
    \Score
      \override BreakAlignment.break-align-orders =
  #(make-vector 3 '(
                    left-edge
                    cue-end-clef
                    ambitus
                    breathing-sign
                    clef
                    cue-clef
                    staff-bar
                    key-cancellation
                    key-signature
                    time-signature
                    custos))
    }
}

Switch the order of these two:
                staff-bar
                key-cancellation

Or, if you don't want this to occur every time, use this in a variable with \once to ensure it only happens once.
temp_change = \once \override Score.BreakAlignment.break-align-orders =
  ...

music = \relative c'' {
  g2 \temp_change \break
  ...
}


SSRS - Using Expressions with "If" statements and multiple parameter values

Question: So I'm trying to set up some dynamic text for a report in SSRS with 4 user parameter fields and I keep running into the same error.  I'm still pretty new to SSRS and Visual Basic, so it's a bit hard to understand the error message.
System.Web.Services.Protocols.SoapException: The Value expression for the textrun
'Textbox2.Paragraphs[2].TextRuns[1]' contains an error: [BC33104] 'If' operator
requires either two or three operands.

The 4 parameter fields are beginYear, beginMonth, endYear, & endMonth.  The following is the code I have in the expression:
If (bYear = eYear) And (bMonth = 1) And (eMonth = 3)
"3rd Quarter January - March " & eYear

ElseIf  (bYear = eYear) And (bMonth = 4) And (eMonth = 6)
"4th Quarter April - June " & eYear

ElseIf  (bYear = eYear) And (bMonth = 7) And (eMonth = 9)
"1st Quarter July - September " & eYear

ElseIf  (bYear = eYear) And (bMonth = 10) And (eMonth = 12)
"2nd Quarter October - December " & eYear

ElseIf  (bYear = eYear) And (bMonth = 1) And (eMonth = 12)
"Calendar Year " & eYear

ElseIf  (bYear = eYear) And (bMonth = eMonth)
eYear & " " & eMonth

ElseIf  (((Convert.toInt32(bYear)) = (Convert.toInt32(eYear)) - 1) And (((Convert.toInt32(eYear)) = (Convert.toInt32(bYear)) + 1) And (bMonth = 7) And (eMonth = 6)
"Fiscal Year " & bYear & "-" & eYear

Else
             bMonth & " " & bYear & "-" & eMonth & " " & eYear
End If

So if I selected the following parameters from the report as follows (in the month parameters, I assigned numerical values to months):
-Begin Year=2018
-Begin Month=April
-End Year=2018
-End Month=June

I should see the following expression in the text box of the report => "4th Quarter April - June 2018"
Comment: Try adding Then statements...  And (eMonth = 3) Then  ... And (eMonth = 6) Then ... etc
Comment: I think you have an extra opening parenthesis in front of both of your **Converts**. Isn't your **year** already an **INT**? Why not? `((Convert.toInt32(bYear)) = (Convert.toInt32(eYear)) - 1) And ((Convert.toInt32(eYear)) = (Convert.toInt32(bYear)) + 1) And (bMonth = 7) And (eMonth = 6)`
Answer: That is not the format of If in SSRS. See below:
=Iif(Parameters!yourParameter.Value = Parameters!yourAnotherParameter.Value, "value if true", "value if false")

For your case you should use Switch.
=Switch(Parameters!yourParameter.Value = Parameters!yourAnotherParameter.Value
        AndAlso Parameters!yourParameter.Value = "something else"
        AndAlso Parameters!yourParameter.Value = "again something else", "desired output if all condition are met",
        Parameters!yourNextParameter.Value = Parameters!yourNextAnotherParameter, "desired output if this condition is met")

Comment: I think your SWITCH syntax is incorrect. After a comparison there should be the result if true - maybe ` ...AndAlso Parameters!yourParameter.Value = "again something else", "something old", ` . To be fair, he did mention VB (though vaguely).
Comment: Thanks for pointing that out, I confused myself by putting more than 1 condition in the first part of my example.


how can I get the file version on the Internet but not download it?

Question: I get a file url,for example, http://cidian.youdao.com/download/YoudaoDict.exe
how can I get it's  version but not download it ?
nots 1: if you download the file first on your computer,there are many ways to get it's
version, for example ,you can use the window tools "filever.exe" to get the version.
but i want to not download it ,at least not download it all.how can I do? Waiting your
help! thanks.
nots 2: I have tried the way to get a portion of the file to get the version:
first, I used the download tool "wget.exe" to download a portion of the file ( wget.exe is
a single-threaded download tool,it can make sure download form the head)
second, I used the "filever.exe" to get the file version.
In this way, some software i can get it's version,but some cann't(they must all be
downloaded).I don't know why.
Answer: I notice that that particular exe link supports byte range requests.
$ curl -I http://cidian.youdao.com/download/YoudaoDict.exe
HTTP/1.1 200 OK
...
Accept-Ranges: bytes
Content-Length: 4820792
...
Content-Type: application/octet-stream

You could make one or more HTTP byte range request to get the parts of the file you need to determine the version. You'd just be making several requests to get the parts of the file you'd look at if it were on your hard drive.
For example, based on the HTTP/1.1 spec, you can request the first 500 bytes with this request header:
curl -H"Range: bytes=0-499" http://... -o bytes-0-499.dat

Comment: "You could make one or more HTTP byte range request to get the parts of the file you need to determine the version. "
how can I used parts of the file to determine the version? Can you tell more ?
Comment: Since you're using filever.exe, part of Windows, you're looking at the DLL version set in the binary format for a DLL/EXE file. My first try would be to download about 4k (-H"Range: 0-4095") and try running filever.exe on that part of the file. Reason: the version is probably part of the header at the beginning of the EXE file.
Comment: but if you try this, http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe
it will fail,it cann't get it's version until you download it all.
do you know why?
Answer: Version numbers, if any, are embedded in the .exe file itself. You will have to download at least a portion of the file to retrieve these bits of metadata.
Check out the .exe file format spec.
Comment: I have tried the way to get a portion of the file to get the version:
first, I used the download tool "wget.exe" to download a portion of the file ( wget.exe is a single-threaded download tool,it can make sure download form the head)
second, I used the "filever.exe" to get the file version.
In this way, some software i can get it's version,but some cann't(they must all be downloaded).I don't know why.
Answer: You can do an HTTP HEAD request, and the server may report the size of the item in Content-Length.  It may also report a version under the Last-Modified header.  Further, ETag may be present for the same purpose.
You can test this with netcat:
> nc cidian.youdao.com 80
HEAD /download/YoudaoDict.exe HTTP/1.1
Host: cidian.youdao.com

HTTP/1.1 200 OK
Date: Mon, 10 Aug 2009 06:11:59 GMT
Server: Apache
ETag: "Dcm1w6Vxg51"
Last-Modified: Sat, 08 Aug 2009 02:18:40 GMT
Accept-Ranges: bytes
Content-Length: 4820792
X-Request-Received: t=1249884719506801
X-Request-Processing-Time: D=906244
Content-Type: application/octet-stream

As you can see, in your example case, all three headers are given, so you can guess version changes based on that information.  I'd always check to insure Date and Last-Modified aren't the same, as sometimes the latter is set to the former for pages generated by scripts.
Answer: Well in theory this is the kind of task that an HTTP HEAD request is designed for but iirc the only relevant info you'd get by default (if the request was handled at all of course) would be Content-Length and Last-Modified. Edit: and ETag!
That probably gets you much of what you need to know, but if you really wanted to have version number you'd have to be in control of the web service and be able to obtain and append that information to the response headers. Not so hard to do but only if you have control of the service.
Answer: If your purpose is to detect when a new version becomes available, you could look at the response of a HEAD HTTP request as others have suggested.
Otherwise, you could screen scrape the (download page) and extract the latest version details. There is a convenient
 tag within which version info is listed and could conceivably be harvested. I have no idea whether this is going to be reliable; the site's authors could change this without notice.
I'd look at using BeautifulSoup  for this.


Feedback module block doesn't follow visibility rules

Question: I'm using the Feedback module on my Drupal 6 but I found out a strange behaviour about its block's visibility.
The module appeared even if the block was in the disabled region, not assigned to any site space, and moreover it still appears even if I set for example a PHP code which returns false, or if I set it to appear only on listed pages without giving it any valid page.
If I move the block to different regions it still appears on the bottom right corner, so I have no control on how it works.
Am I missing something or is it a wanted feature of the Feedback block to be always there?
Answer: Wow.  It's pretty snarky, for no better word, and does the following...
/**
 * Implementation of hook_footer().
 */
function feedback_footer($main = 0) {
  if (user_access('access feedback form') && $_GET['q'] != 'admin/reports/feedback') {
    $block = (object)module_invoke('feedback', 'block', 'view', 'form');
    $block->module = 'feedback';
    $block->delta = 'form';
    $block->region = 'footer';
    return theme('block', $block);
  }
}

...which basically puts it on every page except admin/reports/feedback by stuffing the form into page.tpl's $closure variable.
So, yes, it does appear to ignore standard block visibility rules somewhat on purpose.
Comment: Thanks... so this is the point in the code where I have to insert my logic for excluding it from some pages, isn't it? :)
Comment: either here, or do some fancy editing of $closure in your theme's preprocess_page() hook.  both aren't pretty.
Comment: ACTUALLY... probably the best thing to do so you aren't 'hacking core' is to copy `block.tpl.php` to your theme (if not there already) and then create a `block-footer-feedback-form.tpl.php` that does the logic there (or in a preprocess_block hook) and returns nothing on the pages you don't want to see it on.  More info on template suggestions here:  http://drupal.org/node/1089642


Understanding solution to first-order differential equation written in integral form, $y(x)=\int_0^xy(t)dt + x + 1$

Question: I have a differential equation and I'm trying to understand the solution printed in the back of the book. I will specify what part I'm struggling to understand:
Problem statement: Solve the following equation. $y(x)=\int_0^xy(t)dt + x + 1$.
Verbatim solution from back of the book that I'm trying to understand:
$y(x)=\int_0^xy(t)dt + x + 1 ⇒ \frac{dy}{dx} = y(x) + 1 ⇒ \frac{dy}{dx}- y = 1 ⇒ u(x) = e^{\int-1dx} = e^{-x} ⇒ \frac{d}{dx}[e^{-x}y] = e^{-x} ⇒ e^{-x}y = \int e^{-x}dx = -e^{-x} + C ⇒ y = Ce^{x} - 1.$
But there is an implied initial condition here: $y(0)=1.$ Therefore, $1=y(0)=Ce^{0}-1⇒C=2$, so that the solution is $y=2e^{x}-1.$ [Try any other value of C and see that the function doesn't satisfy the original equation.]
I have 2 questions:

Why is $y(x)=\int_0^xy(t)dt = y(x)$, and not $y(x)-y(0)$?
Why is there an implied initial condition when there is no implied condition stated in the problem?
Answer: 1) This is the direct result of the first part of the Fundamental Theorem of Calculus.
2) You can see in the original equation, when $x=0$ the integral vanishes, as does $x$, leaving you the condition $y(0)=1$. This is certainly true, so this condition has to be satisfied.
Comment: Nice edits, thank you. I was being lazy.


OpenGL Texture won't draw

Question: I followed an opengl tutorial and created a more object oriented version.
I want to draw a Texture but the only thing which works is the glClearColor command. I have no idea why it doesn't work. I tried everything. Here's the code:
Sprite.cpp
<code>#include "Sprite.h"
#include <SOIL\SOIL.h>

Sprite::Sprite(const char* texturePath, float x, float y, GLuint width, GLuint height)
{
    Sprite::init(texturePath, x, y, width, height);
}

Sprite::~Sprite()
{
}

void Sprite::init(const char* texturePath, float x, float y, GLuint width, GLuint height)
{
    Logger::info("Initializing Sprite...");
    _x = x;
    _y = y;
    _width = width;
    _height = height;

    // Build and compile our shader program

    // Set up vertex data (and buffer(s)) and attribute pointers
    const GLfloat vertices[] = {
        // Positions                        // Colors           // Texture Coords
        _x,        _y,         0.0f,        0.0f, 0.0f, 0.0f,   1.0f, 1.0f,
        _x,        _y + _height, 0.0f,        0.0f, 0.0f, 0.0f,   1.0f, 0.0f,
        _x + _width, _y,         0.0f,        0.0f, 0.0f, 0.0f,   0.0f, 0.0f,
        _y + _width, _y + _height, 0.0f,        0.0f, 0.0f, 0.0f,   0.0f, 1.0f
    };

    /*GLfloat vertices[] = {
        // Positions          // Colors           // Texture Coords
        0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f,   // Top Right
        0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f,   // Bottom Right
        -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f,   // Bottom Left
        -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f    // Top Left
    };

    */

    constexpr GLuint indices[] = {  // Note that we start from 0!
        0, 1, 3, // First Triangle
        1, 2, 3  // Second Triangle
    };

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // Color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    // TexCoord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);

    glBindVertexArray(0); // Unbind VAO

                          // Load and create a texture
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture); // All upcoming GL_TEXTURE_2D operations now have effect on this texture object
                                           // Set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);   // Set texture wrapping to GL_REPEAT (usually basic wrapping method)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // Load image, create texture and generate mipmaps
    int twidth, theight;
    unsigned char* image = SOIL_load_image(texturePath, &twidth, &theight, 0, SOIL_LOAD_RGB);
    if (image == 0)
    {
        Logger::fatalError("Image is null!");
    }

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture.

    //_texture2 = texture2;
    Logger::info("Sprite initialization succesful!");

}

void Sprite::draw(Shader *shader)
{
/*  glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _texture1);
    glUniform1i(glGetUniformLocation(shader->_programID, "ourTexture1"), 0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, _texture2);
    glUniform1i(glGetUniformLocation(shader->_programID, "ourTexture2"), 1);
    */

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    // Bind Texture
    glBindTexture(GL_TEXTURE_2D, texture);

    if (texture == 0) {
        Logger::fatalError("texture1 is null");
    }

    if (shader == 0) {
        Logger::fatalError("shader is null");
    }

    if (VAO == 0) {
        Logger::fatalError("VAO is null");
    }

    // Activate shader
//  glActiveTexture(GL_TEXTURE0);
//  glBindTexture(GL_TEXTURE_2D, texture);
    //glUniform1i(glGetUniformLocation(shader->_programID, "ourTexture"), 0);
    //shader->Use();

    // Draw container
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);

}
</code>
Shader.cpp
<code>#include "Shader.h"

Shader::Shader(const GLchar* vertexShaderPath, const GLchar* fragmentShaderPath)
{
    std::string vertexCode;
    std::string fragmentCode;
    std::ifstream vertexShaderFile;
    std::ifstream fragmentShaderFile;
    // ensures ifstream objects can throw exceptions:
    vertexShaderFile.exceptions(std::ifstream::badbit);
    fragmentShaderFile.exceptions(std::ifstream::badbit);
    try
    {
        // Open files
        vertexShaderFile.open(vertexShaderPath);
        fragmentShaderFile.open(fragmentShaderPath);
        std::stringstream vShaderStream, fShaderStream;
        // Read file's buffer contents into streams
        vShaderStream << vertexShaderFile.rdbuf();
        fShaderStream << fragmentShaderFile.rdbuf();
        // close file handlers
        vertexShaderFile.close();
        fragmentShaderFile.close();
        // Convert stream into GLchar array
        vertexCode = vShaderStream.str();
        fragmentCode = fShaderStream.str();
    }
    catch (std::ifstream::failure e)
    {
        Logger::info("ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ");
    }
    const GLchar* vertexShaderCode = vertexCode.c_str();
    const GLchar* fragmentShaderCode = fragmentCode.c_str();

    Shader::compileShaders(vertexShaderCode, fragmentShaderCode);

}

void Shader::compileShaders(const GLchar* vertexShaderCode, const GLchar* fragmentShaderCode) {
    Logger::info("Compiling Shaders...");
    GLuint vertex, fragment;
    GLint success;
    GLchar infoLog[512];

    // Vertex Shader
    vertex = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex, 1, &vertexShaderCode, NULL);
    glCompileShader(vertex);
    // Print compile errors if any
    glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertex, 512, NULL, infoLog);
        Logger::fatalError("ERROR::SHADER::VERTEX::COMPILATION_FAILED");
    };

    // Similiar for Fragment Shader
    fragment = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment, 1, &fragmentShaderCode, NULL);
    glCompileShader(fragment);
    // Print compile errors if any
    glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragment, 512, NULL, infoLog);
        Logger::fatalError("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED");
    };

    // Shader Program
    this->_programID = glCreateProgram();
    glAttachShader(this->_programID, vertex);
    glAttachShader(this->_programID, fragment);
    glLinkProgram(this->_programID);
    // Print linking errors if any
    glGetProgramiv(this->_programID, GL_LINK_STATUS, &success);
    if (!success)
    {
        glGetProgramInfoLog(this->_programID, 512, NULL, infoLog);
        Logger::fatalError("ERROR::SHADER::PROGRAM::LINKING_FAILED");
    }

    // Delete the shaders as they're linked into our program now and no longer necessery
    glDeleteShader(vertex);
    glDeleteShader(fragment);
    Logger::info("Shader compilation succesful!");
}

void Shader::Use() {
    glUseProgram(this->_programID);
}

Shader::~Shader()
{
}
</code>
MainGame.cpp
<code>#include "MainGame.h"

MainGame::MainGame()
{
    _window = nullptr;
    _screenWidth = 1024;
    _screenHeight = 768;
    _gameState = GameState::PLAY;
}

MainGame::~MainGame()
{
}

void MainGame::run() {
    initSystems();
    gameLoop();
}

void MainGame::initSystems() {
    //Initialize SDL
    SDL_Init(SDL_INIT_EVERYTHING);
    //Create Window
    _window = SDL_CreateWindow("Half Life 3", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _screenWidth, _screenHeight, SDL_WINDOW_OPENGL);
    //glViewport(0, 0, _screenWidth, _screenHeight);
    if (_window == nullptr) {
        Logger::fatalError("SDL Window could not be created!");
    }
    SDL_GLContext glContext = SDL_GL_CreateContext(_window);
    if (glContext == nullptr) {
        Logger::fatalError("SDL_GL context could not be created");
    }

    GLenum error = glewInit();
    if (error != GLEW_OK) {
        Logger::fatalError("Could not initialize glew!");
    }

    Logger::info("Initialization succesful");

    //Double Buffer: Smooth, no flickering
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    glClearColor(0, 0, 1, 1.0);

    Shader shader("Shaders/Shader.vert", "Shaders/Shader.frag");
    _shader = &shader;
    Sprite sprite("Textures/wall.jpg", 0.5f, 0.5f, 100, 100);
    _texture = &sprite;

}

void MainGame::gameLoop() {
    while (_gameState != GameState::EXIT) {
        processInput();
        drawGame();
    }
}
void MainGame::processInput() {
    SDL_Event evnt;
    while (SDL_PollEvent(&evnt) == true) {
        switch (evnt.type) {
        case SDL_QUIT:
            _gameState = GameState::EXIT;
        //  std::cout << "Quit Event" << std::endl;
            break;
        case SDL_MOUSEMOTION:
        //  std::cout << "x: " << evnt.motion.x << " y: " << evnt.motion.y << std::endl;
            break;
        }
    }
}
void MainGame::drawGame() {
//  glClearDepth(1.0);
//  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //_shader->Use();

    // Bind Textures using texture units
    _texture->draw(_shader);

    // Swap the screen buffers
    SDL_GL_SwapWindow(_window);

}
</code>
Fragment shader:
<code>#version 330 core
in vec3 ourColor;
in vec2 TexCoord;

out vec4 color;

uniform sampler2D ourTexture;

void main()
{
    color = texture(ourTexture, TexCoord);
}
</code>
Vertex shader:
<code>#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 color;
layout (location = 2) in vec2 texCoord;

out vec3 ourColor;
out vec2 TexCoord;

void main()
{
    gl_Position = vec4(position, 1.0f);
    ourColor = color;
    TexCoord = texCoord;
}
</code>
Console log:
<code>Initialization succesful
Compiling Shaders...
Shader compilation succesful!
Initializing Sprite...
Sprite initialization succesful!
</code>
You see, everything loads correctly and initializes correctly and there are no errors. It still displays nothing but the glClearColor.
What's wrong?
Comment: First of all, as  @JamesBean already pointed out, you are trying to draw without having any program activated. Second, your `shader` and `sprite` objects are just local variables in `initSystems`, taking their address and storing that for later isn't going to help you.
Comment: in your sprite.cpp are the lines under `//Activate shader` comment suppose to be commented out?
Comment: @James Bean Yes, the lines under "// Draw container" however are not commented out
Comment: You haven't set up a projection matrix.
Comment: @derhass Thank you, now it works :D
Comment: @SurvivalMachine It currently works without a projection matrix
Answer: The blank screen effect is very common with Open GL graphics. It means the view, camera, lighting, or something has been set up in such a way that you see nothing.
The cure is to comment out all your code, except the clear which works (that's an important first step, you are at least getting Open GL output). Then add code until you see something, anything, on screen.
You then gradually shift the anything ) to what you want to see by commenting the code back in, and commenting it out again if you go back to the blank screen effect.

OpenGL Texture won't draw


Dynkin's $\pi-\lambda$ theorem clarification

Question: I reading Klenke's - Probability Theory book and having some trouble following this proof. Here is the theorem:

This is how the proof starts:

And here is theorem 1.18 for your convenience, it just says that $\pi$-system implies $\sigma$-algebra under certain conditions.

So in our proof we just need to show that $\delta(\mathcal{E})$ is a $\pi$-system. The proof then says that is enough to show that $\delta(\mathcal{E}) \subset \mathcal{D}_B$ for any $B \in \delta(\mathcal{E})$. And this is precisely what I do not understand. i.e. how can something that is a larger collection of sets be a subset of something that is smaller...
Here is how it goes in the book:
Comment: Many authors use $A\subset B$ and $A\subseteq B$ interchangeably. Usually, when we want to say that $A$ is a *proper* subset of $B$, we will be explicit.
Comment: What is $\delta$? Also the proof doesn't imply $D_B$ is larger than $\delta$, only that $\delta$ is contained in $D_B$, (clearly they must be equal after asserting $\delta\subset D_B$).
Comment: it is a $\lambda$-system generated by $\mathcal{E}$
Comment: but how can that be the case. What about the following argument:
1) If $\delta(\mathcal{E}) \subseteq \mathcal{D}_B$ for some B, then how can it be a proper subset for some other $A \in \delta({\mathcal{E}})$, unless of course, the set $\mathcal{D}_A \subseteq \mathcal{D}_B$
Comment: @isquared-KeepitReal: If I were you, I wouldn't complain for the use of $\subset$ in place of $\subseteq$. I would complain for the use of $\delta(\mathcal E)$ to denote the $\lambda$ system generated by $\mathcal E$; that should be $\lambda(\mathcal E)$.
Answer: In order to prove that the $\lambda$-system generated by $\mathcal{E}$ - denoted $\delta(\mathcal{E})$ - is a $\sigma$-algebra, we want to prove that it is closed under pairwise intersections.  That is, if $E,F\in\delta(E)$, then $E\cap F\in\delta(E)$.  Fix $E\in\delta(E)$.  Saying that $F\cap E\in\delta(\mathcal{E})$ for every $F\in \delta(\mathcal{E})$ is the same as saying that $\{F\subset X : E\cap F \in \delta(P)\}$ contains every element of $\delta(E)$. It changes nothing in the previous sentence to do as your book does and consider $\mathcal{D}_E = \{F\in \delta(\mathcal{E}) : F\cap E \in \delta(\mathcal{E})\}$, since we only care about $\delta(\mathcal{E})$ and not arbitrary subsets of $X$.
Note: the notation $A\subset B$ does not exclude the case that $A = B$.  Here, it is going to be true that $\mathcal{D}_E = \delta(\mathcal{E})$.  The common notation for being a proper subset is $A\subsetneq B$.


gulp watch on gulpfile.js itself

Question: I'd like to not only have gulp watch watch for changes to specified files, but also to the gulpfile.js itself. Notably, I'm using Laravel and its Elixir asset management tool, which wraps Gulp.
I came across this link which seems to be exactly what I need but when I implement it and then type either gulp watch or gulp and then make changes to my gulpfile those changes aren't reflected.
I'm pretty sure I need to add something to the elixir but not sure what. I have the following for bower but probably need something similar for watch.
Here's the relevant contents of my gulpfile:
/*gulpfile.js*/
gulp.slurped = false; // step 1

gulp.task("watch", function(){

    if(!gulp.slurped){ // step 2
        gulp.watch("gulpfile.js", ["default"]);
        //gulp.watch("etc...");
        gulp.slurped = true; // step 3
    }

});

gulp.task("default", ["some-task", "another-task", "watch"]);

gulp.task('bower', function() {
  return bower();
});

elixir(function(mix) {
  // Run bower install
  mix.task('bower');
  //mix.task('default'); //uncommenting this causes an error when running "gulp"
  //mix.task('watch'); //uncommenting this causes an error when running "gulp"

  // all other elixir.mix tasks...
  mix.copy('resources/assets/js/**', 'public/js');

Answer: gulper is one possible answer: https://github.com/anatoo/gulper
So instead of running gulp watch you can run gulper watch

gulp watch on gulpfile.js itself


Binomial theorem and sum from $k = 0$ to $N/2$

Question: While calculating a partition function in physics, I stumbled across a weird sum, namely:
$$Z=\sum_{k=0}^{N/2}{N \choose 2k}b^{N-k}e^{ak}$$
Wolfram says that it's equal to:
$$Z = \frac{1}{2}\left((b-\sqrt{b}e^{a/2})^N+(b+\sqrt{b}e^{a/2})^N\right)=\frac{(x-y)^N+(x+y)^N}{2}$$
But I dont understand how we can link it to the binomial theorem since the coefficient is: ${N \choose 2k}$ and not ${N/2 \choose 2k}$ and then prove the formula.
Comment: Hint: What happens if you use the binomial theorem for the two $N$-powers in the closed form for $Z$ and then simplify the result?
Answer: It might be easier to see what is going on if we write out some terms:
$$
\begin{align}
&\overbrace{\sum_{k=0}^N\binom{N}{k}b^{N-k/2}e^{ak/2}}^{b^{N/2}\left(\sqrt{b}+e^{a/2}\right)^N}+\overbrace{\sum_{k=0}^N(-1)^k\binom{N}{k}b^{N-k/2}e^{ak/2}}^{b^{N/2}\left(\sqrt{b}-e^{a/2}\right)^N}\tag1\\[6pt]
&=\phantom{2}\binom{N}{0}b^Ne^0+\binom{N}{1}b^{N-1/2}e^{a/2}+\phantom{2}\binom{N}{2}b^{N-1}e^a+\binom{N}{3}b^{N-3/2}e^{3a/2}+\cdots\tag{2a}\\
&+\phantom{2}\binom{N}{0}b^Ne^0-\binom{N}{1}b^{N-1/2}e^{a/2}+\phantom{2}\binom{N}{2}b^{N-1}e^a-\binom{N}{3}b^{N-3/2}e^{3a/2}+\cdots\tag{2b}\\[6pt]
&=2\binom{N}{0}b^Ne^0\phantom{{}+\binom{N}{1}b^{N-1/2}e^{a/2}}+2\binom{N}{2}b^{N-1}e^a\phantom{{}+\binom{N}{3}b^{N-3/2}e^{3a/2}}+\cdots\tag3\\[6pt]
&=2\sum_{j=0}^{\lfloor N/2\rfloor}\binom{N}{2j}b^{N-j}e^{aj}\tag4
\end{align}
$$
The terms with even $k$ in $(1)$ become the terms with $2j$ in $(4)$ and the term with odd $k$ in $(1)$ cancel each other. Since $k$ goes from $0$ to $N$, $j$ goes from $0$ to $\lfloor N/2\rfloor$.
We can substitute $j\mapsto k$ in $(4)$, if desired.
Answer: Because $$\frac{1+(-1)^k}{2}=\begin{cases}1 &\text{if $k$ is even}\\0 &\text{if $k$ is odd}\end{cases}$$
we have
$$\sum_{k \ge 0} c_{2k} = \sum_{k \ge 0} \frac{1+(-1)^k}{2} c_k.$$
Now take $c_k=\binom{N}{k}b^{N-k/2}e^{ak/2}$
and apply the binomial theorem to each of the two resulting sums.
Answer: $$Z=\sum_{k=0}^{N/2}{N \choose 2k}b^{N-k}e^{ak}=b^N\sum_{k=0}^{N/2}{N \choose 2k}\left(\sqrt{\frac{e^a}{b}}\right)^{2k}$$
$$\sum_{k=0}^{N/2}{N \choose 2k}x^{2k}=\frac{1}{2} \left(\left(1-x\right)^N+\left(1+x\right)^N\right)$$
Make $x=\sqrt{\frac{e^a}{b}}$ to get the formula


Lazy initialization @ManyToMany. What is the error?

Question: Please, Help me implement lazy initialization.
I wrote Java code in Spring Core, Spring Security, and Hibernate. There are two user and Role entities. I link them with @ManyToMany(fetch = FetchType.EAGER). But for the task, I need to implement lazy initialization.
If I set @ManyToMany(fetch = FetchType.LAZY), an error occurs after successful authorization:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: web.model.User.roles, could not initialize proxy - no Session

Google directed to these links: First Link / Second Link
It suggests adding the user.getAuthorities () method.size();.
Isn't this a workaround???
Then authorization is successful, but with lazy initialization, I can't access the roles. And they don't appear on the jsp page.
org.apache.jasper.JasperException: An error occurred during processing [/WEB-INF/pages/admin_panel.jsp] in line [71]

68:             ${user.lastName}
69:             ${user.username}
70:             ${user.password}
71:             ${user.roles}
72:

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:617)

Below I will present the main parts of the code. If something is missing, then let me know.
My code:

User

@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "firstName")
private String firstName;

@Column(name = "lastName")
private String lastName;

@Column(name = "username")
private String username;

@Column(name = "password")
private String password;

@ManyToMany(fetch = FetchType.LAZY) // there was an EAGER here.
@JoinTable(name="user_role",
        joinColumns={@JoinColumn(name="userId")},
        inverseJoinColumns={@JoinColumn(name="roleId")})
private Set<Role> roles;

public User() {
}
...

class UserServiceImp

@Service
public class UserServiceImp implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional
    @Override
    public void add(User user) {
        userDao.add(user);
    }

    @Transactional
    public List<User> listUsers() {
        return userDao.listUsers();
    }

    @Transactional
    public boolean deleteUserById(long id) {
        return userDao.deleteUserById(id);
    }

    @Transactional(readOnly = true)
    public User getUserById(long id) {
        return userDao.getUserById(id);
    }

    @Transactional
    public void update(User user) {
        userDao.update(user);
    }

    @Transactional
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.getUserByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        int size = user.getAuthorities().size(); //added this line as indicated in the links
        return user;
    }
}

page *.jsp

...
<c:forEach items="${users}" var="user">

        ${user.id}
        ${user.firstName}
        ${user.lastName}
        ${user.username}
        ${user.password}
        ${user.roles}

            <a href="<c:url value='${pageContext.request.contextPath}/admin/editUser?id=${user.id}'/>" >Edit
            |
            <a href="<c:url value='${pageContext.request.contextPath}/admin/deleteUser/${user.id}'/>" >Delete

</c:forEach>
...

UserDaoImp

@Repository
public class UserDaoImp implements UserDao {

    @PersistenceContext
    private EntityManager manager;

   ...

    @Override
    @SuppressWarnings("unchecked")
    public User getUserByName(String username) {
        Query query = manager.createQuery("FROM User u WHERE u.username = : username");
        query.setParameter("username", username);
        try {
            return (User) query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }
...

Answer: What FetchType.LAZY does is that it doesn't take the entity collection (or entity in some cases e.g. @OneToOne) it is applied to when the entity containing it is returned from the db. It makes an additional request to fetch it later if its getter method is called in the same transaction. The workaround you found works because you call the getter getRoles() within getAuthorities() (although you haven't added that to the question) therefore fetching the set of roles explicitly.
After that you try to access a list of users which I assume you get from public List<User> listUsers() and if you understood the above paragraph you probably already know what I am going to say. In that method you don't fetch the roles, leave the transaction and then try to access the roles with ${user.roles}	. Now there are a few possible solutions to this problem.

First off it is usually not a great idea to send entities to the frontend because that way you introduce unnecessary coupling. What I would suggest is you make a UserDto class which contains all the fields you will need to display (but not a single one more) which has a Set of RoleDto to which the same things apply and you convert your list of users you get from the db into a list of user dtos in the listUsers() method. That way you solve 3 problems -> 1. your code is decoupled 2. you eliminate data redundancy (e.g. unnecessary for the frontend db fields) 3. you fetch every user's roles when converting from users to user dtos.
Another option would be to separate the User entity from the class implementing UserDetails by adding a new class to implement it. You can then add to this class on login all the information spring needs which basically means to transfer the necessary information from the User class to this new UserDetailsImpl class in the loadUserByUsername(String username) method so that all methods inherited by the UserDetails interface could be adequately implemented. From that point on any validation of roles or authorities will pass through the non-entity UserDetailsImpl which will eliminate the need for your workaround and the class will never throw a LazyInitializationException because it's not an entity. But copying fields like firstName and lastName from User is highly discouraged because of the possible data discrepancy.
(NOT recommended) If you are feeling really lazy you can always just do the exact same workaround in the listUsers() method and just iterate trough the users and call their getRoles() method to fetch the roles.
And lastly I understand that for whatever reason you can't do this and that's why I left this point for last but if you have to on many occasions access a collection of an entity outside of a transaction then FetchType.EAGER is clearly the easiest and best option. This is literally the problem it's made to solve.


what's the equation of these functions , could not find the equation from the picture

Question: Sometimes I encounter with a situation when I need to know the equation of the function from the pictures, what should I do?

Comment: What are the situations specifically, multiple choice problems? There is no recovering equations from pictures without a lot of additional information, a host of different equations can have similar looking graphs. The linked ones could correspond to cubic polynomials, for example, $x^3$ and $x(x-1)(x+1)$.
Comment: you could note symmetries .... in both graphs, seems that $f(-x)=-f(x)$
Comment: @Conifold Please post that as an answer. (I think the first curve is meant to be $x^3$ but it's drawn badly. The slope at the origin should be  $0$.)
Comment: @EthanBolker Done.
Answer: Typical situations of matching curves to equations occur in multiple choice problems. In general, there is no recovering equations from pictures without a lot of additional information, a host of different equations can have similar looking graphs. If we know that the curves are low degree polynomials we can roughly guess the equations by looking at the roots and behavior at infinity. The OP ones could correspond to cubic polynomials, for example, $x^3$ (single degenerate root, positive at infinity) and $x(x−1)(x+1)$ (three simple roots, positive at infinity).


If $\mu(E)=0$ then $\int_E f d\mu=0$

Question:
Prove that if $f,g\in\mathscr{M}^+$ then if $\mu(E)=0$ then $\int_E f d\mu=0$ even when $f(x)=\infty$ for all $x\in E$.

This is a little bit contradictory. If $\mu$ is the Lebesgue measure in the space $(\mathbb{R},\mathscr{B}_{\mathbb{R}})$ then I can define a measurable function for example $x=5$ whose integral is infinite and the Lebesgue measure of its domain is $0$.
Question:
Could someone provide me a hint for this proof?
Is the problem I raised a contradiction? If not. Why not?
Thanks in advance!
Answer: By definition, $\int_E f \, d\mu = \int \chi_E \,f \, d\mu = \sup \{ \int \psi \, d\mu  \mid \psi \text{ simple function with } 0 \leq \psi \leq \chi_E \, f \}.$
What is the value of $\int \psi \, d\mu$ if $\psi$ is a simple function with $0 \leq \psi \leq \chi_E \, f$?
What makes you think that $\int_E 5 \, d\mu = \infty$ if $\mu(E) = 0$?
Comment: $x=5$ is a line segment going up to infinity. $\infty$ when x=5 and $\emptyset$ when $x\neq 5$
Comment: @PedroGomes, We have $\int_E f \mathrm{d}m = 0$ even when $f = \infty$ and $m(E) = 0$. Try to apply the definition appearing in this answer.

If $\mu(E)=0$ then $\int_E f d\mu=0$


Running an ODEProblem until given a signal

Question: Is it possible for the timespan of an ODEProblem to be open-ended, i.e. for the problem to run until given an external signal (possibly via a discrete callback with an appropriate condition)? Intuitively, this would mean giving something like tspan = (0.0, Inf), although I'm not sure if that is allowed and can't seem to find anything in the documentation. TIA.
Answer: Yes, you can use tspan = (0.0, Inf). Of course, if you do this, you'll want to make sure you setup a terminating event like in this example so that it doesn't run forever, or you can use the integrator interface to control the steps and stop whenever you want.
Comment: Thank you, I'm always glad when Julia works like I expect it to. :)


application of binomial theorem

Question: I read the following in a textbook and can't understand how the binomial theorem is being applied here:
$x_n=n^{1/n}-1$. Then $x_n\ge 0$ and by binomial theorem,
$$n=(1+x_n)^n\ge \frac{n(n-1)}{2}x_n^2$$
Answer: The binomial theorem says that
$$
(1 + x_n)^n = \sum_{k = 0}^n \binom{n}{k} x_n^k
$$
which is greater than just the term when $k = 2$:
$$
\binom{n}{2} x_n^2
$$
since $x_n \geq 0$. Notice now that
$$
\binom{n}{2} = \dfrac{n!}{2!(n-2)!} = \frac{n(n-1)}{2},
$$
so we get
$$
(1 + x_n)^n = \sum_{k = 0}^n \binom{n}{k} x_n^k \geq \binom{n}{2} x_2^2 = \frac{n(n-1)}{2} x_n^2.
$$

application of binomial theorem


Recommended module or method for a generic map/media embed field?

Question: I'm aware of lots of modules for embedding media (especially https://www.drupal.org/project/emfield) and for embedding or generating Google Maps, but what I'd like is one general purpose field in which the user can paste any valid embed code, and it will get rendered in the page. (Possibly resized, if I can dream a little.)
Is there any good module for this? Or should I build the field myself and make a template for its display? If so, how should I configure that in Drupal 7? I know how to make a template for a field in general, but my PHP is pretty shaky.
Answer: The built-in text area field seems like it would be sufficient, assuming that this field would only be accessible to trusted user types (see "Tread with Care" later in my post).  If you configure your filters to allow "Filtered HTML" (with embed/iframe allowed) or even "Full HTML",  users can just copy and paste embed codes to their heart's content.
Any HTML snippets that are posted will get rendered when viewed without needing any extra template code or a custom module to handle them.  A "Filtered HTML" filter might still strip important attributes away, but "Full HTML" will not.
There is not really a generic way I can think of that would allow you to verify (even if you felt confident about your PHP) that iframe/embed html is a Vimeo video vs a banner advertisement vs a reference to malware.  That is why there are 20 different emfield modules; the sources for each type of content all do things differently and can constantly change how they approach embedding.
Text filters are available at: /admin/config/content/formats (in Drupal 7) and full documentation can be found here: Specifying the allowed formats for user input
Tread with care!
Keep in mind that users will be able to post anything else they want, too.  The "Full HTML" filter offers minimal protection and even if you went with "Filtered HTML" instead of "Full HTML" and permitted iframe or embed tags you are still in potentially dangerous territory if this field is going to be used by just anyone in your userbase.
Example/Demonstration
Comment: Thanks. My users are limited to the staff of an institution, so I'm not worried about malware in this case.

If a user posts code in a field with format filters on, won't it get converted (eg: >)? That won't allow the embed to work properly. I could remove all formatting from the field and let them paste it as plain text, but then I would need to figure out how to call that in the template without mangling the text.
Comment: Using the Full HTML filter will allow you to copy-paste any embed code except maybe javascript code.  Setting the filter to Full HTML means that it will not escape valid HTML.

I have attached images to illustrate.

If you are using nice "wysiwyg" editors like TincyMCE or CKEditor, you will probably need to switch them to showing the raw code before you try pasting anything.