Is there a limit to the SPSS random number generator?

Question: Will the random number generator in SPSS be serviceable if I need  250,000 random numbers, or will the randomness start to degenerate?
Asked another way, what practical limits are there to using the random number generator in SPSS to generate large numbers of random numbers?
Answer: I think SPSS, like most modern software, uses the Mersenne Twister. Its period is $2^{19937} − 1$ so you're pretty safe from this point of view.
Up to 623 successive outcomes are uncorrelated, so you can safely consider a few consecutive outcomes as independent (this would not be the case with a classical Linear congruential generator).
To summarize: modern random number generators are performant enough for all ordinary applications in statistics... don't worry.
Comment: I do not think advising to build one's own generator is a sensible piece of advice. Existing generators have been tested and cross-tested, stick to them!
Comment: @Xi'an Marsaglia's MWC is a very good RNG, it has been extensively tested (Marsaglia is the creator of the so called ["Diehard tests"](http://en.wikipedia.org/wiki/Diehard_tests) for RNG).  It is not difficult to construct high dimensional variants of MWC.

However, I think that you are right on one point: if you do so, you should ensure your generator pass the Diehard tests.
Comment: Thank you for your answer.  Let me ask a follow-on question.

You say:

What size correlation might be seen in numbers past 623?
Comment: To be more precise: if you use the full 32 bits numbers it generates, the vectors of length 624 are not equidistributed. So if you use Monte Carlo method to compute $\int_{x \in [0,1]^{624}} f(x) \mathrm d x$ you shouldn't use Mersenne Twister – at least in theory, in practice for reasonnably shaped $f$ this should be ok, and I don't think this is the main issue you would run into.

If you use only the most significants bits (let's say the 16 upper bits), I think you can go further but I don't this precisely.
Comment: Moreover, if you know 624 successive outputs, you can retrieve the internal state of the generator and predict alol its behaviour, but this is not a true issue for Monte Carlo applications.

Finally, if you need uncorrelated vectors in very high dimensions, you may create your own generator in the family of Marsaglia's [Multiplicative With Carry generators](http://en.wikipedia.org/wiki/Multiply-with-carry), which are easy to deal with.
Answer: SPSS Statistics provides both the Mersenne Twister and, for compatibility, an older shift-congruential generator.  By default, the older generator is used.  Use SET RNG=MT or the Transform>Random Number Generators menu item to change this.  The MT should give you all the numbers you need.
There is also a user-contributed Python function that fetches truly random, not pseudo random numbers generated from atmospheric noise.  These are fetched from a website that has some rules about quantities that you should read.  The package is tr_rnd0.1.zip.  It can be downloaded from the SPSS Community website in the Python Modules collection.  Of course, this requires you to use Python programmability.  The tools for that can also be downloaded from the Community site.
Answer: I used the SPSS uniform function to create a random sample weekly for two years. Do not do this. They DO NOT generate random samples. The same dataset will generate the same random sample upon re-opening SPSS. Not all cases have the same probability to be selected (depends on sorting of your file).
My recommendation would be to use several methods of randomization sequentially. E.g. first randomize sorting, then use the select random sample function.
Comment: `The same dataset will generate the same random sample upon re-opening SPSS`. Sure. Because at the start of the session, random seed is one the same. You should first command to set it random before doing random generations of data.
Comment: Correct. Also note that similar datasets will generate similar random queries if you don't set the seed to random.


Views Filter 2 Content types but with condition on one of them

Question: I looked up this one before posting: Views filter criteria multiple content types (Drupal 7)
And even though the problem is the same, the solutions provided do not seem to work.
I have Content Types A and B. B has a boolean field.
I need to filter and display all As and Bs if boolean is true.
My filter setup looks like this:
Content : Published AND
Content Type : A
OR
Content : Published AND
Content Type : B AND
Boolean Field : True
The Query that gets produced is the following:
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM `node`
INNER JOIN `field_data_field_boolean` ON node.nid = field_data_field_boolean.entity_id
  AND (field_data_field_boolean.entity_type = 'node'
  AND field_data_field_boolean.deleted = '0')
WHERE (( (node.status = '1')
  AND (node.type IN  ('poll')) )OR( (node.status = '1') AND (node.type IN  ('webform'))
  AND (field_data_field_boolean.field_boolean_value = '1') ))
ORDER BY node_created DESC

The problem is that Inner Join that gets produced instead of a Left Join for instance.
Which setup would allow me to perform the required filtering?
EDIT: Seems it's a know bug. Related links:
http://drupal.org/node/1766338
Changing an inner join to a left join in views 3.3?
Comment: I think this is a bug reported at http://drupal.org/node/1766338
Comment: Is there any link between Content Type A & B? In other words, does A refer to B in any way?
Comment: nope, none at all.
Comment: Answering this as a bug/can't be done. For more information visit http://drupal.org/node/1766338
Answer: Although this post is quite old, it appears it's still an issue going up to Views 7.x-3.7. Referring to the post already mentioned here and specifically comment 36 on that page, I found my working solution.
I had two content types that I wanted to show the title from: an Event and a Blog, however I only wanted the blog posts which had a Boolean field returning as true.  Below is a screenshot of what my grouping filters look like but the trick is, on the Boolean filter, make sure you select the 'Reduce duplicates' check-box. Once I did that, I got the results I was expecting.
Hope that helps.
Comment: Thanks! That's what I was missing. Checking the `Reduce duplicates` on each field, changed the query from `INNER JOIN` to `LEFT JOIN` which made all the content appear
Comment: My god! I've been using Drupal for 8 years or longer and never have I known about this feature until now!
Answer: I often struggle with views doing what I want. My solution is to override the automatically generated query with my own.
Below I give you an example of a list of members of the currently viewed group with the specific group role:
function mymodule_views_pre_execute(&$view) {
    if($view->name=="og_members") {
        $nid = arg(1);
        $gid = mymodule_get_gid_from_nid($nid);
        $query = db_select('users');
        $query->join('og_users_roles', 'roles', 'users.uid = roles.uid');
        $query->addfield('users','name','users_name');
        $query->addfield('users','uid','uid');
        $query->condition('roles.rid', VISITOR_ROLE_ID,'!=');
        $query->condition('roles.gid', $gid,'=');
        $view->build_info['query'] = $query;
    }
}

A thing to not here is that returned field should match the fields that the view will expect.
Comment: that kinda defeats the whole purpose though, doesn't it? :)
Comment: You still get the very powerful engine for displaying the results. Access control and other goodies that views give you.
Using gui you will never be able to click-out the more complicated queries.


Windows Server 2008 Task Scheduler

Question: I have a task that waits for a user to enter any key to die. I have that task scheduled twice a day. However if the window is still up it will not run the task again. Is there any way around this?
Answer: Edit the scheduled task.  Go to the settings tab.  Check the drop down menu at the bottom which says "If the task is already running, then the following rule applies" to "Run a new instance in parallel".
I'm looking at Windows 7 at the moment, but the task scheduler is pretty similar.

Windows Server 2008 Task Scheduler


Morphisms between locally ringed spaces and affine schemes

Question: I need some hints to understand the conclusion of the proof of the following lemma from the Stacks Project:

Lemma $\mathbf{6.1.}\,$ Let $X$ be a locally ringed space. Let $Y$ be an affine scheme. Let $f\in\operatorname{Mor}(X,Y)$ be a morphism of locally ringed spaces. Given a point $x\in X$ consider the ring maps $$\Gamma(Y,\mathcal O_Y)\xrightarrow{f^{\#}}\Gamma(X,\mathcal O_X)\to\mathcal O_{X,x}$$ Let $\mathfrak p\subset\Gamma(Y,\mathcal O_Y)$ denote the inverse image of $\mathfrak m_x$. Let $y\in Y$ be the corresponding point. Then $f(x)=y$.
Proof. Consider the commutative diagram
$$\require{AMScd}\begin{CD}\Gamma(X,\mathcal O_X) @>>> \mathcal O_{X,x}\\ @AAA @AAA \\ \Gamma(Y,\mathcal O_Y) @>>> \mathcal O_{Y,f(x)}\end{CD}$$ (see the discussion of $f$-maps below Sheaves, Definition $21.7$). Since the right vertical arrow is local we see that $\mathbf m_{f(x)}$ is the inverse image of $\mathbf m_x$. The result follows.$\qquad\qquad\qquad\qquad\quad\square$

I don't understand  the last sentence, i.e.  "The result follows". If $m_{f(x)}$ (the maximal ideal of $\mathcal O_{Y,f(x)}$) is the inverse image of $m_x$, why should be $f(x)=y$?
Thanks in advice.
Answer: $Y$ is an affine scheme, so $f(x)$ is a prime ideal of $\mathscr{O}_Y(Y)$ and $\mathscr{O}_{Y,f(x)}$ is the localization of $\mathscr{O}_Y(Y)$ at $f(x)$. A basic fact about localization is that the inverse image in $\mathscr{O}_Y(Y)$ of the unique maximal ideal $\mathfrak{m}_{f(x)}$ of $\mathscr{O}_{Y,f(x)}$ is $f(x)$. Now it follows from the commutativity of the diagram, together with the fact you mentioned, which amounts to the map on stalks being local, that $f(x)$ is the inverse image in $\mathscr{O}_Y(Y)$ of $\mathfrak{m}_x$ under the map $\mathscr{O}_Y(Y)\rightarrow\mathscr{O}_X(X)\rightarrow\mathscr{O}_{X,x}$.


How do I get the blog teaser view display on a content type?

Question: I know. I write English language really bad, horrible. I apologize.
I created a blog (with the core's blog module. Also I have a content type called my-content-type :). I need the blog teaser view is displayed in my my-content-type.
I installed Display Suite. So, my-content-type has the Display settings option. With this option I can choose the desired view, in my case the teaser view. OK, very good! Now, but how do I get the blog teaser view is displayed in my-content-type?
Can I do this without Views?
Greetings!
Comment: Views is primarily for making **lists** of nodes.  What are you trying to achieve here?
Comment: Please do not cross post http://stackoverflow.com/q/32752510/1312737
Answer: Short answer:
Yes, you could do it without views. But, it wouldn't be ideal.
Long answer:
Display suite module will let you control the display of the particular content type and its fields. It won't allow you to control the display of a different content type from the other.
E.g. For your my-content-type, it will allow you to change the display settings of the fields of this content type.
If you wish to display teasers of nodes of the blog content type, on the node pages of my-content-type, you will have to do the follow the steps below:
Without views:

Create a custom module.
Load the blog $node using node_load on my-content-type node page.
Using node_view on the $node get the node in the teaser view of the node.
Use drupal_render to render the loaded teasers in a custom block created using hook_block_info.
Place this block in an region only on the my-content-type node page.

With views:

Create a view block of content of type blog.
Select the display method to be content, and select teaser from the settings.
Apply additional settings (filters, relations) as required.
Place this block on the node page of my-content-type.

In other words you let views build your query for you. And you also get an additional advantage of using other features provided by the views module like caching, etc.
Comment: Yes! With Views everything is easy. However, I think it's strange that Drupal has no way to process the teaser views. Drupal forces me to install a contributed module to achieve teaser views.


Criar link para download de uma gravação de áudio

Question: Peguei um exemplo na net em JavaScript que captura o áudio do dispositivo e com um botão na página é possível gravar o áudio e exportar o mesmo:
Neste código segue temos os botões:
<button onclick="startRecording(this);">record</button>
<button onclick="stopRecording(this);" disabled>stop</button>

A partir deles vai comando para startRecording para iniciar a gravação
function startRecording(button) {
    recorder && recorder.record();
    button.disabled = true;
    button.nextElementSibling.disabled = false;
    __log('Recording...');
}

e stopRecording para parar a gravação
function stopRecording(button) {
    recorder && recorder.stop();
    button.disabled = true;
    button.previousElementSibling.disabled = false;
    __log('Stopped recording.');

    // create WAV download link using audio data blob
    createDownloadLink();
    //recorder.clear();
  }

Nesta function tem uma chamada para a função createDownloadLink() que até onde entendi deveria criar um link para download do áudio gravado anteriormente
e ai esta o problema, o link não esta criando.
function createDownloadLink() {
  recorder && recorder.exportWAV(function (blob) {
      var url = URL.createObjectURL(blob);
      var li = document.createElement('li');
      var au = document.createElement('audio');
      var hf = document.createElement('a');

      au.controls = true;
      au.src = url;
      hf.href = url;
      hf.download = new Date().toISOString() + '.wav';
      hf.innerHTML = hf.download;
      li.appendChild(au);
      li.appendChild(hf);
      recordingslist.appendChild(li);
  });
}

Como habilitar o link para fazer o download do áudio quando clicar em Stop?
Comment: você já tem o base64 do arquivo gerado?
Comment: não tenho, como seria e pra que serve?
Comment: Qual o valor da var url? Você já tem ela? Se tiver basta criar uma tag a para realizar o download.
Comment: Debuguei agora e quando chega no 'stopRecording / createDownloadLink();'  nem entra na 'function createDownloadLink()'.    porém coloquei o mouse em cima do URL.cre... e aparece o caminho "http://localhost:59564/example_simple_exportwav.html" e o resultado deste link da erro: Causas mais prováveis:
* O diretório ou arquivo especificado não existe no servidor Web.
* A URL contém um erro tipográfico.
* Um filtro ou módulo personalizado, como URL Scan, restringe o acesso ao arquivo.
Answer: Este repositório realmente está faltando alguns arquivos, e não ficaria viável colocar ele aqui.
O repositório completo você pode encontrar neste github.
E o tutorial completo de como utilizar, você verá aqui.
Fonte: NusoftHq / Audioec.

Utilizando o Chrome 46 não funcionou em meu computador. Porém no firefox 42 funciona normalmente.
Comment: perfeito, muito obrigado pela ajuda.


Build OpenCV 4.x with Anaconda bindings (Linux)

Question: I've been trying to stay with Anaconda for all projects (neural net development, etc), so I have the Anaconda folder in the front of the path.  Problems arise when trying to build OpenCV 4.1.2 (master).  First few error messages listed at bottom.
I'd also like to make sure that OpenCV's Python bindings are built for Anaconda.  This also seems to be problematic, though I haven't had much chance to pursue it yet.
Is there an elegant workaround, or do I need to abandon attempts to use Anaconda for OpenCV?
Error messages indicate that OpenCV/Cmake has trouble with folders that are 'shadowed' by Anaconda:

CMake Warning at cmake/OpenCVUtils.cmake:1471 (add_executable):
  Cannot generate a safe runtime search path for target opencv_test_videoio
  because files in some directories may conflict with libraries in implicit
  directories:
<code>runtime library [libgstbase-1.0.so.0] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
  /opt/Anaconda/3.7/lib
runtime library [libgstreamer-1.0.so.0] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
  /opt/Anaconda/3.7/lib
runtime library [libgobject-2.0.so.0] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
  /opt/Anaconda/3.7/lib
</code>
etc....
Comment: try to work on virtue, or install by Anaconda navigator
Answer: Development with conda packages (and especially with compiled libraries with many dependencies like opencv) is pretty hard.  To be specific, I mean changing code in opencv and rebuilding it - hacking on opencv.
If you only need to create packages of some specific version of opencv, to then use in conda environments, you can use conda-build to build packages.  There is a good recipe for opencv at https://github.com/conda-forge/opencv-feedstock


Error handling in loop in R

Question: I am new to programming in R, I am running a loop in R and try to output the result into a dataframe. But I encounter some error I am not able to solve it myself, it would be great if someone can have a look and give me some hints as to how to solve the problem. The process runs until it encounters a "Error" output from one of the loop.
Basically the loop stops producing output to the dataframe and it stops at the point where the loop encounters the error of:
Error in start:end : NA/NaN argument
This is my loop script:
<code>for (i in seq(2,880)){
rscheck<-as.data.frame(cbind(as.matrix(chr1only[,i]), chr1only$SIF1))
rscheck$V2<-as.numeric(as.character(rscheck$V2))
rscheck<-na.omit(rscheck)
pvaluelevenetest2[i-1,1]<-lawstat::levene.test(rscheck$V2,    rscheck$V1,correction.method="zero.correction", location="median")$p.value
}
</code>
I have the pvaluelenetest2 dataframe contains loop 1 to loop 856 result. But afterward, there is no more result. The dimension of the pvaluelenvenetest2 data is only 1 by 856 (so nothing was returned to the pvaluelentest2 dataframe after the very last non-error test).
I then test the 858th column without using loop and indeed the levene's test produces NA values and gives me this error:
Error in start:end : NA/NaN argument
So I am just wondering is there anyway the loop can continues when it encounters such an error?
thank you
Answer: So your loop is stopping because the levene function is throwing an error. You could write a tryCatch block in R to handle the error:
How to write trycatch in R
But wouldn't it be better to to find out why the function is crashing and fix the inputs, or filter out bad inputs to begin with?
For example, add code to check if rscheck$V2 or rscheck$V1 is NA before calling levene. Is it possible that rscheck$V2 contains some characters which can't be converted to numbers, causing the introduction of the NA?

Error handling in loop in R


Where are these audio clicks coming from Ableton Live 11 Suite?

Question: Audio clicks and pops in Ableton are nothing new to me.  Needing to fade audio clicks at the beginning (and sometimes ending) of clips is part of my workflow if I don't want to re-record an instrument, (and sometimes it's just unavoidable regardless).
That being said, one of my guitar tracks on a particular song is laden with them.  Practically half of the chords I played had clicks when I listened back.  I was using an American-made Fender Stratocaster.
I was going to let it go, since I can either just grit my teeth and repair all of the clips or re-record (though I am hoping this issue didn't arise from the recording process, since I put a lot of time and effort into the performance).  However, if you listen to the audio sample in the SoundCloud link below, you will hear the closing chord of the song, interspersed with audio clicks that are curiously timed with the kick drum.  I feel like this might be a clue . . . though I am not sure.
I played with the sample rate in audio preferences, as too high (or was it low . . . ) of a sample rate has led to buffering issues (and lots of similarly painful clicking) in the past, but this didn't help any.  I also toggled the other instruments on and off--the clicks were still there.
The fact that the same click happens across two instruments (guitar and bass)--see screenshot of session below--leads me to believe this is not related to my recording of the instruments or my subsequent splitting/consolidating or other manipulating of the tracks (the clicks occur in the middle of the sound wave--not at the beginning or ending of the clip regions).  That would be a crazy coincidence.
Would you happen to have any suggestions for me?
Here are some very basic details of my setup:
MacBook Pro (Big Sur 11.6)
Ableton Live 11 Suite
Focusrite Scarlett Solo 2nd Gen

https://soundcloud.com/21-21-21/clicking-issue/s-X6aTU960itX?si=f7d33f21590b4f6887cbcefe4da1125b
Comment: I'm not hearing any clicks. Have you tested the resulting exported track?
Comment: Do you have the metronome turned on?
Comment: @Duston good thinking, but I do not
Comment: @Tetsujin the audio sample I uploaded to Soundcloud is the exported Ableton file.  The clicks accompany the first and second (not third apparently) kick drums hits.  It might help to turn up the volume/listen in headphones
Comment: I've had it in the main monitors & in the cans. I don't hear a click, all I hear is a bit of a crunchy kick drum. The file isn't set to be downloadable so I can't see if Izotope RX can 'see' it.
Answer: The processing needs of the set exceed my system's resources.  Live's overload indicator (to the right of the CPU meter) is engaged during playback, displaying the text 'CPU'.
So, I am experiencing irregular crackles, pops, and silences when playing back my set. These interferences are called 'audio dropouts'.
Comment: That's why I said to check the export. Non-realtime export on any DAW will eliminate those processing overs because it can take its own sweet time generating the file.
Comment: Have you listened to the exported version yet? General rule, for tracking switch off unnecessary plugins & lower latency [buffer size]. For mixing, raise the latency as far as it will go.
Comment: So you're suggesting that the audio file itself isn't damaged—the audio dropout only interferes with the playback?  Trying to determine if I need to re-record or not.

It's really hard having confidence mixing a track when it's full of clicks.  I tried reducing the load on my MacBook by deleting other tracks, freezing tracks, removing unnecessary plugins and so on.  The crackling remains.
Comment: I just checked the exported audio.  The crackles are still present.  I'm going to plug back in and re-record.  I'll take your suggestions above re: tracking and keep an eye on the CPU meter.  Thank you!
Comment: It does continue to puzzle me how you can hear it yet I can't… If you make that soundcloud track downloadable, or a larger segment, then we could *all* have a look.
Comment: Not sure how to make it downloadable, but I can send another clip without the bass drum--that should make it more easy to hear
Comment: Click the edit button, then Permissions - https://i.stack.imgur.com/NgnzT.png
Comment: okay--have a listen.  I selected a few chords that are affected.  I have included the chord from the prior example as well.  In this case, you're just hearing one electric guitar. https://soundcloud.com/21-21-21/ex-2-clicking-issue/s-nPLP4RuCUR5?si=6aff5b1f2f6942cd8355ab3647a2118f
Comment: Ah, in the final sustained chord, I can finally hear the glitch. The other chords are too short to really hear it. Try disabling as much stuff as possible while tracking.
Comment: are Tetsuji and henrebotha the same user?
Comment: Why would they be?? I can hear a glitch in the second file too - though I would have never described it as a click, so that's not what I was listening for. You still didn't set them to be downloadable, so no-one can look at the data close-up, but it does now sound like it glitched whilst recording, not at playback.
Comment: you originally said you couldn't hear the clicks and then henreboth said "I can finally hear the glitch", so the context confused me
Comment: I believe I made the first sample downloadable but not the second, since I forgot (new to soundcloud).  I just made sure both are downloadable.  please let me know if it still isn't working for you.  can tracks be both private and downloadable?


Generate parser that runs a received parser on the output of another parser and monadically joins the results

Question: given the following type and function, meant to parse a field of a CSV field into a string:
type Parser resultType = ParsecT String () Identity resultType
cell :: Parser String

I have implemented the following function:
customCell :: String -> Parser res  -> Parser res
customCell typeName subparser =
  cell
    >>= either (const $ unexpected typeName)
               return . parse (subparser <* eof) ""

Though I cannot stop thinking that I am not using the Monad concept as much as desired and that eventually there is a better way to merge the result of the inner with the outer parser, specially on what regards its failure.
Does anybody know how could I do so, or is this code what is meant to be done?
PS - I now realised that my type simplification is probably not appropriate and that maybe what I want is to replace the underlying Identity Monad by the Either Monad.... Unfortunately, I do not feel enough acquainted with monad transformers yet.
PS2 - What the hell is the underlying monad good for anyway?
Answer: Elaborating on @Daniel Wagner's answer...  The way parsers are normally built with Parsec, you start with low-level parsers that parse specific characters (e.g., a plus sign or a digit), and you build parsers on top of them using combinators (like a many1 combinator that turns a parser that reads a single digit into a parser that reads one or more digits, or a monadic parse that parsers "one or more digits" followed by a "plus sign" followed by "one or more digits").
However, each parser, whether it's a low-level digit parser or a higher-level "addition expression" parser, is intended to be applied directly to the same input stream.
What you don't typically do is write a parser that gobbles a chunk of the input stream to produce, say, a String and another parser that parses that String (instead of the original input stream) and try to combine them.  This is the kind of "vertical composition" that isn't directly supported by Parsec and looks unnatural and non-monadic.
As pointed out in the comments, there are some situations where vertical composition is the cleanest overall approach (like when you have one language embedded within the components or expressions of another language), but it's not the usual approach taken by a Parsec parser.
The bottom line in your application is that a cell parser that produces only a String is too specialized to be useful.  A more useful Parsec framework for CSV files would be:
import Text.Parsec
import Text.Parsec.String

-- | `csv cell` parses a CSV file each of whose elements is parsed by `cell`
csv :: Parser a -> Parser [[a]]
csv cell = many (row cell)

-- | `row cell` parses a newline-terminated row of comma separated
--   `cell`-expressions
row :: Parser a -> Parser [a]
row cell = sepBy cell (char ',') <* char '\n'

Now, you can write a custom cell parser that parses positive integers:
customCell :: Parser Int
customCell = read <$> many1 digit

and parse CSV files:
> parse (csv customCell) "" "1,2,3\n4,5,6\n"
Right [[1,2,3],[4,5,6]]
>

Here, instead of having a cell subparser that explicitly parses a comma-delimited cell into a string to be fed to a different parser, the "cell" is an implicit context in which a supplied cell parser is called to parse the underlying input stream at the appropriate point where one would expect a comma-delimited cell in the middle of a row in the middle of the input stream.
Answer: Sadly I know of no parser library or parser generator for Haskell that supports vertical parser composition like this. Something like what you wrote is about as good as it gets. Dang!
Comment: I'm not sure what you mean by vertical parser composition. Do you mind expanding a bit?
Comment: @gallais I mean the operation you're asking for: a way to take a `Parser Foo [Bar]` and a `Parser Bar Baz` and turn it into a `Parser Foo Baz`.
Comment: Oh I see. With simple types like these the goal is much clearer than in OP's question I think. Thanks for the clarification!
Comment: I wrote a parser library that supports vertical composition `https://github.com/quickdudley/phaser`


Como transformar várias colunas em 2 colunas com vba?

Question: Eu tenho uma planilha com as seguintes informações.

Quero criar uma nova sheet com algumas colunas dessa planilha e transformar as colunas Nominal, Umidade, Primeira_Entrega,
Grau Bebida, Standard, Medicinal e Restr_Horario em uma coluna chamada ITEM e o valor dessas colunas em outra coluna chamada FLAG.
A minha nova planilha ficaria assim:

Além disso quero criar a coluna N_ITEM que é baseada no valor da coluna ITEM.
Se Item = STANDARD então N_ITEM = 1,
Se Item = NOMINAL, UMIDADE, GRAU_BEBIDA, MEDICINAL então N_ITEM = 2
Se Item = PRIMEIRA_ENTREGA então N_ITEM = 4
Se Item = RESTR_HORARIO então N_ITEM = 5.
Eu fiz a macro abaixo, mas não está funcionando...
Public Sub Atualizar()
'
'faz outra tabela listando cada ganho individual
'facilita a manipulação de pivot's
Dim BD As Worksheet
Dim base As Worksheet
Dim b As Integer
Dim c As Integer
Dim itens As Range
Dim k As Long

Set BD = Sheets("Base_Distribuicao")
Set base = Sheets("base")
Application.ScreenUpdating = False
With base
.Range("A:M").ClearContents
.Range("a1").Value = "Cod_JDE"
   .Range("B1").Value = "CNPJ_8"
    .Range("C1").Value = "CNPJ"
    .Range("D1").Value = "CLIENTE"
    .Range("E1").Value = "REGIAO"
    .Range("F1").Value = "SUBREGIAO"
    .Range("G1").Value = "NEGOCIO"
    .Range("H1").Value = "PUBLICO_PRIVADO"
    .Range("I1").Value = "CDL_RESPONSAVEL"
    .Range("J1").Value = "PRODUTO"
    .Range("K1").Value = "ITEM"
    .Range("L1").Value = "N_ITEM"
    .Range("M1").Value = "FLAG"
End With
BD.Select
k = BD.Range("A1", BD.Range("A1").End(xlDown)).Rows.Count
For c = 1 To 7 'contagem de colunas dos itens, ajuda a generalizar o preenchimento por offset
If itens Is Nothing Then 'definindo a ptimeira coluna
Set itens = BD.Range("A1:AB5000").Find(what:="Nominal")
itens.Offset(1, 0).Select
Else
Set itens = itens.Offset(0, 1) 'definindo as colunas restantes
itens.Offset(1, 0).Select 'primeiro flag do item
End If
For b = 1 To k
If ActiveCell.Value <> "" And ActiveCell.Value <> "-" Then
base.Range("A2").EntireRow.Insert
Else
base.Range("A2") = ActiveCell.Offset(0, -(5 + c)).Value
base.Range("B2") = ActiveCell.Offset(0, 14 - c).Value
base.Range("C2") = ActiveCell.Offset(0, 15 - c).Value
base.Range("D2") = ActiveCell.Offset(0, 16 - c).Value
base.Range("E2") = ActiveCell.Offset(0, 17 - c).Value
base.Range("F2") = ActiveCell.Offset(0, 18 - c).Value
base.Range("G2") = ActiveCell.Offset(0, 19 - c).Value
base.Range("H2") = ActiveCell.Offset(0, 20 - c).Value
base.Range("I2") = ActiveCell.Offset(0, -(3 + c)).Value
base.Range("J2") = ActiveCell.Offset(0, -(2 + c)).Value
base.Range("M2") = ActiveCell.Value
base.Range("K2") = itens.Value

End If
ActiveCell.Offset(1, 0).Select ' proximo flag
Next
Next

Application.ScreenUpdating = True

End Sub

Comment: Olá Thaís, bem-vinda! Por favor, se puder, deixe o enunciado mais claro e as vezes mais simplificado porque ficaria mais fácil de responder.
Ao invés de colocar o problema real, contextual da sua empresa, poderia diminuir e fazer a pergunta direto ao ponto:
Tenho uma planilha A com colunas (nome, rua, bairro, cidade, numero, cep) - gostaria de criar uma coluna B, com as colunas nome e endereço - é o mesmo problema mas de forma que as pessoas entendam melhor.
Answer: Boa tarde Thaís,
Tudo bem com você?
Minha sugestão de código ficou gigante, mas acredito que resolverá seu problema.
Primeiramente, note que a estrutura das abas que eu usei para testar são as seguintes:

Aba "Base_Distribuicao":

Aba "base":

Basicamente, o que eu fiz foi copiar os cabeçalhos e valores que você queria transformar em colunas como células transpostas na aba base.
E, para preencher as demais linhas com os valores correspondentes, eu fiz o código percorrer célula por célula da aba "Base_Distribuição" e ir colando na aba "base.
Sugiro fortemente que você dê uma lida no meu código e teste "debugando (ou seja, pressionando a tecla F8 linha a linha)", pois para o código funcionar bem os comandos precisam corresponder exatamente à estrutura da planilha.
Por fim, segue aqui:
Sub Transposicao()

Dim W       As Worksheet
Dim WB      As Worksheet
Dim A       As Integer
Dim B       As Integer
Dim C       As Integer
Dim L       As Integer
Dim UltCel  As Range

Application.ScreenUpdating = False

Set W = Sheets("Base_Distribuicao")
Set WB = Sheets("base")

WB.Select
WB.Range("A2:M1048576").Clear

W.Select
A = 2
B = 2
C = 2
'Set Col = W.Range("I1:O1")
Set UltCel = W.Range("A1048576").End(xlUp)

Do While A <= UltCel.Row

    'Copia as células da aba Base_Distribuicao a serem transpostas e cola na aba base, transpondo
    W.Select
    W.Range("I1:O1").Select
    Selection.Copy
    WB.Select
    WB.Range("J" & C).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

    'Copia os valores correspondentes para a coluna FLAG
    W.Select
    W.Range("I" & A).Select
    Selection.Copy
    WB.Select
    WB.Range("K" & C).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    W.Select
    W.Range("J" & A).Select
    Selection.Copy
    WB.Select
    WB.Range("K" & C + 1).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    W.Select
    W.Range("K" & A).Select
    Selection.Copy
    WB.Select
    WB.Range("K" & C + 2).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    W.Select
    W.Range("L" & C).Select
    Selection.Copy
    WB.Select
    WB.Range("K" & C + 3).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    W.Select
    W.Range("M" & A).Select
    Selection.Copy
    WB.Select
    WB.Range("K" & C + 4).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    W.Select
    W.Range("N" & A).Select
    Selection.Copy
    WB.Select
    WB.Range("K" & C + 5).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    W.Select
    W.Range("O" & A).Select
    Selection.Copy
    WB.Select
    WB.Range("K" & C + 6).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    'Copia os demais valores referentes ao respectivo IDE

    ''Copia o IDE
    B = WB.Range("A1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("C" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("A" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    ''Copia o CNPJ
    B = WB.Range("B1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("V" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("B" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    ''Copia o nome do cliente
    B = WB.Range("C1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("W" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("C" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    'Copia a região atual
    B = WB.Range("D1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("X" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("D" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    'Copia o subgrupo
    B = WB.Range("E1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("Y" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("E" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    'Copia o negócio
    B = WB.Range("F1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("Z" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("F" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    'Copia o públlico/privado
    B = WB.Range("G1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("AA" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("G" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    'Copia o CDL_Responsável
    B = WB.Range("H1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("E" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("H" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    'Copia o Installation Product
    B = WB.Range("I1048576").End(xlUp).Row + 1
    For L = 1 To 7
        W.Select
        W.Range("F" & A).Select
        Selection.Copy
        WB.Select
        WB.Range("I" & B).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        B = B + 1
    Next L

    A = A + 1
    C = C + 7

Loop

'Preenche a coluna N_ITEM
WB.Range("L2").Select

Set UltCel = WB.Range("K1048576").End(xlUp)

A = 2

Do While A <= UltCel.Row

    If WB.Range("J" & A).Value = "Standard" Then

        WB.Range("L" & A).Value = 1

    ElseIf WB.Range("J" & A).Value = "Nominal" Or WB.Range("J" & A).Value = "Umidade" Or WB.Range("J" & A).Value = "Grau_Bebida" Or _
        WB.Range("J" & A).Value = "Medicinal" Then

        WB.Range("L" & A).Value = 2

    ElseIf WB.Range("J" & A).Value = "Primeira_Entrega" Then

        WB.Range("L" & A).Value = 4

    ElseIf WB.Range("J" & A).Value = "Restr_Horario" Then

        WB.Range("L" & A).Value = 5

    End If

    A = A + 1

Loop

Application.ScreenUpdating = False

MsgBox "Pronto", vbOKOnly, "Status"

End Sub

Se você tiver algum problema, me chame aqui.
Espero que ajude.


Does k-fold cross validation change the model in each iteration?

Question: My basic understanding is that the machine learning algorithms are specific to the training data. When we change the training data, the model also changes.
If my understanding is correct, then while performing k-fold cross-validation, the training data is changed in each k iteration so is the model. Therefore, if the model is changed each time then how the accuracy in all k iterations is reliable?
Is it better to split the model in training, validation, and testing (just perform hyperparameter tuning based on training and validation sets and test it on the testing set) than performing k-fold cross-validation?
Answer: My basic understanding is that the machine learning algorithms are specific to the training data.
The weights of parameters for machine learning models are determined by the training data. Depending on the size of your training data, small variations in training data can have significant effects on the weights of the composed model. Neural Networks trained on small training data can also experience fluctuation if the weights are randomly assigned to each neuron before training.
Therefore, if the model is changed each time then how the accuracy in all k iterations is reliable?
The weights of the parameters probably will change with each iteration of k-fold CV due to varying training data. This is expected, but shouldn't discourage use. One of the primary purposes of performing k-fold CV is to assess how well your model structure generalizes to test data, which can be evaluated using the validation error on each fold. By structure, I'm referring to type of model used (linear, logistic, neural network, etc) and/or parameters used (using variables $x,y$ and $z$ versus just using variables $x$ and $y$). We compare how each model structure generalizes to the test data, and we can determine if certain structures are over-fitting to the training data.
Is it better to split the model in training, validation, and testing than performing k-fold cross-validation?
I'm not sure exactly what you're proposing here, but k-fold CV is a method of splitting your training data into training and validation sets, and once you have settled on a model structure, you train the model on the entirety of the training data. Generally the more data in the training set, the more representative a sample we have of the data we are trying to predict; and if this is true then the more generalizable the model should be.
Creating a second level of testing may be seen as redundant, as I'm not sure what you would gain besides incremental testing/training of your model. I would defer to a more knowledgeable person on this.


extract package name from apk file

Question: In my java application, I have tried to get the package name of an android application. I have tried it by executing command line argument. The command is :
aapt dump badging <apk file>
And this command returned whole meta data of the application.I have to extract the package name from the returned string suppose named 'result' ;
Comment: possible duplicate of [Resolving the package name of Android APK](http://stackoverflow.com/questions/6289149/resolving-the-package-name-of-android-apk)
Answer: hoe you are looking for this try this code :
String line;
        while ((line = r.readLine()) != null) {
            int ind = line.indexOf("package: name=");
            if (ind >= 0) {
                String yourValue = line.substring(ind + "default =".length(), line.length() - 1).trim(); // -1 to remove de ";"
                System.out.println(yourValue);
          }

Answer: Try this code..
Get package name of application from apk file.
All information from manifest
aapt dump badging <path-to-apk>

Get only package name and main Activity
Create applicationInfo.sh file with below data
package=`aapt dump badging $* | grep package | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
activity=`aapt dump badging $* | grep Activity | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
echo
echo package : $package
echo activity: $activity

execute command as
applicationInfo.sh <path-to-apk>

This will print package name and main activity. You can modify .sh file as per your need.

extract package name from apk file


what measures you look at the determine over fitting in linear regression?

Question:
Which of the following is NOT a valid measure of overfitting?

Sum of parameters $\left(w_1+w_2+\ldots+w_n\right)$
Sum of squares of parameters $\left(w_1^2 + w_2^2 + \ldots +w_n^2\right)$
Range of parameters, i.e., difference between maximum and minimum parameters
Sum of absolute values of parameters $\left(|w_1| + |w_2| + \ldots + |w_n|\right)$

Can somebody try to explain this to me?
Comment: Given that the parameters in a model literally could have any value, in what sense could you possibly conceive of *any* of these as being a measure of *anything*? Is this question perhaps extracted from a context in which a specific model is under consideration and its parameters have somehow been standardized?
Comment: I think that whuber is saying that without more context (ie, assuming only the $w_i$ are the parameters of a linear regression model fit on any data), we can't hope to interpret the $w_i$ meaningfully. Is this related to linear regression on data in any particular domain?
Comment: Hint: putting aside for now the issue of whether any of these is a measure of overfitting, consider how these various measures would behave if some parameter values were negative and others were positive.
Comment: linear regression model.
Comment: Are you asking this question in the context of linear model regularization?
Answer: First of all, let me describe the meaning of over-fitting in general. Overfitting means your model not only fits the relationship between the dependent variables and independent variable, but also fits random noise into it. Here is a good example of underfitting, right fitting and overfitting.
Fitting such a over fitting model will result in a very low error in predicting your training data (or you can image that you are using the model fitted by the data to predict the same data, of cause the more complex the model the lower the error) but a very high error when you predict NEW data (testing data). Error can be defined as $\sum(\hat{y} - y)^2$, where $\hat{y}$ is fitted value.
In general, I don't think any of the methods you mentioned in your question would help you to prevent or detect over-fitting in a linear regression model.
For example, if you are fitting a linear model between the area of house (Y, in $m^2$) and the price of the house (X, in $k$ dollars). The model is like
$Y = \alpha + \beta X + \epsilon,$ where $\epsilon \sim N(0, \sigma^2)$
Then, for example, the sum of parameter is
$\hat{\alpha} + \hat{\beta} + \hat{\sigma}$, if I understand your question correctly.
However, if you change the unit of price of the house from $k$ dollars to million dollars, your $\hat{\beta}$ will change to $\hat{\beta}/1000$. Thus the sum of the parameter reduce to $\hat{\alpha} + \hat{\beta}/1000 + \hat{\sigma}$. But you cannot say either of the model is more over-fitting than the other one even the sum of parameters changes.
What I usually use to prevent over-fitting is cross validation. Cross validation means that you split your data into several subsets. For each subset, you use it as testing set while using others as training set to fit a model and use it to predict the testing set and calculate the prediction error for this testing set. Then you average your prediction errors among all the testing set, you'll get a cross validation error.
Or for simple cases, I would use adjusted $R^2$ from the output of lm in r.  Adjusted $R^2$ takes into the complexity of your model into account. Complexity will tend to reduce the adjusted $R^2$.
Comment: It's a very good answer.  Thank you for continuing to improve it!
Comment: Are you familiar with the idea of the `self-study` tag? An answer should help the asker gradually progress with his/her own thinking. See more [here](http://stats.stackexchange.com/tags/self-study/info).
Comment: Oh, thanks. I am new to cross validated. I'll edit my answer.
Comment: If you are new then -- warm welcome to CV!
Comment: Note that this is a self-study question and should be answered accordingly...
Comment: @Richard Hardy, what do you mean? Without knowing the field of study, I don't think the four ways of combination of $\omega$'s can be related to overfitting.


how to call/using geofield in a custom module

Question: I`m trying to use the geofield module, and load it with google maps widget in one my custom forms.
Yet i can't find any way to use the form api to display this field.
<code>$form['geofield'] = array(
'#title' => 'geofield',
'#type' => 'geofield',
);
</code>
Any suggestion is welcome, i don't mind reading some docs.
Answer: Geofield module is rather complex module which adds a lat/long fieldset and so many other stuff such as adding new fields, validation, etc.
Anyway, you can create a latitude and longitude input field using the <code>#type => 'geofield_latlon'</code>.
<code>$form['geofield'] = array(
  '#title' => 'geofield',
  '#type' => 'geofield_latlon',
);
</code>
Note that this will return a generic longitude latitude form. NOT a Google Maps choose-location field.
See geofield.elements.inc for more information on how this element is validated and themed.
Update: I forgot to mention that the above element is available in the 7.x-2.x branch.
Comment: Geofield_latlon doesn't seem to show anything either, its like nothing happends, what ever the type i`m trying to use.
Comment: My bad... I've installed 7.1 geofield module instead of the 7.2 branch. Now i'd have the latlon field.
Comment: Sorry I forgot to mention the branch. 2.x branch has proximity filters as well, so I'm using that version in all my sites. Did `geofield_latlon` work ?
Comment: Yeah it seems to work now. Next step would be the map. I figured out i needed to install geofield gmap module to be able to have the widget for it. Any idea, how i would call that widget?
Comment: the only type i can find in the geofield_gmap files is geofield_gmap


SQL to GROUP BY calculated date

Question: I need some assistance in grouping data by date via SQL but seem to be running into errors.
Here's my current SQL statement used as a variable passed into Excel VBA macro.
SQLtext = "SELECT [Offered], [MidnightStartDate], tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"FROM tblData_QueuePerformanceByPeriod INNER JOIN tblConfig_Queue on tblConfig_Queue.Pkey = tblData_QueuePerformanceByPeriod.FKQueue " & _
"Where [Offered]>0 AND[MidnightStartDate]>" & MakeUSSQLDate(Sheet13.Range("A1").Value) & " AND [MidnightStartDate]<" & MakeUSSQLDate(Sheet13.Range("A2").Value + 1) & _
""

The field MidnightStartDate is a date & time field in a US format. The MakeUSSQLDate procedure converts this into a UK format. I then want to remove any time values from the field, and have date only, and group by this field to give me a total of [Offered] for each of the [Name] and [Reporting] values for each date. I have used the convert function to strip out the times, and this currently works as below.
SQLtext = "SELECT [Offered], convert(varchar, [MidnightStartDate], 103) AS [Date2], tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"FROM tblData_QueuePerformanceByPeriod INNER JOIN tblConfig_Queue on tblConfig_Queue.Pkey = tblData_QueuePerformanceByPeriod.FKQueue " & _
"Where [Offered]>0 AND[MidnightStartDate]>" & MakeUSSQLDate(Sheet13.Range("A1").Value) & " AND [MidnightStartDate]<" & MakeUSSQLDate(Sheet13.Range("A2").Value + 1) & _
""

However I can't seem to get the thing to group by the date. I have added GROUP BY CONVERT(varchar, [MidnightStartDate], 103) ORDER BY CONVERT(varchar, [MidnightStartDate], 103) to the end of the SQL statement in an attempt to solve this but only get error messages back.
Comment: Could you post the errors?
Comment: What error do you get?
Comment: I get the following error:
[Microsoft][ODBC SQL Server Driver][SQL Server]Column 'tblData_QueuePerformanceByPeriod.Offered' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Comment: I have now included tblConfig_Queue.[Name], tblConfig_Queue.[Reporting] in my GROUP BY, but the total of [Offered] doesn't seem correct.
Comment: Thanks everyone - it's all working now .The total seems to be correct when i change SELECT [Offered] to SELECT SUM([Offered]). I also removed [Offered] from the GROUP BY statement as it was causing errors.
Answer: I'm waiting for your error but...
If you use GROUP BY as follow:
convert(varchar, [MidnightStartDate], 103)

and you have in the SELECT fields these fields:
[Offered], convert(varchar, [MidnightStartDate], 103),
tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]

It's logic the error, because you must add all fields in your group by clause.
When you use a GROUP BY in the SELECTE field list you can have only:

Constants
Grouped fields
Aggregate functions

So you must extend your GROUP BY clause like the following:
GROUP BY [Offered], convert(varchar, [MidnightStartDate], 103) AS [Date2],
tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]

Answer: Assuming your error is to do with not including your other fields or wrapping them in an aggregate function try:
SQLtext = "SELECT [Offered], convert(varchar, [MidnightStartDate], 103) AS [Date2], tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"FROM tblData_QueuePerformanceByPeriod INNER JOIN tblConfig_Queue ON tblConfig_Queue.Pkey = tblData_QueuePerformanceByPeriod.FKQueue " & _
"WHERE [Offered]>0 AND [MidnightStartDate]>" & MakeUSSQLDate(Sheet13.Range("A1").Value) & " AND [MidnightStartDate]<" & MakeUSSQLDate(Sheet13.Range("A2").Value + 1) & _
"GROUP BY convert(varchar, [MidnightStartDate], 103), [Offered], tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"ORDER BY convert(varchar, [MidnightStartDate], 103)" & _
""

Cleaning up with BETWEEN
SQLtext = "SELECT [Offered], convert(varchar, [MidnightStartDate], 103) AS [Date2], tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"FROM tblData_QueuePerformanceByPeriod INNER JOIN tblConfig_Queue ON tblConfig_Queue.Pkey = tblData_QueuePerformanceByPeriod.FKQueue " & _
"WHERE [Offered]>0 AND [MidnightStartDate] BETWEEN" & MakeUSSQLDate(Sheet13.Range("A1").Value) & " AND " & MakeUSSQLDate(Sheet13.Range("A2").Value + 1) & _
"GROUP BY convert(varchar, [MidnightStartDate], 103), [Offered], tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"ORDER BY convert(varchar, [MidnightStartDate], 103)" & _
""

Answer: Thanks for the help - my final working code
SQLtext = "SELECT SUM([Offered]), CAST([MidnightStartDate] AS INT), tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"FROM tblData_QueuePerformanceByPeriod INNER JOIN tblConfig_Queue on tblConfig_Queue.Pkey = tblData_QueuePerformanceByPeriod.FKQueue " & _
"Where [Offered]>0 AND[MidnightStartDate]>" & MakeUSSQLDate(Sheet13.Range("A1").Value) & " AND [MidnightStartDate]<" & MakeUSSQLDate(Sheet13.Range("A2").Value + 1) & _
"GROUP BY CAST([MidnightStartDate] AS INT), tblConfig_Queue.[Name], tblConfig_Queue.[Reporting]" & _
"ORDER BY CAST([MidnightStartDate] AS INT), tblConfig_Queue.[Reporting];"

SQL to GROUP BY calculated date


intellij Scala Project issue

Question: I try to import an Scala Project into intellij. Intellij founds starts to load the dependencies then I got this error
How can I solve this issue?
<code>[error] Expected non-whitespace character
[error] --addPluginSbtFile=C:\Users\Firstname Lastname\AppData\Local\Temp\idea1.sbt
[error]                                      ^
</code>
Thanks in Advance
Answer: The path should not contain BlankSpaces.
You have a blank space between Firstname LastName:
C:\Users\Firstname Lastname\AppData\Local\Temp\idea1.sbt
Possible solution:
C:\Users\FirstnameLastname\AppData\Local\Temp\idea1.sbt
Comment: Its the System Path from Windows wich comes up with the microsoft User Account. So Its not possible. Any hints to set the path into `""` don't know from where this comes.
Comment: ok that seems to be an known issue in current intellij version
Comment: Try to add `%20` to the PATH: `C:\Users\Firstname%20Lastname\AppData\Local\Temp\idea1.sbt`
Comment: issue tracker link for reference: https://youtrack.jetbrains.com/issue/SCL-15360
Answer: This is fixed in the Scala plugin for IntelliJ IDEA update 2019.3.18 and release 2020.1
https://youtrack.jetbrains.com/issue/SCL-15360

intellij Scala Project issue


existence of $(K,\alpha)$-disperser with degree $D=O(\log\frac{N}{K})$

Question: A bipartite graph $G=(V_1=[N],V_2=[M],E)$ is a $(K,\alpha)$-disperser if for every $X\subseteq V_1$ of cardinality $K$, $|\Gamma(X)|>(1-\alpha)M$. That is, every large enough set in $V_1$ misses less than an $\alpha$-fraction of the vertices in $V_2$.
Prove that for every $M\leq K\leq N$ and constant $0\lt\alpha\lt1$ there exists a $(K,\alpha)$-disperser $G=(V_1=[N],V_2=[M],E)$ with degree $D=O(\log\frac{N}{K})$.
Comment: No it is the degree of all the vertices, i.e. each vertex has degree D
Comment: Yes each vertex
Answer: We prove the existence using the probabilistic method, with the simplest possible construction - for each $v \in V_1$ pick $D$ neighbours uniformly at random and independently from $V_2$. Fix $X \subseteq V_1, |X| = K, Y \subseteq V_2, |Y| = \alpha M, D = c \log N/K$ (we will pick the constant later). We first want to compute the probability that $\Gamma(X) \cap Y = \phi$. Pick $x \in X, y \in Y$, and observe that $\Pr[x \not\sim y] = 1 - \frac{D}{M}$. As all edges are drawn independently, we get that: $$\Pr[\Gamma(X) \cap Y = \phi] = \Pr[\forall x \in X, y\in Y \ : \ x \not\sim y] = (1 - \frac{D}{M})^{|X| \cdot |Y|} = (1 - \frac{D}{M})^{K \alpha M} = (1 - \frac{1}{M/D})^{(M/D) \alpha K D} \approx e^{-\alpha KD}$$ We now apply a crude union bound as follows:
\begin{align}
\Pr[G \text{ is not } (K,\alpha)-disperser] & = \Pr[\exists X \subseteq V_1, Y \subseteq V_2, |X| = K, |Y| = \alpha M \ : \ \Gamma(X) \cap Y = \phi] \\
& \leq \sum_{\stackrel{X \subseteq V_1}{|X|=K}} \sum_{\stackrel{Y \subseteq V_2}{|Y|=\alpha M}} \Pr[\Gamma(X) \cap Y = \phi] \\
& = \tbinom{N}{K} \tbinom{M}{\alpha M} e^{-\alpha KD} \\
& \leq \left(\frac{eN}{K}\right)^K \left(\frac{eM}{\alpha M}\right)^{\alpha M} e^{-\alpha KD} \\
& = e^{K+ K\log N/K+\alpha M + \alpha M \log \alpha - \alpha K D} \\
& \leq e^{4 K \log N/K - \alpha K D} \\
& = e^{4 K \log N/K - \alpha K c \log N/K}
\end{align}
We now see that if we pick $c = 5/\alpha$ for example, we will get: $$\Pr[G \text{ is not } (K,\alpha)-disperser] \leq e^{-K \log N/K} < 1$$ And therefore there exists such a $(K,\alpha)$-disperser with the desired parameters (in fact, a random graph drawn in this manner is a.a.s a disperser)


Three level indirection char pointer in C causes a segment fault

Question: I got a segment fault error at the line with the comments that contains lots of equals signs below.
The function below str_spit, I wrote it because I want to split a string using a specific char, like a comma etc.
Please help.
 int str_split(char *a_str, const char delim, char *** result)
    {
       int word_length = 0;
       int cur_cursor = 0;
       int last_cursor = -1;
       int e_count = 0;
       *result = (char **)malloc(6 * sizeof(char *));
       char *char_element_pos = a_str;
       while (*char_element_pos != '\0') {
        if (*char_element_pos == delim) {
            char *temp_word =   malloc((word_length + 1) * sizeof(char));

            int i = 0;
            for (i = 0; i < word_length; i++) {
                temp_word[i] = a_str[last_cursor + 1 + i];
            }

            temp_word[word_length] = '\0';
            //
            *result[e_count] = temp_word;//==============this line goes wrong :(
            e_count++;
            last_cursor = cur_cursor;
            word_length = 0;
        }
        else {
            word_length++;
        }
        cur_cursor++;
        char_element_pos++;
    }
    char *temp_word = (char *) malloc((word_length + 1) * sizeof(char));
    int i = 0;
    for (i = 0; i < word_length; i++) {
        temp_word[i] = a_str[last_cursor + 1 + i];
    }
    temp_word[word_length] = '\0';
    *result[e_count] = temp_word;
    return e_count + 1;
  }

   //this is my caller function====================
  int teststr_split() {
    char delim = ',';
    char *testStr;
    testStr = (char *) "abc,cde,fgh,klj,asdfasd,3234,adfk,ad9";

    char **result;

    int length = str_split(testStr, delim, &result);
    if (length < 0) {
        printf("allocate memroy failed ,error code is:%d", length);
        exit(-1);
    }
      free(result);
      return 0;
    }

Comment: Standard warning: do not cast `void *` as returned by `malloc`!
Comment: You should start with one and two stars as a beginner, before becoming a three star programmer (if that really is what you want/need).
Comment: str_spit would indeed be a perfect naming here *scnr*
Answer: I think you mean
( *result )[e_count] = temp_word;//

instead of
*result[e_count] = temp_word;//

These two expressions are equivalent only when e_count is equal to 0.:)
Answer: [] has a higher precedence than *, so probably parentheses will solve THIS problem:
(*result)[e_count] = temp_word;

I didn't check for more problems in the code. Hint: strtok() might do your job just fine.


ffmpeg rename output if the file already exists

Question: I am recording one hour long video clips from an rtsp stream through ffmpeg with a custom filename and I want it to check if the video file already exists each time it saves a clip to my hard drive and rename the new output to conserve both files.
For example if it is saving the clip video-02222018.mp4 instead of overwriting it will rename it to video-02222018-01.mp4 if the file already exists or video-02222018-02.mp4 and so on as long as the file exists.
Note: I am going to run this using crontab on a linux system so it would fire this script each hour.
Comment: ffmpeg can't rename any files. But you can use the segment [muxer](https://ffmpeg.org/ffmpeg-formats.html#segment_002c-stream_005fsegment_002c-ssegment) with a segment_time of 3600.
Comment: @Mulvya Would that work with an rtsp stream?
Comment: As input? I don't know your full command, but generally not a problem.
Comment: Yeah I am grabbing the clips from an rtsp stream. I will try it out and post back as soon as I get results.
Answer: As far as I understand, ffmpeg can't do this, as @Mulvya said. I'd suggest python script and using datetime to name your file so you will know which is most recent without having to search through all your files and increment.
outputFilename + '-' + timestamp


Epanechnikov in R

Question: Suppose I have one data point, $x_1=0$ and I estimate the Epanechnikov kernel using bandwith $h=1$. The formula is then:
$\hat f(x,1)=\frac{3}{4}(1-x^2)$ for $|x|\leq1$
I use the code: density(x=0, bw=1, kernel=c("epanechnikov"))
Yet, I get that instead of getting the parabola from $-1$ to $1$, it has a larger domain. Why is this?
Answer: Bandwidth in kernel density estimation is a matter of definition -- it varies from book to book and implementation to implementation (more specifically, it's a multiple of some unit bandwidth, and the exact definition of the kernel for a bandwidth of 1 is the thing that varies). You're not using the definition that the function you're calling uses; they clearly state what they're doing.
They specify it in the help on the function under Arguments:
    bw
         the smoothing bandwidth to be used. The kernels are scaled such that
         this is the standard deviation of the smoothing kernel. (Note this
         differs from the reference books cited below, and from S-PLUS.)

For the Epanechnikov kernel, this means specifying bw=1 defines the density corresponding to that kernel to be nonzero on $(-\sqrt{5},\sqrt{5})$.
This choice makes the same bandwidth on different kernels have more-or-less similar effects.
Comment: So if I specify `bw=sqrt(1/5)` I get the graph from $-1$ to $1$. So what's the relation between the $h$ parameter and $bw$?
Comment: Typically, $h$ is a bandwidth. The `density` function doesn't have aparameter called `h`, it calls it `bw`, which is as I already explained, clearly defined. Since both $h$ and `bw` are simply notations for bandwidth parameters, my opening sentences above applies ... so if you want me to compare it with some other unit kernel, *which* definition of the unit kernel, $K$ are you using?
Comment: I have edited my first sentence in the answer; perhaps that will clarify it.

Epanechnikov in R


Find percentage of column with where constraints in SQL Server

Question: So I have the following table format in SQL Server. I want to find the percentage of animals where the color is black.
Type    Color
--------------
Dog      Black
Cat      Brown
Dog      Brown
Cat      Black
Dog      white
Dog      Black

So in other words the output would be something like this.
Dog  black  33%
Cat  black  16.6%

How can I do this in a single query?
Comment: You can do it with math.   What did you try so far?
Comment: Possible duplicate of [How to calculate percentage with a SQL statement](http://stackoverflow.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement)
Answer: SELECT [Type]
     , Colour
     , CAST( COUNT(*) * 100.00 /(Select COUNT(*) FROM TableName) AS DECIMAL(5,2))
FROM TableName
GROUP BY [Type] , Colour

Answer: You can do this by grouping on the type of animal, and getting the count for that group by COUNT(*) for that group. Divide that by the total number of animals ((SELECT COUNT(*) FROM #tt)).
SELECT* INTO #tt FROM (VALUES('Dog','Black'),('Cat','Brown'),('Dog','Brown'),('Cat','Black'),('Dog','white'),('Dog','Black')) AS t(Type,Color)

SELECT
    Type,
    color='black',
    [percentage]=CAST(COUNT(*)*100.0/(SELECT COUNT(*) FROM #tt) AS DECIMAL(28,2))
FROM #tt
WHERE color='black'
GROUP BY type;

DROP TABLE #tt;

Prints out:
+------+-------+------------+
| Type | color | percentage |
+------+-------+------------+
| Cat  | black | 16.67      |
| Dog  | black | 33.33      |
+------+-------+------------+


How to set jquery datapicker options from within Drupal?

Question: I want to customize a jQuery datapicker in Drupal 7. I found code to set an event:
(function ($) {
Drupal.behaviors.only_monday = {
  attach: function (context, settings) {
   // $( ".selector" ).datepicker( "option", "showWeek", true );
   $.datepicker._defaults.beforeShowDay = onlyMonday;
    function onlyMonday ( date ) {
      if ( date.getDay() == 1 ) {
        return [true, 'ui-datepicker-days-cell'];
      }
      else {
        return [false, 'ui.datepicker-unselectable'];
      }
    }
  }
};
}(jQuery));

This works great, except for commented line. According to the jQuery docs that line (added by myself) should make visible the numbers of the weeks:
$( ".selector" ).datepicker( "option", "showWeek", true );

The context from within Drupal is probably different. But I have no knowledge of js :-(
In what way does this code for setting an option has to be adjusted ?
Comment: Have you had a look at date module ? http://drupal.org/project/date (it has a jquery datepicker)
Answer: Your are working within a Drupal behavior that could be reapplied several times on the DOM tree, in order to avoid processing the same element several times you should limit the $($selector) call to the passed-ind `context and use a marker CSS class for already processed class. Something like
$('.selector:not(.only-monday-processed)').addClass('only-monday-processe').doSomethingwithTheElements();

To defines then set the datepicker options from Drupal server-side PHP, you need to store the selector(s) and options in the settings object received by your behavior attach function using the drupal_add_js() function or the #attached property of your form/render array element. Then your function can use the selector to apply the option to the element. Something like
In your module code, store the selector and options in settings:
drupal_add_js(array('myModule' => array('.selector' => array('showWeek' => TRUE))), 'setting');

In your JavaScript, for each stored selector, apply the datepicker options:
(function ($) {
  Drupal.behaviors.only_monday = {
    attach: function (context, settings) {
      var selector;
      if (typeof settings.myModule === 'object') {
        for (selector in settings.myModule) {
          if (settings.myModule.hasOwnProperty(selector)) {
            $(selector, context).filter(':not(.only-monday-processed)')
              .addClass('only-monday-processe')
              .datepicker('option', settings.myModule[selector]);
          }
        }
      }
    }
    // ...
  };
}(jQuery));

Comment: I could not reply, only answer. Strange and confusing. So I had no choice. Maybe because my question was migrated while I still was not registered on Stackexchange.
Comment: I cannot get this to work. I added the `drupal_add_js()` code to my module.
I replaced my JS code with your JS code.
In both cases I replaced 'myModule' with the name of my module. Like I said, I still do not see the numbers of the week, especially this line (and your remarks about it) do not have any meaning to me: `$('.selector:not(.only-monday-processed)').addClass('only-monday-processe').doSomethingwithTheElements();`. I have not enough knowledge of JS to understand this. Is it just an explanation? It is also in your JS code which I added. Do I have to modify it?
Comment: There's a small bug `$('.selector:not(.only-monday-processed)').addClass('only-monday-processed').doSomethingwithTheElements();`, a d was missing in the `addClass` part ;)
Comment: I added the d, but that did not make it work.
Comment: Yep, this is part of the explanation and not part of the solution. The larger JavaScript code at the end of my answer contains similar behavior. Also, you shouldn't use an answer to reply to another answer. drupal.stackexchnage.com is not a forum.
Comment: The added complexity for passing vars from php to jquery has no need for me. I would be happy with a simple working js-only alternative for: $( ".selector" ).datepicker( "option", "showWeek", true );
Answer: Via '#datepicker_options':
First we add a callback to the #process on date field:
/**
 * Implements hook_element_info_alter().
 */
function MODULE_OR_THEME_element_info_alter(&$type) {
  if (isset($type['date_popup'])) {
    array_unshift(
      $type['date_popup']['#process'],
      '_process_date_popup_helper'
    );
  }
}

And now in the helper we can set any js option:
function _process_date_popup_helper($element, &$form_state, $form) {
  $element['#datepicker_options']['changeMonth'] = FALSE;
  $element['#datepicker_options']['changeYear'] = FALSE;

  return $element;
}

Comment: Since you're setting static options, you actually don't need the process callback. You can do all this in hook_element_info_alter()


High availability architecture for a small business

Question: We are a small startup. In our current setup we have a dedicated server in a remote location. Our website and applications are hosted in that server. Website and some applications are in PHP and the rest are java applications using Tomcat and JBoss. Our database server is mysql. We backup mysql data to our local server using replication. Obviously thing can go wrong in multiple ways in this setup and they have. We had some serious downtime issues and other scares recently.
The new setup we have in mind is as follows.
1) Buying a new server with the same configuration as the current one. Setting this up similar to the current server with all the apps and software
2) Doing hot backup to the new server using BackupPC. (syncing only the often changing files like website, php apps, jboss and tomcat apps)
3) Running a mysql slave in the new server with semi-synchronous replication
4) Running apache/nginx/lighttpd as a reverse proxy in a separate server that points to the primary server.
5) Continue to run a slave in the local server
In case of downtime we can point the reverse proxy to the secondary server. We don't want to do automatic failover, because we have to make sure that the secondary server is fully synced before pointing to it.
What are the pros and cons of the above approach? Or how this can be improved? I understand the reverse proxy will be a SPOF. At this point we are looking for a cost effective solution. Can the reverse proxy be a low priced server with somewhat decent configuration?
I just put this together by reading various articles. It is possible that some of my understandings are wrong. Please feel free to correct them.
Comment: You should elaborate a bit more on the kind of outages you want to prepare for. What you should do largely depends on what you want to prevent.
Comment: There was a spambot issue once. We had to disconnect the server and clean up the system. Then there was a bad sectors issue which resulted in some downtime. Mostly we want a backup server we can resort to in case of emergency so the we can work on the problem without worrying about the increasing downtime.
Answer: a cheap and easy solution that would eliminate your SPOF and need for a reverse proxy would be to set your DNS with low TTL value (e.g. 60 seconds), and simply change the IP address when you want to switch servers.
If you use a DNS provider with Dynamic DNS support (or Amazon Route 53), you can even write a small script that would even automate the process for you.


Automatically have an email sent to page author 11 months after its published date

Question: Hello I was wondering if anybody could help.
I'm using Drupal 8 and for every page that exists I need a custom email to automatically get sent to the page author 11 months after that page was published. It's just to act as a reminder to the author that their page is still published incase they have forgot.
I can't find any info online that outlines exactly what i'm trying to achieve however anything remotely similar I found seems to be using the 'Rules' and 'Scheduler' modules however i'm really not sure how I can achieve what I need to do using them.
Absolutely any help would be amazing, many thanks in advance.
Comment: The D7 Rules module came with a `rules scheduler` module, not to be confused with the `scheduler` module. The D8 version has no such `rules scheduler` module and doesn't appear to have any scheduling functionality. Therefore, you'll have to build such feature via custom code.
Comment: No real need for Rules, you can write a cron hook that adds nodes older than 11 months and add them to a job queue, then process the job queue by sending email(s).
Comment: In D7 this is trivial to do with Rules and Rules Scheduler, and is extensively documented in many places including many answers here on Stack Exchange.
Answer: There isn't a scheduler or Rules available for D8/9 anymore which would've made this easy, but you can build a somewhat simple module that creates a cron job, and in that job you can query each piece of content you want to send emails for, check the 'published' date, find out if it was 11 months ago, and if so email the 'author' of the published content. Then set up a local system cron task to run cron once a day.
You'd obviously want to put checks in place to make sure the email only sends once, and that the user still exists. Setting the conditional to check to make sure that it's 11 months to do the day, and only checking once a day should prevent it from sending more than once for each piece of content.


What is the scaling applied to Helmert contrasts in emmeans?

Question: I'm trying to understand why the values under 'estimate' from an emmeans contrast function differ from those of the default 'Estimate' values from, say, 'summary.lm()' in R. As an example, let's use Helmert contrasts (sometimes called 'reverse Helmert', but the R way of doing these suits my purpose) on a subset of the 'warpbreaks' data set.
Default R output
> data("warpbreaks")
> contrasts(warpbreaks$tension) <- contr.helmert(3)
> wbA <- subset(warpbreaks, wool == "A")
> wbA.lm1 <- lm(breaks ~ tension, data = wbA)

And the coefficients give me the differences that I'd expect based on the cell means
> coef(wbA.lm1)
(Intercept)    tension1    tension2
  31.037037  -10.277778   -3.240741

For the record the cell means are:
       L        M        H
44.55556 24.00000 24.55556

So that, for example, 'tension1' is the mean of the first two means minus the mean of the first level.
emmeans estimates
Function to compute (reverse) Helmert:
helmert.emmc <- function(levs, ...) {
  M <- as.data.frame(contr.helmert(levs))
  names(M) <- paste(levs[-1],"vs earlier")
  attr(M, "desc") <- "Helmert contrasts"
  M
}

And applying this to our model's emmeans:
> wbA.lm1.emm <- emmeans(wbA.lm1, ~ tension)
> contrast(wbA.lm1.emm, "helmert")
 contrast     estimate    SE df t.ratio p.value
 M vs earlier    -20.6  6.13 24  -3.351  0.0027
 H vs earlier    -19.4 10.63 24  -1.830  0.0797

So the 'estimate' for 'M vs earlier' is  twice the value given by the default coef(), and 'H vs earlier' is six times the value given by coef().
I can't help feeling that I'm close to understanding why this happens from this post, but the final answer eludes me. So apologies in advance if  the respondents to that post have answered this.
Regards,
Leon Barmuta
Answer: The post you link does indeed try to explain the same thing.
The basic point is this: A regression model relates the means $\mu$ to the regression coefficients $\beta$, via a matrix equation $\mu = X\beta$. This says that each $\mu_i$ is a linear function $\sum x_{ij}\beta_j$. Note that:

The contrast codings contr.helmert and such give you the $x_{ij}$ values.
Those are weights that are applied to the $\beta_j$.

When you want to estimate a contrast of means, you are looking at something like $\sum c_i\mu_i$. Those $c_i$ are weights that are applied to the $\mu_i$ values.

The bottom line: Weights applied to the $\beta$s are not to be confused with weights applied to the $\mu$s.
Comment: Excellent and thanks for your patience. Others still confused by this issue I found the vignette from Bill Venables's "codingMatrices" package (whcih I have only just discovered) really helped clarify the difference between coding matrices and contrast matrices.
Comment: I simply don't pay attention to the regression coefficients at all, unless perhaps in an ordinary multiple regression situation with no factors. I think packages like my **emmeans** simply make it unnecessary to try to interpret regression coefficients. What matters is what the model predicts, and how much some predictions differ from other predictions.


Odds and expected value in betting

Question: I'm reading an article about expected value in betting, I got stuck at the very beginning:

Let's use a coin toss as an example of calculating expected value.
Assuming the coin and the toss are fair, each outcome (heads or tails)
has an equal probability of 50% - therefore the odds offered on a fair
market would be 2.0.
This would result in an EV of 0 for either a Head or Tail - because
the probability of the two outcomes is the same, so if you tossed a
coin infinitely it would theoretically end up all square.

I think odds =  p / (1 - p) so in this case, where the probability of landing head or tail is 0.5 so the odds should be 0.5 / (1 - 0.5) = 1? And the next point,

If however you were offered odds of 2.15 for the coin to land on
heads, this is a value bet.
If you placed £10 on the coin landing on heads at 2.15, the EV is
calculated likewise:
(11.50 X 0.5) – (10 X 0.5) = 0.75 This shows an EV of 0.75. Therefore
you would expect to make an average profit of 75p for each £10 bet,
because the odds received are better than the implied odds of the coin
toss.

How is the expected value actually calculated? Where is that number "11.5" from?
The article link: https://help.smarkets.com/hc/en-gb/articles/214554985-How-to-calculate-expected-value-in-betting
Answer: I think I get it now. The odds mentioned in the article is the decimal odds (not the "standard" odds ratio that I was thinking). Having understood the decimal odds, I can calculate the expected value.
Answer: If the odds would be 1 than each player who wins the coin toss just get back his bet instead of winning anything from the other player.  The expected value is calculated by the probability of winning x the potential outcome in the case of winning - the probability that you lose x your loss.
The 11.50 can be calculated by 10 (your bet) x 1.15 (your expected winning ratio).

Odds and expected value in betting


How to compare alphanumeric values in Perl?

Question: Here is my code-
print $cpu_arch."\n";
if ($cpu_arch eq'AMD64') {
    print "Remote machine is 64bit\n";
}

Depending upon the CPU architecture, $cpu_arch returns x86 or AMD64.
The problem is that no matter what $cpu_arch returns, the if loop condition is not getting satisfied. I've tried chomp'ing the $cpu_arch but that doesn't seem to help either.
Comment: Have you tried double quotes, like "AMD64"? Also, are you sure you're not getting extra whitespace? Regex comparison may be easier.
Answer: The operator for string is eq as you have. Your issue isn't in your operator it is in the data. More than likely you are buffering improperly ( change the $| variable ) or your $cpu_arch has trailing white-space. Or maybe you are looking for regex match and not literal match ( then you want /AMD64/ )
Comment: Thanks! Regex works just fine. Probably something wrong with buffering as you mentioned.
Comment: The regex working suggests that it's not a buffering issue but rather a trailing whitespace issue.
Comment: What the heck are you talking about when you say "buffering improperly"?
Comment: That is probably bad phrasing. What I mean is that STDOUT isn't flushing so it looks like nothing is printing when in fact it is, but your terminal isn't displaying it.
Answer: Your code is correct. Either $cpu_arch doesn't contain AMD64, or you are mistaken about the if condition being false (perhaps because of buffering).
The following might help you examine $cpu_arch.
use Data::Dumper;

{
   local $Data::Dumper::Useqq = 1;
   print(Dumper($cpu_arch));
}


Why doesn't static route work here?

Question: I am studying the course of CCNA all by myself, and I've been trying to set up a really simple network with only two hosts and two routers on Cisco Packet Tracer. The problem here is that I cannot ping router0 from laptop0 without using a dynamic routing protocol(I tried RIP, which proved successful, so there is no problem with the ip configuration...).

I tried configuring a static route on router1 with the following command:
router(config)#ip route 192.168.10.0 255.255.255.0 192.168.10.2
and I also tried the default route command:
router(config)#ip route 0.0.0.0 0.0.0.0 192.168.10.2
Both of these two commands proved useless.
Please kindly advise me what is the problem here...
Thank you in advance!
Answer: You will need to configure static routes on both devices. Try this configuration:
on 192.168.10.1
ip route 192.168.30.0 255.255.255.0 192.168.10.2
on 192.168.10.2
ip route 192.168.20.0 255.255.255.0 192.168.10.1
Also notice you shouldn't need to configure routes to the directly connected networks. When you configure the ip address and subnet on that it should add a connected route.
Comment: Thank you for the answer, sir, really helpful, I forgot the Ping command is somewhat a "two-way" street. :-)
Comment: But... if I do not configure the directly connected route, that is, if I do not use RIP or static route command like above, I would not be able to ping router0 from host0, is it a problem with the software Cisco Packet Tracer?
Comment: Sorry I am a little confused with what you are saying. So for the directly connected routes when you do interface XXX ip address YYY that should add a connected route for the given network. If yo do show ip routes you should be able to see these routes.
Comment: yes, the route should have been added right after I configured the ip addresses of the interfaces of all devices. For example, _show ip route_ on router1 produces the following results:

`C    192.168.10.0/24 is directly connected, FastEthernet0/0
C    192.168.20.0/24 is directly connected, FastEthernet0/1`

and _show ip route_ on router0 produces:

`C    192.168.10.0/24 is directly connected, FastEthernet0/0
C    192.168.30.0/24 is directly connected, FastEthernet0/1`

hmmm, should I add "192.168.0.20/24" to router0? !
Comment: The problem is solved, thank you so much for your answer. ;-)
Answer: firstly i aggre with David Mokon Bond for his answer. You can use also this way for default routing:
on router 1: ip route 0.0.0.0 0.0.0.0 192.168.10.2
on router 0: ip route 0.0.0.0 0.0.0.0 192.168.10.1

Why doesn't static route work here?


How do I include the main navigation block twice?

Question: How can I put one block, for example the main navigation block, in two different regions. In Drupal 7 this was possible through the Menu Block module, but as this module won't be ported to Drupal 8, I guess there is an other method.
Answer: This functionality is present out of the box in Drupal 8. You can actually place the same block multiple times in different regions.
For adding a block multiple times:

Go to Admin -> Structure -> Block layout (/admin/structure/block).
Click on "Place block" button besides the region name.
Select any block you wish to add to that region.

Follow the same steps to add block to a different region.
Comment: Great improvement! Don't know, why I didn't saw this!


how to maintain scroll position of ListView when database data change

Question: I am making chat view which contains plain and image messages..I am using ListView and costumised CursorAdapter .My problem is when anything change in database like updating seen ,sent or delivered status ListView just scroll position to bottom.how to keep position same.Thanks
Comment: Experiencing same issue with recyclerview too...
Answer: I solve the problem by removing the following line from ListView attribute android: transcriptMode="alwaysScroll"


Comparing variable-length pitch contours

Question: Robert Morris defined a contour segment of a set of n pitches as a list of numbers from 0 to n, where each number corresponds to the relative height of its corresponding pitch (for instance, <142320> indicates that the second note is the highest, the last note is the lowest, and the third and fifth notes are the same height).  He also defined a reduction of a contour segment as four numbers describing the relative position of just the first, last, highest, and lowest pitches.
I am interested in a measure of similarity between contour segments of varying numbers of pitches.  I do not want to just reduce each segment to four numbers.  How can I retain the information in the pitch sets while comparing them to each other in a meaningful way?
Comment: Do you mean like have a distinct number for each pitch? Are you aware of MIDI note numbers?
Answer: It's in the nature of metrics that any individual metric will ignore a lot of the information relating to the specimen. But for the purposes of comparison, don't think of evaluating a metric as throwing away information; think of it as gathering one piece of information. If you need more information, take more metrics.
It may be that your particular notion of similarity requires the use of more than one metric at a time. We can see this from the reduction that you describe - it actually in itself contains four different metrics. Perhaps none of those individual metrics seem to say much about a segment; together, they may seem more informative.
It's fairly straightforward to think of more metrics that you can do on a segment. In fact in googling "Robert Morris pitch contours", most of the highest hits relate to people making their own extensions to the ideas. In general, people aren't shy about proposing their own ideas on what might be considered important metrics, in many cases without particularly rigorous psychoacoustic underpinnings. So feel free to make up your own!
Some ideas:

Number of local minima
Number of local maxima
Overall range (highest pitch to lowest pitch)
Start-pitch to end-pitch range
longest number of consecutive +, or -
Longest repeating pattern of +/- movements - e.g. if a segment moves: +--+--, it has two repeating patterns of length 3
ratio of + to - movements
average pitch (mean, median, mode)
statistical deviation from average pitch
largest difference between consecutive pitches