Arduino state not declared in this scope

Question: I am currently working on a small project using arduino and the below is my code:
#include <SoftwareSerial.h>
#include <Adafruit_Fingerprint.h>
#include <Keypad.h>

const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns

// Define the Keymap
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'}
};

// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = {2, 3, 4, 5};
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = {6, 7, 8};

// Create the Keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

#define ledpin 13
#define LOCKED 2
#define PASSWORD_OK 1
#define UNLOCKED 0

//State Variables; initialise to locked state
int LockState = LOCKED;
int position = 0;

void setup()
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);

  //Initialize state and communications
  setLockState(LOCKED);
  Serial.begin(9600);

}

void loop()
{
  char key = keypad.getKey();
  if(key)  // Check for a valid key.
  {
    switch (key)
    {
//      case '*':
//        digitalWrite(ledpin, LOW);
//        break;
//      case '#':
//        digitalWrite(ledpin, HIGH);
//        break;
      default:
        Serial.print(key);
    }
  }
}

It was from Adafruit. however, when i upload to my uno, it keeps giving me the error: 'setLockState' was not declared in this scope.
Can anyone shed some light on this?
Answer: I think you did not declare the function setLockState() in your code. I don't know about your project details, but  it looks like you want to lock a thing via keypad or fingerprint. You can find a great Tutorial (including the missing setLockState() function) for a biometric-security-box on the website of Adafruit.
Comment: Whoops i am so sorry for the dumb question i found out after a while hahaha thanks!


Javascript to add tr element with #text

Question: I have a function for adding a new row into a table but since i have lots of inner nodes for each td (with lots of attributes for each node) I am just changing the .innerHTML of the row.
However this is causing problems to other functions because the #text node is not inserted.
I've tried adding a <text/> tag but that didnt do it..So..any suggestions?
My javascript code is:
var newTrNode = document.createElement('tr');
newTrNode.setAttribute('id', resultArray[0]);

var putInside = '<text/><input readonly="readonly" value="'+assetName+'" type="text"  class="field left"/>	<input type="text" value="credentials" class="field left" readonly="readonly" />	';
var rowNode = but.parentNode.parentNode;
putInside += rowNode.childNodes[5].innerHTML;
putInside += '</optgroup></select>	<input type="text" value="'+resultArray[1]+'" class="field left" readonly="readonly" />	<input type="password" value="'+resultArray[2]+'" class="field left" readonly="readonly" />	<input onClick="editField('+resultArray[0]+',this)"type="button" value="Edit" class="field left"/><input onClick="deleteAsset('+resultArray[0]+')" type="button" value="Delete" class="field left"/><input onClick="lockUnlock('+resultArray[0]+',this, false)" type="button" value="Unlock" class="field left"/>	';
newTrNode.innerHTML = putInside;

Comment: What's the "function" you have? What are the "problems" caused? What qualifies "lots of tds with lots of extra info"?.. etc.
Comment: do you strip whitespace?
Comment: care to give us your code so far?
Answer: Don't use innerHTML to modify the content of a table row (or any part of a table) as it is specified to fail in at least some versions of IE. Use DOM methods. You can use innerHTML for an entire table or the content of cells (TD elements).
There is no text element in HTML, browsers will create text nodes for text in the document. You can create text nodes using the createTextNode method of the document interface:
var textNode = document.createTextNode('text');

You can add rows using innerHTML with a function like:

    index
    item

   0
   foo
 </tbody

<button onclick="
 rowsFromMarkup(document.getElementById('t0'),'
1bar');
">Add a row</button>

Comment: Yeah thats what I thought...was just trying to avoid that cause its a lot of extra writing :D..Thanks tho
Comment: If you are getting bits of tables, you can wrap it in table and tr tags as appropriate, insert it as the innerHTML of a created DIV element, then extract the rows and insert them in the DOM. It might be easier than creating tr, td etc. using DOM.

Javascript to add tr element with #text


Firebase realtime .indexOn

Question: after reading quite some about .indexOn I thought I understood how it worked but it seems I am still a bit lost for one case.
My trouble is that I am getting a warning on .indexOn on the tag search that I am doing as follow :
postRef
 .orderByChild(`i/tags/${tag}/a`)
 .equalTo(1)

${tag} being the searched tag
I have the following structure :

And rules :
"posts": {
      ".read": "auth != null",
      ".write": "auth != null",
      ".indexOn": "i/ts",
      "$pid": {
        "i": {
          "tags": {
            ".indexOn": "a",
          },
        }
      }
    },

from what I understood my wildcard should work for the postId and the .indexOn should work in this case but I get the warning at every search
The warning I am getting is :
[Firebase/Database][I-RDB034028] Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "i/tags/test/a" at /posts to your security rules for better performance

Comment: Please check the following post - https://stackoverflow.com/q/39238374/2765346. I think that here you will find the answer :)
Comment: I guess so... Frank van Puffelen, the author of the answer that I sent you, is an engineer for Firebase and he offers this is a solution. Unfortunately, I couldn't find another solution to this problem or any describe why this is not possible. I have also faced with the same deep dynamic key and I had to change the data model.
Comment: @tuledev not sure what you are saying but I changed my code to create a table specially dedicated to the tags it's easier even if it takes a little more space
Comment: What warning did you get?
Comment: @tuledev I just added the warning I am getting
Comment: @HristoEftimov it seems to be a work around more than the answer that I am trying to find or maybe this is impossible to achieve in my current state ? :)
Comment: @CladClad Yes, I think that you cannot achieve it in this data model... you need to change it :)
Comment: @HristoEftimov Sad but at least it's an answer xD do you know the reason why it's not possible is it because of the double dynamic keys level ?
Comment: @HristoEftimov okay sounds fair and if it comes from the tech of firebase indeed I will do it this way thanks for your help
Comment: @CladClad Please, accept my comments like advice/helpful resources, not like a solution :)
Comment: How about try to create `a` is a child of postID? We will have dup `a`. But can be order by `a`
Answer: As suggested by Hristo Eftimov I change my way to stock the tags in order to have a better access. I did that by creating different table for tag that is more easy to access and doesn't need an particular index
Firebase .indexOn dynamic keys

Firebase realtime .indexOn


Forcing a set of numbers to a gaussian bell-curve

Question: (This relates to my programming question on Stack Overflow: Bell Curve Gaussian Algorithm (Python and/or C#).)
On Answers.com, I found this simple example:

Find the arithmetic mean (average)
=> Sum of all values in the set, divided by the numbers of elements in the set
Find the sum of the squares of all values in the set
Divide output of (2) over the numbers of elements in the set
Subtract the square of mean (1) from the output of (3)
Take the square root of the outcome of (4)

Example: Set A={1,3,4,5,7}

(1+3+4+5+7)/5 = 4
(1*1+3*3+4*4+5*5+7*7)=1+9+16+25+49 = 100
100 / 5 = 20
20 - 4*4=20-16 = 4
SQRT(4) = 2

(This comes from a post on wiki.answers.com.)
Now given all that, how can I fit the above data to a bell curve (such as a credit score) ranging from 200 to 800.  Obviously the number 5 in the above set would be 500.  But then what is the formula for determining what 3 should be on the same scale.  Even though the original set Set A={1,3,4,5,7} is not a bell-curve, I want to force it into a bell-curve.
Imagine these are scores of 5 people.  Next month the scores might change as follows: Set A2={1,2,4,5,9} (one guys loses a point, and the top guy gains two more points - the rich get richer and the poor get poorer). Then perhaps a new guy comes into the set: Set A3={1,2,4,5,8,9}.
Comment: If your set changes time from time it is impossible to fit it to the same bell-curve. Suppose you have the set $A=\{1,2,3,4\}$, so 4 should be 800, but if a new observation 5 arrives, then it should become 800.
Comment: Welcome to CrossValidated, NealWalters. You may find that a common response to asking a statistician "How do i do this" is "Why do you want to do that?"
Comment: @onestop - see my link to previouspost.  In school, I remember of hearing of teachers who graded "on the curve". So no matter what score you got on a test, only a certain percentage of people would get each grade.  I have no idea how credit scores work, but that's very similar to what I'm simulating.  I give people points for example when they pay off a loan.  But some people will pay off dozens of loans.  I want to condense my wild points into a set of normalized points.
Comment: reading your last comment, I wonder what approach is best: give, e.g. 1 point for each loan paid off, other points for other things, then try to tame the enormous score at the end, or perhaps do something more meaningful with each component that makes up the final score? For example, if you give points for loans paid off you could calculate your Loans Paid Off (LPO) points as log (1 + NumberOfLoansPaidOff). So someone with zero loans paid off gets an LPO of 0, someone with 3 loans paid off gets an LPO of 1.1, while someone with 100 loans paid off gets an LPO of 4.6. Cap LPO at 5.
Answer: A scaled range, like 200 to 800 (for SATs, e.g.), is just a change of units of measurement.  (It works exactly like changing temperatures in Fahrenheit to those in Celsius.)
The middle value of 500 is intended to correspond to the average of the data.  The range is intended to correspond to about 99.7% of the data when the data do follow a Normal distribution ("Bell curve").  It is guaranteed to include 8/9 of the data (Chebyshev's Inequality).
In this case, the formula 1-5 computes the standard deviation of the data.  This is simply a new unit of measurement for the original data.  It needs to correspond to 100 units in the new scale.  Therefore, to convert an original value to the scaled value,

Subtract the average.
Divide by the standard deviation.
Multiply by 100.
Add 500.

If the result lies beyond the range $[200, 800]$ you can either use it as-is or "clamp" it to the range by rounding up to 200, down to 800.
In the example, using data $\{1,3,4,5,7\}$, the average is $4$ and the SD is $2$.  Therefore, upon rescaling, $1$ becomes $(1 - 4)/2 * 100 + 500 = 350$.  The entire rescaled dataset, computed similarly, is $\{350, 450, 500, 550, 650\}$.
When the original data are distributed in a distinctly non-normal way, you need another approach.  You no longer compute an average or SD.  Instead, put all the scores in order, from 1st (smallest) up to $n$th (largest).  These are their ranks.  Convert any rank $i$ into its percentage $(i-1/2)/n$.  (In the example, $n=5$ and data are already in rank order $i=1,2,3,4,5$.  Therefore their percentages are $1/10, 3/10, 5/10, 7/10, 9/10$, often written equivalently as $10\%, 30\%$, etc.)  Corresponding to any percentage (between $0$ and $1$, necessarily) is a normal quantile.  It is computed with the normal quantile function, which is closely related to the error function.  (Simple numerical approximations are straightforward to code.)  Its values, which typically will be between -3 and 3, have to be rescaled (just as before) to the range $[200, 800]$.  Do this by first multiplying the normal quantile by 100 and then adding 500.
The normal quantile function is available in many computing platforms, including spreadsheets (Excel's normsinv, for instance).  For example, the normal quantiles (or "normal scores") for the data $\{1,3,4,5,7\}$ are $\{372, 448, 500, 552, 628\}$.
This "normal scoring" approach will always give scores between 200 and 800 when you have 370 or fewer values.  When you have 1111 or fewer values, all but the highest and lowest will have scores between 200 and 800.
Comment: +1, I've deleted my answer, since your was way better and made mine obsolete :)
Comment: Where are you getting the 5 in the 1-5?  4 is the average. Should it be 1-4?  I'm testing today with Python, thanks again.
Comment: @NealWalters Sorry, that was a slip of the finger.  I have fixed it now so it reads (1-4)/2*100+500.
Answer: You could try this approach - normalise your data set to range between the values -1 and +1 thus:
$$
\left(\frac{\text{individual_value} - \text{min_of_all_values}}{\text{max_of_all_values} - \text{min_of-all_values}}-0.5\right)*2.
$$
This will convert every value in your data set to a value between -1 and +1, with the actual maximum and minimum values being set to +1 and -1 respectively, and then reset these +1 and -1 values to be +0.9999 and -0.9999 (necessary for following calculations.)
Then apply the Fisher Transformation to each of the above normalised values to "force it" to approximately conform to a normal distribution, and then "un-normalise" each of these Fisher Transform values to range in value between 200 and 800 thus:
$$
\frac{\text{Fish_value} - \text{min_all_Fish_values}}{\text{max_all_Fish_values} - \text{min_all_Fish_values}}*600 + 200
$$
The maximum Fisher Transform value will be set to exactly 800, the minimum Fisher Transform value will be set to exactly 200, and all the other values will lie between these two extremes, according to an approximate normal distribution.
Referencing your original question on SO and the issue of scalability, the advantage of this approach is that provided any new data point is not itself a new maximum or minimum for the data set as a whole you can apply the above calculations to the new data point to get its score between 200 and 800 without affecting any of the existing scores of the original data set. If a new data point is a new maximum or minimum you will have to recalculate the scores for the whole data set with this new "normalising" maximum or minimum value.


Outlook refuses to display customized ribbon

Question: My situation is similar to this one, but neither of the answers there worked for me.
In a brand-new project with no code, I have a very simple ribbon button:

...but Outlook (latest version, M365) will no longer display it. I say "no longer" because at first it did. I then removed it manually by Customizing the Ribbon and removing the custom group from the right-hand list:

Apparently, however, I should have removed it via the File\Options\Add-ins dialog, as it now won't display at all, no matter what I do. Oddly, the stock Add-ins\Get Add-ins combo flickers ever so slightly when I F5 run the project with Visual Studio (2022).
The more common solutions don't work. Web searches turn up answers to every problem but this one. ChatGPT is AWOL, presumably out trying to catch Rosie the Robot.
How do I get my button (and group) to show up again?
--EDIT--
I have since discovered that the ribbon does at least attempt to load when I start a new email message (but only the first time after I restart Outlook).
After turning on Show VSTO Add-in user interface errors in the Advanced options, I get this:

I tried renaming the tab in the designer to TabMail, but that didn't bring any improvement.
Here're the Properties for the RibbonTab:

...and here're my selected RibbonTypes:

Out of sheer curiosity I turned on the StartFromScratch property, and my button does display without error under that configuration:

I can also start a new email (using Ctrl+N) without the previous error message.
Here's the XML from my ribbon export:
<?xml version="1.0" encoding="UTF-8"?>
<customUI onLoad="Ribbon_Load" xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <tab idMso="TabAddIns">
        <group id="Group1" label="Group1">
          <button id="Button1" label="Click Me" showImage="false" />
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>

After wiring up the Override in the new Ribbon.vb, there's no improvement in the overall situation when I use an XML ribbon vs. the ribbon designer.
Is my Outlook setup broken somehow? It sure feels like it.
Comment: Do you see the `Add-ins` tab on the ribbon?
Comment: I don't, no. I do, however, have an `Add-ins` _group_, as indicated in the second screenshot. My button first appeared just to the right of that.
Comment: From the screenshot it is not clear what settings you have for the `RibbonTab`.
Comment: I see that your custom UI should be added to the default tab in Outlook. Try to place it in a custom one.
Comment: I put it in a custom tab just now, and it works. All is well.
Answer: First, try to unregister and then register the add-in back by running the Clean command of your add-in project and then Build to register it back.
By default, if a VSTO Add-in attempts to manipulate the Microsoft Office user interface (UI) and fails, no error message is displayed. However, you can configure Microsoft Office applications to display messages for errors that relate to the UI. You can use these messages to help determine why a custom ribbon does not appear, or why a ribbon appears but no controls appear. For Outlook, the Show VSTO Add-in user interface errors checkbox is located in the Developer section of the details pane.
There are two ways of creating a custom ribbon UI with VSTO:

Walkthrough: Create a custom tab by using the Ribbon Designer
Walkthrough: Create a custom tab by using Ribbon XML

Second, if you use the ribbon designer you need to check whether the Add-ins tab is visible on the ribbon or not. So, you may try to place your controls to the custom tab. Just click on the right hand side of your ribbon tab on the designer surface to add a custom tab. Also you may try to change ribbon controls IDs.
The last resort is to export your custom ribbon UI to the ribbon XML and troubleshoot the UI using callbacks. See How to: Export a ribbon from the Ribbon Designer to Ribbon XML for more information.
Comment: Thanks for having a look. I've edited my question to include the additional troubleshooting steps that you've advised. Alas, still no improvement.
Comment: What's the difference between removing an Add-in via the `File\Options\Add-ins` dialog and removing it by right-clicking the ribbon and choosing `Customize the Ribbon`? Did I send my setup sideways by opting for the latter by mistake?
Comment: In case of ribbon only the custom UI is removed, but the add-in continue its work.
Comment: Well, duh. I've been looking for my custom control on the `Home` tab. As I recall, you specifically asked me whether I had an `Add-ins` tab, and I said _no_. Wish I hadn't, 'cause I do. So my control is displaying and functioning correctly. Thank you.
Comment: _"the add-in continue its work"_ Yes, I just discovered that by starting a new email (and reproducing the error), and then right-clicking to customize the ribbon. There was an empty Add-ins group there, so I removed it. I restarted Outlook, started a new email, and the error was gone.
Comment: Observation: this thing sure is quirky.


Variable Importance for different methods

Question: Is it possible to compare variable importance, obtained for different models, built on different datasets with simular variables, using caret package? The property are different, but close, and the variables used for modelling are the same. For example, one can calculate importance for pls and random forest model, then scale them to obtain values from 0 to 1.
Would it be valid to compare such values for two different Y? Is there any way to compare two different statistical models, built on two different datasets in terms of variable influence?
Comment: When you say "different datasets" do you mean the same dataset( ex: wine dataset) which has been partitioned into different dataset or are trying to compare variable importance in the wine dataset with variable importance with Iris dataset? please clarify. As it stands your question does not make sense.
Comment: When I say different datasets, I mean datasets like let's say some imaginary beer and whisky datasets. The property would be different, but close, and the variables used for modelling are the same (let's say, % of alcohol and average density). Hope this helps.
Answer: Following additional information, I would suggest looking at avg. rank of a variable across datasets.
For ex:
Lets say we have a binary target variable, Like_or_not_like which is :

1 if the user liked the drink and
0 if the user didn't like the drink

Now, we have captured the following variables for a set of wines, beer & whiskies in three datasets respectively and would like to understand how variable importance changes by the type of drink:

pH_level
Sugar_Content
Alcohol_Percentage
Average_Density

You can get relative ranking for each variable in each dataset as output by each algorithm applied.

Then, you can simply avg. out the ranks to get a finally tally like the following:

NOTE: Lower the rank number, higher the importance.
Comment: One little additional question: can be ranking for PLS and RF (for example) compared?
Comment: I thought that's what I explained in my answer. You are only looking at relative ranking output by whatever method ( RF, PLS etc...) for each variable in question. You should study the 1st image in my answer.


Constructing rationals from countable ordinals

Question: Take the set of all countable ordinals $\omega_1$. Define $+$ and $\cdot$ by the Hessenberg sum and product. In a similar fashion to the naturals, construct the integers and the rationals from these by taking equivalence classes of ordered pairs. We'll call these the "$\omega_1$ rationals". I have a few questions about this construction:

What is the cardinality of the $\omega_1$ rationals? My assumption is that it is $\aleph_1$, as at each step we have only taken pairs of countable ordinals.
Are the $\omega_1$ rationals a field?
Assuming they are a field, what are its properties? Is it metrically complete? Algebraically closed? If it is neither, how far is it from being metrically complete or algebraically closed?
Comment: What do you mean by "metrically complete"?  With respect to what metric?
Comment: Yes I should have been more specific. I was wondering about the metric given by the absolute value of the difference.
Answer: You're exactly right about the cardinality being $\aleph_1$.  This construction does yield a field.  To understand it better, note that by Cantor normal form, the semiring $(\omega_1,+,\cdot)$ can be identified with the set of formal polynomials with coefficients in $\mathbb{N}$ in variables $x_\alpha$ for $\alpha<\omega_1$, where $x_\alpha$ corresponds to the ordinal $\omega^{\omega^\alpha}$. So, taking formal differences of such things will just give polynomials in the variables $x_\alpha$ with coefficients in $\mathbb{Z}$, and then taking formal quotients will give rational functions in the variables with coefficients in $\mathbb{Q}$.  So this field is a field of rational functions in $\aleph_1$ variables over $\mathbb{Q}$.  In particular, it is very far from being algebraically closed (for instance, it contains no elements algebraic over $\mathbb{Q}$ besides the elements of $\mathbb{Q}$ themselves).
(Of course, there is nothing particularly special about $\omega_1$ here.  You could do the same thing for any ordinal $\omega^{\omega^\alpha}$, and you would get a field that is a field of rational functions on variables $x_\beta$ corresponding to $\omega^{\omega^\beta}$ for all $\beta<\alpha$.)
Comment: Since the only elements algebraic over $\mathbb{Q}$ are $\mathbb{Q}$ themselves, it seems this field cannot be metrically complete with any metric that extends the metric of $\mathbb{Q}$. This is because rational numbers can converge to algebraic numbers - for instance, you could come up with a Cauchy sequence of rationals that converges to $\sqrt{2}$ in $\mathbb{R}$, and thus would have to converge to a square root of 2 in the $\omega_1$-rationals.


Problema com Filtro

Question: Boa Noite
Pessoal necessito saber se alguem conseguira me orientar em como resolver a seguinte situação eu tenho um textarea onde eu digito @ ele me mostra uma lista de cidades, gostaria que após eu continuar digitando a informação no textarea o meu select fosse sendo filtrado existe essa possibilidade?
Eu implementei uma rotina usando chosen-select porém acredito que não vai resolver o meu problema.
Abaixo segue o exemplo:

 function getLogins(event) {
                if (event.keyCode === 64){
                    $("#logins").chosen({ width: '100%' });
        $("#logins").chosen({ allow_single_deselect: true });

                    $("#logins").show();

                    $("#logins").trigger('chosen:open');
        $('.chosen-drop').css('left', 0);

                    window.addEventListener('load', chosenfunc());
                }
            }

            function getLogins2() {
                if (event.keyCode === 64){
                    $("#logins2").show();
                }
            }

            function postLogins(id){
                document.getElementById("comentario2").value =
    document.getElementById("comentario2").value + document.getElementById(id).innerText + " ";

                if (document.getElementById("listalogins").value == '0') {
     $("#listalogins2").val($("#logins2").val());
    } else {
     $("#listalogins2").val($("#listalogins2").val() + "," + $("#logins2").val());
    }

                $("#logins2").hide();

            }

            function getSelectValor(id){
       var e = document.getElementById(id);
       var itemSelecionado = e.options[e.selectedIndex].value;

         return itemSelecionado;
       }

            function chosenfunc(){

    jQuery("#logins").chosen().change( function(e){
     var id;
     id = $("#logins").val();

     document.getElementById("comentario").value =
     document.getElementById("comentario").value + document.getElementById(id).innerText + " ";

     if (document.getElementById("listalogins").value == '0') {
      $("#listalogins").val($("#logins").val());
     } else {
      $("#listalogins").val($("#listalogins").val() + "," + $("#logins").val());
     }

     $("#logins")
         .find('option:first-child').prop('selected', true)
         .end().trigger('chosen:updated');

     $("#logins").hide();
     $("#logins").trigger('chosen:close');

       });
         }
 <link rel="stylesheet" href="https://github.com/harvesthq/chosen/blob/master/public/docsupport/prism.css" />
        <link rel="stylesheet" href="https://github.com/harvesthq/chosen/blob/master/public/docsupport/style.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css" />
Exemplo 01 - Usando Chosen Select: Ao digitar @ é exibido um chosen-select para o filtro dos dados ao clicar nas informações é inserido a informação no textarea comentario

        <input id="listalogins" type="text" value="0">

        <textarea id="comentario" class="col-sm-12 col-xs-12" onkeypress="getLogins(event,this);"></textarea>

        <select id="logins" classe="chosen-select col-sm-12 col-xs-12" style="display:none" >
            <option id="00" value="00">Nenhum</option>
            <option id="01" value="01">São Paulo</option>
            <option id="02" value="02">Rio de Janeiro</option>
            <option id="03" value="03">Parana</option>
        </select>

        Exemplo 02 - Usando Select Multiple: Ao digitar @ é exibido um select com a lista de logins quando se clica em uma das opções o select some e o textearea2 recebe a informação do item selecionado

        <input id="listalogins2" type="text" value="0">

        <textarea id="comentario2" class="col-sm-12 col-xs-12" onkeypress="getLogins2(event,this);"></textarea>

        <select id="logins2" class="select col-sm-12 col-xs-12" multiple="" style="display:none" >
            <option id="00" onclick="postLogins(this.id)" value="00">Nenhum</option>
            <option id="01" onclick="postLogins(this.id)" value="01">São Paulo</option>
            <option id="02" onclick="postLogins(this.id)" value="02">Rio de Janeiro</option>
            <option id="03" onclick="postLogins(this.id)" value="03">Parana</option>
        </select>
Answer: Você pode usar o evento change para realizar o filtro e preencher o seu combo:
$('#listalogins').change(function(){
    texto = $('#listalogins').val();

  if(texto[0] === "@"){
  alert (' PREENCHA SEU COMBO AQUI ')

  }

});

Sempre que preencher com @ na primeira letra ele cai nesse if, dentro dele faça seus filtros e o preenchimento dos combos.
Também existe a possibilidade de usar o autocomplete do Jquery:
!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

  Tags:
  <input id="tags">

Comment: mas no caso o campo em questão é um campo comentário essa ou seja haverá mais textos funcionaria tambem ?
Comment: Entendi, ao ler a primeira vez tinha entendido que queria no campo login na hora que colocasse o @ preenche-se uma lista com os logins filtrando. Sobre o campo texto teria que pesquisar alguma biblioteca que faça isso. Existe a autocomplete do Jquery mais é para o tipo input.

Problema com Filtro


Typescript if string is included in options

Question: When I make an if statement like this typescript knows it is either "a" or "b"
if (str === "a" || str === "b") {
    // typescript knows it is either "a" or "b"
}

But that is too verbose, and with many options it can look even worse.
Is there a shorter way of doing that, with typescript being able to infer the same thing as above? I am thinking somehting like this
if (["a", "b"].includes(str)) {
    // too bad typescript doesn't know that it is either "a" or "b" only
}

I oversimplified the example, but a more complete example can be seen here, where I need to know if an arbitrary string is the name of a boolean property in an interface:
interface Filters {
    isPromo?: boolean,
    isFreeShipping?: boolean,
    isNew?: boolean,
    isInStock?: boolean,
    title?: string
}

let filters: Filters = {};

for (const filterValuePair of location.search.split("&")) {
    const [urlFilter, value] = filterValuePair.split("=");
    // here typescript has no warnings because it can tell that it must be a boolean property because of how the "if" is implemented
    if (urlFilter === "isPromo" || urlFilter === "isFreeShipping" || urlFilter === "isNew" || urlFilter === "isInStock") {
        filters[urlFilter] = Boolean(value);
    }
    // this is more succint, but typescript cannot help me infer
    if (["isPromo", "isFreeShipping", "isNew", "isInStock"].includes(urlFilter)) {
        filters[urlFilter] = Boolean(value);
    }
}

See playground here
Answer: You can make use of a user-defined type guard which is a function where you assert "if this function returns true, then some variable is some type."
We can use includes as the implementation of the function and assert your type through the return.
const isFilterKey = <K extends string & keyof Filters>(
    properties: K[], urlFilter: string
): urlFilter is K => {
    return (properties as string[]).includes(urlFilter);
}

We have to say (properties as string[]).includes(urlFilter) instead of just properties.includes(urlFilter) because properties is of type K[], so it expects includes to be called with a variable of type K.  (Alternatively, you could do properties.includes(urlFilter as K), but I find the other version more semantically sound since we know that properties is a subset of string[] but we don't know that urlFilter is K).
if (isFilterKey(["isPromo", "isFreeShipping", "isNew", "isInStock"], urlFilter)) {
    filters[urlFilter] = Boolean(value);
}

In this example, it's fine to assign filters[urlFilter] since the type of urlFilter is now known to be the union of the keys in that array.
Playground Link
In a more general sense, like your "a" | "b" example, your typeguard would look like:
const isSpecificString = <K extends string>(
    strings: K[], value: string
): value is K => {
    return (strings as string[]).includes(value);
}

Comment: Great answer, thank you very much :) I continue to be impressed about how Typescript has tackled the many challenges of typing a loosely typed language :D


How to inflate a view from a fragment?

Question: I wanted to try out WizarDroid library in my app. But since I am fairly inexperienced with inflators I got stuck on this error for hours.
I get a NullPointerException while trying to findViewById and I can't figure out why.
public class WizardStep1 extends WizardStep {

    //Wire the layout to the step
    public WizardStep1() {
    }

    //Set your layout here
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.wizard, container, false);
        TextView tv = (TextView) v.findViewById(R.id.wizard_textView); // tv = null
        tv.setText("This is an example of Step 1 in the wizard. Press the Next " + // NullPointerException gets thrown here
                "button to proceed to the next step. Hit the back button to go back to the calling activity.");

        return v;
    }
}

So TextView tv is null for some reason. I can't figure this out because I clearly defined it in XML R.layout.wizard
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/wizard_textView"
        android:layout_marginTop="10dp"
        android:textSize="20dp"
        android:text="gtsets" />
</LinearLayout>

This code is also from their documentation so it just further confuses me :/
Edit:
Here's wizardStartup class :
public class wizardStartup extends BasicWizardLayout {

    /**
     * Note that initially BasicWizardLayout inherits from {@link android.support.v4.app.Fragment} and therefore you must have an empty constructor
     */
    public wizardStartup() {
        super();
    }

    //You must override this method and create a wizard flow by
    //using WizardFlow.Builder as shown in this example
    @Override
    public WizardFlow onSetup() {
        /* Optionally, you can set different labels for the control buttons
        setNextButtonLabel("Advance");
        setBackButtonLabel("Return");
        setFinishButtonLabel("Finalize"); */

        return new WizardFlow.Builder()
                .addStep(WizardStep1.class)           //Add your steps in the order you want them
                .addStep(WizardStep2.class)           //to appear and eventually call create()
                .create();                              //to create the wizard flow.
    }
}

LogCat :

07-15 17:58:05.491  10299-10299/ba.imasoft.dfms.app E/AndroidRuntime﹕
  FATAL EXCEPTION: main
      java.lang.NullPointerException
              at ba.imasoft.dfms.app.wizards.steps.WizardStep1.onCreateView(WizardStep1.java:28)

Line 28 is 'tv.setText("This'..
If I comment out the lines that contain tv variable It works but not the way It's supposed to.. I need to edit the view for each step.
tv = null proof...

Comment: How did you find tv is null? If LogCat, please show it.
Comment: I don't see where you've defined your TextView in your XML?
Comment: If the layout you posted is R.layout.wizard Xml then I don't see the TextView with id R. id.wizard_textView. Please check your layout again.
Comment: Yeah, that's why is null, findViewById returns null if the ID is not found.
Comment: is the XML file name exactly wizard.xml?
Comment: Yes It is. wizard.xml
Comment: @l0oky This is puzzling. Is wizard.xml in res/layout, and there are no other wizard.xml files in other directories?
Comment: @matiash Correct. There is only one wizard.xml in res/layout.
Comment: @l0oky And in other directories? Such as layout-port, layout-large, ...? Because as stated, this error would seem "impossible" :)
Comment: @matiash haha you're starting to scare me because I don't have any other wizard.xml layouts or 'layout-large' packages..
Comment: I debugged.. Added tv to Watch and while the breakpoint was on line 'tv.setText("..' It said that tv = null.
Comment: Isn't it annoying when you get downvotes but not answers? :)
Comment: @david.pfx I edited the question with logcat. And that's the only thing 'useful' I got from it.
Comment: From this and your answer I would say that the true cause is something you aren't telling us. VTC.
Comment: @david.pfx So I was supposed to tell you the answer while I didn't know it? I was perfectly clear about every class, name and library. Not to mention the other details. It clearly says in my answer 'I can't figure this out because I clearly defined it in XML R.layout.wizard' so the problem was in the name that XML the library required..
Answer: The problem was bizarrely strange..
Anyway all I did is change wizard.xml to wizard_step.xml figured it was using wizard.xml as something else in the library hmm..
It worked.
Comment: That is very much correct! The library already has a layout file named `wizard.xml` as you can see [here](https://github.com/Nimrodda/WizarDroid/blob/develop/wizardroid/src/main/res/layout/wizard.xml). I will add it to the FAQ and rename this file in future releases.

How to inflate a view from a fragment?


training approaches for highly-imbalanced data set

Question: I have a highly-imbalanced test data set. The positive set consists of 100 cases while the negative set consists of 1500 cases. On the training side, I have a  larger candidate pool: the positive training set has 1200 cases and  the negative training set has 12000 cases. For this kind of scenario, I have several choices:
1)  Using weighted SVM for the whole training set (P: 1200, N: 12000)
2)  Using SVM based on the sampled training set (P:1200, N :1200), the 1200 negative cases are sampled from 12000 cases.
Is there any theoretical guidance on deciding which approach is better?  Since the test data set is highly imbalanced, should I use the imbalanced training set as well?
Comment: please check the following questions: [Supervised learning with "rare" events](http://stats.stackexchange.com/questions/9398/supervised-learning-with-rare-events-when-rarity-is-due-to-the-large-number-o) and [Best way to handle unbalanced multiclass dataset with SVM](http://stats.stackexchange.com/questions/20948/best-way-to-handle-unbalanced-multiclass-dataset-with-svm). Does this help ? Frankly, your questions sounds rather similar ;).
Answer: From a recent post on reddit, the reply by datapraxis will be of interest.
edit: the paper mentioned is Haibo He, Edwardo A. Garcia, "Learning from Imbalanced Data," IEEE Transactions on Knowledge and Data Engineering, pp. 1263-1284, September, 2009 (PDF)
Answer: Pairwise Expanded Logistic Regression, ROC-based learning, Boosting and Bagging (Bootstrap aggregating), Link-based cluster ensemble (LCE), Bayesian Network, Nearest centroid classifiers, Bayesian Techniques, Weighted rough set, k-NN
and a lot of sampling methods to handle imbalance.


Where does the normal to the graph of $y = \sqrt x$ at the point $(a, \sqrt a)$ intersect the $x$-axis?

Question:
Where does the normal to the graph of $y = \sqrt x$ at the point $(a, \sqrt a)$ intersect the $x$-axis?

I know how to find equation with numbers, but got really confused with this one. If anybody could break it down it would be greatly appreciated.
Here is what I've done: Took derivative $= .5x^{-.5}$, then plugged in $x$ value $a$ to get $1/2a^{-1/2}$, so the slope of tangent is $1/2a^{-1/2}$? so the slope of normal is $2a^{-1/2}$? So $y-\sqrt{a} = 2a^{-1/2}(x-a)$?
Thank you in advance
Comment: What is the slope of the line normal to the curve at $(a,\sqrt{a})$?  What did you find the line normal to the graph of $y=\sqrt{x}$ at the point $(a,\sqrt{a})$ to look like using that slope?  Did you try writing in point-slope form?  If you plug in $0$ for $y$ in the equation for that line, that corresponds to the point where it intersects the $x$-axis.
Comment: The slope of the normal line is the *negative* reciprocal of the slope of the tangent line.  Fix that, then solve for $x$ when $y = 0$.
Comment: Where are you stuck?
Comment: @G.Sassatelli Here is what i've done. Took derivative = .5x^-.5.   then plugged in x value (a) to get 1/2a^-1/2. so the slope of tangent is 1/2a^-1/2? so the slope of normal is 2a^-1/2? So y-sqrta = 2a^-1/2(x-a)? I am confused.  Also thank you very much for quick response!!
Comment: You have fallen victim to your own poor notation, it seems, and confused $1/2a^{-1/2}$ with $\dfrac{1}{2a^{-1/2}}$. Better to write $\frac12 a^{-1/2}$ or $\dfrac{1}{2a^{1/2}}$. (But $.5x^{-.5}$ is even worse!)
Answer: The function $y = \sqrt{x} = x^{\frac{1}{2}}$ has derivative
$$y' = \frac{1}{2}x^{-\frac{1}{2}} = \frac{1}{2\sqrt{x}}$$
as you found.  The tangent line to the graph of $y = \sqrt{x}$ at the point $(a, \sqrt{a})$ has slope
$$y'(a) = \frac{1}{2\sqrt{a}}$$
which is defined for $a > 0$.
You made a mistake when you calculated the slope of the normal line.  Since the normal line is perpendicular to the tangent line, its slope is the negative reciprocal of the slope of the tangent line.  Thus, the slope of the normal line is $-2\sqrt{a}$. Hence, the equation of the normal line at the point $(a, \sqrt{a})$ is
$$y - \sqrt{a} = -2\sqrt{a}(x - a)$$
To solve for the $x$-intercept of the normal line, we set $y = 0$ and solve for $x$.
\begin{align*}
0 - \sqrt{a} & = -2\sqrt{a}(x - a)\\
-\sqrt{a} & = -2\sqrt{a}x + 2a\sqrt{a}\\
2\sqrt{a}x & = (2a + 1)\sqrt{a}\\
x & = a + \frac{1}{2}
\end{align*}
Thus, for $a > 0$, the normal line to the graph of $y = \sqrt{x}$ at the point $(a, \sqrt{a})$ intersects the $x$-axis at the point $(a + \frac{1}{2}, 0)$.
Since
$$\lim_{x \to 0^{+}} \frac{1}{2\sqrt{x}} = \infty$$
the tangent line to the graph of $y = \sqrt{x}$ is vertical, so the normal line is horizontal.  Since the tangent line to the point $(0, \sqrt{0}) = (0, 0)$ is the $y$-axis, the normal line is the $x$-axis.
Comment: Very clear answer.
Answer: \begin{align*}
  y' &= \frac{1}{2\sqrt{x}} \\
  \text{slope of the normal} &=-2\sqrt{a} \\
  y-\sqrt{a} &= -2\sqrt{a}(x-a) \\
  2\sqrt{a}x+y &= \sqrt{a}(2a+1) \\
  \frac{x}{a+\frac{1}{2}}+\frac{y}{\sqrt{a}(2a+1)} &= 1 \\
  x\text{-intercept} &= a+\frac{1}{2}
\end{align*}
Comment: The equation $2\sqrt{a}x + y = 2a - \sqrt{a}$ is incorrect.  It should read $2\sqrt{a}x + y = 2a\color{red}{\sqrt{a} +} \sqrt{a}$.
Comment: @N.F.Taussig Corrected, many thanks.


Remove last argument from argument list of shell script (bash)

Question: This question concerns a bash script that is run in automator osx. I am using automator actions to get and filter a bunch of file references from the finder. Then I append to that list the name of the parent folder, also via an automator action. Automator then feeds these arguments to an action called "run shell script". I am not sure exactly how automator invokes the script but the argument list looks like this when echoed with: echo "$@"

/Volumes/G-Raid/Online/WAV_TEST/Testbok 50/01/01000 43-001.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/02/02000 43-002.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/03/03000 43-003.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50

In this case path to 3 files and a folder.
In the shell script I launch an application called ripcheckc* with the args passed from automator minus the last argument(the folder) in the list.
I use this to remove the last argument:
_args=( "$@" )
unset _args[${#_args[@]}-1]

And this is echo $_args:

/Volumes/G-Raid/Online/WAV_TEST/Testbok 50/01/01000 43-001.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/02/02000 43-002.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/03/03000 43-003.wav

Same as before but without the folder.
Now, if I run ripcheckc with "$@" as argument it works (but fails later on because of that last path in the argument list) If I use ${_args[@]} the application will just abort silently. When I echo $@ and _args the output looks identical except for the last argument.
My question is - what is the difference between $@ and $_args that make the first valid input and the second not?
*The application is ripcheckc
I hope my question makes sense.
EDIT: Solved.
Comment: I solved it by using double quotes. Like this: ripcheckc "${_args[@]}".
Answer: I have used this bash one-liner before
set -- "${@:1:$(($#-1))}"

It sets the argument list to the current argument list, less the last argument.

How it works:

$# is the number of arguments
$((...)) is an arithmetic expression, so $(($#-1)) is one less than the number of arguments.
${variable:position:count} is a substring expression: it extracts count characters from variable starting at position. In the special case where variable is @, which means the argument list, it extracts count arguments from the list beginning at position. Here, position is 1 for the first argument and count is one less than the number of arguments worked out previously.
set -- arg1...argn sets the argument list to the given arguments

So the end result is that the argument list is replaced with a new list, where the new list is the original list except for the last argument.
Comment: @StevenLu I have amended the answer to provide an explanation for you. I hope it helps.
Comment: Simple and elegant: I like it.  I used a variation of @chepner's suggestion below to "remove" the first two arguments in order to properly spawn a sub-process: spawnProc "${@:3:$#}".  Admittedly cryptic but that's due to BASH's roots.  It's elegant though and simple.
Comment: Could I request a play-by-play of this thing?
Comment: That's perfect!
Comment: Great explanation, note there's an even more compact way of writing by @uvsmtid below, which is `"${@:1:${#}-1}"`
Comment: The "special case" applies to any array variable, not just `@`.
Answer: Assuming that you already have an array, you can say:
unset "array[${#array[@]}-1]"

For example, if your script contains:
array=( "$@" )
unset "array[${#array[@]}-1]"    # Removes last element -- also see: help unset
for i in "${array[@]}"; do
  echo "$i"
done

invoking it with: bash scriptname foo bar baz produces:
foo
bar

Comment: @Nordanfors _Always_ quote variables.
Comment: The next answer should be accepted, not this one. It has triple the upvotes.
Comment: Thank you, that is a better way to get rid of the last argument. My issue is that there seems to be something different about $@ compared to $array that qualifies it as valid input for the application I am passing it to. I just can't figure out what it is.
Comment: @user1047256 Try passing `${array[@]}` to your application.
Comment: I tried what you suggested but still no go. Fyi I changed my nick to Nordanfors. :-)
Comment: @Nordanfors How do you pass parameters to your __application__ otherwise?  (Could you update the question with the information?)
Comment: Your help is most appreciated. All that was missing was double quotes around the array to get the application to process it. Thanks!
Comment: @Noumenon: **Bienvenue StackOverflow.** The accepted answer declining to abject uselessness over time is the common case, rendering this StackOverflow feature an anti-pattern in UX design. The evolving democratic wisdom of the crowds `>>>>` the non-democratic and rapidly obsoleted decision of a single individual.
Comment: There's an advantage to this approach: The "pop" operation becomes O(1), so you can put it in a loop. Allocating the array is still O(n) and slower than using the subarray approach, but this has its merits.
Answer: You can also get all but the last argument with
"${@:0:$#}"

which, honestly, is a little sketchy, since it seems to be (ab)using the fact that arguments are numbered starting with 1, not 0.
Update: This only works due to a bug (fixed in 4.1.2 at the latest) in handling $@. It works in version 3.2.
Comment: Code `"${@:1:${#}-1}"` is exactly what makes full list of arguments like in "$@" without the last one.
Comment: It would appear this worked in `bash` 3.2 due to a bug that was subsequently fixed.
Comment: Right. The sketchy part is using 0 as the first argument to avoid having to subtract 1 from the second.
Comment: Actually, index 0 includes non-argument - path to the script being executed (a value automatically provided by shell). You are not avoiding subtraction of 1 - the last argument is still included and you must subtract 1. Using 0 is simply adding one more (likely not required) value to the list.
Answer: set -- "${@:1:$#-1}"

sets the parameter list to first up to penultimate, removing the last one


I need help with this divisibility problem.

Question: I need help with the following divisibility problem.
Find all prime numbers m and n such that $mn |12^{n+m}-1$ and $m= n+2$.
Comment: You have primes $p$ and $p+2$, and you want to choose $p$ so that $p(p+2)\mid 12^{2p+2}-1=\left(12^{p+1}-1\right)\left(12^{p+1}+1\right)$.
Comment: What theorems do you know that could be helpful for this problem?
Comment: $(5,7),(11,13),(29,31)$
Answer: You want to solve $p(p+2)|(12^{p+1}-1)(12^{p+1}+1)$.
Hint: First exclude $p=2,3$, so we have
$$\eqalign{
12^{p+1}-1 \equiv 143 &= 11 \cdot 13 &\pmod p,\\
12^{p+1}+1 \equiv 145 &=  5 \cdot 29 &\pmod p,
}$$
and deduce that $p$ must be one of $5,11,29$.
Edit: I'll just add more details: We want that $p$ divides $(12^{p+1}-1)(12^{p+1}+1)$, so $p$ must divide one of the factors of this product. Suppose $p|12^{p+1}-1=k\cdot p+143$ (the congruence follows from Fermat's little theorem). This means $p|143$ and hence $p=11$ or $p=13$. If $p+2$ is prime then we automatically have $p+2|12^{p+1}-1$ again by Fermat's theorem, so $p=11$ is a solution. $p=13$ isn't, as $p+2$ is not prime.
In the other case, $p|12^{p+1}+1$ we get 2 solutions, $p=5$ and $p=29$.
Comment: I think I fixed the TeX, but I'm not sure which moduli your congruences are using. You can use `\pmod{...}` for that.
Comment: Something's wrong with the tex-compiler. I wanted to insert a linebreak into the equations, which is properly displayed in the preview, but not here. Does anybody find my mistake?
Comment: I don't see how you got $143$, could you elaborate?
Comment: @Gigili: $12^2-1|12^{2k}-1$ for all $k\in\mathbb{N}$
Comment: Ah yes, thank you @bgins.
Comment: This isn't enough to make that deduction. Surely $12^{p+1}\pm1$ have other prime factors. It is a nice *sufficient* condition, but not a *necessary* one.
Comment: @bgins: I am saying that in order to solve the problem $p$ necessarily divides $12^{p+1}+1$ or $12^{p+1}-1$. $12^{p+1}-1$ (resp. $+1$) is divisible by $p$ iff $p=11,13$ (resp $5,29$).
Comment: For example, $p,p+2$ could divide $\Phi_d(12)$ for any $d|2(p+1)$ since $x^t\pm1=\prod_{d|\frac{3\pm1}{2}t}\Phi_d(x)$.
Comment: I think the argument is okay, but could use a little more explanation. Since $12^{p-1}-1$ is divisible by $p,$ we do have $12^{p+1} -1 \equiv 143$ (mod $p$) and $12^{p+1}+1 \equiv 145$ (mod $p$). But given that $p$ divides the product of these two numbers, either $143$ or $145$ must be divisible by $p.$ Since we are told that $p+2$ must be prime, we can't havd $p =13.$ Also, since $p+2$ is prime, $12^{p+1}-1$ is divisible by $p+2.$
Comment: @bgins: I'm sorry I still don't get your remark. I added some details to my answer, do you still think it's wrong? I see one mistake you made though. The 143,145 both come from Fermat's little theorem and not from $12^2|12^{2k}-1$.
Comment: Okay, I'm convinced now. Looks great! You should also mention as @GeoffRobinson (and I did in my post) that we get $p+2|12^{p+1}-1$ "for free" from Euler's theorem since $\operatorname{ord}_{p+2}(12)|\phi(p+2)=p+1$.
Comment: @bgins: Thanks, added!
Comment: I was confused because I didn't see that you were using Fermat's little theorem and looking at these `\pmod p`; in my confusion, I glossed over that and assumed you were using the property of primes that $p|ab \implies p|a$ or $p|b$. I changed the TeX to reflect that (the `\mod p` wasn't rendering at all on my system -- even hiding the $p$), lest anyone else make my mistake.
Comment: I would start your post off like this: You want to solve $p(p+2)|(12^{p+1}-1)(12^{p+1}+1)$.

Clearly $p\ne2,3$ since $12^{2p+2}\equiv1\pmod p$.

For the larger prime,
$(p+2)|(12^{p+1}-1)$ follows from Euler's theorem:
$\operatorname{ord}_{p+2}(12)\,|\,\phi(p+2)=p+1$.

From the smaller prime, we can then solve the problem.
Answer: Here are some thoughts to start off...
The first twin primes are $(n,m)\in\{(3,5),(5,7),(11,13),(17,19)\}$. Clearly $3\not\mid12^{m+n}-1$ since $12^{m+n}\equiv0\pmod3$. Furthermore, $12^{m+n}\equiv1\pmod{m,n}\implies2,3\not\mid m,n$ and $m+n\equiv0\pmod{m-1,n-1}$, which seems like it could disqualifies many candidates.
However, $11\cdot13=12^2-1\mid12^{24}-1$ so $(11,13)$ is a solution...
If $m=6k+1,~n=6k-1$ is prime, then $m-1=6k\mid m+n=12k$ $\implies$
$12^{12k}\equiv1\pmod m$ for free (from Euler's theorem), while $12^{12k}\equiv1\pmod n$ iff $\operatorname{ord}_n12\mid12k$.
Now

for $k=1$, $\operatorname{ord}_512=4\mid12$;
for $k=2$, $\operatorname{ord}_{11}12=1\mid24$;
for $k=3$, $\operatorname{ord}_{17}12=16\not\mid36$;
for $k=4$, $m$ is not prime;
for $k=5$, $\operatorname{ord}_{29}12=4\mid12\cdot5$;
for $k=7$ (the next twin prime pair), $\operatorname{ord}_{41}12=40\not\mid12\cdot7$.

Perhaps there is a good argument why all solutions must be of the form $6k\pm1$.
A little checking in sage shows that @Pedja's solutions, $k=1,2,5$, are the only ones of this form for $k\le10^6$.
<code>for k in range(1,100):
    m = 6*k+1
    n = 6*k-1
    if is_prime(m) and is_prime(n):
        test_order = multiplicative_order(mod(12,6*k-1))
        test_value = 12*k % test_order
        print '%5d%5d%5d%5d%5d' % (k, m, n, test_order, test_value)

1 4
2 1
5 4
</code>
In fact, there is a good argument using Fermat's little theorem, and @Michalis presents it in his post.


Suspender processo

Question: Estou tentando suspender um processo do windows pelo Delphi, porém sem sucesso, estou usando o seguinte código:
function SuspendProcess(pid:dword):boolean; // Suspende processo pelo PID
var module,module1:thandle;
    SusPendProcess:TNTdllApi;
begin
  result := false;
  SetTokenPrivileges;
  module := LoadLibrary('ntdll.dll');
  @SusPendProcess := Getprocaddress(module,'NtSuspendProcess');
  if @SusPendProcess <> nil then
    begin
      module1 := OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);
      SusPendProcess(module1);
    end;
end;

Onde informo o PID, porém nada ocorre, agora utilizando a ferramenta PC Hunter, ele suspende sem nenhum problema.
Seria possível fazer uso da PSSuspendProcess/ZwSuspendProcess?
Poderiam me ajudar com algum exemplo? obrigado!
Answer: Encerrar o processo resolveria o seu problema?
Se resolver tente:
PostMessage(FindWindow(<nome_da_tela_principal_do_processo>, nil), WM_CLOSE, 0,0);

Suspender processo


looping through element of XDocument and getting specific attributes

Question: I am currently in the process of rewriting my XmlDocument and XmlElements to XDocument and XElement. I've run into a small problem, I used to simply select a single node ModuleRequests and than loop through it. I thought simple right I'll just rewrite this:
var propertiesRequested = new XmlDocument();
propertiesRequested.LoadXml(propertiesConfiguration);
var requests = propertiesRequested.SelectSingleNode("ModuleRequests");
foreach (XmlNode request in requests)
{
    var propertyValue = request.Attributes["Id"].Value;

    if (systemProperties.ContainsKey(propertyValue) == false)
    {
        systemProperties.Add(propertyValue, request.Attributes["Request"].Value);
    }
}

To this:
var propertiesRequested = XDocument.Parse(propertiesConfiguration);
var requests = propertiesRequested.Element("ModuleRequests");

foreach (XNode request in requests)
{
    var propertyValue = request.Attributes["Id"].Value;

    if (systemProperties.ContainsKey(propertyValue) == false)
    {
        systemProperties.Add(propertyValue, request.Attributes["Request"].Value);
    }
}

Well needless to say it isn't that easy, then I thought fine i'll make it:
foreach(XNode request in requests.Nodes())

but this gave me even more problems since an XNode does not have an attribute.
As you can probably tell I'm a bit of a novice when it comes to xml reading. I'm hoping someone can help me out. What is the correct way to rewrite from XmlDocument to XDocument
Answer: You want to use XElement.Elements() to iterate through all child elements of your requests element, then use XElement.Attribute(XName name) to fetch the specified attribute by name.
You might also consider explicitly casting your XAttribute to a string rather than using the Value property, as the former will return null on a missing attribute rather than generating a null reference exception.
Thus:
var propertiesRequested = XDocument.Parse(propertiesConfiguration);
var requests = propertiesRequested.Element("ModuleRequests");
foreach (var request in requests.Elements())
{
    var propertyValue = (string)request.Attribute("Id");

    if (systemProperties.ContainsKey(propertyValue) == false)
    {
        systemProperties.Add(propertyValue, (string)request.Attribute("Request"));
    }
}


What are the greek modes, and how do they differ from modern modes?

Question: This Question might be TwoFold, based on an uncertainty I have
I understand the construction of traditional Ionian-Locrian modes, and I have read that various notes in the modes have traditionally been slightly sharpened/flattened from what they are today, so for example instead of DEFGABCD perhaps the Dorian Mode was DE(slightly flat)FGABC
What are the original greek modes?
How do the slightly sharp/flat notes translate to playing a mode today? (how would you notate greek modes now including microtonal pitch differences)
Comment: This may be related to just intonation vs equivalent temperament, see [http://music.stackexchange.com/a/3487/28](http://music.stackexchange.com/a/3487/28)
Comment: Maybe someone over at [history.SE](http://history.stackexchange.com) can provide an extensive answer? Perhaps repeat the question there?
Answer: I am really not knowledgable in ancient music theory so the following might be riddled with errors, but here is what I've gathered.
What are the original Greek modes?
Ancient Greek music scale theory was built upon the concept of the "tetrachord" - literally meaning four strings. A tetrachord consists of a group of four notes with three smaller intervals that together span the total interval of a perfect fourth (a 4:3 frequency proportion). The fourth was viewed as the basic unit for tuning, perhaps comparable to the octave of modern western music. In short there were three tuning genera or tonoi for a tetrachord, signified by the greatest appearing interval. (Example notes are in descending order as is apparently historically correct.)

Diatonic (a-g-f-e)
{Greatest interval: approximately a whole tone}

Chromatic (a-f#-f-e)
{Greatest interval: approximately a minor third}

Enharmonic (a-f-fd-e) [fd denotes the quarter tone below f]
{Greatest interval: approximately a major third}

The three internal intervals of a genus could be arranged in different permutations.
These tetrachord permutations or harmoniai were:

The dorian group (a-g-f-e)

The phrygian group (a-g-f#-e)

The lydian group (a-g#-f#-e)

Tetrachords were stacked to form greater systems of intervals. For instance, if you stack two diatonic lydian tetrachords on top of each other with a whole tone in between, you end up with what we today refer to as the diatonic major scale: e-d#-c#-b+a-g#-f#-e. The whole tone distance [9:8 frequency proportion] between the tetrachords is natural since it is the difference between a perfect fourth and a perfect fifth. Also, having two tetrachords of perfect fourths with a whole tone in between means that you end up with a perfect octave.
One important system of stacked tetrachords was the "Greater Perfect System". It can be constructed using diatonic dorian tetrachords thus: Stack two of them (e-d-c-b and a-g-f-e) with a whole tone in between. Extend this system at each end by adding two conjunct tetrachords each sharing one note with the existing tetrachords. Finally add a whole tone to the bottom of the system in order to end up with a complete two octave span:

The Greater Perfect System

      | tetra | tetra |
 a-g-f-e-d-c-b-a-g-f-e-d-c-b-a
| tetra |           | tetra |

Starting from different places in the Greater Perfect System gives the seven different harmoniai, or ancient greek modes, as follows (with example note names to illustrate the distribution of intervals - semitone intervals in bold):

Dorian (e-d-c-b-a-g-f-e)

Phrygian (d-c-b-a-g-f-e-d)

Lydian (c-b-a-g-f-e-d-c)

Mixolydian (b-a-g-f-e-d-c-b)

Hypodorian (a-g-f-e-d-c-b-a)

Hypophrygian (g-f-e-d-c-b-a-g)

Hypolydian (f-e-d-c-b-a-g-f)

Although the names of the modern church modes are drawn from the nomenclature of the ancient Greek modes, their uses don't match up. A german wikipedia article speaks of a translation error regarding this. And the english version has this text

"The Greek concepts of scales (including the names) found its way into
later Roman music and then the European Middle Ages to the extent that
one can find references to, for example, a "Lydian church mode",
although [the] name is simply a historical reference with no
relationship to the original Greek sound or ethos." [Emphasis is mine]

And another site says that mediaeval European music scholars misinterpreted the Latin works of Boethius, causing the shift of what mode is refered by what name.
How do the slightly sharp/flat notes translate to playing a mode today?
The Pythagorean Philolaus defined the interval ratios of the diatonic dorian tetrachord as 9:8, 9:8, and 256:243. This is the basis for what is refered to as the Pythagorean diatonic scale. Another Pythagorean, Archytas, defined interval divisions for all three tetrachord genera as:

the enharmonic 5:4, 36:35, and 28:27

the chromatic 32:27, 243:224, and 28:27

the diatonic 9:8, 8:7, and 28:27

More on Pythagorean tunings of tetrachords is found here.
The following table compares the tunings of Philolaus (Pythagorean diatonic) and Archytas to the modern equal tempered tuning (12-TET).

How would you notate greek modes now including microtonal pitch differences?
Regarding notation of microtonal shifts from a base system, besides the use of a backwards flat sign (b) and a half sharp/hash sign (#) to denote quarter notes, I have seen various signs including plus signs and arrows to denote microtonal shifts from a base system. But how to represent the differences according to the table above is for someone more well-versed in the area to elaborate on.
My guess, though, would be that, if the whole composition is to be performed using a specific tuning, you simply state that in the liner notes and then use regular modern notation.

The following are some of my sources:
http://en.wikipedia.org/wiki/Musical_system_of_ancient_Greece
http://www.midicode.com/tunings/greek.shtml
http://en.wikipedia.org/wiki/Ancient_Greek_music
http://en.wikipedia.org/wiki/Tetrachord
http://en.wikipedia.org/wiki/Pythagorean_tuning
http://de.wikipedia.org/wiki/Musiktheorie_im_antiken_Griechenland
http://sv.wikipedia.org/wiki/Den_grekiska_antikens_musik
http://no.wikipedia.org/wiki/Tetrakord
http://sv.wikipedia.org/wiki/Tetrakord
http://mixolydian.askdefine.com
Comment: Good answer, supplement Harry Partch's "Genesis of a Music" where he covers the Greeks very nicely.
Comment: Brilliant answer, but might I suggest you include a link to what stacking is? there's a great one introduction at http://www.youtube.com/watch?v=hV7UDp5V1AE
Comment: I'm sooooo tempted to give you the bounty now. But I'm gonna wait a few days at least to try to attract more. You're definitely the front-runner. :D
Comment: @luserdroog :-) I'm hoping for an ancient music expert historian to turn up and give a complete exposé on tetrachords, early music theory, and the evolution of the concept of modes.
Answer: What you are asking about doesn't really have to do with modes or accidentals. Essentially what you are talking about is the difference between modern equal temperament on the one hand, and just intonation on the other.
Up until the late 1800s, musical instruments could play the traditional Greek modes and scales based on pure intervals, but a given instrument could only play in tune in a few keys, certainly not all 12 keys. Since the late 1800s, a new system in tuning instruments was developed: that system is called equal temperament.
With modern equal temperament, our instruments are calibrated to play 12 notes in an octave, all of which are equally spaced apart by 100 cents. This system is only about 125 years old.
Before that, people used various kinds of compromises on just intonation, where intervals are pure. In a just-intonation C-major scale, there are half-steps and whole steps, and we call the pitches by the same names that are used in equal temperament, but the various half-step intervals all have a slightly different size, as do the whole-step intervals.
The music written by Bach or Mozart  or any of those composers, and certainly all of the ones that came before, was not composed to be played in equal temperament like we usually do today.
This is a deep and complex subject that requires a lot of mathematics to explain, and I don't choose to go into that here. You can find plenty of references on just intonation online.
Here is one observation for you to think about: On a modern piano or guitar, which is tuned to equal temperament, all the major third intervals are considerably sharp compared to a pure, just-intoned major third. The equal-temperament system was developed to permit an instrument like a piano or guitar to play all the modes in all 12 keys and have them reasonably in-tune, but not perfect. Before about 125 years ago, a piano would be tuned to a mean-tone system, a modification of just intonation, that enabled certain keys and certain intervals to sound really in tune, and certain other keys would sound really out-of-tune.
Today, when singers in an acapella choir sing together, they can make pure major-third intervals (and other intervals as well), and so can a string quartet, where the instruments have no frets. But if singers or string instruments play along with a piano or guitar, they can no longer make those pure intervals because they clash very slightly with the equal-tempered pitches on the piano or guitar. So, really without even thinking about it, singers and string players adjust their intonation away from just intonation and toward equal-temperament, depending on the situation.
None of this distinction between just intonation, or meantone intonation, or equal temperament, has any impact on how the music is notated. We use the same 12 pitches and the same sharps, flats and naturals (although G-sharp and A-flat may be distinct pitches which are tuned slightly differently, for example). The difference is how it is performed and on which instruments and how they are tuned.
Again, this is a deep subject and I can't thoroughly explain it without writing a book on it, but there are plenty of books already written on the subject and you can go looking for them if you would like to.
Update: See my post from December 23, 2012 where I present a chart showing the differences between equal temperament and just intonation, measured in cents. (A cent is 1/100th of a modern equal-tempered half-step interval.)
https://music.stackexchange.com/a/8022/1044
Comment: I am downvoting this, because the OP is really asking about the original greek modes, like Hypophrygian, not intonation or temperament. Also, according to wikipedia (https://en.wikipedia.org/wiki/Just_intonation), it was actually a Roman that first described just intonation. Apart from that, good text.
Answer: There are two things you need to be aware of when it comes to modes.

the modes of the major key (Ionian, Dorian, etc)
the "modal" style of jazz created by McCoy Tyner and others in the 1960s which includes, among other things, the use of quartals and side-slipping of pentatonic scales

So when you talk about modes be sure to specify which one.
Regarding the Greek modes, there aren't/weren't any "slightly sharp or flat" notes, you must have misinterpreted something you read. There are certain cases where a sharp might occur in order to produce a secondary dominant.
Comment: -3: Any professional musician needs to know about justly tuned 3rds, 5ths, and 7ths, and entire cultures of music are based around non-equal-tempered scales -- to say nothing of the present-day microtonal composers... heck, I've taken an entire college course about those.
Comment: As has been mentioned in other answers, modes have Existed long before jazz.  I already know modern modal theory, but modern modes originated from greek modes.   As far as slightly flat/sharp goes, the equal temperament system didn't come around until much later, so playing a D Dorian scale would not have the same frequencies as a modern D dorian. (IE some notes would be slightly sharp, and some flat).
Comment: First two points: correct. Your last point: doesn't matter when it comes to making music; completely irrelevant to being a musician.
Comment: @Michael: I find it odd that you find differences between [tuning systems](http://en.wikipedia.org/wiki/Musical_tuning#Tuning_systems) irrelevant to musicians. I believe a lot of people would disagree with you including Bach, Pythagoreans, middle east musicians, etc, and anyone not using or limiting themselves to the equal tempered scale or tuning.
Comment: @MichaelMartinez I think the history of music, and the way it was originally played is very relevant to being a musician.  The way our entire system ended up is the result of one set of paths from that origin.  Going back and seeing what the sound is like allows not only music that hasn't been heard in centuries, but a deeper understanding of sound and the potential to open peoples ears to music that they've never heard.  If you're claiming that's useless then by extension you're claiming all music theory is useless.


upload de imagens + web service php

Question: Boa pessoal, estou meio atrasado no meu tcc por motivos de não conseguir fazer o upload da imagem. O que tenho hj funcionado e tirar a foto, salvar em no bando sqlite o caminho e latitude e longitude, porem tenho uma tela no meu app que devo enviar uma imagem com um cadastro, o cadastro esta ok somente faltando a imagem. Os dados do cadastro são enviado para um web service em PHP, porem não sei como vou fazer pra enviar a imagem, sendo que tenho que selecionar a imagem da galeria e enviar,retornando o caminho dela e salvar no banco junto com os demais dados do formulario enviado. Se alguem puder me dar um help ai agradeço...
CODIGO DO WEB SERVICE
 <?php
 if($_SERVER["REQUEST_METHOD"]=="POST"){
require 'connect.php';
inReg();
 }
 function inReg() {

    global $connect;

    $id_usuario = $_POST["id_usuario"];
    $tipo_atividade = $_POST["tipo_atividade"];
    $tipo_local= $_POST["tipo_local"];
    $quantidade = $_POST["quantidade"];

    $query = " Insert into registro_animal(id_usuario, id_tipo_atividade,id_tipo_local,quantidade) values ('$id_usuario','$tipo_atividade','$tipo_local','$quantidade')";
        mysqli_query($connect, $query) or die (mysqli_error($connect));
    mysqli_close($connect);
}

 ?>

Comment: Eu sei fazer isso, mas estou no serviço e não posso te ajudar agora! =)
Comment: Sem estresse, a hora que puder me ajudar será ótimo, pois estou atrasado nesta questão. Fico no aguardo!
Comment: Coloquei uma resposta e um link no final que vai te ajudar bastante. Praticamente está pronto para você, só tem que ter as manhas de adaptar ao seu código.
Answer: Recebendo imagem
A princípio é necessário fazer um upload clássico e rápido de apenas um arquivo.  Um dos atributos que não podemos esquecer para fazer upload, é o que seta o enctype ao nosso formulário. Uma das maneira é usar method="POST" e enctype="multipart/form-data".
Método POST

Este recurso permite realizar uploads de arquivos de texto e binários.
  Com as funções de autenticação e manipulação de arquivos do PHP, você
  tem o controle completo de quem pode fazer o upload e o que deve ser
  feito com o arquivo após o upload estar completo.

PHP
if(isset($_FILES['fileUpload'])){
      date_default_timezone_set("Brazil/East"); // definindo timezone padrão

      $ext = strtolower(substr($_FILES['fileUpload']['name'],-4)); //pegando extensão do arquivo
      $new_name = date("Y.m.d-H.i.s") . $ext; //definindo um novo nome para o arquivo
      $dir = 'uploads/'; //diretório de destindo do arquivo

      move_uploaded_file($_FILES['fileUpload']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo
   }

Como um "boa prática" é definido uma variável com o ano, mês, dia, hora, minuto e segundo, concatenando com a extensão da imagem. Para finalmente fazer o upload do arquivo, é usado a função move_uploaded_file, passando dois parâmetros, primeiro o nome temporário da imagem armazenado pelo servidor, e o novo nome do arquivo, já com diretório padrão.
Enviando imagem
Já no envio por parte do Android, uma das formas é você usar:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

build.gradle
android {
    useLibrary 'org.apache.http.legacy'
}

Para mais detalhes, você pode acessar este artigo Android Uploading Camera Image, Video to Server with Progress Bar que te ajudará bastante.
Comment: Obrigado pela resposta, vou tentando aqui, qualquer coisa volto a perguntar !

upload de imagens + web service php


Compare sytem time to user input time php mysql

Question: I have a form and one of the requirements I need from the user is a specific time. this is done via a drop down menu. An example of a time in the drop down menu is
<option value="06:00:00">6:00 AM</option>

The above saves time as 06:00:00 in mysql database.
However I need to compare this time to the current system time but I get a null value. I tried comparing it with time() but it doesnt work. Converting the 06:00:00 to unix time using strtotime function gives me 838:59:59 as the saved time value in my database for ALL time options.
How can I compare the User input time to the system time. All help will be appreciated.
Comment: compare means `<= >= ==` what... ?
Answer: 6AM isn't a timestamp. 6AM on February 7th is a timestamp.
You can't compare them. 6AM is both before 6AM on February 7th (because there was a 6AM yesterday) and after (because there is a 6AM tomorrow).
Once you define what you want this 6AM to mean in your application, you should have some idea how to compare it to the current time (hint: add a date).
Comment: I totally understand you. However I want to send a reminder to someone at 6 AM everyday for a time period specified i.e the user gets to specify from which date till which date he/she wants the reminder. The server basically checks for reminders every hour e.g 6AM, 7AM and so on and and if it gets one, sends an sms
Answer: use mktime and time
    <?php
      $lastpost = mktime(5,15,0,10,1,2002); // mktime is as follows (hour, minute, second, month, day, year)

        $timenow = time();

        if ($timenow > $lastpost ) {
        return true;
        } else {
        return false;
        }

?>


How to accumulate and appy gradients for Async n-step DQNetwork update in Tensorflow?

Question:
I am trying to implement Asynchronous Methods for Deep Reinforcement Learning and one of the steps requires to accumulate the gradient over different steps and then apply it.
What is the best way to achieve this in tensorflow?
I got so far as to accumulate the gradient and I don't think is the fastest way to achieve it (lots of transfers from tensorflow to python and back).
Any suggestions are welcome.
This is my code of a toy NN. It does not model or compute anything it just exercise the operations that I want to use.
import tensorflow as tf

from model import *

graph = tf.Graph()

with graph.as_default():

    state = tf.placeholder(tf.float32, shape=[None, 80,80,1])

    with tf.variable_scope('layer1'):
        W = weight_variable([8, 8, 1, 32])
        variable_summaries(W, "layer1/W")
        b = bias_variable([32])
        variable_summaries(b, "layer1/b")
        h = conv2d(state, W, 4) + b
        activation = tf.nn.relu(h)
        pool1 = max_pool_2x2(activation)

    print(pool1.get_shape())
    pool1 = tf.reshape(pool1, [-1, 3200])

    with tf.variable_scope('readout'):
        W = weight_variable([3200, 3])
        b = bias_variable([3])
        logits = tf.matmul(pool1, W) + b
        variable_summaries(h, "y")

    action_indexes = tf.placeholder(tf.int32, shape=[None], name="action_indexes")

    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, action_indexes)

    starter_learning_rate = 1e-6

    global_step = tf.Variable(0, trainable=False)

    # decay every 1000 steps with a base of 0.96:
    learning_rate = tf.train.exponential_decay(starter_learning_rate,
        global_step,
        10000, 0.96, staircase=True)

    optimizer = tf.train.RMSPropOptimizer(learning_rate)

    gradients_and_variables = optimizer.compute_gradients(loss, tf.trainable_variables())

    discounted_values = tf.placeholder(tf.float32, shape=[None, 1])

with tf.Session(graph=graph) as s:

    for v in tf.trainable_variables():
        print(v.name, v.dtype, v.get_shape())

    s.run(tf.initialize_all_variables())

    feed_dict= {
        state : np.zeros([1, 80, 80, 1]),
        action_indexes: [1],
    }

    var_to_grad = dict((var.name, grad) for grad, var in gradients_and_variables)
    keys = sorted(var_to_grad.keys())
    print(keys)

    name_to_var = dict((var.name, var) for _, var in gradients_and_variables)

    for i in range(10):

        gradients = s.run([ var_to_grad[k] for k in keys], feed_dict=feed_dict)

        for k,v in zip(keys, gradients):
            var_to_grad[k] += v

    for k in keys:
        print(var_to_grad[k])

    s.run( optimizer.apply_gradients( (g, name_to_var[v]) for v,g in var_to_grad.iteritems()), feed_dict=feed_dict)

Updated code after @yaroslave suggestion:
import tensorflow as tf

from model import *

graph = tf.Graph()

with graph.as_default():

    minibatch = 32
    state = tf.placeholder(tf.float32, shape=[minibatch, 80,80,1], name="input")

    with tf.variable_scope('layer1'):
        W = weight_variable([8, 8, 1, 32])
        variable_summaries(W, "layer1/W")
        b = bias_variable([32])
        variable_summaries(b, "layer1/b")
        h = conv2d(state, W, 4) + b
        activation = tf.nn.relu(h)
        pool1 = max_pool_2x2(activation)

    print(pool1.get_shape())
    pool1 = tf.reshape(pool1, [-1, 3200])

    with tf.variable_scope('readout'):
        W = weight_variable([3200, 3])
        b = bias_variable([3])
        logits = tf.matmul(pool1, W) + b
        variable_summaries(h, "y")

    action_indexes = tf.placeholder(tf.int32, shape=[minibatch], name="action_indexes")

    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, action_indexes)

    starter_learning_rate = 1e-6

    global_step = tf.Variable(0, trainable=False)

    # decay every 1000 steps with a base of 0.96:
    learning_rate = tf.train.exponential_decay(starter_learning_rate,
        global_step,
        10000, 0.96, staircase=True)

    optimizer = tf.train.RMSPropOptimizer(learning_rate)

    trainable_variables = tf.trainable_variables()
    varname_to_var = dict( (v.name, v) for v in trainable_variables )
    keys = sorted(varname_to_var.keys())

    gradients_and_variables = optimizer.compute_gradients(loss, [ varname_to_var[k] for k in keys])

    var_to_grad = dict((var.name, grad) for grad, var in gradients_and_variables)

    name_to_var = dict((var.name, var) for _, var in gradients_and_variables)

    # save the gradients in memory
    var_to_ref_grad = {}
    for k in keys:
        grad = var_to_grad[k]
        print(k, grad.get_shape())
        ref = tf.Variable(tf.zeros_like(grad))
        ref = ref.assign_add(grad)
        var_to_ref_grad[k] = ref

    discounted_values = tf.placeholder(tf.float32, shape=[None, 1], name='discounted_values')

    # control when to apply gradients
    compute_gradients_flag = tf.placeholder(tf.int32, name="compute_gradients")
    def fn1():
        var_grad_list = []
        for k in keys:
            grad = var_to_ref_grad[k]
            var  = varname_to_var[k]
            var_grad_list.append((grad,var))

        optimizer.apply_gradients(var_grad_list)
        return tf.no_op()

    fn2 = lambda : tf.no_op()

    last_op = tf.cond(tf.equal(compute_gradients_flag, 1), fn1, fn2)

with tf.Session(graph=graph) as s:

    feed_dict= {
        state : np.zeros([minibatch, 80, 80, 1]),
        action_indexes: [1],
        compute_gradients_flag: False,
    }

    s.run(tf.initialize_all_variables())

    for i in range(10):

        # accumulate gradients
        s.run(last_op, feed_dict=feed_dict)

Comment: You could keep everything in TF by running `assign` ops that save gradients in Variables instead of fetching the values, and then doing `assign_add` instead of to accumulate
Comment: @SungKim There's an immediate execution interface [in the works](https://github.com/tensorflow/tensorflow/pull/2595) so you could use standard Python constructs while keeping data on GPU
Comment: @YaroslavBulatov Do you think TF will add more interfaces for implementations like this? It would be nice if we can use TF for reinforcement-learning as well.
Comment: @YaroslavBulatov so I updated the code as you suggested, but now the interesting bit is that `tf.initialize_all_variables()` requires to run the operations in the graph to initialize the variables. Maybe I am doing it wrong and I would not have to use initialize_all_variables and just initialize those manually.
Comment: Hm, I don't understand the problem, `initialize_all_variables` should just run the initializers to set the initial value for the vars, what does it run that it shouldn't?
Comment: I think you should add trainable=False in this line ref = tf.Variable(tf.zeros_like(grad)). If not, the trainable_variables you called before will have the initialisation problem.
Comment: But it seems that this code doesn't reset the accumulated gradients to 0 after applying them to variables. Am I wrong? Is there any new updated code for sharing? Thanks.
Answer: You don't really have to manually accumulate gradients. You can have Tensorflow accumulate them for you by applying the rollout update as a batch.
s_list = list_of_states_visited
a_list = list_of_actions_taken
R_list = list_of_value_targets

sess.run(local_net.update, feed_dict={
    local_net.input: s_list,
    local_net.a: a_list,
    local_net.R: R_list
})

Answer: Something like this might work to create ops for accumulating gradients, resetting the accumulated gradients, and applying the accumulated gradients (untested!):
def build_gradient_accumulators(optimizer, gradients_and_variables):
    accum_grads_and_vars = []
    accumulators = []
    resetters = []

    for grad, var in gradients_and_variables:
        accum = tf.Variable(tf.zeros_like(grad))
        accum = accum.assign_add(grad)
        accumulators.append(accum)
        accum_grads_and_vars.append((accum, var))
        resetters.append(tf.assign(accum, tf.zeros_like(accum)))

    reset_op = tf.group(*resetters)
    accum_op = tf.group(*accumulators)
    apply_op = optimizer.apply_gradients(accum_grads_and_vars)
    return reset_op, accum_op, apply_op


How to prove the uniqueness of a polynomial with such properties?

Question: Let $p(x)$ be a polynomial of degree $n$ with real coefficients such that $$p(x-2)=p(x)-4x+14$$ for every real number $x$ and $$p(0)=6.$$ How can we prove that $n$ is $2$ and not higher than $2$?
Comment: $\forall x\in\mathbf{R}$,$\frac{p(x)-p(x-2)}{2}=2x-7$I don't think a polynomial with a degree higher than 2 will have such property.
Comment: Because of this formula:  $\frac{(x+h)^n-x^n}{h}=(x+h)^{n-1}+(x+h)^{n-2}x+\cdots+(x+h)x^{n-2}+x^{n-1}$
Answer: By differentiating twice we get:
$$p^{(2)}(x-2)=p^{(2)}(x)$$
Thus, $p^{(2)}(x)$ is  the constant polynomial. Now it follows that the degree of $p(x)$ is 2
Comment: I was thinking about that $+14$ above and could guess that was just for misleading.
Comment: @Amr That's a good answer. Thanks!
Answer: Amr's answer is much simpler, and was posted whilst I typed this out. I'll post this anyway because it's a different approach that doesn't require calculus (but is clunkier).
Restrict to even integer values of $x$: if $a_n = p(2n)$ for integer $n$, then rearranging gives
$$a_n - a_{n-1} = 8n - 14,\ \ a_0=6$$
so the sequence $(a_n)$ is one where the difference between any two terms is linear; hence $a_n$ is a quadratic polynomial in $n$.
So $p(2n)$ is a quadratic polynomial in $n$. This means that $p$ agrees with a quadratic polynomial at every even integer. But this means that it must be equal to this quadratic polynomial everywhere.
Why? Because if $q$ and $r$ are polynomials and $q(x)=r(x)$ for infinitely many values of $x$ then $q(x)-r(x)=0$ for infinitely many $x$, so $q(x)-r(x)$ has infinitely many roots, so it must be zero, and so $q=r$.
Comment: @Clive_Newstead I liked your answer too, because we don't need use derivatives. Thanks!
Comment: @Clive_Newstead : Nice approach
Answer: The solution of this problem is $p=x^2-5x+6$. It should be easy to prove that any formula $p=ax^n$ with $n>2$ will not work, by filling it in in the formula, and expanding $(x-2)^n-x^n$
Comment: I think that u need to show why $p(x)=a_nx^n+a_{n-1}x^{n-1}+...+a_0$ will not work even if $a_{n-1},a_{n-2},...$ are non zero when n>2


Chord inversions and consonance

Question: So the way I understand chords is based on the interval of the individual notes present in them. This is what gives the chord a consonant or dissonant quality.
However, this doesn't seem to sit well considering how people handle chord inversions.
For instance, if i play a C and the G a perfect fifth above it, that's a very consonant chord as a result of the perfect fifth interval. Sounds good.
But now if I invert the chord and play a C with the G below it, i have an chord with a perfect fourth interval, much less consonant than the first one.
As I read about inversions, people seem to consider these to be the same chord, but in some inversion. But it's clearly not the same chord any more, since the intervals have changed.
So why even have the concept of inversions? Just call it whatever you would call a G with the C a perfect fourth above it. It's a different chord with different intervals.
Comment: If the chord is being arpeggiated, yes... as then it's a melody and each note is an interval away from the next different note. But a strum or plucking notes simultaneously aren't playing intervals but instead solfege ... So and Do (sound similarly) along with a Mi.

Does an up strum sound different than a down strum if each one takes a very small time?
Answer: Inversions of a chord do have the same root but do not have the same uses in general. A major or minor triad (C-E-G or C-Eb-G or 1-3-5) in root position is considered stable (in itself it does not imply other chords to follow.)
In first inversion (with the 3 in the bass or E-G-C) the chord is nearly as stable; it doesn't often end a piece but is used to end phrases. Another use is to make a smoother sounding bass line. Take the Romanesca pattern (which is still being used though four or five hundred years old): C-G-a-e or in minor c-g-Ab-Eb; the bass rises a fifth (or falls a fourth), rises a second (or drops a seventh), and repeats. (Pachelbel's Canon among others.) By using inversions one has C-G/B-a-e/g or c-g/Bb-Ab-Eb/G which gives a stepwise descending bass line. Similarly for the circle of fifths (or cycle or fourths depending) one can alternate root position with first inversion chords to yield smoother bass lines.
The second inversion major or minor chords are a bit less stable. According to "strict" counterpoint, this chord is dissonant because of the fourth between the bass and middle note. One use is in arpeggios a C-E-G-C-E-G-C-E-G (in different octaves of course) doesn't sound much different from (E-G-C-E-G-C... or G-C-E-G-C-E...). Another use is as a neighbor chord C-G-E followed by C-F-A then C-G-E. A more idiomatic use from the Common Practice Period is similar the the previous but with a dominant seventh chord. The common chord progression (again 500 or so years old) of ii6-V7-I or ii06-V7-i or ii6-V-I, etc. is often has a I64 (sometimes notated as V64) between the V and I chords. Thus one gets the chord progression ii-I64-V7-I (or in C major D-F-A, G-C-E, G-B-D, C-E-G with voice leading adjusted). The G-C-E acts as a neighbor to G-B-D, similar to the other neighbor usage. Another (common in the 1700s but often discussed at present) occurs in the Romanesca (Pachelbel's Canon) C-G/B-a-C/G-F-C/E-F-G (or variants like C-G/B-a-C/G-F-C/E-d/F-G).
So the inversions are root (53)(most stable), first inversion (63) a bit less stable, second inversion (64) dissonant. The more unstable or dissonant, the more careful one tends to be in using that inversion.
Answer:
...So why even have the concept of inversions?

A real answer is a deep delve into music theory history. One very important thing to read about is Rameau's theory of the Fundamental Bass. The essential idea is that harmony is based on chord roots rather than the lowest tone in the bass voice. Understanding chord inversions allows you to identify a chord root. Modern harmony analysis is based on chord roots using Roman numeral analysis.

...Just call it whatever you would call a G with the C a perfect fourth above it.

You can. Figured Bass was the system used before Roman Numeral Analysis and chord inversions were used. You need staff notation to actually write it, but in English it would be described just as you suggest: "a G with a perfect fourth and a (diatonic) sixth above."

...It's a different chord with different intervals.

Prior to the concept of fundamental bass that's sort of what people thought. But we should not overstate things or overlook how important counterpoint was in the system of harmony.
Musicians could obviously see that (from bass to treble) ECG was the same collection of tones as CEG and in the key of C major clearly are a collection of the tonic chord. Rather that thinking of it as a E chord, it was something like: an E bass should be harmonized with a chord of the sixth (meaning a first inversion chord.) The progression of the harmony was then a question of stable perfect chord & unstable chords of the sixth within a scale, voice leading, and tonal goals rather than the movement of roots.
A chord inversion concept in necessary to define chord roots and do RNA harmonic analysis (a music analysis purpose.)
Chord inversions are not necessary to do figured bass or 18th century counterpoint based harmony (a music performance and composition purpose.)
Comment: I know you didn't mean it like that, but in a way I read your answer like "chord inversions are useful only in theory, or for theory". ;) My perspective is completely the other way around: chord inversions were an obvious necessity in order to play music in practice, and I was using them before even hearing the word "inversion" or knowing much theory at all. It seemed weird when I learned about all these weird names and seemingly complicated theoretical concepts for this very basic thing.
Comment: Well, I meant something more like 'useful only in music analysis not composition.' I very much do mean that. If someone wants to play or write in an 18th century style, I think the _actual 18th century methods_ are better than RNA. Mine isn't an argument like 'inverted chords aren't real' it's more about which system is better at explaining the practical use of inverted chords.
Answer: I want to give a different view for why chord inversions are useful.
Why do chords exist? Because by playing multiple notes at the same time you're able to manipulate the feeling of harmonic context in the listener's mind more effectively than you can by playing just one note at a time. With harmony voices, music feels fuller, has the possibility to create stronger emotions, and can re-direct the interpretation of melodies. The lead melody can consist of only C notes, but when accompanied with different harmony notes, each C is felt from a different point of view.  And musicians have noticed that the note combinations are not at all arbitrary or chaotic, but there's a certain logic to them... So, simultaneous note combinations are called chords, which are used as handy reusable building blocks for harmonic changes. And we have a system for naming chords based on their structural patterns ... So now we can accompany the C note with e.g. Bb11, Am, Ab, G11, Dbmaj7, and it will sound much more interesting than just C all the time, making it feel as if there was a progression.
If you take a melody and harmonize it by placing chord notes below it, you create inversions. Pianists and organists will inevitably end up doing this, if they want to play both the melody and accompanying harmony notes at the same time, with just one hand. (or two hands, but with one hand it's more obviously seen that you're playing chord inversions)
Maybe you've noticed that when the lowest note is moved, it creates a different sensation than when the highest note moves. If you want to move the bass line, and place chord notes above it, you create inversions.
If you want to keep the bass note and the melody note, but move the notes in between them, you create inversions of some chords.
If you want to do all this at the same time: move the highest note along a melody line, move the bass note, and the notes in between, you create inversions. In whatever way you want to place more than one note, it can always be seen as some inversion of some chord.
All inversions of C major can be used to perform essentially the same harmonizing function of a C major chord. No matter which inversion you pick, it will work as accompaniment. Or, can you find a way to order the notes C, E and G so that it just completely won't work as the first accompaniment chord of Yesterday, spoiling the whole thing?
It is useful to look at the group or "class" of chords consisting of inversions of a chord as practically the same chord, because any chord inside the same class can be used in the same basic harmonic role. There are other aspects to harmony like bass movement and movement of inner voices, but they can be considered secondary aspects, because they cannot completely ruin the big overall story line.
Answer: There are a few reasons that come to mind. First, a chord is a by definition set of notes and while voicings and the inversion shape the exact, knowing the set of notes played gives a lot of information for things like function, improvisation, and reharmonization. Don't get me wrong, the inversion does play a part in harmony, but it's one of many aspects that shape it.
If you are coming from classical harmony, building chords in 3rds is the bread and butter of harmony so looking at sets of notes as inversions rather than new constructs is helpful. It's also the source of most names we come up with. There is a more post tonal way to look at chords, but even then they tend not to take voicings into account and they have a much more mechanical inversion simplification called prime form where major chords [0, 4, 7] and minor chords [0, 3, 7] end up having the exact same prime form due to them containing the same exact intervals.

In general, there's a lot more to chords outside the inversions. For example, if you were to try to harmonize a C chord in close position and you did it in a lower octave, most people would call it more dissonant than a close position chord in higher octaves.
Answer: Let's think of the harmonics in the sound. Most musical sounds consist of a fundamental and then further overtones at (roughly) integer multiples of the frequency.
For the sake of simplicity, let's imagine that the instrument timbre we're using has 3 overtones - and that rather than C, we're playing a note of 100Hz. That means it has partials at 100, 200, 300, and 400Hz.
A fifth is a frequency ratio of 3:2, so our fifth will have its fundamental at 150Hz - and then have energy at 300, 450, and 600 Hz.
So the resultant sound has components at  100, 150, 200, 300, 400, and 600 Hz.

But now if I invert the chord...

Ok, let's play the 'fifth' an octave lower. It now has partials at 75, 150, 225, and 300 Hz.
So the resultant set (added to our 100Hz note) is 75, 100, 150, 200, 225, 300, and 400Hz.
What's the difference? Well, 75 and 225 are new, and we've lost 600. But five of the original 6 frequency components (100, 150, 200, 300, and 400 Hz) are sill there. So there's still a lot of similarity between the new sound and the original one.

As I read about inversions, people seem to consider these to be the same chord, but in some inversion. But it's clearly not the same chord any more, since the intervals have changed.

Of course you're right in that it won't sound the same. But because

notes are named in an "octave repeating" way
two musical tones an octave apart will have some overtones in common, because a note's harmonics themselves are an octave apart

...there will be some similarity in the resulting frequency spectrum. The amount of similarity depends on the timbre of the actual notes you're playing.

So why even have the concept of inversions?

It's mainly an expression of similarity, rather than saying that they're actually "the same". They may be "the same chord" in terms of the name of the chord, but the fact that the name is the same shouldn't be taken to mean that they necessarily sound the same.
That's even true with chord names in other senses too - a 'C' chord in the bottom octave of the piano doesn't sound the same as a 'C' chord played in the middle of the piano keyboard, or on a guitar, or on an instrument tuned with a different temperament.

Chord inversions and consonance