Permission Denial: reading androidx.core.content.FileProvider trying to share a video file

Question: There have been several posts about this that I have reviewed and I've tried a half a dozen of the proposed solutions. I have something almost identical to this working without throwing an exception in another app I wrote but I'm just not able to get this not to throw an exception, although the file does get transferred! The permission is being set and the file does transmit just fine, but an exception still gets thrown although it does not crash the app.
What I have is this:
fun shareVideo(videoFile: File, context: Context) {
  if(videoFile.exists()) {
    Timber.i("Video file exists and the length in bytes is: ${videoFile.length()}")
  } else {
    Timber.w("Video file does not exist. Exiting.")
    return
  }

  val uris = arrayListOf<Uri>()
  val uri = FileProvider.getUriForFile(context.applicationContext, context.packageName + ".provider", videoFile)

  Timber.i("Uri: $uri + path: ${uri.path}")

  uris.add(uri)

  val intent = Intent()
  intent.action = Intent.ACTION_SEND_MULTIPLE
  intent.putExtra(Intent.EXTRA_SUBJECT, "Shared files")
  intent.type = "video/mp4"
  intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
  intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
  intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

  Timber.i("Intent: $intent")

  try{
      ContextCompat.startActivity(context, Intent.createChooser(intent, "Shared Videos"), null)
  } catch (e: Exception) {
    Timber.e("Exception starting activity. \nException was ${e.message}\n Stack trace to follow:\n ${e.stackTrace}")
  }
}

The stack trace looks like this:
2021-03-07 14:21:59.570 6039-6207/com.company.app E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri content://com.company.app.provider/external_files/1615148514218.mp4 from pid=32136, uid=1000 requires the provider be exported, or grantUriPermission()
    at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:820)
    at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:684)
    at android.content.ContentProvider$Transport.query(ContentProvider.java:239)
    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:106)
    at android.os.Binder.execTransactInternal(Binder.java:1154)
    at android.os.Binder.execTransact(Binder.java:1123)

The Timber log output looks like this:
2021-03-07 14:33:32.713 7396-7396/com.company.app I/StorageUtilsKt: Video file exists and the length in bytes is: 7511455
2021-03-07 14:33:32.719 7396-7396/com.company.app I/StorageUtilsKt: Uri: content://com.company.app.provider/external_files/1615149206171.mp4 + path: /external_files/1615149206171.mp4
2021-03-07 14:33:37.337 7396-7396/com.company.app I/StorageUtilsKt: Intent: Intent { act=android.intent.action.SEND_MULTIPLE typ=video/mp4 flg=0x10000001 (has extras) }
2021-03-07 14:33:38.604 7396-7589/com.company.app E/DatabaseUtils: Writing exception to parcel

So the file is there, and I see it in the attachment that it does add it and I do get it via email/etc. and can view it, but the exception is thrown in the logs.
My provider_paths.xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<paths>
  <cache-path          name="cache"          path="/"/>
  <external-cache-path name="external_cache" path="." />
  <external-path       name="external"       path="." />
  <external-files-path name="external_files" path="." />
  <files-path          name="app_videos"     path="." />
</paths>

And my manifest has this in it:
        <provider
          android:name="androidx.core.content.FileProvider"
          android:authorities="${applicationId}.provider"
          android:exported="false"
          android:grantUriPermissions="true">
          <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
        </provider>

Everything looks exactly like the app I have that works yet this one throws that exception.
Can anyone see what's wrong with what I am doing?
Comment: Try temporarily removing `Intent.createChooser()` and use `intent` directly. If that works, perhaps [switch to `setClipData()` or `ShareCompat.IntentBuilder`](https://commonsware.com/blog/2021/01/07/action_send-share-sheet-clipdata.html).
Comment: The full path is in the logs above but here it is: Uri: content://com.company.app.provider/external_files/1615149206171.mp4. Again, this does work and I can see the video on the other end in email/etc. but I don't like that it throws this exception when I haven't seen that before.
Comment: I'm seeing the same behavior as you. Did you ever fix it or see any negative consequences of not fixing it?
Answer: Use ShareCompat.IntentBuilder. It is doing all the right things for you.
For the underlying issue, see https://issuetracker.google.com/issues/173137936
fun shareVideo(videoFile: File, context: Context) {
    if (videoFile.exists()) {
        Timber.i("Video file exists and the length in bytes is: ${videoFile.length()}")
    } else {
        Timber.w("Video file does not exist. Exiting.")
        return
    }

    val uri = FileProvider.getUriForFile(context, context.packageName + ".provider", videoFile)

    ShareCompat.IntentBuilder(context)
        .setType("video/mp4")
        .setSubject("Shared files")
        .addStream(uri)
        .setChooserTitle("Shared Videos")
        .startChooser()
}

Comment: Nice answer. I didn't know about the class `ShareCompat`.
Answer: Check this one here https://stackoverflow.com/a/59439316
you need to grant permissions to each available app which is available for this intent.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Obrigado André deu certo!


Cannot import FTP_TLS on EC2

Question: I'm writing an FTP script in python on EC2 where I need to be able to import FTP_TLS for the connection.
from ftplib import FTP_TLS
Except, it gives me:
ImportError: cannot import name FTP_TLS
I can import FTP_TLS on my local python shell, but it fails on EC2.
What's going on?
EC2 Python 2.6.5 / Local Python 2.7.3
Answer: FTP_TLS is only supported in Python 2.7+.
You could upgrade Python on your server, or just grab Lib/ftplib.py from source:
wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz

Put it in your load path and your import will work.
Comment: Just to include the source: http://docs.python.org/2/library/ftplib.html indicates that FTP_TLS was added in 2.7
Comment: I've installed python 2.7.5 but FTP_TLS still gives me the same error. Is it because 2.6 is still there?
Comment: Possibly. Try `python --version` in your console to check which one's running, and the shebang at top of your script to check whether it explicitly starts a specific Python.

Cannot import FTP_TLS on EC2


What is the theoretical basis behind counting dispersion as an implicit additional free parameter in R's logLik() function?

Question: Recently I was attempting to calculate the Akaike Information Criterion (AIC) for a set of fitted models in R, using standard packages available on CRAN.  A package that I was using seemed to be exhibiting unexpected behavior, adding "+1" to the number of free parameters in each model.  While trying to understand the reason for this result, I ran across this stackoverflow question about the same issue.  I wrote my own question seeking further clarification, and confirmed that the extra parameter is intended to count the dispersion of the observed data about the fit model, even though the dispersion does not appear to be a parameter that could be independently adjusted in order to further improve the goodness of a fit.  The result of this "+1" behavior is that if one performs a linear regression against, for example, a simple line, using maximum likelihood techniques to estimate a slope and intercept parameter, then logLik() will report the number of model parameters as 3, rather than 2. A respondent to my question pointed me to this additional answer further confirming that this is indeed the intended behavior, in fact a commit to the source code from 19 years ago even references switching back and forth between the two alternative return values, as if there had been some significant disagreement within the developer community about which option was the correct output.
I looked up Hirotugu Akaike's original article from 1974, and the abstract references the "number of parameters" in a model as meaning "the number of independently adjusted parameters within the model".  Furthermore in the text of the paper (paywalled), in section IV, he additionally clarifies that "$k$ is the [...] number of parameters independently adjusted for the maximization of the likelihood"  It seems clear from context that because the dispersion of a fitted model is not used or referenced in maximizing the likelihood, but only emerges after the fitting procedure is already completed, Akaike would argue that for purposes of calculating AIC, he did not intend for the dispersion to be counted as one of the model's free parameters.  Thus, the practice of adding "+1" to the number of free parameters as the R stats module does, and using that value as input to an AIC calculation, seems counter to how the AIC was originally conceived by Akaike himself.
I am aware that in mathematics, sometimes we define certain concepts in order to enforce consistency within a larger theoretical framework.  So, for example, we define that $\sqrt{-1} = i$, or $0! = 1$, even though the reasons for those definitions wouldn't make much sense if considered only in isolation, without an appreciation of the larger context.  I'm curious whether there's also some broader context here that I'm not yet understanding, which developed within the field only after Akaike published his paper in 1974.
My question: what is the theoretical justification behind adding "+1" in order to count the dispersion among the number of free parameters in R's logLik() function, when the dispersion is not actually an independently adjustable parameter that could be tuned to further increase the maximum likelihood, and earlier thinkers such as even Akaike himself did not seem to have viewed it as such?
Answer: The loglikelihood returned for a linear regression model in R is the full Gaussian loglikelihood, which does depend on maximisation over $\sigma^2$; it isn't just the RSS.
The code (in stats:::logLik.lm) has
0.5 * (sum(log(w)) - N * (log(2 * pi) + 1 - log(N) +
        log(sum(w * res^2))))

which is maximised over both $\beta$ and $\sigma^2$ and so genuinely has $|\beta|+1$ parameters.  It is not $-\mathrm{RSS}/2$ or $-\mathrm{RSS}/2\sigma^2$
Because only differences in AIC have any meaning, the parameter count will only be affected if comparing a model with and a model without a dispersion parameter -- eg comparing a model with a prespecified error variance to one with an estimated error variance. In that setting, you would want to count $\sigma^2$ as a parameter.
Comment: Ok, but the Akaike paper was happy to drop additive constants to get a simpler form for the loglikelihood, so from that point of view he can't be regarded as definitive
Comment: AIC has an independent meaning of twice the negative expected loglikelihood on a new data point. It is thus an indirect measure of expected prediction loss where loss is defined w.r.t. the (log)likelihood. For that it is important to get the degrees of freedom right.
Comment: What I am trying to say is that *only differences in AIC have any meaning* is incorrect. (I am not trying to imply anything about what Akaike himself was thinking at some time point.)
Comment: In the likelihood expression you cite, we identify the weights as $w = 1/\sigma^{2}$.  In the [question](https://stackoverflow.com/q/67291431/3083138) that I wrote for stackoverflow, I explicitly established that the default behavior for `glm()` at least (and probably `lm()` as well) does not actually adjust these weights to obtain a better fit.  Therefore I think your first assertion is wrong: maximization (in the sense of a search over parameter space by an optimization algorithm such as Gauss-Newton or Levenberg-Marquardt) really is only occurring over $\beta$, not $\beta + \sigma^{2}$.


How does one transpose the guitar accompaniment for "Aura Lea" without making it sound like crap?

Question: Aura Lea, a.k.a. Love Me Tender, is a wonderful song: simple, melodious, and fun.
When I play the chords in F on the guitar, it sounds gorgeous.
Now I would like to take it down to C.
And suddenly it all sounds like crap.
The chords are simple enough:
C                D7            G7               C
As the blackbird in the spring neath the willow tree
                D7             G7             C
Sat and piped I heard him sing praise of Aura Lee.
C     E7   Am   C7   F              C
(Aura Lee, Aura Lee, maid of golden hair;
C         A7    D7                 G7              C
Sunshine came along with thee and swallows in the air)
The problem is that on the guitar, all those chords are either higher than the C the song resolves into (if you play the easy C chord);
OR: the C the song resolves into is way too high (on the eighth fret).
This is very, very frustrating.
Any suggestions?
UPDATE:
I just tried re-tuning the guitar, taking each string five semitones down. Unplayabe. Sounds like a tin can.
Comment: Hi @Ricky, you should be able to play it in either key F or C with all open chords. Which should sound fine either way. Are you maybe playing barre chords higher up the neck for some of those chords?
Comment: Someone once asked if I sang Aura Lee. I said I always sang orally...
Comment: @MichaelCurtis: Not really, no. I'm playing the C on the first fret (open), D7 on the first fret (open), G7 on the third fret (barred). That's the verse, and it sounds like crap. When I play it in F, it's F on the first fret (barred), G7 on the third fret (barred), C7 on the first fret (open) - and it sounds just fine.
Comment: Without knowing the exact voicing of the chords you use in each version, it's impossible to answer. There will be barre chords in the F version, and one or two in C. Where's the problem? On guitar, there are at least seven or eight different mixes of chord voicings that may be used.
Comment: Possible duplicate of [Is there a simple way to transpose a song from one key to another? What is the methodology?](https://music.stackexchange.com/questions/43257/is-there-a-simple-way-to-transpose-a-song-from-one-key-to-another-what-is-the-m)
Comment: @NeilMeyer How very thoughtful of you.
Comment: @Ricky if your question is different to the one I linked feel free to clarify how.
Comment: @NeilMeyer: Oh, and the burden of proof is suddenly on the accused, I see.
Answer: The issue I think you're describing is that changing the song's key messes with the voice leading of open chords. One way to get around this is to practice different voicings of each chord so that no key change pushes a chord up too high on the neck for you to handle smoothly. I don't personally play guitar, but I know other string instruments have this issue. Guitar has 6 strings. You could avoid playing some strings in order to make an easier voicing down lower (no way the 8th fret is the second-highest inversion!), or you could just voice the chords that force you to resolve up that high on the neck up high as well, so as to create smooth voice leading.
Or, of course, you could play barre chords, and then open strings and open chords don't matter at all.
Comment: @Ricky You're not wrong...
Comment: The 8th fret is not, to be sure, the second-lowest conversion; but the others are either astoundingly difficult to play smoothly (2 of those), while another one sounds suspiciously like G when you're just breezing through it. There ought to be more strings or something.
Comment: @Ricky - Based on your comment of "There ought to be more strings or something", are you interested in playing a 7-string guitar?
Comment: @dekkadeci: Fourteen or fifteen would be better, I think. Combined with eight fingers on each hand.
Answer: You say you play G7 as a barré on the third fret.  Why?  It's 1-0-0-0-2-3, basically the same shape as C with the fingers moving one string to the outside.  Sounds much more in line with the other chords.  Also you don't need to play the G bass note on the low E string since it's on, well, the G string as well which follows the melodic voice leading better (in case you are doing a fingerpicking style, for example).


Minimal Hover Menu - Da maneira certa

Question: No exemplo abaixo temos um menu interessante, com um efeito hover, que segue o mouse e seus itens. Tudo é muito bonito e funciona bem. O problema é que esse menu está definido com dimensões padrões, não podendo adicionar mais itens ou mudar o tamanho mantendo o efeito.
O que eu gostaria é de ter esse mesmo efeito em um menu tradicional, fluido, flexível, sem dimensões definidas, sem :nth-child

@import url(https://fonts.googleapis.com/css?family=Roboto:100);

body {
  font-family:'HelveticaNeue-UltraLight', 'Helvetica Neue UltraLight', Roboto, Arial, Sans-serif;
  background:#ecf0f1;
}

nav {
  width:400px;
  height:60px;
  margin:125px auto 0;
  text-align:center;
  background:#fff;
  box-shadow:0 1px 2px #ddd;
  backface-visibility:hidden;
}

nav ul {
  position:relative;
}

nav ul li {
  display:inline-block;
  line-height:60px;
  width:100px;
  margin-right:-4px;
}

nav ul li:first-child {
  margin-left:-4px;
}

li:nth-child(4):after {
  content:"";
  width:100px;
  height:3px;
  position:absolute;
  background:#3498db;
  top:0;
  left:0;
  transform:translateX(0);
  transition:.5s;
}

nav ul li:nth-child(2):hover ~ li:nth-child(4):after { transform:translateX(100px); }
nav ul li:nth-child(3):hover ~ li:nth-child(4):after { transform:translateX(200px); }
nav ul li:nth-child(4):hover:after { transform:translateX(300px); }

nav ul li a {
  text-decoration:none;
  color:#2c3e50;
  cursor:pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

Home

About

Clients

Work

Exemplo de menu onde eu gostaria que o efeito do exemplo acima fosse aplicado.

.dropdownmenu ul, .dropdownmenu li {
 margin: 0;
 padding: 0;
}
.dropdownmenu ul {
 background: gray;
 list-style: none;
 width: 100%;
}
.dropdownmenu li {
 float: left;
 position: relative;
 width:auto;
}
.dropdownmenu a {
 background: #30A6E6;
 color: #FFFFFF;
 display: block;
 font: bold 12px/20px sans-serif;
 padding: 10px 25px;
 text-align: center;
 text-decoration: none;
 -webkit-transition: all .25s ease;
 -moz-transition: all .25s ease;
 -ms-transition: all .25s ease;
 -o-transition: all .25s ease;
 transition: all .25s ease;
}
.dropdownmenu li:hover a {
 background: #000000;
}
#submenu {
 left: 0;
 opacity: 0;
 position: absolute;
 top: 35px;
 visibility: hidden;
 z-index: 1;
}
li:hover ul#submenu {
 opacity: 1;
 top: 40px; /* adjust this as per top nav padding top & bottom comes */
 visibility: visible;
}
#submenu li {
 float: none;
 width: 100%;
}
#submenu a:hover {
 background: #DF4B05;
}
#submenu a {
 background-color:#000000;
}

Home

About Me

Articles on HTML5 & CSS3

Difference between SVG vs. Canvas

New features in HTML5

Creating links to sections within a webpage

News

Contact Us

Source 1: https://codepen.io/joacimnilsson/pen/WbNLwb
Source 2: https://codepen.io/dhanushbadge/pen/olsvi
Answer: Pode usar o JavaScript para ter o mesmo efeito. Fiz uma modificação nesta classe abaixo adicionando position: relative:
.dropdownmenu ul {
    background: gray;
    list-style: none;
    width: 100%;
    position: relative;
}

E criei uma classe que será a "barrinha" que acompanha o mouse. A barrinha será posicionada inicialmente na li com a classe .current-link:
.barra {
  height:3px;
  position:absolute;
  background: #00F71C;
  transition:.5s;
  z-index: 9;
}

O que fiz foi criar a barrinha de forma dinâmica, posicionada na primeira
. Quando o mouse passa pelas outras lis, a barrinha muda de posição e largura, aproveitando o efeito do transition:.5s;.
Veja:

document.addEventListener("DOMContentLoaded", function(){

   function barPos(bar, act){
      var pos = "left:"
      +act.offsetLeft
      +"px;"
      +"width:"
      +act.clientWidth
      +"px;"
      +"top:"
      +act.offsetTop
      +"px;";

      bar.style.cssText = pos;
   }

   var lis = document.body.querySelectorAll(".dropdownmenu > ul > li"),
       act = document.body.querySelector(".dropdownmenu > ul li.current-link"),
       bar = document.createElement("span"),
       cur = Array.prototype.indexOf.call(lis, act);

   bar.className = "barra";
   lis[0].appendChild(bar);
   var bar = document.body.querySelector(".barra");

   barPos(bar, act);

   for(x=0; x<lis.length; x++){
      lis[x].addEventListener("mouseover", function(){
         var idx = Array.prototype.indexOf.call(lis, this);
         if(cur != idx){
            cur = idx;
            bar.style.cssText = "left:"
            +this.offsetLeft
            +"px;"
            +"top:"
            +this.offsetTop
            +"px;"
            +"width:"
            +this.clientWidth
            +"px;";
         }
      });

      lis[x].addEventListener("mouseleave", function(){
         cur = Array.prototype.indexOf.call(lis, act);
         barPos(bar, act);
      });
   }

   window.addEventListener("resize", function(){ barPos(bar, act); });

});
.dropdownmenu ul, .dropdownmenu li {
 margin: 0;
 padding: 0;
}
.dropdownmenu ul {
 background: gray;
 list-style: none;
 width: 100%;
   position: relative;
}
.dropdownmenu li {
 float: left;
 position: relative;
 width:auto;
}
.dropdownmenu a {
 background: #30A6E6;
 color: #FFFFFF;
 display: block;
 font: bold 12px/20px sans-serif;
 padding: 10px 25px;
 text-align: center;
 text-decoration: none;
 -webkit-transition: all .25s ease;
 -moz-transition: all .25s ease;
 -ms-transition: all .25s ease;
 -o-transition: all .25s ease;
 transition: all .25s ease;
}
.dropdownmenu li:hover a {
 background: #000000;
}
#submenu {
 left: 0;
 opacity: 0;
 position: absolute;
 top: 35px;
 visibility: hidden;
 z-index: 1;
}
li:hover ul#submenu {
 opacity: 1;
 top: 40px; /* adjust this as per top nav padding top & bottom comes */
 visibility: visible;
}
#submenu li {
 float: none;
 width: 100%;
}
#submenu a:hover {
 background: #DF4B05;
}
#submenu a {
 background-color:#000000;
}

.barra {
  height:3px;
  position:absolute;
  background: #00F71C;
  transition:.5s;
  z-index: 9;
}

Home

About Me

Articles on HTML5 & CSS3

Difference between SVG vs. Canvas

New features in HTML5

Creating links to sections within a webpage

News

Contact Us

Comment: simplesmente magnifico. é exatamente isso!  O efeito está fixado no link **Home** esse efeito também deverá ficar ativo na página do respectivo link aberto. `li.current-link`
Comment: entendi o que preciso fazer.
Comment: fiz confusão, julguei mal o código, tentei, mas não consegui...
Comment: ficou perfeito.
Comment: https://pt.stackoverflow.com/q/285555/95735
Comment: será que é possível colocar também esse mesmo efeito, com o e evento **focus** ? igual o do css.
Comment: a questão do focus/active para esse menu, seria necessário fazer uma nova pergunta?
Comment: não funciona, também testei com mousedown, e só funciona o click. Mas o hover não. Não dá para utilizar esses valores juntos? `mouseover` e `mousedown`
Comment: Aqui funciona: https://jsfiddle.net/q488npqp/
Comment: inclusive o hover? Porque aqui só funciona o clique.
Comment: Farei outra pergunta.
Comment: Compreendo. De fato, mas o principal é apenas o contextmenu. `Abrir em nova aba.`
Answer: John seguindo todas as regras que vc falou eu consegui chegar nesse resultado.
O exemplo usa FlexBox então é bem responsivo. vc pode acrescentar quantos itens quiser que vai ajustar direitinho (Talvez vc tenha que diminuir a fonte um pouco se tiver itens de mais...) Mas no mais funciona bem em telas menores até certo ponto.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    background-image: url(http://placecage.com/800/600);
    background-size: cover;
    background-repeat: no-repeat;
}
.navbar {
    width: 100%;
    height: 50px;
    padding: 0;
    text-align: center;
    background-color: rgba(0,0,0,.5);
    display: flex;
    align-items: center;
    position: relative;
    top: 0;
}
.box {
    flex: 1;
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    cursor: pointer;
}

.box::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    height: 0.5rem;
    width: 100%;
    background-color: #0f0;
    transform: scaleX(0);
    transform-origin: right;
    transition: transform 350ms;
}
.box:hover::after {
    background-color: #0f0;
    transform: scaleX(1);
    transform-origin: left;
}

.link {
    color: #fff;
    text-transform: uppercase;
    font-size: 1.25rem;
    text-decoration: none;
    font-family: sans-serif;
}

        item 1

        item 2

        item 3

        item 4

        item 5

OBS: o único detalhe é que a animação não fica sempre acompanhando o mouse. Mas se quiser vc pode fazer ela começar no "centro" dos .Box, basta colocar transform-origin: center; pra vc ver como fica.
Comment: Sua solução é boa, mas eu preferiria não usar flexbox, se for possível gostaria apenas de colocar esse efeito, no menu do segundo exemplo, tal como ele é, aquele menu é bem feito, funciona em todos os navegadores, inclusive no ie7... sei que o efeito só vai funcionar nos navegadores modernos...

Minimal Hover Menu - Da maneira certa


How to assign a number to a variable in PHP

Question: I am learning PHP and want to assign a number to my variables for use in math functions.
My current code is:
  <?php $size = 12; ?>

  <?php $quantity = 10; ?>

  <?php echo $size * $quantity; ?>

How could I change it so that 12 in $size equals a number like 19.50, I am trying to do this as if it was a price calculator.
EDIT: To clarify, I don't want to just change 12 to 19.50, the end result I am trying to get to is the user selects a size of "12" from a HTML dropdown menu, and when the PHP math uses the variable it does not multiply it by 12, but rather by a price of 19.
Thanks.
Comment: Your question is very vague. Please be more specific!
Comment: If you know how to assign `12` to a variable, then why wouldn't the same thing work when applying `19.5` to a variable?
Comment: @npav42: Update your question, and explain that you want the values to depend on user input...
Comment: Really? how to assign 19.50? Just because it's a different number doesn't make assignments in PHP magically different. That'd be like saying "I can't drive this car! It's red! I only know how to drive blue cars!"
Comment: As I understand it ... why not just, in the HTML, have `12` and define `$size` based on the `_GET` var?
Comment: Have you tried:
Comment: Do you mean something like `$size = $size * 123;`?
Comment: Do you mean ``?
Comment: That would be like what I have right now, what I want is to eventually add these variables to a dropdown menu that would show 12, but the PHP math would use 19.50.
Comment: just create a set of prices for each sizes, after submission, get the proper price according to size then multiply it by the quantity
Answer: You can add a simple condition using if/else structure
<?php

$size = 12;                // dummy

if($size==12)              // You can add conditions for other sizes
{
  $number=19.50;
}

?>

If there are too many sizes you can consider using switch or a multi dimensional array for this. For example
$sizes=array();
$sizes[]=array('size'=>12,'number'=>19.50);
$sizes[]=array('size'=>10,'number'=>17.50);
$sizes[]=array('size'=>8,'number'=>16.50);

Based on your edited description
You can simply rebuild your select box and you wont have to make those assignments in PHP. Like this
<select name="sizes">
 <option value="19.5"> Size 12 </option>
 <option value="17.5"> Size 10 </option>
</select>

Comment: ... changing the value of the options ... my thoughts exactly ;)
Answer: Ok, as it turns out, you want the user to select "12" from a dropdown menu, which would translate to your using 19.5 internally. That, to my eye, is quite deceptive, though, but that's none of my business.
How to do that? That's pretty simple: build a form like this:
<form method='POST'>
    <select name='number'>
        <option value='19.5'>12</option>
        <option value='20'>1</option>
        <option value'40'>2</option>
    </select>
    <input type='submit' value='Compute'>
</form>

Then, have the form processed by PHP. something like this:
<?php
    if (isset($_POST['number']))
    {
        $number = (float) $_POST['number'];
        echo $number*10;
    }

I can assure you that, if the user selected 12, the actual value that will be sent is a string: "19.5", which I cast to float, and assign to the variable $number, I echo the value of this variable, multiplied by 10, giving me the output "195". Easy
Comment: Thanks for the answer, and haha, not trying to be deceptive, they would select a size for example of 12 inches, which would have a price assigned to it of $19.50.
Comment: @npav42: You're right, that wouldn't be deceptive. But have you thought about product groups where the price varies based on the finishing material, like cloth vs leather or something? It would appear you are building a web shop platform of sorts. I'd opt to pass the product id as a value, then have PHP query the product details, and the exact price. If you don't: it's a piece of cake for me to alter the request data and send _"12"_ or even _"1"_ as the value, which you use as price back to the server. Anyway: sending back the product ID is what most webshops do
Comment: Yes I'm trying to make a shop for a website I built (buygeminisignletters.com) that would allow users to purchase plastic letters, with a few different variables that effect the price, such as size and font, and then pass that on to a payment processor (likely Stripe) to accept the card.   Thanks for the help / tips, I'm learning PHP on the fly here so forgive me if I don't understand everything being said, but it makes sense to keep the important code such as price that could be changed away from user input HTML modules.
Answer:   <?php $size = 19.50; ?>

Works for me ...
Answer: <?php $size = 19.50; ?>

Is this that you want?
Answer: do it the same way you used in assigning 12 to $size:
then try your echo statement again:
this time you should have an answer of 195


Componente Composto em C# não mostra todos os atributos

Question: Tenho um sistema no qual uso um dataGridView para listar os campos de uma tabela através da propriedade dataSource, e um textBox para que o texto escrito sirva de filtro (quando digito algo no textBox, uso o texto digitado para filtrar minha tabela e atualizo no dataSource do dataGridView).
Estou aprendendo C# e vi que no Visual Studio, posso criar um Componente Composto e quis criar um componente unindo o textBox e o dataGridView.
Iniciei a criação com um dataGridView e um textBox e gerei o novo componente (textBoxGrid).
Incluí o novo componente (textBoxGrid) no meu form e quando fui procurar a propriedade dataSource no novo componente, ela não é mostrada.
Como faço pra que ela fique visível?
Answer: Você deve criar um "link" entre a propriedade do seu datagridview e do seu componente.
Algo semelhante a isto:
No seu componente basta criar uma propriedade com get, e set apontando para a propriedade do datagridview:
Se você tiver necessidade de setar o DataSource em design mode, deve-se adicionar os atributos na propriedade.
[AttributeProvider(typeof(IListSource)), DefaultValue(null), RefreshProperties(RefreshProperties.Repaint)]
public Object DataSource
{
    get { return datagridview1.DataSource; }
    set { datagridview1.DataSource = value; }
}

Veja com o atributo na propriedade, o datasource é "desbloqueado"

Lembre-se que toda vez que alterar o componente deve-se dar build no projeto novamente para atualizar.
Comment: vou testar agora mesmo. posso fazer isso com qualquer propriedade?
Comment: Sim pode fazer isto com qualquer propriedade, inclusive você pode abrir o `get` e `set`, para manipular como quiser, inserindo  `if`, por exemplo.
Comment: Você carrega o `DataSource` no design do `visual studio` ou em tempo de execução?
Comment: Deu certo!!! Muito obrigado mesmo. Carrego no design.
Comment: Se você for carregar no design talvez seja necessário adicionar os atributos na propriedade. Como é object vai aparecer a propriedade mas não vai ser possível alterar. Vou alterar a resposta.
Comment: blz, aguardo voce alterar
Comment: obrigado, se não for pedir muito, você pode me explicar essa linha? -> [AttributeProvider(typeof(IListSource)), DefaultValue(null), RefreshProperties(RefreshProperties.Repaint)]
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/50161/discussion-between-marco-giovanni-and-italo-rodrigo).


mod_rewrite and trailing slash

Question: I want to make
www.example.com/test/ rewrite to www.example.com/example.com/test/
www.example.com/ rewrite to www.example.com/example.com/

I can do that with this rewrite configuration:
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$
RewriteCond %{REQUEST_URI} !^/example.com(.*)
RewriteCond %{REQUEST_URI} ^(.*)/$
RewriteRule ^(.*) /example.com/$1  [L]

But I also want to redirect the same without trailing slash:
www.example.com/test redirect to www.example.com/example.com/test/
www.example.com/ redirect to www.example.com/example.com/

I have tried with this:
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$
RewriteCond %{REQUEST_URI} !^/example.com(.*)
RewriteCond %{REQUEST_URI} !^(.*)/$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ $1/ [R=301,L]

but does not work, it redirects to:
IE: http://www.example.com/C:/wamp/www/test/
Firefox: http://www.example.com/C:/wamp/www/example.com/test/

do you know a solution to this (without touching mod-dir conf)?
Answer: I've found the solution:
Options +FollowSymLinks
RewriteEngine On

# Fix missing trailing slashes.
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{DOCUMENT_ROOT}/_l_/example\.com%{REQUEST_URI}/ -d
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]

# Rewrite sub domains.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ /_l_/example\.com/$1 [QSA,L]

Thanks for your answers.
Answer: Try
RewriteCond C:/wamp/www%{REQUEST_FILENAME} !-f

or
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f

See also "What's up with REQUEST_FILENAME in mod_rewrite?"
Answer: I don't know where the "C:" is coming from in your browsers -- a more useful diagnostic would be to find the "Location" header from the HTTP response -- use something like Firebug, LiveHTTPHeaders, or telnet to get that.
Also, given that your second RewriteRule doesn't mention 'example.com' at all, I guess that you have both RewriteRules in your httpd.conf.
If that is the case, then the [L] modifier at the end of your first rule is stopping the second one from executing at all.
Answer: Why not just use this?
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$
RewriteCond %{REQUEST_URI} !^/example.com(.*)
RewriteRule ^(.*) /example.com/$1  [L]

Comment: Not working, when I try www.example.com/test it give me this
    http://www.example.com/C:/wamp/www/example.com/test/

mod_rewrite and trailing slash


drupal_render() and drupal_get_form()

Question: In the following snippet, the form returned has only the hidden values. No name, email, or comment.
require_once drupal_get_path('module', 'contact') .'/contact.pages.inc';
$elements = drupal_get_form(array('contact_site_form'));
$form = drupal_render($elements);

Can anyone say why $form is not returning an HTML form?
Comment: Maybe because drupal_get_form returns an html representation of whatever form is passed in the argument.
Comment: I meant to ask, why is this NOT returning a html string? (oops, my cred is falling faster than some presidential candidates!)
Comment: Are you using D7 or D6?
Comment: This is Drupal 7, and it suddenly started working. Weird ass Drupal (-;
Comment: @stefgosselin drupal_get_form does not return html, it returns the form array.
Comment: Oh, not sure but maybe some data was 'cached', I mean had you tried drush cc all to clear your cache?  when playing in rendering functions I think sometimes stuff in there is cached and running cc all empties the registry among other things.
Answer: drupal_get_form('contact_site_form');

drupal_render() and drupal_get_form()


How to hide homepage link from menu once logged in?

Question: I have a "home" link on my primary navigation menu. Once the user is logged in, the home link is irrelevant and I don't wish to show it.
I've set the access control permissions for the "home" page to only show for "anonymous user", but it's still visible in the menu once logged in. I'm guessing that authenticated users can see everything anonymous ones can, even if they don't have the box ticked. Is there some way around this?
I'm aware of "menu per role", but I read that it's better to set the permission of your content directly and let Drupal hide/show where appropriate, so I'd like to avoid using menu per role if possible.
Answer: Try with this code
function THEME_menu_item_link($link) {
  global $user;
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ( ($link['href'] == '<front>') && ($user->uid == 0) ){
       return '';
  } else {
      return l($link['title'], $link['href'], $link['localized_options']);
  }
}

Answer: You could hook into the menu link in the theme template and hide with some styling.
function THEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $name_id = strtolower(strip_tags($element['#title']));

  if ($name_id == 'home') {
     $element['#localized_options']['attributes']['class'][] = 'hide';
  }
}


Drupal 8 : Get a config settings value being stored in blocs

Question: I have create a block with a form and stored something i called 'submit_action_amu_dud_form_block_settings'
<code> public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['submit_action_amu_dud_form_block_settings'] = $form_state->getValue('submit_action_amu_dud_form_block_settings');

 }
</code>
in a method of the same class i can retrieve the value
<code>      $config = $this->getConfiguration();
      $my_stored value=$config['submit_action_amu_dud_form_block_settings']
</code>
how can i get it from . module hook_form_alter callback ?
<code>    function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

if ($form_id == 'amu_dud_form') {
    $form['actions']['submit']['#submit'][] = 'my_submit_method';
}
}

 function my_submit_method(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

//$my_stored_value=??
</code>
Answer: You need to load the block if your outside of the class, for that you need it's id.
<code>$block = \Drupal\block\Entity\Block::load($bid);
$my_stored_value = $block->get('settings')['submit_action_amu_dud_form_block_settings'];
</code>
The id can be found in it's annotation if it's custom: <code>@Block( * id = "my_fancy_block_id"</code>. If there are several instances of the block this may be altered and can be looked up in the DB, or the block config admin section - check the urls there.
Comment: do u know how to get $bid ? is it no what i have defined in the block class  comment* @Block(
 *  id = "amu_dud_form_block",
Comment: yes - it is -  ;)
Comment: the $block->configuration(....) does not work for instance of block $block = \Drupal\block\Entity\Block::load('amududformblock_3');
Comment: and is it not possible to load the configuration for the my_fancy_block_id loaded in the page? (not a static value put in the module code )
Answer: thanks to remy i have been able to retrieve the value from an instance of block this way:
<code>//instance of block bid found in db
$block = \Drupal\block\Entity\Block::load('my_blockinstance_bid');
$block_settings = $block->get('settings');
$url=$block_settings['my_stored_setting'];
</code>
The problem remain then , when having mutliple instance of blocs, to load a block config dynamically corresponding to the settings value that have been stored for the block being displayed on the page ?
Comment: every instance should have an unique id - thanks for the working code, I updated my answer too, as I just 'guessed'


Strange squished notes and can grace notes be tied? (is what I'm seeing a slur?)

Question: Piece is traümerei, what does this squished note mean (the conjoined crotchet and semibreve) and how do I play it?

Also can grace notes be tied? Or is any kind of connecting line on a grace note a slur no matter the pitch of the subsequent note?

Sorry for image quality
Thanks to all who can help!
Comment: Ouch my eyes!  please try to take in-focus pictures -- no need to get that close to the page
Answer: In the first instance the "extra" crotchet is there because there are in effect two lines of music going on in the lower staff.  One voice is the semibreve low F lasting for the whole bar.  The other voice is a crotchet low F followed by the dotted minim C/A chord 1 beat later.  It is that crotchet that tells you that the C/A chord is meant to be played on the second beat.
The second one:  yes that is a tie.  So you play low B flat, then F (and hold it) then the D.


TypeError when checking for instance of str

Question: I'm trying to write a function such that if a string or a number is passed, the data s returned in reverse order. Otherwise, it is returned as it is.
Here's my code:
def reverse_it(data):
    if isinstance(data, str):
        return data[::-1]
    elif isinstance(data, int):
        return data[::-1]
    else:
        return data

This results in an error:
  File "play.py", line 10, in <module>
    print reverse_it(9000)
  File "play.py", line 5, in reverse_it
    return data[::-1]
TypeError: 'int' object has no attribute '__getitem__'

Why can I check for the data type of a str object but not for an int?
Comment: `elif isinstance(data, int): return int(str(data)[::-1])`?
Comment: You are successfully checking that `data` is an `int`. The error is from trying to slice the `int` as if it were a string.
Comment: The person who asked the question should define, what a string and a number is. There are several possibilities which differ by Python version.
Comment: I apologize, as I don't know much about python versions. The problem came from trying to slice an int, which is where the error came from. NightShadeQueen's solution ended up working
Comment: NightShadeQueens solution might not be what you expect. Try it with the int 1000.
Answer: What do you think should happen here:
elif isinstance(data, int):
    return data[::-1]

The data type check is successful, but you cannot slice an int.
You could write
return str(data)[::-1]

Edit: you might also want
isinstance(data, basestring)

See What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)?
Comment: If data is a number, reverse it. Does the problem come from trying to reverse/slice something that's not a string?
Comment: What you are using is called a slice. It is defined for list-like data structures. Strings are lists of characters (well, not exactly, but you can think of them as lists of characters). I've added a work-around to my answer
Comment: To reverse the digits of a number you must first convert it to a string.
Comment: That's what I ended up doing and it worked fine. Thanks!
Comment: @moose I was responding to Thrashmaniac89's comment, which appeared before yours. I assumed you already knew this.
Comment: It said I had to wait 4 more minutes, but I accepted it now. @moose
Comment: @Zac: sorry, my short term memory is not working properly by now. It's too early. And using the phone doesn't help either.


Use mathematical induction to prove that a function is divisible by 9

Question: I initially posted a question and thought that was the only one I was stuck on, but there's this other question too.
I think I kinda solved it, but I'm getting that it isn't divisible by 9. I'd like a confirmation please!
The question is as follows:

Use mathematical induction to prove that $$5^{2n+1} - 21n + 31$$ is divisible by $9$ for $\forall n \geq 1$.
Comment: "I think I kinda solved it" - so please share with us what you did. I would be glad to see your progress.
Comment: I think it is divisible by 9, can you show us your calculations?
Comment: $5^{2n+1}\equiv(-1-3)^{2n+1}\equiv-1+(2n+1)(-3)\equiv-6n-4\equiv21n-31\pmod9$
Comment: I ended up solving it last night and falling asleep. I basically got the last line as 504k - 765 by subbing for 5^(2k+1) = 21k - 31. And that line is divisible by 9. So kinda similar to what @LearningMathematics did below, but we've never used mod.
Answer: For $n = 1$,
$5^{2n+1} - 21n + 31 = 135$, which is divisible by 9.
Assume the claim hold for $n = k$.
When $n = k + 1$,
$5^{2(k+1)+1}−21(k+1)+31 \pmod9$
$\equiv 25(5^{2k+1})−21k + 10 \pmod9$
$\equiv  25(21k - 31) - 21k + 10 \pmod9$
$\equiv 9(56k) -31*25  + 10 \pmod9$
$\equiv 0 \pmod9$
Therefore the claim is true for all integer n $\ge 1$
Answer: $5^{2n+1}-21n+31$ is divisible by $9$.
Here is a hint for the induction step:
$5^{2(n+1)+1}-21(n+1)+31=25(5^{2n+1}-21n+31)+504n-765$


Dificuldade em agrupamento e cláusula where, no MySql

Question: Preciso buscar no banco de dados os últimos 4 registros mais recentes, sendo que a coluna exr_exa_id esteja de acordo com os id's informados, e os exr_exa_id não podem ser duplicados.
Tentei agrupar de algumas maneiras, porém não tive sucesso, pois, ou não exibe os registros mais recentes, ou exibe registros iguais na coluna exr_exa_id (vide imagem).
Podem me ajudar?
SELECT *
FROM exa_exameresultado
WHERE
   exr_exa_id IN (18,19,20,71) AND
   exr_pac_id = 2128
ORDER BY
   exr_data DESC,
   exr_exa_id ASC
LIMIT 4

Comment: Coloca no http://sqlfiddle.com/, para você nos ajudar a te ajudar :)
Comment: segue link http://sqlfiddle.com/#!9/58d88/1/0
Comment: Ao colocar o group by, ele altera a data...Ex: a data + recente para o campo exr_exa_id de valor 18 é 2015-04-09. Ao colocar um group by no exr_exa_id, ele altera a data deste registro para 2014-10-07
Answer: SELECT
  *
FROM
  exa_exameresultado
WHERE
  exr_exa_id IN (18,19,20,71)
AND
  exr_pac_id = 2128
GROUP BY
  exr_exa_id
ORDER BY
   exr_data DESC, exr_exa_id ASC
LIMIT 4

A única mudança que fiz foi colocar um GROUP BY exr_exa_id.
Mas o GROUP BY funciona nesse caso porquê os outros campos são iguais nos seus valores também. Se depois os valores delas mudarem, talvez esse SELECT não sirva mais para você.


Examples of hidden Markov models problems?

Question: I read quite a bit of hidden Markov models and was able to code a pretty basic version of it myself.
But there are two main ways I seem to learn. One is to read and implement it into code (which is done) and the second is to understand how it applies under different situations (so I can better understand how it relates to problems I might be working on). All the examples I have done so far have involved either some kind of DNA prediction or coin tossing.
I'm wondering if there are any resources to get other Markov problems (language doesn't matter but hopefully with the answers as well so I can know if I'm right or wrong)?
Comment: I don't want to spend weeks working on it, but for example a case study of someone using markov models in a non-coin toss or weather prediction way might help me understand the range of problems it can solve better.  i'm basically looking to build a better understanding by testing what markov models can do.
Comment: I was advised to cross post this from http://stackoverflow.com/questions/8661941/how-can-i-find-examples-of-problems-to-solve-with-hidden-markov-models
Comment: Could you be a little more specific in terms of "code a pretty basic version"? Did you simulate from a Hidden Markov process, or did you code the Viterbi, forward, or Baum–Welch algorithms? (The last three would be used to compute the most-likely corresponding sequence of states, the probability of the sequence of observations, or the starting probabilities, transition function, and observation function of a hidden Markov model, respectively.)
Comment: Hi Wayne, I basically coded a version of this page(the spreadsheet) for baum-welch: http://www.cs.jhu.edu/~jason/papers/#tnlp02 and basically implemented the code for the viterbi wiki page and followed a few basic tutorials on hidden markov models.  This might sound stupid but I wanted to see other types of problems I could try to solve so I can gain a better understanding of what markov models are capable of.
Comment: I think HMM also have very important applications in Finance(interest rates) and Economics(GDP).
Comment: HMMs are used for tagging parts of speech
Answer: I've used HMM in a demand / inventory level estimation scenario, where we had goods being purchased from many stores that might or might not be out of inventory of the goods.  The sequence of daily demands for these items thus contained zeroes that were legitimate zero demand days and also zeroes that were because the store was out of stock.  You would think you'd know whether the store was out of stock from the inventory level, but errors in inventory records propagate and it is not at all uncommon to find a store that thinks it has a positive number of items on hand, but actually has none; the hidden state is, more or less, whether the store actually has any inventory, and the signal is the (daily demand, nominal inventory level).  No references for this work, though; we were not supposed to publish the results for competitive reasons.
Edit:  I'll add that this is especially important because, with zero demands, the store's nominal on hand inventory doesn't ever decrease and cross an order point, triggering an order for more inventory - therefore, a zero on hand state due to erroneous inventory records doesn't get fixed for a long time, until somebody notices something is wrong or a cycle count occurs, which may be many months after the problem has started.
Comment: I believe this is known as a zero-inflation problem, and they're fairly widespread. You need one model that models the "excess zeroes" (when the reading is zero because there cannot be any reading, as opposed to a legitimate reading of zero), then a second-level model that models the rest. For example, the number of customers in a bank: sometimes there actually are none, other times the bank is closed so there can't be any. Or the speed of a car: sometimes it's sitting still with a driver in it, other times it's parked. Etc.
Comment: True enough, from the point of view of the demand signal.  The other part of the problem is identifying the binary "inventory = 0 | inventory record > 0" hidden state, which was actually more important for the customer.
Comment: I should also point out that the "inflated zeroes" are not i.i.d. over time - there are runs where all the zeroes are "extra" and runs where none of them are, hence the need for the HMM with the state indicating which is happening at each observation.
Answer: I pretty much experienced the same thing and didn't find much beyond the weather. Areas that come to mind include: speech recognition, change point detection, tagging parts of speech in text, aligning overlapping items/text, and recognizing sign language.
One example I found and did some exploration of was in Section 8 of this introduction, which is one of the references for HMM's in Wikipedia. (It's actually pretty fun: your analysis discovers that there are vowels and consonants.) This also introduces you to working with a text corpus, which is useful.
(If you want to play with generation with HMMs, you could train on Shakespeare text and then generate faux-Shakespeare.)
Answer: Most speech recognition software uses Hidden Markov Models. You can experiment with natural language processing if you want to get a feel for HMM applications.
Here's a good source: Probabilistic Graphical Models, by Koller and Friedman.
Comment: Thanks, Carlos.  Great book, I started reading it a while back but didn't finish it.  Got it to learn about machine learning and graph theory, but I'll go back and look for questions related to markov models.  I'll also take a look at natural language processing(I have never worked with it before)
Answer: Hidden markov models are very useful in monitoring HIV.  HIV enters the blood stream and looks for the immune response cells.  It then sits on the protein content of the cell and gets into the core of the cell and changes the DNA content of the cell and starts proliferation of virions until it burst out of the cells.  All these stages are unobservable and called latent.  An ideal example for hidden markovian modelling.
Comment: So in what way exactly do hidden Markov models help to monitor HIV? Do clinicians use HMMs to diagnose HIV? Do researchers use them to better understand mechanisms of the disease or create anti-HIV drugs and therapies? Any references would be very helpful.
Answer: For me, very nice application of HMM is chord identification in musical composition. See for example this lecture.
Answer: Markov models may be useful in analyzing the interactions of a user with a website - For Example on Amazon.com where figuring out what series of interactions lead to a checkout to give recommendations in the future.
A fun example showing the use of Markov Model is the following-
http://freakonometrics.blog.free.fr/index.php?post/2011/12/20/Basic-on-Markov-Chain-(for-parents)
Comment: Not HIDDEN Markov models here though - huh?


Call Drupal behaviour when AJAX form is submitted?

Question: I have a form with an AJAX callback. I need to run some JavaScript when the form is submitted. Ive got this working by following the tutorial below:
http://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7
However I already have a JavaScript file in the module and I would prefer to put my code in there. This file is loaded on page load so I think I would need to listen for an event and run when this was detected. Can I use the AJAX callback to trigger an event thats within a Drupal behaviour?
function after_ajax_form($form, &$form_state)
{
    // First we create a form element with AJAX enabled
    $form['ajax_example'] = array
    (
        '#type' => 'select',
        '#title' => t('Change me'),
        // Note that I am setting the value and the display of the elements to be the same, for convenience sake in our callback function
        '#options' => array(t('Select something') => t('Select something'), t('Something selected') => t('Something selected')),
        '#prefix' => '
',
        '#suffix' => '
',
        '#ajax' => array
        (
            'callback' => 'after_ajax_ajax_callback',
            'event' => 'change',
        ),
    );

    // Next we add our JavaScript file, named after_ajax.js. This file
    // lives in the /js folder inside our module:
    $form['#attached']['js'] = array
    (
        array
        (
            'type'  => 'file',
            'data' => drupal_get_path('module', 'after_ajax') . '/js/after_ajax.js',
        ),
    );
    return $form;
}

function after_ajax_ajax_callback($form, &$form_state)
{
    // First, we initialize our $commands array. This array will
    // contain each of the commands we want to fire for our
    // #AJAX callback:
    $commands = array();

    // Next, we create our insert function that will insert our updated content
    // back into the page. To do this, we use the system provided
    // ajax_command_html() function. We pass this function two values:
    // 1) Our AJAX wrapper (that we defined as the #prefix and #suffix of our form element)
    // 2) The rendered HTML that needs to be inserted into the wrapper in the page.
    $commands[] = ajax_command_html('#after_ajax_element_wrapper', render($form['ajax_example']));

    // Next, we will use the system provided ajax_command_alert() function as an example to show it's
    // working:
    $commands[] = ajax_command_alert(t('ajax_command_alert() is working'));

    // Next we will include a custom function that we will call ourselves in our JavaScript file:
    $commands[] = array
    (
        // The command will be used in our JavaScript file (see next section)
        'command' => 'afterAjaxCallbackExample',
        // We pass the value that the user selected in the select element to our
        // JavaScript function:
        'selectedValue' => $form_state['values']['ajax_example'],
    );

    // And finally, we will return all of our commands to the system to be executed:
    return array('#type' => 'ajax', '#commands' => $commands);
}

(function($, Drupal)
{
    // Our function name is prototyped as part of the Drupal.ajax namespace, adding to the commands:
    Drupal.ajax.prototype.commands.afterAjaxCallbackExample = function(ajax, response, status)
    {
        // The value we passed in our Ajax callback function will be available inside the
        // response object. Since we defined it as selectedValue in our callback, it will be
        // available in response.selectedValue. Usually we would not use an alert() function
        // as we could use ajax_command_alert() to do it without having to define a custom
        // ajax command, but for the purpose of demonstration, we will use an alert() function
        // here:
        alert(response.selectedValue);
    };
}(jQuery, Drupal));

Answer: AJAX callbacks only return an array of commands, and those commands are then executed by Drupal. It is the method I prefer when dealing with AJAX in Drupal.
Behaviors are attached to every page. If you really want to call the behavior, detached from a Drupal AJAX response, then your behavior needs to react when the form is submitted by attaching to that event without using AJAX event on the submit button of the form. See this answer: https://drupal.stackexchange.com/a/87600/57.
With an AJAX command, you can ensure that your command only executes if the form is validated without messing around with a lot of Javascript - though it depends on what you are doing. If you are showing a modal or some notification to the user about submitting the form, you may want to opt for the command so that you aren't running JS if the form did not really submit (i.e. not validated).
In your case, if you are using AJAX submission, then the submit event won't bubble up to the document. You can use ajax_command_invoke however to call a method. I recently had to do this on an AJAX'd form to push data to Google. Here is an example:
$commands[] = ajax_command_invoke(NULL, 'onFormSubmitSuccess');
return array('#type' => 'ajax', '#commands' => $commands);

Javascript file:
(function($) {
  $.fn.onFormSubmitSuccess = function(data) {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      'event' : 'formSubmitted',
    });
  };
})(jQuery);

https://api.drupal.org/api/drupal/includes!ajax.inc/function/ajax_command_invoke/7


Take screensot and save android

Question: I'm a very new android developer with a basic understanding of java. I've undertaken a large project and I've hit a problem I can seem to fix.
Basically my problem has three different parts:

I need to take a screenshot of my layout. I can't just use the built in screenshot function, it needs to be done on button press.
I then need to crop the picture so that the picture is only of an ImageView and the TextView that is on top of it. (Unless there is a simpler way to do this?)
Finally I need to save the cropped picture to some kind of memory, whether it is the sd card, the device's memory, or to gallery(not preferable).

Any help is much appreciated, thanks a lot
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rl"
    tools:context=".Preview" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:scaleType="centerCrop"
        android:src="@drawable/bottom_black" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="3dp"
        android:background="@android:color/transparent"
        android:onClick="bold"
        android:text="Edit" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:src="@drawable/block" />

    <ImageView
        android:id="@+id/imageView7"
        android:layout_width="80dp"
        android:layout_height="20dp"
        android:layout_alignParentTop="true"
        android:layout_alignTop="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="6dp"
        android:src="@drawable/logo_black" />

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/imageView2"
        android:layout_marginRight="10dp"
        android:src="@drawable/icon_fb_sel" />

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/imageView6"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/icon_twit_sel" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/imageView5"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/save" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignBottom="@+id/imageView2"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:src="@drawable/icon_trash" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="55dip"
        android:layout_height="44dip"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="14dp"
        android:layout_marginLeft="35dp"
        android:layout_marginRight="50dp"
        android:layout_toLeftOf="@+id/imageView7"
        android:onClick="sendMessage"
        android:src="@drawable/icon_album" />

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="55dip"
        android:layout_height="44dip"
        android:layout_alignTop="@+id/imageButton1"
        android:layout_marginLeft="-30dp"
        android:layout_toRightOf="@+id/imageButton1"
        android:maxHeight="44dp"
        android:maxWidth="55dp"
        android:src="@drawable/icon_new" />

    <ImageButton
        android:id="@+id/imageButton4"
        android:layout_width="55dp"
        android:layout_height="44dp"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/imageButton2"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="35dp"
        android:layout_toRightOf="@+id/imageView7"
        android:src="@drawable/icon_options" />

    <ImageButton
        android:id="@+id/imageButton3"
        android:layout_width="55dip"
        android:layout_height="44dip"
        android:layout_alignTop="@+id/imageButton2"
        android:layout_marginRight="-30dp"
        android:layout_toLeftOf="@+id/imageButton4"
        android:maxHeight="44dp"
        android:maxWidth="55dp"
        android:minHeight="44dp"
        android:minWidth="55dp"
        android:src="@drawable/icon_edit" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="297dp"
        android:layout_height="297dp"
        android:layout_alignBottom="@+id/imageView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="30dp"
        android:text="text"
        android:textSize="65dp" />

</RelativeLayout>

This is my xml code
Comment: it way too much commenting. i can't do that anymore. The name entered by the user is a string.
Comment: the name entered by the user is a string. I don't know what you are talking about. String name= input.getText().toString();
Comment: So is the name the variable "file" or "name"?
Comment: i am not sure why the image is not displaying it in gallery. It is stored in sdcard and when i open gallery may be it fetches all images from phone memory and sdcard. But i am sure it gets stored in sdcard. I used samsung galaxy s3 for testing
Comment: @Raghunandan any chance you could test your app on the emulator from eclipse and tell me if it works there?
Comment: i am busy answering a question. posted it here. i will test it on my device and let you know
Comment: post the code now i will give it a try
Comment: @Raghunandan i mean the code you posted in your answer. I essentially just copy pasted it. I just don't see the image in my gallery
Comment: i have tested it and it gets stored in sdcard and it does show in my gallery. you see the snap shot below. has gallery icon also
Comment: is that in the emulator though? I thought that was on an actual device?
Comment: i tested on device. you need to create a sd card on emulator and mount the same
Comment: How large should the sd cad be? what size is the average image?
Comment: i am not sure about it. if you still have doubts ask a new question.
Answer: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

My layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rl"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="70dp"
    android:text="Button" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="72dp"
    android:src="@drawable/afor" />

    </RelativeLayout>

My Activity class
public class MainActivity extends Activity {

RelativeLayout rl;
final int PIC_CROP = 1;
ImageView iv;
 File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl = (RelativeLayout) findViewById(R.id.rl);
     Button b= (Button) findViewById(R.id.button1);
     iv= (ImageView) findViewById(R.id.imageView1);
     b.setOnClickListener(new OnClickListener()
     {

      @Override
      public void onClick(View v) {
          save();
     }
     });
}

   public void save()
   {
       AlertDialog.Builder editalert = new AlertDialog.Builder(MainActivity.this);
       editalert.setTitle("Please Enter the name with which you want to Save");
       final EditText input = new EditText(MainActivity.this);
       LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
               LinearLayout.LayoutParams.FILL_PARENT,
               LinearLayout.LayoutParams.FILL_PARENT);
       input.setLayoutParams(lp);
       editalert.setView(input);
       editalert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int whichButton) {
               rl.setDrawingCacheEnabled(true);
               String name= input.getText().toString();
               Bitmap bitmap =rl.getDrawingCache();
               String root = Environment.getExternalStorageDirectory().toString();
               File myDir = new File(root + "/MyDraw");
               myDir.mkdirs();
               file = new File (myDir, name+".png");
               if (file.exists ()) file.delete ();
               try
               {
                   if(!file.exists())
               {
                   file.createNewFile();
               }
                   FileOutputStream ostream = new FileOutputStream(file);
                   bitmap.compress(CompressFormat.PNG, 10, ostream);
                   ostream.close();
                   Uri uri = Uri.fromFile(new File(file.getAbsolutePath()));
                   performCrop(uri);
               }
               catch (Exception e)
               {
                   e.printStackTrace();
               }
           }
       });
       editalert.show();
   }

   private void performCrop(Uri picUri) {
    try {

   Intent cropIntent = new Intent("com.android.camera.action.CROP");
   // indicate image type and Uri
   cropIntent.setDataAndType(picUri, "image/*");
   // set crop properties
   cropIntent.putExtra("crop", "true");
   // indicate aspect of desired crop
   cropIntent.putExtra("aspectX", 1);
   cropIntent.putExtra("aspectY", 1);
   // indicate output X and Y
   cropIntent.putExtra("outputX", 128);
   cropIntent.putExtra("outputY", 128);
   // retrieve data on return
   cropIntent.putExtra("return-data", true);
   // start the activity - we handle returning in onActivityResult
   startActivityForResult(cropIntent, PIC_CROP);
 }
 // respond to users whose devices do not support the crop action
 catch (ActivityNotFoundException anfe) {
  // display an error message
  String errorMessage = "Whoops - your device doesn't support the crop action!";
  Toast toast = Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT);
  toast.show();
  }
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);

 if (requestCode == PIC_CROP) {
  if (data != null) {
      // get the returned data
      Bundle extras = data.getExtras();
      // get the cropped bitmap
      Bitmap selectedBitmap = extras.getParcelable("data");
      FileOutputStream ostream;
    try {
        ostream = new FileOutputStream(file);
        selectedBitmap.compress(CompressFormat.PNG, 10, ostream);
         ostream.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

      iv.setImageBitmap(selectedBitmap);
  }
  }
  }

snap shots
My Layout snap shot

On button click prompting the user to enter a name to save

Image cropped and saved opened in gallery

Note: I have saved the cropped image in sdcard. The snap shots size varies.
This worked for me on my device. I have posted the same. If anyone has a better idea pls edit the above post.
Manifestfile
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cropimagefromsdcard"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.cropimagefromsdcard.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Comment: thank you very much for your answer, but I'm getting an error. "The field ViewGroup.LayoutParams.FILL_PARENT is deprecated" Is there a proper way to do this? Will this still work?
Comment: @James have you used the above code coz it works for me and i have posted the snapshot. check this for a similar link http://stackoverflow.com/questions/10976714/setcontentview-and-layout-android. The code above works. if not you are doing somethign wrong
Comment: One thing that might be causing my problem is my manifest. I'm not entirely sure where or ho to implement the code into my manifest to allow my app to write to external storage. Any chance you could show more of the manifest so I can see where in the manifest it goes?
Comment: @James this more than what i would normally post. check the edited answer above.
Comment: Thanks for the link btw. I've looked at it and I think I know where my problem is. I have a relative layout already created through xml. And I have a lot of stuff set up in it, and then I turn around and added a new layout through my .java file. Will your code work without adding that layout? and thanks for posting the manifest
Comment: i don't know what you are trying to do. yes it should work. set this rl.setDrawingCacheEnabled(true) enabled for your layout for which you wish to take screen shot. in the above its relative layout
Comment: My app crashes whenever I try to open that activity and my logcat is telling me my imageView cannot be cast to Button. In past when I've had this error the solution was to clean my project, but now it's not working. Any ideas?
Comment: Posted my xml. Feel free to ask if you need anything else
Comment: @James no problem in xml code. try clean and build or create a new xml and paste the code there. set the content to your activity.
Comment: What do yo mean by set the content to my activity?
Comment: just a try copy the contents to a different xml. say test.xml and set content as setContentView(R.layout.test);
Comment: Was the setContentView(R.layout.test); included in your code? I'm not sure where it's supposed to be and might that be the problem? and i'll try that
Comment: forget it. clean build your project.
Comment: i am not sure what more i can do to help you. i posted a working code with snap shot. that's the max i can do .
Comment: I'm an idiot, your code worked fine, but I actually tried to cast an imageView as a button. Sorry for all the trouble and thanks a lot
Comment: Yup will do, also I just tested and thankfully got no errors, but the image didn't show up in gallery? I'd assumed it would be shown in the gallery app, but it's not. Is it saved elsewhere?
Comment: in my case it was stored in sdcard and i opened the same in gallery
Comment: How do I open it in gallery in the emulator?
Comment: i am not sure about your device. i have a galaxy s3 and i browsed the image and used the gallery app to view the same.image stored under sdcard under MyDraw folder
Comment: Ok, well I currently only have access to an emulator, so that may be the problem. Thanks for your answer though it helped a lot.
Comment: @James you can also upvote my answer to show your appreciation by clicking the up arrow once
Comment: Is there a way to make it so that the name entered by the user could be bound to a string?
Comment: would you please tell me how to attach the name entered by the user to a string?
Comment: The picture, unlike yours, is not displaying in the gallery
Answer: Hey You Can just use the below Code to capture screen shoot in android and save it in ur SDCard and then you can use it later
// image naming and path  to include sd card  appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;

// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

OutputStream fout = null;
imageFile = new File(mPath);

try {
    fout = new FileOutputStream(imageFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
    fout.flush();
    fout.close();

} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Then, when you need to access use something like this:
Uri uri = Uri.fromFile(new File(mPath));

Comment: My app will end up saving multiple pictures and I need to be able to access each of them individually from another activity. Is there a way to change the name of the file for each picture that is saved?
Comment: You can save the image wit current `Time` and `Date`.Is the above code working in your scenario?
Comment: @James on button click prompt a pop for the user to enter a name and then save. Do want that as a solution? i can post the same for the save part.
Comment: @Raghunandan that would work I'm pretty sure, I'm just wondering if there was an easier way? Like naming the file after an int value that += 1 every time a file is saved?
Comment: @Ayush It's part of the answer I need so thank you for that, I still need the other two parts though
Comment: @James i am not aware of an alternative solution but if you need the solution of prompting a popup to allow the use to enter the name i can post the solution.
Comment: @James take  look at this link http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html
Comment: @James you can try my answer posted.

Take screensot and save android


statistical disclosure control: finding 2/3 anonymity violations (or, how to find items in one data frame that are missing in the other)

Question: I'm learning about data anonymization and would like to anonymize a dataset, in this case the adult dataset from https://archive.ics.uci.edu/ml/machine-learning-databases/adult, which I loaded using
library(sdcMicro)
data <- read.table("/home/thijser/Downloads/adult.data",sep=",")
sdc <- createSdcObj(ndata, keyVars = c('V4','V9','V10'),sensibleVar= c('V7','V1'))

I know that I can also get back the data by using
 mdat<-extractManipData(sdc, ignoreKeyVars = FALSE,
  ignoreParamVars = FALSE, ignoreNumVars = FALSE,
  ignoreGhostVars = FALSE, ignoreStrataVar = FALSE)

and "2-anonymity" means that no record can uniquely be identified by the values in column 4,9 and 10 while "3-anonymity" means that at least 3 records share all permutations of column 4,9 and 10 that exist in the database.
Now this already gives me only 7 2-anonymity violations and I would like to know what they are… Is there any method to get the sdc to tell me which records are in violation?
As an alternative I can also use
sde <- localSupression(sdc,2)
mdat2 <- extractManipData(sdc, ignoreKeyVars = FALSE,
   ignorePramVars = FALSE, ignoreNumVars = FALSE,
   ignoreGhostVars = FALSE, ignoreStrataVar = FALSE)

in order to generate a list in mdat2 that is missing the records in mdat, but that requires me to find all records that are in one list but not in the other.
Answer: Try the command below. It should display the key variables that violate 3-anonymity:
data[sdc@risk$individual[,2]<3,selectedKeyVars]   #displays key variables that violate 3-anonymity


A trivial inequality in complex analysis

Question:
Let, $C(T)$ be the semi-circle centered at $c(>0)\in \Bbb R$ and radius $T$ lying to the left of the vertical segment. If $z=x+iy\in C(T)$ then for all large $T$ we have, $\displaystyle |z(z+1)|\ge \frac{T^2}{2}$.

My book says this. I think it is trivial one, but I'm unable to prove this. I've tried by putting $z=x+iy$ and also $z=c+Te^{i\theta}$. But I'm not getting the result. Any help?
Answer: $|z| \geq T-c$ so $|z(z+1)| \geq (T-c)(T-c-1) >(T-c-1)^{2}>\frac {T^{2}} 2$ for $T$ sufficiently large. In fact this is true for $T > \frac {1+c} {1-\frac 1 {\sqrt 2}}$
Comment: How you get the last inequality ?
Comment: Upto $|z| \geq T-c$ so $|z(z+1)| \geq (T-c)(T-c-1)$ I've already got in my work..But I'm not getting the last one.
Comment: @Topo What you need is $T-c-1> \frac T {\sqrt 2}$. Just transfer the right side to the left side and $c+1$ to the right side.


Find a meromorphic function with given principal parts

Question: I have the homework problem of finding an "elementary" meromorphic function $f(z)$ with the same principal parts as the sum $$\frac{1}{\pi z^2} + \frac{2}{\pi} \sum_{n=1}^\infty (-1)^n \frac{\cos n}{z^2 - n^2}$$ (and, for extra credit, computing the sum itself).  I don't know how to proceed; I've been blindly trying several likely-seeming trigonometric functions, but with no success.  I've tried to manipulate various cotangent identities, such as $$\pi \cot (\pi z) = \frac{1}{z} + \sum_{n=1}^\infty \frac{2z}{z^2 - n^2},$$ into the desired form, but didn't really get anywhere with it, because I'm not sure how to handle the alternating sum.
EDIT: Response to Robert Israel's comment.  My first thought is to rewrite the given sum as $$\frac{1}{\pi z^2} + \frac{2}{\pi} \sum_{n=1}^\infty (-1)^n \frac{\cos n}{z^2 - n^2} = \frac{1}{\pi} \sum_{n = -\infty}^\infty  \frac{(-1)^n \cos n}{z} \frac{1}{z-n}.$$  Then, if we try to evaluate, for $n \in \mathbb{N}$, $$\lim_{z \to n} \sin (\pi z) \sum_{k=-\infty}^\infty \frac{ (-1)^k \cos k}{\pi z(z-k)},$$
then all the terms in the sum except for $k=n$, being finite, vanish at the limit when multiplied by $\sin (\pi z)$, leaving $$\lim_{z \to n} \frac{(-1)^n \cos n \sin (\pi z)}{\pi z(z-n)} = \lim_{z \to n} \frac{(-1)^n \cos n \cos (\pi z)}{2z - n} = \frac{ (-1)^n \cos n \cos (\pi n)}{n} = \frac{\cos n}{n},$$ implying that the sum's principal parts should agree with those of $z \mapsto \cos z/z \sin z$; is this reasoning correct?  Graphing $\sin (\pi z)$ times the fifteenth partial sum of the original sum (with domain restricted to the reals) shows a function that looks plausibly close to $z \mapsto \cos z/z$.  Also, is there a similar way one could prove the equality of the sum and $\cos z/z \sin (\pi z)$?
Answer: Hint: If it was $f(z) = g(z)/\sin(\pi z)$, what would $g(n)$ be?
Comment: I think I understand what you're hinting at.  See my edit to the original question.


IdHttp : how to deal with json request and response

Question: I have encountered a few sites that uses JSON for request and response
I come across two types :
1- application/x-www-form-urlencoded as request and return a response application/json content type
2- application/json content type for both request and response
in type 1 i tried changing the the response content type using
mIdHttp.Response.ContentType := 'application/json';
but using http analyzer i can see that it doesn't change and its still text/html
now i do not know if the problem is with the fact that i can't change content type or not but i do not know how to deal with json !
a few question regarding json :
1- do i have to encode json data when posting ? how ?
2- how can i parse the json response code ? how to get it ? does it need some kind of encode or special convertion ?
3- what kind of idhttp setting for json changes with each site and needs configuring ?
I understand my questions sound a bit general, but all the other questions are very specific and don't explain the basics when dealing with 'application/json' content type.
Edit 1 :
thanks to Remy Lebeau  answer i was able to successfully work with type 1
but i still have trouble sending JSON request, can someone please share an working example, this is one of the sites posting information please use this for your example :

One important note :  this particular site's post and request content are exactly like each other ! and it baffles me because at the site, i specify an start date and an end date then click on a folder like icon and this post is sent (the one you can see above), and the result should be links (and it is) but instead of appearing only in request content they also appear in post !  (also i'm trying to get the links but at the post the links, the thing i want, are also being sent, how can i post something i don't have !!?)
just for more clarity here is the place i fill the date and the icon i mentioned :
Comment: There is no universal solution. Each implementation can be different. You can control if you want Indy to encode parameters using `hoForceEncodeParams` in `FHTTP.HTTPOptions` (if you send JSON data in your request, many sites don't allow encoded request). You should NOT set `Response.ContentType`. That is what server returns. You have to set `Request.ContentType` (what you send) and `Request.Accept` (what you expect from server)
Comment: @smooty86 the `hoForceEncodeParams` flag only applies when posting a `TStrings` in `application/x-www-form-urlencoded` format. It does not apply in this situation, as you cannot post JSON using a `TStrings`, you have to use a `TStream` instead.
Comment: @RemyLebeau you bet I can send JSON in TStrings :) Though I understand it can be less effective.
Comment: You send JSON like any other Post request. Provide your code how you send it. How exactly looks the "Raw stream" with post? It is not not clear in the parsed mode.
Comment: @smooty86 if you post a `TStrings` with `TIdHTTP`, it is expected to be a list of "name=value" pairs, and will be encoded accordingly. I have yet to encounter a website that accepts something like "fieldname=json" as input. Not that it can't, but it is extremely rare. Same goes with XML, too.
Comment: @RemyLebeau If hoForceEncodeParams is off and JSON is one line TStrings, then it will work correctly. No encoding involved.
Comment: @smooty86: It might "work", but that is not how `TIdHTTP` is intended to be used. Why would you use a `TStrings` to send a complete JSON document as a single string? I would suggest using `TStringStream` for that, if not `TMemoryStream` or even `TIdMemoryBufferStream`.
Answer: You cannot specify the format of the response, unless the requested resource offers an explicit input parameter or dedicated URL for that exact purpose (ie, to request a response be sent as html, xml, json, etc).  Setting the TIdHTTP.Response.ContentType property is useless. It will be overwritten by the actual Content-Type header of the response.
To send JSON in a request, you must post it as a TStream, like TMemoryStream or TStringStream, and set the TIdHTTP.Request.ContentType as needed, eg:
var
  ReqJson: TStringStream;
begin
  ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
  try
    IdHTTP1.Request.ContentType := 'application/json';
    IdHTTP1.Post(URL, ReqJson);
  finally
    ReqJson.Free;
  end;
end;

To receive JSON, TIdHTTP can either

return it as a String (decoded using a server-reported charset):
var
  ReqJson: TStringStream;
  RespJson: String;
begin
  ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
  try
    IdHTTP1.Request.ContentType := 'application/json';
    RespJson := IdHTTP1.Post(URL, ReqJson);
  finally
    ReqJson.Free;
  end;
  // use RespJson as needed...
end;

write the raw bytes to an output TStream of your choosing:
var
  ReqJson: TStringStream;
  RespJson: TMemoryStream;
begin
  RespJson := TMemoryStream.Create;
  try
    ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
    try
      IdHTTP1.Request.ContentType := 'application/json';
      RespJson := IdHTTP1.Post(URL, ReqJson, RespJson);
    finally
      ReqJson.Free;
    end;
    RespJson.Position := 0;
    // use RespJson as needed...
  finally
    RespJson.Free;
  end;
end;

The HTTP response code is available in the TIdHTTP.Response.ResponseCode (and TIdHTTP.ResponseCode) property.
Comment: @AliAhmadi: I have added examples to my answer.  But how do you expect to send the JSON if you don't know how to produce it in the first place? See [Embarcadero's JSON documentation](http://docwiki.embarcadero.com/RADStudio/en/Json).
Comment: what you said helped me with the `first type`, but i still have problem with `second type`, i edited my question can you please read it and answer me accordingly, Thank you very much!
Comment: @AliAhmadi what exactly are you having trouble with? Your edit does not make it any clearer. What is so hard about putting the JSON content as-is into a `TStream` descendant and then posting it? Do you know how to produce JSON in the first place?
Comment: what do you mean by `produce JSON`, maybe that is my problem ? (as i said, i do not know the basics about `JSON`, a simple example would be more than enough, thx)


Comparison for the value with the value inside the arraylist

Question: I want to compare the file path where captured by the FileVisitResult visitFile in my arraylist. The reason for this comparison is preventing there's duplicate file path store in the arraylist since FileVisitResult visitFile will keep on looping while the condition is true. I want to make sure all the file had just visited by the method once. So each time the FileVisitResult method will capture the file path and store into arraylist, when the next round for the method execution, any new file path detected will compare to the file path in the arraylist, but it's still fail to do it after I search some information online,the Thread.sleep() use to halt the program for my understanding the flow of my source code
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{

    String f;
    File file1;
    Path tempPath1,tempPath2;
    if(counter == 0)   //first round for the execution
    {
        counter++;
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("The abs path of the file is"+file);
        y2j.add(file);  //add path to arraylist

         f = file.toString();
         file1 = new File(f);
        if ( file1.exists())  //checking the file process whether still consume by any other process
        {
            RandomAccessFile statusCheck = null;
                try
                {
                    statusCheck = new RandomAccessFile(file1,"r");
                    if(statusCheck != null)
                    {

                        System.out.println("Not hodling by any process,clear to send for scanning");
                        statusCheck.close();
                        ambrose();  //do something in this method
                    }
                }
                catch(Exception e)
                {
                    System.out.println("In processing : " + e.getMessage());

                }
         }
    }
    else if(counter > 0)  //after first round of execution
    {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("larger than 0");
        System.out.println("The abs path of the file is"+file);
        for(int i = 0 ; i<y2j.size()-1;i--)
        {
            System.out.println("In the for loop" +y2j);
            for(int k = i+1 ; k<y2j.size();k++)
            {
                if(file == y2j.get(k))
                {
                    System.out.println("they are same");
                }
                else if(file != y2j.get(k))
                {
                    y2j.add(file);  //add path to arraylist
                        ambrose();  //do something in this method

                }
            }
        }

    }
    return FileVisitResult.CONTINUE;
}

The abs path of the file isC:\REST API\source\abc\abc.xlsx
Not hodling by any process,clear to send for scanning
Dirty deed here
larger than 0
The abs path of the file isC:\REST API\source\abc\def.txt
larger than 0
The abs path of the file isC:\REST API\source\abc\abc.xlsx
larger than 0
The abs path of the file isC:\REST API\source\abc\def.txt

It's seen like not entering the for loop, I have spent some time on it but can't figure where is my problem.
Comment: I don't know what you're trying to do, but `for(int i = 0 ; i<y2j.size()-1;i--)` is an infinite loop. Also, your question is very unclear.
Comment: Also, see [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)
Comment: hmm. next time I should explain it more further for what I plan to do with the distinct file path
Answer: Instead of file == y2j.get(i) use equals method. Also instead of going through whole list you can use method contains that will return true if list contains element.
== in java compares if this is exacly the same object by comparing reference, but it will not distinguish between objects that look the same but are not same, ex: new String("n") == new String("n") will return false.
Answer: If you want distinct set of file paths, then you can use Set instead of List. If you use Set then you don't have to run an extra loop for removing duplicates.
Comment: Hi Nishesh, thanks for your comment, I found out the way to solve it but another issues pop up, try to solve it now


Creating a view of relation fields limited to the relations that a currently viewed node is an endpoint of

Question: To first explain the set up, I have a custom content type that represents a candidate. I have a relation between candidate and users where the relation has some fields (using the relation module). I want to have a view that displays the fields of relation on the candidate page that has that relation.
So far I have tried Entity Views Attachment but the issue with that is it adds the relation view I have set up to every instance of candidate. I've also been trying view reference but that doesn't seem to be the module I'm after either.
I think I need to add something like an extra filter or something to the EVA view that only will show relations that involve the current candidate node, but I'm not sure if that is possible or not.
Answer: Instead of creating a view of relations, you should create a view of candidate nodes. Then you can use a contextual filter to limit the results of the view to the candidate node you are currently viewing. The fields of the relation can then be added via a relationship.
Create a view of content of type candidate, for example located at node/%/info; then under the Advanced settings of the view add a contextual filter with Provide a default value: Content ID from URL (i.e. the candidate node id) as the argument. You can use the same setting when the argument is provided by EVA instead of via the URL, with the default configuration of Use the ID of the entity the view is attached to (but the first example is useful to understand where the argument comes from).
Now in order to get the relevant Relation fields displayed, under Advanced add a relationship using Content: Relation: <your relation label> (node → relation).
Under Fields you can now add the desired Relation fields, specifying that it should use the relationship you just added.
Note the difference between relationship (≈ SQL table join) and relation.


What does the covariance matrix of a Gaussian Process look like?

Question: Let's assume $\{X_t\}_{t \geq0} $ is a Gaussian Process with a certain covariance matrix. In order for this process to be stationary the mean vector should not depend on $t$ and the covariance function should not depend on $t$. However, what additional restrictions should the covariance have?
In order for the process to be stationary, the variance of each realization should be the same. So,that means that the diago$nal elements of the covariance matrix should all be equal to the commn variance. Am I wrong? In general what does the covariance matrix of a stationary Gaussian process look like?
Answer: Here is a somewhat informal explanation:
The covariance matrix for a Gaussian process is a gram matrix obtained by evaluating some kernel function $k(x, x')$ pairwise between a set of observations.
Stationary in the context of a Gaussian process implies that the covariance between two points, say $x$ and $x'$, would be identical to the covariance between the same two points perturbed by some $\Delta$, i.e:
$k(x, x') = k(x+\Delta, x' + \Delta)$
This implies that the hyper-parameters of $k$ (if they exist) do not vary across the index (here $x$). As an example, the popular exponetiated quadratic (also called the squared exponential, or "RBF") kernel is stationary:
$k(x,x') = \alpha^2 e^{ \frac{- (x - x')^2}{2 l^2} } + \delta_{ij} \sigma_0^2$
($\delta_{ij}$ being the kronecker delta)
Because the hyperparameters ($\alpha, l, \sigma_0$) have no dependency on the index, $x$.
If, for example, the lengthscale $l$ would be permitted to vary over $x$, the covariance between any two points $k(x,x')$ would not necessarily be the same as $k(x + \Delta,x'+ \Delta)$.
If the covariance kernel is stationary, one can see that for the diagonal elements of the covariance matrix we will be evaluating $k(x,x)$. Since the pairwise distance between $x$ and itself is zero, in the case of the kernel above, the covariance collapses to:
$k(x,x) = \alpha^2 +  \sigma_0^2$
Implying all diagonal elements of the unconditional covariance matrix will be identical, as neither $\alpha$ nor $\sigma_0$ depend on $x$.
Answer: The variance covariance matrix of a stationary Gaussian process should have the same value for all its diagonal elements. Its auto-covariance should also be the same through time. In other words, the off-diagonal lines that are parallel to the diagonal should have the same values in each line. And obviously, the matrix needs to be positive semi-definite.