Reset the values on Modal box on reload

Question: Reset the values on Modal box on reload

            <button type="button" class="close" data-dismiss="modal">
            ×
            Close
            </button>

               Create Job Vaccination

         <form name="vaccjobctrl.vaccineForm" class="form-inline" >

                     Screening Type:

                        <select style="width: 100%;"
                           ng-model="vaccjobctrl.vaccineForm.screeningTypeMast.screeningTypeId"
                           ng-options="sctype.screeningTypeId as sctype.screeningType for sctype in vaccjobctrl.screeningTypeList"
                           class="form-control field-size ng-pristine ng-invalid ng-invalid-required ng-valid-maxlength ng-touched" name="screeningType"
                           id="screeningType" required>
                           <option value="">--SELECT--</option>
                           <option value="{{sctype.screeningTypeId}}">{{sctype.screeningType}}</option>
                        </select>

               <button type="button" class="btn btn-default" data-dismiss="modal">
               Cancel
               </button>
               <button type="button" class="btn btn-primary-joli"  ng-click="vaccjobctrl.saveJobVaccination(vaccjobctrl.vacc);" ng-disabled="vaccjobctrl.vaccineForm.$invalid" data-dismiss="modal">
               Create Vaccination
               </button>

         </form>

this is the modal box.
On click on open Modal this function will be called
vm.showModal = function() {
      $('#detailsModal').modal('show');
};

values in the select box are pre-populated, on reopening the modal box it show the previously selected values. If trying to clear that the the select box border color changed to red on reopen.
Answer: In Bootstrap 3 you can reset your form after your modal window has been closed as follows:
$('.modal').on('hidden.bs.modal', function(){
    $(this).find('form')[0].reset();
});

You can just reset any content manually when modal is hidden.
HTML:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch modal
</button>

        <button type="button" class="close" data-dismiss="modal">×Close
        </button>

Modal title

Close and open, I will be gone!

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

You can use:
$(".modal").on("hidden.bs.modal", function(){
    $(".modal-body1").html("");
});

You can do more like:
$(document).ready(function() {
  $(".modal").on("hidden.bs.modal", function() {
    $(".modal-body1").html("Where did he go?!?!?!");
  });
});

There are more about them in http://getbootstrap.com/javascript/#modals-usage.
UPDATE AS PER YOUR NEED:
If you want to do it angular way, use the jquery src above angularjs source in index.html. You can simply use the jquery functions inside the angularjs controller.
Working JsFiddle: http://jsfiddle.net/tnq86/15/
For using document.ready function in angular.
 angular.module('MyApp', [])

.controller('MyCtrl', [function() {
    angular.element(document).ready(function () {
        document.getElementById('msg').innerHTML = 'Hello';
    });
}]);

However Creating directive is the right way to do it. Follow the link to get some help with creating directive to execute jquery functions in angularjs.
jquery in angularjs using directive
Comment: Is there any angular js way of doing this ?
Comment: Normally, when you have to do external script stuffs such as jquery in angular you have to create directive. That is the correct way of doing it. work around is simply inject the jquery source and embed the code in script tag to that page.

Reset the values on Modal box on reload


Como alterar outro elemento com CSS puro?

Question: Como consigo alterar um outro element com CSS Puro, a partir de um elemento?
Tentei fazer isso mas não rolou. Não conheço a fundo os seletores e maravilhas do CSS.

input {
  display: block;
  transition: top .3s, left .3s;
}
label {
  position: relative;
  top: 17px;
  font-size: 12px;
  left: 5px;
}
input:focus ~ label {
  top: 0px;
  left: 0px;
}
Label
<input type="text">

O que quero fazer é ao focar no input, subir o label com CSS puro.
Comment: Beleza. Acho que seria importante ter essa descrição na pergunta.
Comment: O label é pra ficar dentro do input mesmo?
Comment: Quero fazer a mesma coisa do Materialize, quando clicar no input o label volta para sua posição inicial. So que preciso  no focus do input, alterar a posição do label e não sei se é possível fazer isso com CSS puro, essa é minha esperança. Abs
Answer: Você pode fazer assim:

div {
  position: relative;
}
input {
  display: block;
  transition: top .3s, left .3s;
  position: relative;
  top: 17px;
  font-size: 12px;
}
label {
  transition: .2s linear;
  position: absolute;
  top: 20px;
  font-size: 12px;
  left: 5px;
}
input:focus + label {
  top: 0px;
  left: 0px;
}

  <input type="text">
  Label

Basicamente peguei seu input e label adicionei dentro de uma div e troquei de posição, o seletor "+" significa que sera pego o elemento imediatamente precedido, no caso "input:focus + label", quando o input estiver focado ele pegara o próximo elemento label, troquei alguns posicionamentos do seu css e adicionei o "transition: .2s linear;", ele sera responsável pela animação suave do texto subindo.
O seletor "~" também iria funcionar, mais no caso, todas as label para baixo também aplicaria o efeito.
Comment: Explicado, espero ter ajudado!
Comment: Perfeito cara, era exatamente isso que queria! Obrigado e bem vindo!
Comment: Eu que agradeço!
Comment: @VictorPereira gostei demais do exemplo, se explicar tem o meu +1


I need to find the formula for the truth table by using ∨ ∧ ¬

Question: This is the process I did, but I'm not sure if the procedure is correct:
P | Q | ?
F | F | F
F | T | T
T | F | T
T | T | F
(¬P ∧ Q) ∨ (P ∧ ¬Q)
=> ((¬P ∧ Q) ∨ P) ∧ ((¬P ∧ Q) ∨ ¬Q)
=> (P ∨ Q) ∧ (¬P ∨ ¬Q)
Comment: But a general procedure is: consider the rows in which the table outputs T and write a disjunct  corresponding to each row where the single disjunct is a conjunction made of prop letter (if it occurs in the row with T) or negation of a prop letter (if it occurs in the row with F).
Comment: The formula **must** be $P \lor Q$...
Comment: @MauroALLEGRANZA I wrote the last value of the table wrong. It's supposed to be F
Comment: See also [this post](https://math.stackexchange.com/questions/10392/how-to-find-the-logical-formula-for-a-given-truth-table)
Answer: My apologies if this should be a comment, I don't have the rep. It's been a while since I learned this, but isn't it going to be $P \oplus Q$ or $P \veebar Q$, the XOR/exclusive or operator? Unless there is more information that's not available, that fits all of your datapoints.
Comment: Your are right. It's my mistake, I forgot to mention that I must only use ∨  ∧ ¬. I will edit the post.
Comment: Ah I see. In that case I agree with what you found - $(P\vee Q)\wedge (\neg P\vee \neg Q)$ works.


flexlm error on solaris

Question: I'm configuring a solaris server to be used with flexlm license system.
My software provider provided the script to install Flexlm, and I have its license.
I launched the script, which asks me for the path for the default installation, the path for the license, and at the end it says that the license is installed well.
The problem is the response when the script launches "lmgrd", which is:
nohup: (path of the installation)...lmgrd: Invalid argument
I'm stuck with this.
Can anyone give me some advise to work around this problem?
It's my first try with Flexlm on a non-windows machine and everything appears much more complicated than the straightforward installat
Answer: The first question I would ask is "does the path exist on that server?"
Can you cd /path/to/your/installation and does that work?
The next question I would ask is; "Is there a symbolic link in the path somewhere?"
For example, if you gave FlexLM the installation path of /usr/local/my_app and the local directory in /usr is really a symbolic link to /mnt/local...
...then you need to use /mnt/local/my_app for the installation path.
It's been about 10 years since I setup a FlexLM server on Solaris, but FlexLM implementations can be customized by the vendor that provides the software to you, so you might want to double-check with them.

flexlm error on solaris


Has no attribute getitem

Question: I'm trying to integrate Pagseguro (a brazilian payment service, similar to PayPal) with this lib
https://github.com/rochacbruno/python-pagseguro
But, I don't know how to access the data from notification that the service sends to me. This is my code:
notification_code = request.POST['notificationCode']
pg = PagSeguro(email="firstname.lastname@example.com", token="token")
notification_data = pg.check_notification(notification_code)
print notification_data['status']

In the las line I receive this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'PagSeguroNotificationResponse' object has no attribute '__getitem__'

Answer: The documentation in the README doesn't seem to match the code.  It looks like rather than notication_data being a dictionary it is an object that has attributes matching the dictionary keys from the README.
So this should work if you just change print notification_data['status'] to the following:
print notification_data.status

Has no attribute getitem


htmlspecialchars utf-8 returns empty string

Question: I'm doing a .php RSS generator and I have a problem trying to get data from my database in this line:
<description><![CDATA[<?=htmlspecialchars(utf8_substr($row['texto'], 0, 100), ENT_QUOTES, 'utf-8') ?>...]]></description>

Some entries show just fine, and others wont return any text... Any idea on what could be wrong?
This is all the code:
<?php

require('php/config.php');
require('php/db.php');
require('php/utils.php');

header("Content-type: application/xml");

$db = new TSQL('SELECT * FROM entradas WHERE estado = 1 ORDER BY fecha DESC LIMIT 20');
if ( $db->executeQuery() ) {

?><?='<?xml version="1.0" encoding="utf-8" ?>' ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Tu Secreto</title>
        <link>http://www.tusecreto.com.ar/</link>
        <description>TuSecreto / No se lo cuentes a nadie, contaselo a todos</description>
        <language>es-ar</language>
        <copyright>TuSecreto (C) 2005-<?php print strftime("%Y", time()); ?></copyright>
        <lastBuildDate><?=strftime("%a, %d %b %Y %H:%M:%S ", $row['fecha']) ?></lastBuildDate>
        <atom:link href="http://www.tusecreto.com.ar/rss.php" rel="self" type="application/rss+xml" />
        <docs>http://www.tusecreto.com.ar/rss.php</docs>
        <generator>TuSecreto RSS Generator v1.0</generator>
        <ttl>10</ttl>
        <? while ($row = $db->getRow(MYSQL_ASSOC)) { ?>
        <item>
            <title><?=($row['sexo'] == MUJER)?'Mujer':'Hombre' ?> | <?=$row['edad'] ?> <?="A\xC3\xB1os" ?></title>
            <description><![CDATA[<?=htmlspecialchars(utf8_substr($row['texto'], 0, 100), ENT_QUOTES, 'utf-8') ?>...]]></description>
            <link>http://www.tusecreto.com.ar/<?=$row['id'] ?></link>
            <guid isPermaLink="true">http://www.tusecreto.com.ar/<?=$row['id'] ?></guid>
            <pubDate><?=strftime("%a, %d %b %Y %H:%M:%S ", $row['fecha']) ?></pubDate>
        </item>
        <?php } ?>
    </channel>
</rss>

This is one result that returns an empty string:

una vez en el colectivo (sentada en el asiento individual) me dormí y cuando doblo me caí en el pasillo re mal! se mataron de la risa todos!! hasta el colectivero! Pasalo y comento con mi Facebook. E.P.
Comment: How is `utf8_substr` defined?
Comment: Give an example of some that are resulting in the return of an empty string.
Comment: I've updated the post with all the code and one result... Maybe it's because the accented characters? "dormí". Is spanish...
Answer: Your code uses htmlspecialchars($string, ENT_QUOTES, 'utf-8'). Quoting from the manpage

If the input string contains an invalid code unit sequence within the
  given encoding an empty string will be returned, unless either the
  ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Use e.g. htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'utf-8') as a quick workaround.
If invalid input is indeed your problem, of course, you should find out why utf8_substr($row['texto'], 0, 100) does not return a valid UTF-8 string in the first place.
Comment: (1) The default isn't `ENT_QUOTES` but `ENT_COMPAT`. (2) What the doc says about `ENT_IGNORE`: "Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications." (3) `ENT_SUBSTITURE` is only available starting from PHP 5.4.0
Comment: Definitely do not ignore this error with `ENT_IGNORE` as this has security implications, per the docs.
Answer: This is still unresolved, and I recently found a solution to a problem I had similar to this: abnormal characters would make the function print an empty string. Therefore I intend to place my input.
In the flags area, add " | ENT_SUBSTITUTE" and change the encoding type to "cp1252." The ENT_SUBSTITUTE flag will ensure to replace any unrecognized characters instead of creating an empty string. The encoding type "cp1252" is Windows-specific however, and I suggest looking at the other types on the manual page if it does not work (https://www.php.net/manual/en/function.htmlspecialchars.php). (I presumed why this encoding worked for me was because my server is running on Windows IIS)
EDIT: You also have the option to remove the encoding type in XML files, and PHP will work fine with it.


Hiding features from your client

Question: I have to automate a yes/no type business decision problem for a customer (think: Is the use of chemical compound X beneficial in combination with chemicals A,B,C?). He dumped on me a very large dataset that contains all the data that I need (and much more) and basically said "I don't care what you do, as long as in the end a yes or no answer comes out in which I can be fairly confident".
From this dataset I tried various sets of features, so that I can achieve a very good prediction score via a binary classification algorithm.
This model I have incorporated in a software that I will deliver to him, where the input is his whole dataset. Internally the software then computes the features that I have identified in my own analysis as being good ones and makes the prediction.
The problem is: The customer now wants me to prove to him that the good prediction score that I claim is actually true. But it seems to me I cannot prove that to him, unless I give him a good part of my features, so that he can check himself, which I don´t want to do, since that is my IP....
Comment: "The customer now wants me to prove to him that the good prediction score that I claim is actually true." You should ask how the customer wishes to do that. They can have your code, or send validation data without an outcome, for them to cross reference... "But it seems to me I cannot prove that to him, unless I give him a good part of my features": that is the last conclusion I would make.
Answer:
The customer now wants me to prove to him that the good prediction score that I claim is actually true

As analytical chemist, I think this a totally valid request. It is part of the necessary method validation.
As business owner, I'd say that who is to do the work (you, the customer themselves or a third, independent party) is a matter of contract and possibly regulations. Likewise, the question of whether the features should be handed over to the client is a matter of the contract/license.

But it seems to me I cannot prove that to him, unless I give him a good part of my features

I'm sorry to be so harsh, but at least in the context of analytical chemistry/chemometrics (which your application description hints at as the relevant field) this is so blatantly wrong that it would make me quite wary in accepting any claim of your's about the predictive quality of your model.

Verification of your model's predictive performance can (and should) be done with a (well designed) test of test cases which are subject to blinded or double-blinded prediction.
Depending on the application, this may be subject to regulations that may even prescribe these blinded tests to be done by an independent third party, in regular ring trials or the like.
While we work a lot with resampling validation up to some point, we are also aware of the limitations of resampling: it is often very hard (or plainly impossible within a given dataset) to achieve statistical independence in the splitting procedure for resampling. To the point where it is usually less expensive to check performance against a set of new samples, where independence is easier to achieve (acquired later = comprises drift, at a different facility/reactor, etc.).
The client may be thinking of such a verification which would not imply that you reveal the features.
Validation has a wider scope, and as soon as your predictions do have a certain importance in term of harm that may be done by wrong predictions, I'd at least think it very desirable that the actually evaluated features are subject to some scrutiny during validation. I.e. customer (or the third party doing the validation) should compare your findings from the data with their knowledge about the application.
Even many kinds of models that are hard to interprete in terms of their features allow at least to check whether the evaluated features do not contradict with known behaviour of the application system.
So in the context of such a wider validation, I'd think it a sensible request from the customer to ask for your features.

So I'd recommend to

find out what exactly the customer wants, and then
if they are asking for the features and your contract really does not include handing over the features, you can surely prepare an offer to them at which price you are willing to sell the features.
Comment: Thanks, Claudia! I'm not a chemist, but a data scientist in training, so I did not knew about these domain-specific issue. (And I apologize for answering so late, I got swept away with other projects and did not have time to follow up on this one until now.)
Comment: Could you please clarify two things in your answer: 1) What exactly do you mean by double-blinded **predictions**? I know of double-blinded (or triple-blinded) experiments, where various parts of the data of the experiment are not share to various parties involved in the experiment. But I haven't come across that term in terms of predictions of a statistical model.
Comment: 2) Could you please help me understand why one should use domain-knowledge to check whether "features do not contradict with known behaviour of the application system"? It seems to me to be an essential part of machine learning to precisely discover features (for example by using model selection, neural networks, or other techniques) that help to create a model that achieves excellent predictive performance, *even though those features might not seem very helpful, or compelling if one relies on domain knowledge of the application system*.
Comment: For example, insurance companies might detect that people that drive blue cars have more accidents (and thus would raise their premium for owners of blue cars), even though domain knowledge at first would suggest that the feature "car_color" should not influence significantly driving behavior. Only statistics can discover it (One could imagine that darker cars perhaps are less easier to spot- that actually make this feature relevant; though without further testing we won't know the exact reason of relevance of the feature).
Comment: So we should not use domain knowledge to verify features, as you implied -  but rather use discovered features to improve domain knowledge. (If you don't like the "car_color" example, one can always some come up with other features that seem even more obscure when relying in domain knowledge but might make sense statistically.) Also, please note that it is not my goal to be polemic here, and I apologize in advance if I sounded so. I know that I'm still in training, so if you see a flaw in the argument above, please point it out.
Comment: blinding for validation: no, the term is not standard. What I mean here is that I've met *a lot* of mdoel validation/verification results that actually were far from being as independent as claimed/considered, for various reasons ranging from dependence in the data that was not known to or suspected by the data analyst over computational short cuts that use unrealistic assumptions long forgotten all the way to cheating (which in accordance with Hanlon's razor I think is rare). Very similar problems have existed for a long time when determining whether medical procedures or drugs are efficient.
Comment: I see resampling validation or a hold-out test set set aside by the data analyst who trains the model as analog to single-blinding (the model isn't told what the outcome is). Test data that the data analyst receives without knowing outcome themselves would be analog to double-blind (avoiding inadvertently giving hints - e.g. via dependence due to clusters in the data the analyst doesn't realize). Note that this is still just verification. (I'm not so sure we need a direct analogy to triple blinding - at least not before we have established good design of validation experiment practices).
Comment: So: blinding is a technique to improve independence of validation data. As you say, ML can be used to *discover* features. But after that we need to validate the features and/or the quality of the predictions. This is done by data independent of the data you used for training the model. And while maybe not as convenient for you and not as easily included in numerical descriptions of model validity, chemical knowledge can be used here (in several ways). And it can be highly efficient in the sense that it may allow to concentrate experimental effort during validation to some crucial points ...
Comment: (i.e. to narrow down the design of the validation experiment, or to put dedicated stress tests on crucial features) compared to needing *huge* numbers of test cases without such knowlege that guides the DoE. Your blue car example is IMHO actually a nice example. a) Note how you immediately start to propose possible (understandable, causative) mechanisms *why* blue cars are more prone to accidents. So the next step would be to check literature/domain knowlege whether blue cars have been known to be more prone to accidents and whether/which reasons have been proposed. You are correct to say that
Comment: without further experiment we cannot say more than that the training algorithm found a correlation in the training data. But knowing that the training algorithm found "blue cars" is crucial for formulating these further experiments. Including formulating alternatives that may be correlated with blue cars (dark car rather than blue car; in a chemical setting maybe the pH feature was a surrogate for acetic acid - or the other way round). For the insurance company it may very well be sufficient to know that a car being blue needs to be compensated by an additional fee of at least $x$. Now imagine
Comment: ... the underlying reason is that blue cars were the fashion n years ago, so they are now the age cohors (car wise) that is predominantly driven by young drivers who are more prone to accidents (as you don't know the underlying chemistry, you may be able to spot a correlation iff driver age happens to be among your features. If not, tough luck. But even so, you are not able to decide which of the correlated features is the primary reason). Now, the insurance company can show their blue car owners data that they belong to a risk group, and charge tham accordingly. If that's spurious, it doesn't
Answer: You could provide the predictions themselves and have your client compare them to the observed values himself. But then your client has no guarantee that you trained the model properly, with cross-validation or something, instead of just giving him back the observed values with a little noise added to make them look like predictions. In general, the client has no way to check that the model isn't cheating in some sense without being able to see the model.
An exception would be if the client sends you only the covariates for some observations, keeping the true corresponding values of the dependent variable to himself. He could then get predictions from you which he knows you couldn't have cheated to get. But this is only an option if he hasn't already given you all the data he has, or he can get more data.
Even more generally, it's never wise to make decisions with proprietary software, especially software you can't even see the source code of. Instead of putting a client in this position, make your work transparent and publish your source code.
Comment: In my experience, there's a whole lot of proprietary software in (analytical) chemistry. But I think it decidedly unusual for the client to not get the full information about the model (*all* parameters + hyperparameters + specifications, including all pre-processing/feature calculation) in a model developed as contract work. For such contract work, I'd have expected an exclusive license of the model to the client (which wouldn't allow OP to retain the features for reuse).

Hiding features from your client


How can I use rsync from serverA to serverB via USB hard disk drives?

Question: I'm trying to syncronize two NAS remotely located. They run FreeNAS 8.0.3 and I've been using rsync to syncronize data over the Internet. The sync literally copies NAS1 to NAS2. Unfortunately, the internet pipe is not big enough and I'm now about 100Gb off sync.
I wrote a script on NAS1 that using <code>--dry-run</code> writes the list of files to sync. I now would like to use this list to copy data from NAS1 into a USB hard disk drive that can be carried over manually and plugged into NAS2.
I haven't tested it yet, but in theory it works. I'm just concerned that file attributes will not be maintained when copying from NAS1 to USB and from USB to NAS2. Thus, when running my overnight rsync-over-the-internet it will find the files, but with different attributes and decides to overwrite them.
Is there any way to work around this attributes problem? Disabling the attributes checks is not an option.
Answer: As SvenW says, format the USB drive in the native filesystem for FreeNAS, and you should be fine.
Alternatively, tar up the files from NAS1 to the hard drive.  That should insulate the attributes regardless of the the filesystem of the hard drive.
I think attribute changes will not cause rsync to transfer the file again, anyway.  rsync should just be changing the attributes in that case.
Answer: I don't know FreeNAS, but if you can connect an USB disk with an ext3/4 filesystem (or whatever is native to it), the attributes should be transferred correctly. \


accepts_nested_attributes_for - Preventing destroy on primary model?

Question: I have a photo gallery that has a Gallery model and an Asset model. See below:
class Gallery < ActiveRecord::Base
  attr_accessible :gallery_name, :description, :assets_attributes
  has_many :assets, :dependent => :destroy
  accepts_nested_attributes_for :assets, :allow_destroy => true

  def find_featured_image
    assets.featured
  end

  def find_only_featured
   assets.only_featured
  end

class Asset < ActiveRecord::Base
  belongs_to :gallery

  has_attached_file :image,
    :styles => {
      :thumb => '150x150#',
      :medium => '300x300>',
      :large => '600x600>'
    }

  def self.featured
    where( :featured => true ).limit(1)
  end

  scope :only_featured, where(:featured => true)

end
end

I am able to destroy the assets through my Gallery form, but when I try to destroy the Gallery itself, I am simply redirected to the Show view with no confirmation notice.
Here is my form:

MDN Photo Gallery

    <% @galleries.each do |gallery| %>

<%= gallery.gallery_name %>

<%= gallery.description %>

                <% for asset in gallery.assets.featured %>
                  <%= link_to( image_tag(asset.image.url(:medium)), asset.image.url(:large), :class => "fancybox", :rel => gallery.id ) %>
                <% end %>

            <% for asset in gallery.assets %>
              <%= link_to( image_tag(asset.image.url(:thumb)), asset.image.url(:large), :class => "fancybox", :rel => gallery.id ) %>
            <% end %>

            <%= link_to 'Show', gallery %>
            <%= link_to 'Edit', edit_gallery_path(gallery) %>
            <%= link_to 'Destroy', gallery, :confirm => 'Are you sure?', :method => :delete %>

    <% end %>

<%= link_to 'New Gallery', new_gallery_path %>

I'm using the standard destroy method that gets created with scaffold:
def destroy
@gallery = Gallery.find(params[:id])
@gallery.destroy

respond_to do |format|
  format.html { redirect_to(galleries_url) }
  format.xml  { head :ok }
end

Is there some change I need to make to the model? the destroy method? anything else? in order to be able to delete the parent of the nested model?
Thanks in advance for your insights.
Any ideas?
Answer: It sounds there's something wrong with how the JavaScript support is being loaded. There's no way to have an anchor make a DELETE request directly, so Rails uses JavaScript to respond to the link's click event, and then make the proper request. Without that, the link simply acts as a GET.
Comment: Do you happen to know which .js library in rails is responsible for this? Perhaps the loading order of javascripts has something to do with this.
Comment: Which version of Rails are you using? If prior to 3.1, have you installed jQuery support, or are you using the default Prototype support?
Comment: I'm using v3.0.3. I am not familiar with the need to install JQuery support. I added JQuery to the default Prototype support. Do you have a link you can refer me to? Thanks!
Answer: I found this discussion on another site that describes exactly the situation I'm faced with:
http://railsforum.com/viewtopic.php?id=38460
The recommendation was made to use the button_to instead of the standard link_to for purposes of security against web bots. I had not heard that before.
Also it was observed that the absence of the <%= csrf_meta_tag %> was found and that the original issue went away and the link_to worked. That is not the case for me.
So now I have a button_for and am able to destroy the record. However, I am not getting the confirmation notice (:confirm). So there is still something wrong, but I can at least deal with the need to delete the record.
Answer: I am now able to get the confirmation notification working (:confirm). What I had done was changed javascript_include_tag :defaults to javascript_include_tag :all. I had forgotten I made that change. I'm not sure what is included when the :defaults method is called, but just wanted to let anyone else running into this problem know that is how I fixed it. Sounds like using the Button_to instead of Link_to is still the best solution even though link_to will work now.


SVM low accuracy but significant p value

Question: I'm also new at doing SVM...
We have a data set of about 50 (25 in each group). We are trying to identify babies at a high risk of developing a disorder from babies that are low risk for developing a disorder. When I run SVM (LOOCV, linear kernal, ttest filtering), I'm getting really low accuracy levels (i.e. 24% in one case), but with statistically significant p-values. Can anyone help me understand why this is happening/what this could mean?
Thanks!
Comment: Also, you're saying that you're getting worse than random chance (50%) accuracy?  So, based on your high level description: if you're doing a two-tailed t-test then you might be picking up significance in the wrong direction.  A one-tailed t-test might give you the proper (high) p-values you are expecting.
Comment: how do you calculate the p-values?
Comment: Some option is that your data contains meaningful information, but only enough to get a ~25% accuracy. Do you have any clue it is actually really low?
Comment: I'm running these analyses in MATLAB with the spider code and a wrapper written by someone else a while back. The code shows p_acc: binopdf(tp + tn, tp+fp+tn+fn, 0.5) (tp/fp = true/false pos & tn/fn = true/false neg)

I am not sure if it is truly that low. When I rerun the analyses on the 50 subjects using 100 or 200 features instead of 50 features, the accuracy goes up quite a bit. Not sure how to interpret this...
Comment: I'm a bit rusty on my MATLAB...does the binopdf function there test the hypothesis that arguments 1 and 2 are significantly different from each other?
Answer: It's possible that you don't have enough data to reliably use an SVM. That, and, in my experience, they tend to perform best with high-dimensional data (e.g., 1000s of variables). How many predictor variable are you working with?
As a more direct answer to your p-value question, you should look at what the p-value is actually associated with--are you saying that it's associated with the accuracy statistic, or something else?
Comment: Kyle - thanks, I have heard this as well and have been wondering if this might be part of the problem. So, what we are doing is taking two groups of 25 subjects (high risk and low risk for a disorder) and looking at various ROIs & their connections in the brain. Our matrices are 247x247x50. I posted a comment above to answer some other questions that may provide you with a little more information.

I believe the p value is associated with the accuracy statistic.


Method to show a time series of ~300 values is not stationary

Question: I have a data series with approximatelly 300 values. I want to show that it is not weakly stationary, that is, show as mathematically as possible that its mean or its standard deviation vary with time.
What would you recommend? I would like to be capable of implementing it on excel.
Comment: What did you do finally? Would be glad to know.
Answer: What about simply computing moving averages (MA) and moving variances (MV) so as to compare them side-by-side, respectively performing Welch's test for equality of means and F-test of equality of variances.
E.g. the variance over the period $t:t+n$ with the one over $t+\ell:t+n+\ell$, where $n\in(0,299-t-\ell]$ is the MV window size, $\ell\in(0,299-t-n]$ is the time distance between the two compared periods (possibly overlapping, but imperfectly), and $t\in[0,299−n-\ell]$. An illustration below

The F-test (1) as well as Welch's test (2) are easily doable with excel (see, e.g. (1) and (2)).
Comment: Any question @John ?


Cannot add 'Page Title' and 'Main Content' blocks to panel

Question: Configuration:

Drupal 8.1.5
Panels 8.x-3.0-beta4
Page Manager 8.x-1.0-alpha23
Layout plugin 8.x-1.0-alpha22
Panelizer 8.x-3.0-alpha2

When I create a Panel variant for /node/{node} with Page Manager, I can add field blocks, like

entity_field:node:title
entity_field:node:body

These get rendered.
However, if I add blocks

CORE / Page Title (page_title_block)
SYSTEM / Main page content (system_main_block)

these render to nothing.
Can someone explain why?
Answer: Answering my own question after I found some more info.
This is indeed a bug, hopefully to be fixed soon: https://www.drupal.org/node/2626090


Translate a PHP Array to a javascript array

Question: I'm trying to convert that PHP array :
<code>    Array
(
    [1] =>
Array
        (
            [ID] => 6927
            [Town] => Paris
            [latitude] => 48.867521
            [longitude] => 2.3317145
        )

    [2] => Array
        (
            [ID] => 6928
            [Town] => Paris
            [latitude] => 48.8615398
            [longitude] => 2.3496911
        )

    [3] => Array
        (
            [ID] => 6929
            [Town] => Paris
            [latitude] => 48.8675335
            [longitude] => 2.3292922
        )

    [4] => Array
        (
            [ID] => 6930
            [Town] => Paris
            [latitude] => 48.8686698
            [longitude] => 2.3413497
        )
</code>
to a javascript array, but I don't know how.
How can I do that?
Comment: echo "var my_js_array=" . json_encode( $my_php_array ) . ";";
Comment: You could have it print out and target it's container to convert to array. I don't know much about JSON but that's one way.
Answer: You need to translate this into JSON.
Have a look at this function http://php.net/manual/en/function.json-encode.php
Answer: Ever heard of JSON?
<code><?

$jsarray = json_encode($phpArray);

?>

<script>

var myArray = <? echo $jsarray; ?>;

</script>
</code>
And perhaps this helps: http://php.net/manual/en/ref.json.php


On the summability of Wold Form coefficients

Question: Let $y_{t}$ be a scalar stationary stochastic process with its Wold representation
$y_{t} = \mu_{t} + \sum_{k = 0}^{\infty} \phi_{k}\epsilon_{t-k}$.
I understand that the theorem says that $\sum_{k=0}^{\infty} \phi_{k}^2$ is finite. Although, we if assume that $Var(\epsilon_{t}) = \sigma^2, \forall t$, can we state that $\sum_{k=0}^{\infty} |\phi_{k}|$ is also finite?
I don't think so, but I would like some clarification. For example, if we let $\mu_{t} = 0, \forall t$ and $\phi_{k} = 1/k$ for every $k$, then the above conjecture fails. What do you guys think? Is this a valid counterexample? Thanks in advance!
Comment: I don't see how $\operatorname{Var}(\epsilon_t) = \sigma^2$ has anything to with whether $\sum_{k=0}^{\infty} |\phi_{k}|$ or $\sum_{k=0}^{\infty} |\phi_{k}|^2$ are finite.
Answer: Yes, that's a valid counterexample.
It might be fun/useful to think about this more broadly. An equivalent question to yours might be, "Are there sequences in $ℓ_2$, the space of square summable sequences, that aren't in $ℓ_1$, the space of absolutely convergent sequences?
Those sums you have are basically the p-norm.
The p-norm and its generalizations:

In a finite, $n$ dimensional vector space, the the p-norm is:
$$ \|\phi \|_p =  \left( \sum_{k=1}^n |\phi_k|^p \right) ^\frac{1}{p}$$
In a countably infinite $ℓ_p$ space, the p-norm is:
$$ \|\phi \|_p =  \left( \sum_{k=1}^\infty |\phi_k|^p \right) ^\frac{1}{p}$$
In $L_p$ spaces, the generalization for the p-norm  is:
$$ \|f\|_p = \left( \int_S |f|^p d \mu\right)^\frac{1}{p}$$

As described in this answer, $f(x) = \frac{1}{x}$ for $x >0$ and $f(0)=0$ is an example of a function that is in $L_2$ but not $L_1$.
Comment: Thanks! I have already some stuff on Lp spaces but I didn't see the link! That kind of stuff you learn in different course along life and fail to connect dots. Very welcome answer!


Can I accomplish this in Varnish?

Question: I have a website that fetches news articles via RSS feeds from many different sites. The script adds those articles to a mysql db. I display 10 articles per page over many many pages to the viewers.
Currently I am caching full pages and purging the cache every time the update script adds new articles to the database. It's fast but not very efficient. Pages cached only have a lifespan of a few minutes, even though the articles themselves can be cached for a longer time.
Can I use varnish to store the individual articles on cache? So every page generated would have links/pointers/references to the articles, instead of having the articles themselves in there. I can then cache those pages for a short period of time while caching the articles for much longer.
How would I go about doing this on Varnish or any other caching mechanism? Would that perform worse/same as full page caches on cache hit?
I'm on Ubuntu 12.04 and nginx.
Thanks!
Answer: You want to use edge side includes. Basically, your pages use ESI links like this:

  <esi:include src="/path/to/article/1"/>
  <esi:include src="/path/to/article/2"/>
  <esi:include src="/path/to/article/3"/>

Now in Varnish, have this:
sub vcl_fetch {
  set beresp.do_esi = true;
}

or in Varnish 4:
sub vcl_backend_response {
  set beresp.do_esi = true;
}

When the above code goes through Varnish, Varnish will replace each esi:include with the contents of the URL /path/to/article/1. You can cache the page itself for a few minutes, and each article for days.
Comment: Thank you so much for your reply!

"/path/to/article/1" would be something like "get-article.php?id=1" and that would be fine right? Varnish won't be hitting that file if it's already in cache I assume.

Having a dozen of those ESIs per page wouldn't be significantly slower than loading a cached page with the articles already in it?
Comment: Correct, that url is fine. Varnish doesn't parallelize requests, so each ESI include adds a small amount of loading time to uncached pages, depending on your backend (probably only a few ms). However, if you cache those pages it's not a big deal.
Comment: Thank you so much! Going to add Varnish now and will benchmark it against fastcgi-cache.

Can I accomplish this in Varnish?


Problem using smart home on Raspberry pi with integrated Alexa not certified?

Question: I have installed Alexa Voice Service (AVS) Device SDK on a Raspberry Pi.
I want to use smart home to turn on a led on my raspberry pi via the Alexa command.
To do this, I followed the following tutorial: https://developer.amazon.com/en-US/blogs/alexa/device-makers/2020/04/create-a-sample-alexa-built-in-disco-ball-with-smart-home-for-av
When I ask Alexa to turn on my led, the answer is "this feature is only supported by Alexa integrated devices".
I wait for Alexa to execute my request.
Is it really impossible to use this feature until the device is certified? Or have I done something wrong?
Thank you very much in advance for your help!
Answer: Your observation is correct. When you create your own AVS device using the AVS Device SDK, for example installing The AVS Device SDK on a Raspberry Pi, not all AVS features will be available.
That said, if your intent is to bring a product to market and would like access to a particular AVS feature, you may be interested in hiring a Systems Integrator (SI). Systems Integrators offer hardware modules, software, and services to help you easily integrate Alexa into connected products. For more information and a list of available SIs for hire, please visit the below resource:

https://developer.amazon.com/en-US/alexa/solution-providers/systems-integrators

Additionally, if you would like help with manufacturing an end device, you may be interested in hiring an Original Design Manufacturer (ODM). ODMs provide custom hardware and software design, development, certification, and manufacturing. For more information and a list of available ODMs for hire, please visit the below resource:

https://developer.amazon.com/en-US/alexa/solution-providers/odm-solutions


How can I create a Postgres user and database whenever I create a new rails app?

Question: I have followed this really helpful tutorial:
http://blog.willj.net/2011/05/31/setting-up-postgresql-for-ruby-on-rails-development-on-os-x/
I would really like to run rails new myapp and have the postgres db set up automatically. Is there any way I can do that using a Rails application template or something similar?
Comment: I suppose I could create a user and database that I use for all my little test applications. However for larger stuff I obviously want separate databases.
Answer: On a unix based system:
sudo -u postgres createuser -d -R -P APPNAME
sudo -u postgres createdb -O APPNAME APPNAME

You can create a script and put it somewhere in your $PATH if you can't remember.
Comment: Just for completion sake,
`createuser -d -R -P will create a user that can create a db (-d), can't create role (-R), and prompt for password(-P)`

http://www.postgresql.org/docs/9.1/static/app-createuser.html

`createdb -O will create a db with the specified owner (-O)`

http://www.postgresql.org/docs/9.1/static/app-createdb.html
Comment: You shouldn't need sudo for those command - only a "superuser" account for the Postgres database.
Answer: Actually you don't need to create a new user each time you create a new rails app.
All you have to do is create the new application and change the username in your database.yml
development:
  adapter: postgresql
  encoding: unicode
  database: newapp_development
  pool: 5
  username: #your username
  password:
...

than just:
rake db:create:all

Comment: You can create a database template... I haven't tried yet, but there is a [railscast](http://railscasts.com/episodes/148-app-templates-in-rails-2-3) about it.
Comment: Thanks for that. I didn't realise that. Is there anyway I can customise that database.yml file as it's created? I know it's two seconds to change it but I just like being able to quickly try out different ideas.
Comment: Really great screencast. I want to create a template.rb file with   `'config/database.yml',
%Q{stuff for database.yml here}` However I need to get the name of the app into the template.rb file. Is that possible?


Stored Procedures and Variables

Question: I made a stored procedure which has the following parameter: @UserName
Would that mean, in the ASP.NET, I would have to do the following code to update the value of username?
dbCommand.Parameters.Add("@UserName", SqlDbType.VarChar).Value = userName;

Or would this make a new parameter? If this just makes a new parameter, how can I just set the Parameter's value?
Answer: You can do something like dbCommand.Parameters.AddWithValue("@UserName", userName); or
dbCommand.Parameters.Add("@UserName", SqlDbType.VarChar);
dbCommand.Parameters["@UserName"].Value = userName;

Comment: What do each of those statements do?
Comment: The first one adds the parameter with an initial value. The second pair of lines adds the parameter, then edits the value.
Answer: dbCommand.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar)
    { Value = userName });

Comment: Adds a parameter to the collection with a value. I may have misunderstood your question.
Answer: That would create a new parameter.  Parameters is a collection that you can access by name, so you can do something like this to update an existing param:
dbCommand.Parameters["@UserName"] = userName;
Answer: It depends on your implementation.  Here are a few common cases:
If you're using a datasource in your mark-up, then just use the wizard to configure your datasource, and it will discover your parameter automatically.  Then you can see how it adds your parameter to your datasource's mark-up.
If you're using a datasource + code-behind, you can add parameters as you have in your post.  As long as you don't ALSO have the parameter in your datasource mark-up, this will be fine.
If you're using a datasource + code-behind, you can assign values to parameters it already has like this: .Parameters["@UserName"].defaultvalue = "some value"
If you're NOT using a datasource, and doing everything in code-behind, then you can do this: .Parameters.AddWithValue("@UserName", "some value, some text value of a control, etc.")

Stored Procedures and Variables


When taking a copy of the node template do you need to maintain the article tag that is in there

Question: When taking a copy of the node template, should you keep/maintain the original code that is in the file?
Example the article tag.
nid; ?>" class=" clearfix"> etc..
What are the implications of removing this, if any?
Comment: remove it and find out.
Comment: If you keep the original code then what is the point of making a copy. You are making the copy so that you can make changes.
Answer: Actually you're free to edit templates !

The theme's css might depend on some tags, especially the article tag, so you could lose layout/design
If you're a forward thinking brave drupalista you definitely want to keep title logic and the possibility of rendering all fields (and comments) and respect the view modes ;)


How to make Language Switcher Block work with unpublished nodes?

Question: On a multilingual Drupal 7 site, the Language Switcher Block used to work for both published and unpublished nodes.
Example:
node/1: English, alias=map, published
node/2: German, alias=karte, published
node/3: English, alias=table, unpublished
node/4: German, alias=tabelle, unpublished
On /node/1 or /map, the Language Switcher shows the link to German and it correctly links to /de/karte. This works also the other way around.
However, on /node/3 or /table, the block does show a link to German version, but it links to /de/node/3 instead of /de/tabelle. On the German version at /de/tabelle (or /de/node/4) the block links to /node/4 instead of /table.
As far as I know, this change was introduced between Drupal 7.24 and 7.28 and might even not be a Core issue. However, I couldn't find the source of this behaviour.
Does anyone know, if it is related to some Security Issue with unpublished nodes or where I could start looking further? I tried to find it inside core modules locale/translation and language.inc and also in i18n to no avail.
Answer: I was finally able to track this change down. The source lies within a security announcement which led to the i18n-7.x-1.11 update. In /sites/all/modules/i18n/i18n_node/i18n_node.module, l. 124 there's a new line reading
<code>'access' => !$matches[2] ? $node_translation->status : NULL,
</code>
This line shall prevent unauthorized users from even seeing the path alias of nodes they do not have access to. However, there's no real check of permissions, this line just allows the access based on the node's status. So, even for User 1 (Superadmin) the link to the translated node is inactive if the translation is unpublished.
Whether this is only a temporary fix because of the SA or even supposed to be a permanent solution, I don't know. But that's the way it is right now and if you need to switch between unpublished translations often, you might want to comment that line.
There is already an issue at d.o for that.


Is there any way to "linux nice" a process to have less priority

Question: We have some high resource views that would have less impact on the overall performance if they ran at a low priority, e.g. linux nice'd to a low priority.
Comment: This is borderline off-topic, but since it was just asked, I am going to let it sit for a bit.
Comment: @Pierre.Vriens `nice` (https://en.wikipedia.org/wiki/Nice_(Unix)) is a way to lower the priority of a process, so allow more important things to happen.
Comment: There isn't anything Drupal-specific; you just use something that would be used from who is running a WordPress site, or even a plain PHP site.
Comment: PHP performance or DB performance?
Comment: I am really looking for a Drupal module or code snippet that I can insert into a request so that it executes that specific request at a lower priority. Most views are well behaved but some access a large number of rows and peg the cpu while they run.
Answer: Well...
This is rather complicated to solve and probably not suitable for all available configurations. Given you don't reuse processes and the given php process terminates at the end of the request you can use proc_nice().
Next thing will be to be at the right spot to nice the process, does the heavy loading occur before executing? while executing? Also nicing the php process probably won't take any load of the mysql server or whatever other backend this process is requesting.
Looking at view::execute there's no way to distinguish at this point between cached views and uncached ones - so going that route we also have to nice processes which have a cache - probably something to think about.
Drupal 7 Implementation using hook_views_pre_execute().
<code>/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(&$view)) {
  if($view->name=="machine_name_of_my_view") {
    // http://php.net/manual/en/function.proc-nice.php
    // Setting something higher would lead to idle only processing.
    // Please refer to the documentation of proc_nice and nice.
    proc_nice(9);
  }
}
</code>
Drupal 8 implementation using hook_views_pre_execute():
<code>/**
 * Implements hook_views_pre_execute().
 */
function views_pre_execute(ViewExecutable $view) {
  if ($view->id() == 'machine_name_of_my_view') {
    // http://php.net/manual/en/function.proc-nice.php
    // Setting something higher would lead to idle only processing.
    // Please refer to the documentation of proc_nice and nice.
    proc_nice(9);
  }
}
</code>
Keep in mind that this solution requires quiet some constraints to work for you:

Heay load is actually in the php layer
proc_nice() is available (not all environments allow this)
dedicated php processes which terminates at the end


Generating functions of partition numbers

Question: I don't understand at all why:
\begin{equation}
\sum\limits_{n=0}^\infty p_n x^n = \prod\limits_{k=1}^\infty (1-x^k)^{-1}
\end{equation}
Where $p_n$ is the number of partitions of $n$. Specifically how can the sum of positive numbers ever be factored into a fraction or factors to the $-1$ power? Is this something purely notational or am I missing something big?
Thanks for all the help!
Answer: We have $\frac{1}{1-x^k}=1+x^k+x^{2k}+x^{3k}+\cdots$.  These are combined formally in a process known as generating functions.
More details, as requested.  We multiply out $(1+x+x^2+x^3+\cdots)(1+x^2+x^4+x^6+\cdots)(1+x^3+x^6+x^9+\cdots)(1+x^4+x^8+\cdots)\cdots$, and gather the powers of $x$, as if they were polynomials.  For example, $x^3$ has a coefficient of $3$ -- one term from $x^3\cdot 1\cdot 1\cdots$,  one term from $x^1\cdot x^2\cdot 1\cdots$, and one term from $1\cdot 1\cdot x^3\cdots$.  The first corresponds to $3=1+1+1$ (three 1's), the second corresponds to $3=2+1$ (one 2 and one 1), and the third corresponds to $3=3$ (one 3).
Comment: Okay I see that now. Could you explain the rest of the proof?


Name two reasons why the music in the next passage starts in C Major and ends in G major?

Question:
Please help with the question in the title. I am struggling so much, thank you.
Why?
Comment: Hi ANON. Welcome to Music Practice & Theory. Thanks for posting here. As a suggestion, you might wait a while before accepting an answer as others may weight in with additional information. In the meantime, it is certainly appropriate to upvote any answer you find helpful.
Comment: why _two_ reasons?
Comment: One way to analyze melodies and see how keys work is to look for the half steps. Try going through and marking all the places there is a half step in the music.
Comment: @MichaelCurtis - it's a homework question. Those sort can ask what they want!
Comment: @Tim, anyone can ask anything anytime
Comment: I also think it´s a homework. And I think this isn't a good example. If this is a real composition the double bar line might assign the middle  between the 1st and 2nd section, like e.g. of a Suite or a Sonatina, but usually these parts ar repeated.
Answer: The C major passage includes the C major leading tone (B) and emphasizes C major chord tones (C and E) by placing them in metrically strong locations (beats 1 and 2, and opposed to the Ds placed on the half-beats.)
Similarly, the G major passage includes the G major leading tone (F# -- which is not part of C major, thus suggesting a key change), and places G major chord tones (G and B) in metrically strong positions.
Comment: I'd argue that it ends **ON** G major rather than **IN** G major. Modulation rather than key change. Given that we don't know what precedes or follows - if any.
Answer: The premise of the question is pretty weak. C major as a key isn't really established. The main issue being the absence of the subdominant F natural. It's easy to hear the passage as a conclusion in G major outlining G: IV V I
Anyway, let's just say it moves from C major to G major. The question is why? And for some reason there needs to be two reasons.

Lots of music follows a convention of periodic phrasing where a first phrase ends on some kind of dominant harmony which is followed by a second phrase returning to the tonic chord. This passage is such an antecedent phrase.

The melody is a decoration of the tonic chord - the first beat of each bar outlines the tonic C chord C4 E4 G4. But the G4 being the dominant of C major has a dual role where it can be considered a tone of the tonic or dominant chords. This passage could easily be modified to treat G4 as a tone of the tonic C major chord. But it doesn't. Why? Another possibility, which may seems far-fetched, but you asked for two reasons, is an intension to use the line in inverted counterpoint. If the G4 were treated as the fifth of a C major chord, and then it was inverted to be in the bass, you would have a dissonant fourth in the harmony, which is a type of counterpoint problem. That problem is avoided by treating G4 to be the root of a G major chord, and inverting it into the bass won't be a problem.

Keep in mind you asked "why it starts in C and ends in G?" rather than something like "does this start in C and end in G?" Those are two very different questions - why versus is it? You are asking about motivations. In musical art you can do whatever you like any time you like. Reasons aren't necessarily required. My two suggested reasons are based on "classical" conventions.
Answer:
it may be a half cadence (G is the dominant of C) ... we expect a closing phrase ending on the tonic C: in this case the double bar sign (ending) wouldn't be correct.

the song is actually in G and you present the ending phrase: in this case we miss here an F# key-sign and the movable doremi-names are famifaso lasolati dosomire do

edit:
I assume this is a half close ending on the dominant key. There will follow another section leading back from G to C.
My answer is focussing the chord progression, while the question may ask why the first motif is in C and not G?
This is quite obvious: we have the key signature of C, the melody is on the accented beats on the C chord (with changing and passing tones. The F# shows the modulation to G, involving the triad dosomi of G.
Comment: Could it be a change in pitch? or not?
Comment: Given the double bar-line, a half-cadence seems unlikely.
Comment: No, the pitch doesn't  matter. If the F# would be F the secondary dominant D7 would be certainly  before the final G.
Comment: @Aaron: yes, then the answer will be: modulation to G but the double barline could still be a typo ...
Comment: If we allow for typos, then the answer could be anything at all.
Comment: Could it also be because there is an F#? C major does not have an F# ?
Comment: good point about the double barline!
Comment: Compare the French Suites by Bach: they usually have 2 sections: the 1st modulates to the dominant and is separated by a double bar line from the 2nd half of the piece, that continues with the dominant and leads back to the tonic.
Answer: The answer your test paper is looking for will mention the F♯ and the way the melody comes to rest on G, implying a perfect cadence in that key. (Careful about naming cadences.  I'm using the British method.  You may need to call it an Authentic Cadence.)
Others have suggested that the visit to G major is too brief to be considered a change of key.  Maybe.  We don't know what comes before and after this brief extract.  But I've given an answer within the terms of the question.  It is generally unproductive to challenge the terms of this sort of question!
Answer: Uh, it's just a cadence. Music needs to go somewhere, in Western music, that if frequently the dominant chord of the key you are in.
Answer: Theres no.indication that the music indeed switches to G major .
F# is in C major as the #11th . This is a consonant sound for the Key of C major . Remember the F natural is  a Dominant  function in the Key of C major .
The simplest way to understand  why is the look at how all 12 notes fit into The KEY of C major
C is root of C major
C# is b5th of G7
D is 9th of Cmajor or 5th of G7
D# is b13th of G7
E is 3rd of C major
F is 7th of G7
F# is #11th of C major tonic
G is 5th of Cmajor or root of G7
G# is b9th of G7
A is 6th of C major or 9th of G7
A# is #9th of G7
B is 3rd of G7 or 7th of Cmaj
C is root of C major
Here is Key of C major how all 12 notes belong to the tonic or dominant functions.
( the subdominant combines notes of these 2 functions)
Now even after demonstrating this,  let's say you are are the Key of C major but you are unwilling to use any extensions .
It is still factually true that strong beats are chord tones and weak beats are any of the 12 notes .
In the above passage the F# is on a weak beat
( another reason why it does not leave the key of C major )
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115617/discussion-between-mmj2020-and-aaron).
Answer: A,G,A,D, E,D,E,F#,G,D,B,A,G
Its all Cmajor chord tonic
( play a Cmajor chord in bass register below the melody it never changes chords or functions )
Its a melody in the C major Key on the tonic function.


If I start an Internet Radio Station, and later start a VPN, do the packets just flow across my network?

Question: Say I do the following on Windows 7 Ultimate:

Open iTunes and start an Internet Radio Station.
Then next I VPN into work.

Now at this point (I would think...) the that the iTunes radio station would be flowing over my network and not over the VPN.
But! Say I'm still logged in to the VPN and I need to restart iTunes and restart the radio station, does it now go through the VPN?  How can I tell?  Do I have to worry about this?  And can I change it so that iTunes travels through my network connection and not the VPN all the time?
Comment: How do you start an iTunes radio station? Do you mean listen to an iTunes radio station?
Comment: If the radio station is multi-cast, does the VPN allow multi-cast through?
Answer: Usually connections that DO NOT RELATE to VPN are using your normal routing rules applied to your machine and the network it's in. However, it's up to the sysadmin who configured the VPN server is to force ALL connections through VPN tunnel or not.
Comment: So I should probably ask the system admin then?
Comment: Yes, the setting is usually should be something similar to: "Force all connections through the tunnel"
Comment: They're running ipsec and a Cisco client, is there any way to find out from there?
Comment: Well, you can run `pathping` command while connected to VPN and when not, the output provided should give a hint.
Comment: pathping, that seems a little bit like tracert...is it not?
Comment: Tracert and pathping both use ICMP, which the VPN might treat differently than UDP, TCP, RTSP, etc...
Answer: It's not clear to me what you're asking but I'll give it a shot:
You're listening to an iTunes radio station, that stream is coming in to your computer from the internet, you then make a VPN connection and want to know if the stream is now coming in over the VPN connection? My take is that if the VPN connection is configured to use the default gateway on the remote network (VPN network) then the stream is going to stop and you'll need to restart it and yes it will then stream in from the VPN connection. If the VPN connection is not configured to use the default gateway on the remote network then the stream is not going to come in over the VPN connection.
This scenario is applicable whether you connect to the VPN before or after starting the stream.
Comment: the stream wouldn't necessessarily stop if he changed DGs, as the ACK might simply traverse the VPN, to the net, and back to the radio source. Alternatively, it might use UDP or something that doesn't require ACKs to keep it running. The client software might also auto-restart the connection when the VPN is started/stopped. Some VPN software (notably Cisco's) tries to intelligently route traffic regardless of DG configuration. In the end, your answer boils down to "maybe" which is the most correct given the question.
Answer: In my vpn properties (network/tcpip/properties again/advanced) I found a checkbox that was checked to use a defualt gateway on the remote network. once I unchecked it and disconnected/reconnected, I was able to get to web pages previously blocked by the corporate webfilter. I think this is what you may want to do.
After unchecking the box and disconnecting/reconnecting recheck to make sure the box is still unchecked...
Comment: this is exactly what Joe suggested already.


Is there a way to prevent stopping the audio in Spark AR on recording without disable the microphone?

Question: In my current project I have an Audio file which plays all the time. As soon as I click the record button the audio stops. When I disable the microphone it works but I actually want to record my own voice (like a karaoke) This Problem only occurs only on Android.
Is there any hack to fix this Problem?
Answer: Just worked on a filter where I had to build a karaoke style gameplay, what I noticed was Spark does not like playing audio AND recording on mic as it probably causes weird artifacting if not implemented properly. It seems like something that will be added line.
Possible fixes to get your filter working for now, add instructions to use the filter with headphones, connecting to an external audio device will let you play audio and record using the mic at the same time. This works on android, not on iOS. You have to give players visual cues to sing along or whatever your objective maybe.
Hope this is sorted out and fixed in the coming updates, really handicaps the kind of experiences possible on the platform.
Hope this helped.


Difference in times is returning a negative number

Question: I have this trial timer code to time euler solutions in Ruby.
$RUNS = 12
def run(solve)
  times = []
  $RUNS.times do
    start_t = Time.now.usec
    solve.call
    end_t = Time.now.usec
    times << (end_t - start_t)/1000.0
  end
  #times = times.delete_if {|i| i < 0}
  puts times.inspect
  times.sort

  mean = times.inject{|a,c| a+c} / $RUNS
  puts("Mean:\t#{mean}");
  if (times.length % 2 == 0) then
    median = (times[times.length / 2 - 1] + times[times.length / 2]) / 2.0
  else
    median = times[times.length / 2];
  end
  puts("Median: #{median}");

end

Unfortunately, I keep getting answers like this:
[409.805, 418.16, -582.23, 402.223, -581.94, 413.196, 426.816, -584.732, 519.457, -569.557, 558.918, -579.176]

What can I do to avoid these strange negative numbers?
Answer: usec returns the microseconds from the time in the same was as month returns the month. It is not the number of microseconds for the given time since the epoch.
So if start_t was 1049896564.259970 seconds and end_t was 1049896592.123130 seconds then you would get 123130 - 259970 if you subtracted the usecs. i.e. a negative number.
Instead you could use Time.now.to_f to convert to floating point number of seconds since epoch and subtract those from each other. You can also just subtract one Time object from another directly e.g.
start_t = Time.now
solve.call
end_t = Time.now
times << end_t - start_t

Comment: You should also take a look at [benchmark](http://ruby-doc.org/stdlib/libdoc/benchmark/rdoc/index.html) in the standard library, although if you look at the source for that I think it still just uses `to_f` when calculating time deltas.
Comment: Then how do I do high-granularity timing in ruby?
Comment: @JBristow Answer updated with a suggestion of how to do what you want.
Comment: It seems like this is asking for floating point errors, but I am multiplying by 1000 to get msec granularity.
Answer: Current time in seconds since the Epoch:
Time.now.to_f
=> 1278631398.143

That should have microsecond resolution, despite only three decimal places being shown here.


Converting response to arraybuffer

Question: I am trying to convert a response to arraybuffer with axios. I keep getting an error message: "TypeError: response.arrayBuffer is not a function". Below is the code I wrote and suggestion on what I am doing wrong or a solution to this error.
<code> axios
      .post("http://127.0.0.1:8000/api/file-api", formData, {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          'Access-Control-Allow-Origin':'http://localhost:8080',
          'Access-Control-Allow-Credentials': 'true',
          'Authorization': `bearer ${token}`

        },
      })
      .then((response) => response.arrayBuffer())
      .then((res) => {
        const arrayBuffer = res.arrayBuffer();
        const objUrl = window.URL.createObjectURL(new Blob([arrayBuffer]));
        return objUrl;

      })
      .catch((err) => {
        console.log(err);
      });
</code>
Comment: you seem to be using `axios` like it were `fetch` - you'd need `responseType: 'arraybuffer'` in the options you pass to axios.post if you want axios to return an arrayBuffer ... also you also seem to have a CORS issue and think sending CORS **response** headers in the **request** will bypass CORS ... it does not ... CORS is 100% controlled by the **server** - [learn CORS in 6 minuntes](https://www.youtube.com/watch?v=PNtFSVU-YTI) is a decent video if reading [documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) isn't your thing
Comment: or you could still use `axios` but use it correctly
Comment: Yes you are right about the CORS response issue. For now everything is running on a local server so I intend to fully resolve that when moving to production. I will try the fetch and see the result.  Thanks for link of the video. I hope it will be helpful.
Answer: After reading this post  [Axios vs. fetch(): Which is best for making HTTP requests?][1],
[1]: https://blog.logrocket.com/axios-vs-fetch-best-http-requests/#:~:text=Axios%20automatically%20transforms%20the%20data,info%20on%20what%20the%20response. and then the comment by @Bravo,
I notice using axios may not be able to provide an arraybuffer as a responseType.
In the case of arraybuffer, it is best to use fetch.

Converting response to arraybuffer


SELinux - canonical way of automatically applying a context on file creation

Question: My current understanding is that you have to manually use restorecon to apply the desired context to a newly created file or directory unless you are happy with the context that it inherits from its parent directory.
I am wondering if it is possible to automatically apply a context on creation based on its path without having to run restorecon.
I googled a bit and found this post by Dan Walsh where he mentions restorecond which uses inotify to change context on creation. He also points out the obvious problem with it (race condition). Is this the only way to automatically solve the issue of re-context-ing in case a child should not inherit its context from the parent directory?
One problem is that restorecond does not seem to handle entries the same way as /etc/selinux/targeted/contexts/files/file_contexts, that is, no regexes and it does not work recursively, so /etc/selinux/restorecond.conf cannot contain something like
/var/www(/.*)?/logs(/.*)?

or
/var/www/*

or even
/var/www/*/logs

Is there a way to work around this problem?
EDIT:
As per @Michael's answer this should work OOTB if a respective rule exists, but it doesn't:
# rm -rf /var/www/foo
# semanage fcontext -a -t httpd_log_t '/var/www/foo/logs'
# grep '/var/www.*logs' /etc/selinux/targeted/contexts/files/file_contexts*
/etc/selinux/targeted/contexts/files/file_contexts:/var/www(/.*)?/logs(/.*)?    system_u:object_r:httpd_log_t:s0
/etc/selinux/targeted/contexts/files/file_contexts.local:/var/www/foo/logs    system_u:object_r:httpd_log_t:s0
# matchpathcon /var/www/foo/logs
/var/www/foo/logs       system_u:object_r:httpd_log_t:s0
# mkdir -p /var/www/foo/logs
# touch /var/www/foo/logs/quux
# ls -alZ /var/www/foo/logs*
drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 .
drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 ..
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 quux
# restorecon -vR /var/www/foo
restorecon reset /var/www/foo/logs context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:httpd_log_t:s0
restorecon reset /var/www/foo/logs/quux context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:httpd_log_t:s0

Comment: Your regex looks fine. I think you may have found a bug.
Comment: @MichaelHampton This is a CentOS6 box. The regex in `file_contexts` ships with the installation. Since that did not work I added the second with `semanage fcontext` with a plain absolute path and no further regex magic, so I agree, that should work. I tried on both a CentOS 6.0 as well as a CentOS 6.3 server and it works on neither. Hm.
Comment: Hey, you're right, that did come with the system. I think it's time to yell at Dan Walsh :)
Answer: The kernel makes the following procedure to determine what the file type of a newly created file will be.

There exists in policy a specific file transition rule. So apply this.
Make the newly created file acquire the type of the parent directory.

In the vast majority of cases, new files inherit the parent directories type. Sometimes this is not desirable -- so a policy writer can create rules based off the conditions of who is doing the labelling and where in order to transition to another type.
This is controlled in policy with the type_transition statement, although normally a policy writer will call the filetrans_pattern macro instead.
In the kernel, these decisions are not based on paths but types (although a minor exception exists in newer policies).
A rule typically looks like this;
type_transition httpd_t var_log_t:file httpd_var_log_t;
In this example, the rule states that. If the process/user performing the file creation is httpd_t and the directory the object is being created in is var_log_t and the object is classified as a file, then the new file must be labelled as httpd_var_log_t.
This, of course has a number of limitations, a good example of this is the condition when you create .htaccess files in apache (in /var/www/html). In this example the default policy of creating a file type with the same type as its parent directory applies, but in reality the proper type of this file is httpd_sys_htacess_t not the default of httpd_sys_content_t.
This was a known problem for a number of years and was eventually fixed by allowing policy writers to specify the filename that the transition applies to in policy -- unfortunately this features is not available in EL6.
In your specific case -- as you have mentioned there are some workarounds involving restorecond. Other than this you should ideally split your data up with different types by putting them in separate subdirectories where the subdirectory is an adequately labelled type. If this is still not possible, and restorecond is not possible -- the only solution is a post-fix of running restorecon on the file after its creation.
Even the 'newer' named filetrans has problems because ultimately it does not support globbing or regex, which severely limits its functionality to specifically well-named files (like .htaccess).
As it stands at this moment, there exists no in-kernel mechanism as flexible as restorecon and its regexes to properly label files correctly to that degree.
Answer: The problem of correct labeling at file creation was addressed in Fedora 16 with a feature called file name transition (although you can find it also as "named file transitions"), whose definition basically states that:

With File Name Transitions Features, policy writers can write rules that take into account the file name, not the file path. This is the basename of the file path. Since the kernel knows at the time of object creation the label of the containing directory, the label of the process creating the object and the objects Name. we can now write a policy rule that states, if an unconfined_t process creates a file named resolv.conf in a directory labelled etc_t, the file should get labelled resolv.conf.

It is known that the way an object gets labeled at creation time can vary depending on the process creating the object (cp vs. mv is a good example). Also, the default way to label an object would be by inheritance: the object gets the label of the parent directory.
While this is convenient, it is not always correct, and the system administrator must correct the situation manually using (a combination of) restorecon + restorecond + semanage fcontext -a -t.
This is the problem Name File Transitions try to correct, by letting

[...] policy writers have the ability to overwrite this by writing a rule in policy that states, if a process with type a_t creates a object of class "file" in a directory labelled b_t, the object will get created c_t.

Obviously, named file transitions don't exist for custom locations. You could find already existing ones with, for example:
# sesearch -ASCT -s unconfined_t | grep Found
...
Found XX named file transition filename_trans:
...

So, in order to address your problem, you need to know beforehand which user (SELinux user) will create what file/directory and where, and then write a custom policy including a file transition. There are a couple of examples in the Fedora Project wiki page I linked above.
Comment: This will help in the future. But it doesn't do a lot of good on CentOS 6 today.
Answer: This is not a problem, you're just approaching it from the wrong direction.
If you want your own file contexts, just create your own using semanage fcontext. This does accept regular expressions.
Here is a common example, used to relocate the directory from which Apache serves files:
semanage fcontext -a -t httpd_sys_content_t "/volume1/web(/.*)?"

Feel free to adapt this to your own needs.
Comment: Exactly. I know all that and that was not the question (hence the `restoreconD` reference). What I want is automatic labelling on *creation* if the target file should get a different context than the parent directory *without* the need to run `restorecon` manually.
Comment: You misunderstood my question. `semanage fcontext` just creates the respective entry in `/etc/selinux/targeted/contexts/files/file_contexts.local` which `restorecon` honors and sets the context according to the regex when you run it. Of course, this is what I do anyway. What I want is the context to be set automatically without having to run `restorecon`, and just having a rule in place created by `semanage fcontext` does not achieve that.
Comment: This _is_ how you have the contexts set automatically. If it didn't work for you for some reason, you should ask a question about that.
Comment: No, you still need to run `restorecon` on the target file(s)/directory to relabel them.
Comment: Of course. This sets the default file context, and will apply to newly created files. If you want to apply it to existing files, you have to run `restorecon`.
Comment: And that is the question I answered.
Comment: OK, I had thought it would do that but it didn't. I will update my question and get back to you...thanks. But if that is how it is supposed to be in the first place, then what's the purpose of `restorecond`?
Comment: I edited the question, apparently I must be doing something wrong - please enlighten me.


How to make a prefilled doughnut in chart.js?

Question: I want to create a prefilled doughnut using chart.js like the picture below.
This doughnut is made of using SVG.

But chart.JS cannot support SVG's
So Is there any way to create a doughnut-like the Image above.
Comment: I'm not sure I understand the question. Have you taken a look at http://www.chartjs.org/samples/latest/charts/doughnut.html
Comment: I used doughnuts from chart.js in some of my works.But Now I want a doughnut with a prefilled grey line where I want to show the main doughnut's data over the prefilled doughnut line.Here is the link where the examples are given openstudio.redhat.com/… – Abdullah Al Mamun
Comment: @AbdullahAlMamun Please check answer. Isn't it that what you asked for?
Answer: It can be done this way:
var canvas = document.getElementById('myChart');
var data = {
  labels: ["1", "2"],
  datasets: [{
    data: [105, 20],
    backgroundColor: ['da5d78', 'gray'],
  }]
};

var options = {
  rotation: 0,
  cutoutPercentage: 85,
  legend: {
    display: false
  },
  tooltips: {
    enabled: false
  }
}

Chart.Doughnut(canvas, {
  data: data,
  options: options
});

HTML
<canvas id="myChart" width="400" height="200"></canvas>

See how it looks on working jsfiddle
See docs for explanations of options (cutoutPercentage, rotation etc).


How to debug an issue of cron's not executing a given script -- or other?

Question: I have a Rails script that I would like to run daily.  I know there are many approaches, and that a cron'd script/runner approach is frowned upon by some, but it seems to meet my needs.
However, my script is not getting executed as scheduled.
My application lives at /data/myapp/current, and the script is in script/myscript.rb.  I can run it manually without problem as root with:
/data/myapp/current/script/runner -e production /data/myapp/current/script/myscript.rb

When I do that, the special log file (log/myscript.log) gets logged to as expected:
Tue Mar 03 13:16:00 -0500 2009 Starting to execute script...
...
Tue Mar 03 13:19:08 -0500 2009 Finished executing script in 188.075028 seconds

I have it set to run with cron every morning at 4 am.  root's crontab:
$ crontab -l
0 4 * * * /data/myapp/current/script/runner -e production /data/myapp/current/script/myscript.rb

In fact, it looks like it's tried to run as recently as this morning!
$ tail -100 /var/log/cron
...
Mar  2 04:00:01 hostname crond[8894]: (root) CMD (/data/myapp/current/script/runner -e production /data/myapp/current/script/myscript.rb)
...
Mar  3 04:00:01 hostname crond[22398]: (root) CMD (/data/myapp/current/script/runner -e production /data/myapp/current/script/myscript.rb)
...

However, there is no entry in my log file, and the data that it should update has not been getting updated.  The log file permissions (as a test) were even set to globally writable:
$ ls -lh
total 19M
...
-rw-rw-rw- 1 myuser apps 7.4K Mar  3 13:19 myscript.log
...

I am running on CentOS 5.
So my questions are...

Where else can I look for information to debug this?
Could this be a SELinux issue?  Is there a security context that I could set or change that might resolve this error?

Thank you!
Update
Thank you to Paul and Luke both.  It did turn out to be an environment issue, and capturing the stderr to a log file enabled me to find the error.
$ cat cron.log
/usr/bin/env: ruby: No such file or directory

$ head /data/myapp/current/script/runner
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/runner'

Adding the specific Ruby executable to the command did the trick:
$ crontab -l
0 4 * * * /usr/local/bin/ruby /data/myapp/current/script/runner -e production /data/myapp/current/script/myscript.rb >> /data/myapp/current/log/cron.log 2>&1

Answer: By default cron mails its output to the user who ran it. You could look there.
It's very useful to redirect the output of scripts run by cron so that you can look at the results in a log file instead of some random user's local mail on the server.
Here's how you would redirect stdout and stderr to a log file:
cd /home/deploy/your_app/current; script/runner -e production ./script/my_cron_job.rb >> /home/deploy/your_app/current/log/my_file.log 2>&1

The >> redirect stdout to a file, and and the 2>&1 redirects stderr to stdout so any error messages will be logged as well.
Having done this, you will be able to examine the error messages to see what's really going on.
Answer: The usual problem when somebody discovers their script won't run in a cron job when it will run from the command line is that it relies on some piece of the environment that an interactive session has but cron doesn't get.  Some frequent candidates are the "PATH" environment, and possibly "HOME".
Answer: On Linux, make sure all the config files (/etc/crontab, /etc/crond.{daily,hourly,etc}/* and /etc/cron.d/*) are only writeable to user root and are not symlinks,  otherwise they will not even be considered.
To allow non-root and/or symlinks, specify the -p option to the crond daemon.
Comment: I've been using a symlink in /etc/cron.d on debian & ubuntu (vixie cron) for years with no problem.  In fact, vixie cron doesn't seem to have such an option.


How does $|g(z)-k|<1/2|k|\Rightarrow |g(z)|>1/2|k|?$

Question: I'm reading Ian Stewart's Complex Analysis, page 27, where he proves $\lim_{z\rightarrow z_0}(1/g(z))=1/k$, and he has the following step:

$$z\in S\;\text{and}\;0<|z-z_0|<\delta_1\;\text{implies}\;|g(z)-k|<1/2|k|$$
$$\text{hence}|g(z)|>1/2|k|$$

How is this right?
My step would be:

$$\text{hence}\;|g(z)|-|k| < 1/2|k|,\; |g(z)|<3/2|k|$$
Answer: Because $|g(z)|-|k| < |g(z) - k| < |k|/2$ and $|k| - |g(z)| < |g(z) - k| < |k|/2$. Thus $|k|/2<|g(z)|<3|k|/2$.


ExpressJS pode ser usado em produção?

Question: Vi recentemente um curso onde era usado ExpressJS para testes em backend em JSON para uma aplicação e fiquei maravilhado, mas me veio varias perguntas:
Ele poderia ser usado em produção?
Pode ser uma alternativa as tecnologias mais usadas atualmente de db e backend?
A performance é boa?
Como ele funciona exatamente?
Answer: Por que não seria? O Express é uma ótima ferramenta para isso, apesar de existirem opções mais avançadas, como o Sails (que é feito com base no Express).
Se você está começando, use o Express; não haverá nada de mau.
O único porém é o fato de não existir um modelo específico para criar as aplicações, isto é, você pode criar da forma como quiser (orientação a objetos, via funções, [...]), que irá funcionar. Isso, em alguns casos, pode acabar desorganizando o seu código.
Se você procura uma framework MVC, sugiro que use o Sails.

Sails

ExpressJS pode ser usado em produção?


How to compile clk, the Android bootloader?

Question: https://github.com/n0d3/lk – this is the repository holding source code for clk 1.5, which is a bootloader for Android and which I am trying to compile. Compiled packages can be found; however, I need to customize it. How can I compile it?
Running  make returns the following:
$ make
makefile:22: *** No project specified.  Use "make projectname" or put "PROJECT := projectname" in local.mk.  Stop.

Running make htcleo returns the following:
$ make htcleo
make[1]: Entering directory '/cygdrive/c/Users/Domas/lk'
make[1]: arm-eabi-gcc: Command not found
LIBGCC =
CFLAGS = -O2 -g -fno-builtin -finline -W -Wall -Wno-multichar -Wno-unused-parameter -Wno-unused-function -include ./build-htcleo/config.h -ffunction-sections -fdata-sections -mlittle-endian -mfpu=neon -mcpu=cortex-a8 -mfpu=neon -mfloat-abi=softfp -mthumb-interwork -mthumb -D__thumb__
including app/aboot dev/battery dev/fbcon dev/keys lib/debug lib/devinfo lib/heap lib/libc lib/ptable
generating build-htcleo/config.h
compiling arch/arm/start.S
make[1]: arm-eabi-gcc: Command not found
arch/arm/compile.mk:30: recipe for target 'build-htcleo/arch/arm/start.o' failed
make[1]: *** [build-htcleo/arch/arm/start.o] Error 127
make[1]: Leaving directory '/cygdrive/c/Users/Domas/lk'
makefile:15: recipe for target 'make-make' failed
make: *** [make-make] Error 2

As you can see the make breaks on make[1]: arm-eabi-gcc: Command not found. I was able to compile an older version (which had a different compilation process) by using a CodeSourcery toolchain, which has arm-none-eabi-gcc.exe, but not arm-eabi-gcc.exe, which seems to be needed to compile this version.
Note:
I appreciate that this might not be a popular type of question here on SO; however, I've been banging my head on this one the whole day, and could really use some guidance.
Answer: I managed to compile it. What I did was find a git repository that had a compilation script and some additional files for compilation along side the source code,  but it was the old source code. So I downloaded this project, and replaced the source code with a recent one, and the compilation script worked. Below instructions, most of it is copy paste from xda forums:

Download this zip archive here: https://github.com/cedesmith/cLK/archive/master.zip
It's the old source code, but it has the necessary scripts to make compilation easy.
Unzip the archive so that the compile script's path is ~/cLK/compile
Delete the ~/cLK/lk subdirectory (this is the old source code).
Download the new source code: git clone https://github.com/n0d3/lk

Now you should have the new source code in ~/cLK/lk. On to the actual compilation: this will depend on whether you're on Linux or Windows:
Linux

on Debian:
sudo apt-get update
sudo apt-get install gcc make git wget unzip zip libc6-dev-amd64 libc6-dev

on Fedora:
yum install gcc make git wget unzip zip

Now download the CodeSourcery toolchain:
wget http://www.codesourcery.com/sgpp/lite/arm/portal/package5353/public/arm-none-eabi/arm-2009q3-68-arm-none-eabi-i686-pc-linux-gnu.tar.bz2
tar xvfj arm-2009q3-68-arm-none-eabi-i686-pc-linux-gnu.tar.bz2
export PATH=$HOME/clk/arm-2009q3/bin:$PATH

Finally, compile:
cd ~/cLK
./compile clean

If everything goes well, you'll find the RUU_signed in this folder: bin/RUU_signed.nbh
Windows

You'll need Cygwin:
Download, the following file, and execute it http://www.cygwin.com/setup.exe
Click Next
Click "Install from internet" and click Next
Click Next (to accept the default directory to install)
Click Next (to accept the default directory for local Package directory)
Click "Direct Connection", and click Next
Select a "local mirror", and click Next
Now in the search bar, you need to search for the following things to install
gcc
make
git
wget
zip
unzip
Once selected click Next to continue, and Finish

Fire up the cygwin terminal (mintty); the following commands probably don't work in cmd.exe.
Now download CodeSourcery toolchain and yang:
wget http://www.codesourcery.com/sgpp/lite/arm/portal/package5354/public/arm-none-eabi/arm-2009q3-68-arm-none-eabi-i686-mingw32.tar.bz2
tar xvfj arm-2009q3-68-arm-none-eabi-i686-mingw32.tar.bz2
wget http://htc-flasher.googlecode.com/files/yang-1.1_win32.zip
cd cLK/bin
rm -rf yang
mkdir yang
unzip ../../yang-1.1_win32.zip yang/yang.exe
mv yang/yang.exe .
cd ..
sed -i s/yang/yang.exe/g compile

And finally, compile:
export PATH=$HOME/arm-2009q3/bin:$PATH
cd ~/cLK
./compile clean

Now your RUU_signed.nbh will be located in the following folder bin/RUU_signed.nbh


10 Band Equaliser using NOVOCAINE

Question: Im trying to build a 10 band Equaliser using NOVOCAINE.
I copied the Equaliser.mm's code in viewWillAppear, and added 9 more Sliders in the xib file, and changed IBAction code too this :
-(void)HPFSliderChanged:(UISlider *)sender {
PEQ[sender.tag - 1].centerFrequency = sender.value;
NSLog(@"%f",sender.value);
}

What I want to know is if I am doing this the right way or not ? and the what will be range of the Sliders ? Like in HPF example, the slider range is 2k to 8k. Need some guidance here.
Thanks.
Answer: EDIT: after your comment, I think it is clearer what you are asking.
Take the code to instantiate a NVPeakingEQFilter:
        NVPeakingEQFilter* PEQ = [[NVPeakingEQFilter alloc] initWithSamplingRate:self.samplingRate];
        PEQ.Q = QFactor;
        PEQ.G = gain;
        PEQ.centerFrequency = centerFrequencies;

you need define 3 parameters: Q, G, and centerFrequency. Both Q and centerFrequency are usually fixed (QFactor in my case is a constant equal to 2.0).
So, you have 10 sliders: each one corresponds to a fixed centerFrequency. I suggested iTunes values: 32Hz, 64Hz, 125Hz, 250Hz, 500Hz, 1KHz, 2KHz, 4KHz, 8KHz, 16KHz. You do not want to change those values when the slider value changes.
What you want to change when the slider value changes is the gain (G). At init time, G can be set to 0.0. This means "no amplification/attenuation".
When the slider moves, you change G, so actually you would do:
PEQ[sender.tag - 1].G = sender.value * kNominalGainRange;

where kNominalGainRange is 12.0, so if sender.value goes from -1.0 to +1.0, G goes from -12 to +12.
Hope this helps.

What I want to know is if I am doing this the right way or not ?

you do not show much code, but HPFSliderChanged seems correct. If you have any specific issue you should describe it and post more code.

and the what will be range of the Sliders ?

Actually, there is no rigid rule when it come to equalisers. iTunes goes from -12db to +12db, but you could use different ranges (with the only caveat being distortion).

Like in HPF example, the slider range is 2k to 8k. Need some guidance here.

again, you can take iTunes equaliser as an example (32Hz, 64Hz, 125Hz, 250Hz, 500Hz, 1KHz, 2KHz, 4KHz, 8KHz, 16KHz), or you can google for images of real equalisers and see which bands they use.
Comment: Actually 1) in HPF example he is doing this `_HPF_cornerFrequency = sender.value;. and i am setting centreFrequency. so am i doing correct.
2) I know iTunes goes from -12db to +12db but i dunno what are these values.
Comment: Can you explain 2 more thing please. 1) why different players have different frequencies like in iTunes values are 32,64,125 ... 16k Hz and in VLC they are different 16 Hz,170,310 ... 16kHz?
2) and why the G(gain) range is -12 to 12?
Comment: no specific reason, I guess tuning things so that they sounds better… but this is subjective… if you allow, e.g., for larger gains, you will easily get some distortion…

10 Band Equaliser using NOVOCAINE


Download data from firebase

Question:

Gostaria de ajuda para poder efetuar o download das informações dentro do "Itens". Pois como seria uma lista criada pelo usuario, eu não colocaria um limite de itens nela, e ao mesmo tempo eu não saberia dizer quantos dados existe.
Gostaria de saber qual a melhor maneira de efetuar isso. Se eu retirar a parte como comentario "Let Itens = value["Itens"] as: String" o código não executa.
Desde já agradeço a ajuda
Answer: Consegui resolver.
Vou deixar registrado como resolvi, espero ajudar o proximo que tenha dúvida semelhante.
Retornei o valor de Lista para uma variavel string (Name).
Usei o didselect (tableview) para passar a informação variavel, para uma outra viewController.
Nesta view controller, criei uma função, onde recebe a seguinte informação.

//ObjectsArray é um array empty criado fora do didViewLoad, para receber os dados do array firebase, e após isso conseguir utilizar na tableView.

//Lembre-se de usar o reloadData, ligar todos os outlet necessarios e usar o tableview.delegate = self e tableview.datasource = self.

Download data from firebase


Supplying the number of lambdas in cv.glmnet

Question: The cv.glmnet function states 2 options for its lambda parameter. First is NULL, and then glmnet chooses the lambda sequence such that the number of nonzero coefficients ranges from 0 to p, where p is the total number of features. And the second option is that the users can supply their own sequences. However, I think a third option where I supply the length of the sequence might be very helpful, such that the number of selected features still ranges from 0 to p, but the number of tested lambdas is dependent on the parameter I supplied. The second option is not always good since it is hard to guess which lambda gives the sparsest or densest model, so one can easily supply a not-very-useful sequence of lambdas. So, is there a way to give the number of lambda values to use in cv.glmnet?
Answer: Okay, I figured it out. There is the nlambda parameter in glmnet() function which also applies to cv.glmnet().
Comment: It seems that you can't fully chose the nlambda, I have a lasso with `cv.glmnet` function which usually test 61 lambda values. When I specify `nlambda=100`, it still tests 61 values (it makes sense but for practical reasons it may be useful to know upstream the right number of lambda tested). I also tried `nlambda=50` but it tested 33 values. Do you know why ; and do you know if there is a way to force the number of lambda tested? Thank you
Answer: To add to the last comment, sometimes the number of evaluated lambdas can be lower than the manually specified number.
The glmnet documentation states that "Sometimes the sequence is truncated before nlambda values of lambda have been used. This happens when glmnet.path detects that the decrease in deviance is marginal (i.e. we are near a saturated fit)"


index show content of an other file in httpd

Question: How can I configure http.conf to do this:
When I request to localhost/myfolder/index.html It will show content of /myfolder/myfile.html
Tks for help
Answer: In Apache, you could use an Alias directive, e.g.:
Alias /myfolder/index.html /somewhere/myfolder/myfile.html

Or you could use mod_rewrite, e.g.:
RewriteEngine On
RewriteRule ^/myfolder/index\.html$ /myfolder/myfile.html


nexus2artifactory Maven Snapshot Version Behavior

Question: I'm using nexus2artifactory tool to migrate form nexus to artifactory (as tool's name obviously says) and am facing a strange behavior and was wondering if I'm doing something wrong.
I'm trying to migrate some maven repositories created  on nexus which handle snapshots and which should be set with UNIQUE as "Maven Snapshot Version Behavior" (default when creating a maven repo in Artifactory) but after the migration all my snapshots repos are set with NON-UNIQUE which is quite annoying especially when using maven3 where the support for uniqueVersion tag was dropped.
Am I alone with this problem ? What can I do to migrate these repos differently ?
Thank you in advance for your kind explanation
Comment: Do you need to use `uniqueVersion`?
Comment: No, I'd like to avoid that as much as possible, however this would be the only solution to get artifacts from a repository set up the way it is now. But anyway this is not supported in maven3
Answer: The reason for this behaviour is that the nexus2artifactory tool is using the Artifactory REST API for creating the repositories.
The default value for snapshotVersionBehavior when working with the REST API is non-unique (for legacy reasons).
This should be fixed in the nexus2artifactory tool (and possibly also change the REST API defaults). In the meantime, if you need a quick fix, the following could be added to Artifactory.py:
<code>jsn['snapshotVersionBehavior'] = 'unique'
</code>
Comment: Thank you very much for this clear explanation, it totally makes sense, I'll try the fix and will also propose a pull request for that (if needed)
Comment: As written above, here is a proposal as a PR on the relevant repo:
https://github.com/JFrogDev/nexus2artifactory/pull/6