what's wrong with my data?

Question: Sorry,owing to my reputation,I have to delete the above word.
Originally I just want to copy this page's method,the author use titanic data to analyze relationship between fare and survivor.
And I finally know what's wrong with my data,my churn definition is daydiff>=180,but it is possible when daydiff>180 but he is not churner,so I test this guess with new variable lastdiff(mean the difference between last order and today) and I add some nonchurner on daydiff>=180 or churner on daydiff<=179,the warning message is gone.
this is the result:

author's page:
https://sites.google.com/site/rlearningsite/analysis/catagory/logit
Comment: @jimmy, the folks here aren't around to do your analysis for you.  I think whuber is suggesting that you do this.  Doing so is a basic first step to any analysis and is something you should do anyway.
Comment: What does a plot of `churner` against `daydiff` look like?
Comment: I never consider draw a plot...you can try it with my data
Comment: @jimmy what data are you deleting and why?
Comment: I delete the data based on unequal proportion of churner and nonchurner,churner is 98% in all data
Comment: What kind of plot should I draw? histogram?
Answer: It's hard to know what is going on with your data, and as @StatsStudent points out, people here aren't going to do your analysis for you.  In the absence of more information, here are two wild guesses based on the fact that the estimate of your (Intercept) is -42497 and the warning message is that "...fitted probabilities numerically 0... occurred":

You have essentially no 0's in your churner variable, and
Your minimum daydiff value is very far from 0.

Beyond those (somewhat educated) guesses, there is no way to know what is wrong with your data.

Upon trying to edit your post, I find it is still largely unintelligible, but did you define a churner as any observation where daydiff is $\ge 180$?  If so, you have induced complete separation into your dataset (in addition to doing something completely incoherent).  You can find out more my clicking on the tag I added.
Comment: is right and I actually looked at your data as well.  There is a complete separation of data points at >=180 of daydiff.
Comment: Hey gung,you mean the data should contain churner with daydiff<=179?,and what is the second message(minimum daydiff far from 0) ,thanks

what's wrong with my data?


Invalid update SQL in DataGrip

Question: I wrote a MySQL update SQL on my DataGrip to update the wrong data:
update common_express_track set step = 135 where express_id in (33, 235, 237) and business_source = 0 and step = 0 and content = 'Out For Delivery' order by content;

I executed it, the console showed that "61 rows affected in 7s 530ms" and then I executed an another query statement to make sure the data has been modified.
select * from common_express_track where express_id in (33, 235, 237) and business_source = 0 and step = 0 and content = 'Out For Delivery' order by content;

Then the console shows that "0 rows retrieved in 3s 751ms".
But when I restart the DataGrip and execute the query statement again, I got 61 rows, that means the update statement didn't work, I don't know why, is it because the cache or something?
How to solve this problem?
Comment: use mysql console and check it there
Comment: Your `SELECT`'s `WHERE` contains `step=0`,while the `UPDATE` set it to 135....
Comment: @Usagi Miyamoto - yes, but rest of question explains why, it is ok
Comment: In sentence ` but when I restart the datagrip and execute the query statement again,` - do you mean second query?
Comment: BTW, what do you mean by "restart the datagrip"?
Comment: @UsagiMiyamoto I mean, I closed the datagrip and open it again, and then I executed the query statement to make sure the data has really changed
Answer: When you execute queries you should use Autocommit

Then by clicking on table in database view you will see refresh

Try use Autocommit with your query and refresh when you browse data. It should help.
Comment: OK! It works, I changed the Transaction Control option to Auto and this time the data is really modified. Thank you very much!  BTW, can you please tell me the difference between the manual option and auto option?
Comment: Without auto commit you should click commit to really execute your query, but you have also possibility to rollback. I recommend use this option on production database (if you do not selects before update), but when you develop it is simpler to use auto commit and confirm any query, then you will not forget about this.
Comment: Auto and Manual mode:
Submit button or ⌘Enter → submits your data, which means that your local changes(they are highlighted) are submitted to the database. If you are in the Manual mode this transaction is not committed.
Revert Selected from the context menu or ⌘⌥Z (it used to be ⌘Z , but Revert isn't Undo, right?) on selected rows → reverts unsubmitted local changes of the selected rows.
Comment: Only in Manual mode:
Commit button or ⇧⌘⌥Enter → commits the transaction. If you have unsubmitted local
changes (again, they are highlighted) they will be automatically submitted before the commit.
Rollback button → rolls back transaction if it's uncommitted.

Invalid update SQL in DataGrip


Including helpers when rendering a template/partial by hand

Question: I use the following code to render a template to a string that I can use later on:
renderer = ActionView::Base.new(MyApp::Application.config.view_path)
# INCLUDE HELPERS HERE
data = renderer.render(:partial => template, :locals => locals)

However, I want to be able to access some helpers (actually all). In rails 2.3 I was able to do this:
renderer.extend ApplicationController.master_helper_module

However, as of Rails 3, this no longer works. So, how do I make my helper methods available to use in my template?
Comment: Why would you want to render a template to a string ???
Comment: Actually, I am rendering to a file, that is later passsed on to a command line utility.
Answer: You may want to look at abstract_controller/rendering.rb It looks like in rails 3 we should be able to do something like this:
renderer = ApplicationController.view_context_class.new(...)

And the module master_helper_module is now accessed by name _helpers, and it should be already included in view_context_class
Comment: Thankyou, works like a charm! I actually ended up including a single helper in order to group functionality, but this is good to know.


Como optimizar meu acesso ao dicionário do Python?

Question: Tenho um dicionário da sequinte forma:
dicionario = {'1':'Banana','7':'Maçã','3':'Pera','2':'Melancia'}
Se eu verificar a chave '2' no dicionário: if '2' in dicionario:. Minha intuição de programador me diz que a complexidade desse comando é  O(n) no pior caso, pois existem n elementos dentro desse dicionário. Porém isso é um dicionário e não uma lista e não sei exatamente como as "engrenagens mágicas" do dicionário do python funcionam.
A complexidade de realizar uma busca em um determinado item do dicionário seja procurando a chave como eu fiz ou acessando o elemento direto: dicionario['2'] possui complexidade O(n)? Ou existe um Hash dentro dessas "engrenagens" ou alguma estrutura que consegue optimizar essa busca, como a busca binária?
Em falar em busca binária, há alguma forma de acessar o elemento de um dicionário como eu fiz e ativar uma busca binárias nas "engrenagens" do dicionário considerando, é claro, que ele esteja ordenado?
Comment: O dicionário é implementado como hash table e no acesso direto a complexidade é O(1). Ver https://docs.python.org/2/faq/design.html#how-are-dictionaries-implemented
Comment: ponha o link para a docuementação do Python 3. O google é último lugar do mundo que fica com esses links para a documentação do Python 2 ainda - só que ele só vai melhorar se os links que a gente põe pela internet forem para a versão 3.
Comment: https://docs.python.org/3/faq/design.html#how-are-dictionaries-implemented
Answer: Até onde eu sei as duas formas de acessar uma chave no dicionário são basicamente equivalentes (claro uma retorna um booleano da existência e o outro retorna o valor, mas ambas conseguem tempo O(1), na maioria dos casos (tem casos extremos que pode ser O(n), mas que não chegam nem perto de ocorrer)).
Dicionários são tabelas de espalhamento, elas possuem performance quase ao do array para acesso aleatório, só perde um pouco porque precisa calcular o código hash antes de acessar o elemento. Existem casos de colisão de chaves onde a busca precisa ser feita de outra forma, podendo até mesmo chegar em complexidade O(n).
Um dicionário é quase o oposto de uma estrutura que permite busca binária. Um dicionário não pode estar nem ordenado (com regra específica), muito menos classificado (com critério determinado).
No exemplo tenho dúvidas se um array não seria a melhor escolha.
Tanto o array,quanto o dicionário terá complexidade O(n) para procurar por valores.
Já demonstrei que o dicionário é diferente do array.
Pode ser útil: Objetos são semelhantes a arrays?.
Coloquei no GitHub para referência futura.
Answer: Como está nos comentários e na outra resposta, dicionários em Python são uma tabela de hash, com tempo de busca O(1) - e a informação sobre isso está aqui: https://docs.python.org/3/faq/design.html#how-are-dictionaries-implemented
Dito isso, sobre o design de código que você pergunta - chave in dict vs dict[chave]: o tempo de acesso é o mesmo - só que se a chave não existir, a segunda forma levanta uma exceção.
Quando você vai recupear um valor que não tem certeza se existe no dicionário o recomendado é usar o método .get:
meu_valor = dicionario.get("chave")

Nesse caso, se "chave" não existir, o .get retorna None e a vida continua. O .get também aceita um segundo parâmetro que é o retornado quando a chave não existe, em vez de None.
Isso economiza linhas de código - do tipo
if chave in dicionario:
    valor = dicionario[chave]
else:
    valor = None

ou
try:
   valor = dicionario[chave]
except KeyError:
   valor = None

Desses, esse segundo caso seria o único que teria alguma diferença de performance, por conta do tempo de criação do contexto do try/except .
Veja também o método .setdefault dos dicts: eles não só recuperam um valor padrão caso não exista um - mas nesse caso, fazem a atribuição do novo valor. Por exemplo, um loop para criar um dicionário com todas as palavras de um texto e  a posição de cada palavra dentro do mesmo, numa lista, poderia ser:
palavras = texto.split()
posicoes = {}
for indice, palavra in enumerate(palavras):
    posicoes.setdefault(palavra, []).append(indice)

Nesse caso, se a palavra ainda não foi encontrada, é criada uma lista vazia que é ao mesmo tempo atribuida lá e retornada pelo método. Se posicoes[palavra] já existe, a lista existente é retornada.
Agora, já que você se interessa por isso e quer saber sobre busca binária, aqui vai o fato interessante: o Python tem uma interface bem definida para objetos do tipo "Mapping" - e é bme tranquilo implementar um objeto que se comporte exatamente como um dicionário, mas com os algoritmos internos que você decidir. Se você quiser criar um dicionário que internamente seja uma árvore binária, é bem fácil - a forma recomendada de se fazer isso é herdar a classe collections.abc.MutableMapping. Há várias classes em collections.abc que são a base para implementar estruturas de dados bem uteis e variadas. Uma árvore binaria teria busca O(log(n)), mas com a vantagem de você poder ter ordenação das chaves e poder usar slices na mesma, por exemplo. Confira em: https://docs.python.org/3/library/collections.abc.html
Eu tenho vários "superdicionários" implementados no módulo extradict  - alguns são mais de brinquedo, outros eu uso mesmo em produção:
https://github.com/jsbueno/extradict
Comment: Sobre o `extradict`: eu não uso nada Python em produção, mas ja aprendi muito com esse projeto


How do we mock fetch in Redux Async Actions?

Question: In the Writing Tests section of Redux,http://rackt.org/redux/docs/recipes/WritingTests.html, how does the store.dispatch(actions.fetchTodos()) not invoke the fetch method, if store.dispatch is literally calling actions.fetchTodos?
it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] })

const expectedActions = [
  { type: types.FETCH_TODOS_REQUEST },
  { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
]
const store = mockStore({ todos: [] }, expectedActions, done)
store.dispatch(actions.fetchTodos())

})

Everytime I try to run something similar to this, I keep getting a fetch is not defined. Even if I use nock. So I have to spy my action to not get the call to fetch.
Here is my unit test:
it('should request a password reset, and then return success on 200', (done) => {
        nock('http://localhost:8080/')
        .post('/password-reset-requests')
        .reply(200);

var email = "firstname.lastname@example.com";
        const expectedActions=[
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ];
        const store = mockStore({}, expectedActions, done);
        store.dispatch(Actions.addPasswordResetRequest());

here is the action:
export default function addPasswordResetRequest(email){
    return dispatch => {
        dispatch(requestAddPasswordResetRequest(email));
        return addPasswordResetRequestAPI(email)
            .then(() =>{
                dispatch(requestAddPasswordResetRequestSuccess());
            })
            .catch((error) => {
            dispatch(requestAddPasswordResetRequestFailure(error));
        });
    };
}

and the function that calls fetch:
export const addPasswordResetRequestAPI = (email) => {
    return fetch(
        SETTINGS.API_ROOT + '/password-reset-requests',
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                code: NC_SETTINGS.GROUP.code
            })
        }
    )
        .then(handleResponse);
};

I'm not sure if the way I am doing is sufficient for the purpose of just testing actions, but then I do run into the problem of store.dispatch only returning the first element of expectedActions, and it doesn't equal the list I supply in the spied addPasswordResetRequest. Below includes the spied action.
it('should request a password reset, and then return success on 200', (done) => {
        nock('http://localhost:8080/')
        .post('/password-reset-requests')
        .reply(200);
        Actions.addPasswordResetRequest = spy(() => {
    return ([
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ]
        );
});
        var email = "firstname.lastname@example.com";
        const expectedActions=[
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST},
            {type: REQUEST_ADD_PASSWORD_RESET_REQUEST_SUCCESS}
        ];

        const store = mockStore({}, expectedActions, done);
        store.dispatch(Actions.addPasswordResetRequest());

Comment: One note: `fetch` is only defined by default in (some) browsers. If you're trying to run the tests in Node, you'll need something like [node-fetch](https://github.com/bitinn/node-fetch), or better, some [isomorphic/universal version](https://github.com/matthew-andrews/isomorphic-fetch) that works in both the browser and in Node.
Answer: The action "addPasswordResetRequest" isn't an action per-say.
it's a composite action with 3 sub-actions
startAction   =requestAddPasswordResetRequest,
successAction =requestAddPasswordResetRequestSuccess
failAction    =requestAddPasswordResetRequestFailure

I generally tests each action separately. so i would have something like
describe("requestAddPasswordResetRequest", () => {
     it("shows the loading spinner or whatever", ...);
     it("does some other state change maybe", ...);
});
describe("requestAddPasswordResetRequestSuccess", () => {
     it("hides the loading spinner or whatever", ...);
     it("changes the password state or something", ...);
});
describe("requestAddPasswordResetRequestFailure", () => {
     it("hides the loading spinner or whatever", ...);
     it("shows the error somehow", ...);
});

//each test would be something like
it("changes the password state or something", ()=>{
    const action = requestAddPasswordResetRequestSuccess({
          some : "payload from the server"
    });
    const newState = myReducer({ state : "somestate" }, action);
    expect(newState).to.be.eql("expected result for that action");
});

Notice how in the test i don't need the store or any async logic. thats the beauty of redux (and functional stuff in general), it's simple :)
after this i would have a separate test for the whole thing and make sure that the correct simple actions get dispatched by the composite action, in which i would mock everything (including store and the "fetch" thing, since i just want to test that the actions get fired in the correct order).
if the actions are dispatched in the correct order and each action work separably i would be pretty confident that the thing works as expected.
Hope this helps.


Android Studio: Open phone gallery with image upload button using php/html

Question: basically i created a website than converted it into an app with the help of Android Studio using this guy's blog .... [link]karthiktechfreak.blogspot.in/2015/07/… [link]... Since its built on html when i open the app on the mobile the html tag [code]      [/code] does not open up the gallery of the android phone
Comment: What is clearly your problem ? What is your code ?
Comment: basically i created a website than converted it into an app with the help of Android Studio with the help of this guy's blog .... [link]http://karthiktechfreak.blogspot.in/2015/07/profesional-android-webview-application.html [link]... Since its built on html when i open the app on the mobile the html tag [code]   [/code] does not open up the gallery of the android phone
Answer: Actually your question is not well received but i think that you want to open phone gallery by clicking event.
Am i right?
If it is so then you have to do like this
First of all initialize
<code>private static final int PICK_IMAGE = 1;
</code>
then
<code> your_Click.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

}
        });
</code>
Comment: Yes thats correct!! I havent asked the question in the right way tho.. But my code is in HTML and PHP
Comment: sure this did not help me.. My file is in php ! any help with that?
Comment: Sorry dear..for php i have no idea.


Is normalizing automorphism in $\mathbb{R}^n$ by Jacobian still an automorphism?

Question: Let $n \in \mathbb{N}$.
Suppose $f: \mathbb{R}^n \to \mathbb{R}^n$ is a $C^\infty$ diffeomorphism. Let $J_f: \mathbb{R}^n \to \text{M} (n, \mathbb{R})$ be the Jacobian of $f$. Is the map $F: \mathbb{R}^n \to \mathbb{R}^n$ defined by $F(x) = [J_f(x)]^{-1}\cdot f(x)$ a $C^\infty$ diffeomorphism?
Answer: I don't think this is even true for $\mathbb{R}$.
Consider the function $x^3 + e^x$. This function is clearly smooth and bijective, and the inverse is smooth by repeated application of the inverse function theorem, as the derivative has no zeros, and the inverse function theorem can be iterated to arbitrarily many derivatives.
However, for us here, the Jacobian is just the derivative, and your map $F$ is just $f/f'$. But for us, this is $\frac{x^3 + e^x}{3x^2 + e^x}$ which is not injective. In particular, it attains the value $1$ at $0$, but also at $x = 3$


Conditional Independence and probability

Question: There are two coins each having probability of heads as $0.9$ and $0.1$ respectively. And probability of choosing a coin for experiment is $0.5$ ( a coin once picked at beginning is used for every toss ).
P(Heads in $11$th toss) = $0.5$
P(Heads in $11$th toss | Heads in first $10$ tosses ) = $0.9$ (approx) as we are almost certain that $1$st coin is used therefore value obtained is $0.9$.
I tried to prove it mathematically
P(Heads in $11$th toss | Heads in first $10$ tosses ) = $$\frac{P(Heads\ in \ 11th \ toss \ ∩ Heads \ in \ first \ 10 \ tosses )}{ P(Heads \ in \ first \ 10 \ tosses)}$$
P(Heads in $11$th toss ∩ Heads in first $10$ tosses ) = $0.5 * ( (0.9)^{11}) + 0.5 * ( (0.1)^{11}) $
P(Heads in first $10$ tosses) =  $0.5 * ( (0.9)^{10}) + 0.5 * ( (0.1)^{10})$
P(Heads in $11$th toss | Heads in first $10$ tosses ) = $( 0.9^{11} + 0.1^{11})/(0.9^{10}+0.1^{10}) = 0.8999$
But there is another way to write P(Heads in $11$th toss ∩ Heads in first $10$ tosses ) as P(Heads in first $10$ tosses|Heads in $11$th toss  ) * P(Heads in $11$th toss)
I am not able to figure out what would be the value of  P(Heads in first $10$ tosses|Heads on $11$th toss ) and how to find it?
If there were no biases in the coins would that make the above events independent?
Answer: If I understand your question correctly, I think that you should also consider the chance that a certain coin was chosen if you got 10 heads in a row.
P(0.9 coin | first 10 heads) = P(0.9 coin and first 10 heads)/P(first 10 heads) = $\frac{0.5*0.9^{10}}{0.5*0.9^{10} + 0.5*0.1^{10}} = 0.9999999997132$ (according to Wolfram Alpha). The chance of 11th coin heads is $0.9999999997132*0.9 + (1 - 0.9999999997132)*0.1$ which is super close to 0.9. Hope this helps!


Probability of selection containing certain options

Question: Question 3.27 from the book Openintro statistics confuses me. The question states:

In a classroom with 24 students, 7 students are wearing jeans, 4 are wearing shorts, 8 are wearing skirts, and the rest are wearing leggings(5). If we randomly select 3 students without replacement, what is the probability that one of the selected students is wearing leggings and the other two are wearing jeans? Note that these are mutually exclusive clothing options.

I tought the answer would be $\frac{5}{24} \times \frac{7}{23} \times \frac{6}{22} = 0.0173$
However, the answer states:

$\frac{5}{24} \times \frac{7}{23} \times \frac{6}{22} = 0.0173$. However, the person with leggings could have come 2nd or 3rd, and these each have this same probability, so $ 3 \times 0.0173 = 0.0519$

This confuses me greatly. How would you for example compare this to the probabilty of drawing 3 hearts from a shuffled deck of cards, assuming no replacement. This would be $\frac{13}{52} \times \frac{12}{51} \times \frac{11}{50} = 0.0129$ But here we don't multiply by 3, why? What about the probability of drawing 2 hearts and 1 diamond?
Answer: The answer is a probability with the number of 'favorable' outcomes
in the numerator and the number of 'all possible' outcomes in the denominator. In many cases, you have your choice whether 'outcomes'
are ordered (order matters) or unordered (doesn't matter). However, once
you make your choice, you need to be consistent, using either ordered
or unordered outcomes both in numerator and denominator.
A method with unordered outcomes is as follows:
$$P(\mathrm{2\, Jeans\, and\, 1\, Leggings}) =
\frac{{7\choose 2}{5\choose 1}{12\choose 0}}{{24\choose 3}}
=  0.05187747.$$
Computation in R:
choose(7,2)*choose(5,1)/choose(24,3)
[1] 0.05187747

Note: By general agreement, for most card games, outcomes are
regarded is unordered. (The order in which cards are dealt has no effect on the value of the hand.)  So a straightforward combinatorial solution
uses unordered outcomes in numerator and denominator.
Thus, getting three hearts (taken as indistinguishable) when dealing three cards from a well-shuffled deck is ${13\choose 3}{39\choose 0}/{52\choose 3}= 0.01294118.$
choose(13,3)/choose(52,3)
[1] 0.01294118

Comment: Thank you for your answer. I have never seen probabilities being calculated this way. It will probably take me a couple of days to get to that section. Do you mind adding a part where you explain using my way of calculating probabilities?
Comment: As soon as you write $\frac{5}{24} \times \frac{7}{23} \times \frac{6}{22} = 0.0173$ you are looking at ordered samples. That's why you need the modification of the answer book. For the the card example you're treating all Hearts as the same, so there is no worrying about order. // By your approach you'd need to consider order for the probability of two Hearts and a Diamond.
Comment: Two Hearts and a Diamond: _Unordered,_ `choose(13,2)*13/choose(52,3)` returns $0.04588235.$ _Ordered,_
`(13*12*13)/(52*51*50)` returns $0.01529412,$ which needs to be multiplied by $3$ to arrange the cards HHD once you've got them. // If you write ${13 \choose 2}$ as $13!/(11!\cdot 2!),$ etc. maybe you can track the difference between the two methods.
Comment: I know I need to multiply by 3, because of it being ordered. I however still don't see the difference between the two examples. I'll work through the book to get to your way of calculating probabilities and see if I understand at that point. I'll get back to you on this. Thanks a lot


Is this algebra a simple ring?

Question:
Is the algebra $ \mathcal{M}_{3} ( \mathbb{C} [X,Y,Z] ) $ a simple ring (a simple algebra)?

$ \mathcal{M}_{3} ( \mathbb{C} [X,Y,Z] ) $ is the matrix algebra over $ \mathbb{C} [X,Y,Z] $. Thanks a lot for your help.
Answer: If $R$ is a ring, then there is a bijection between the set $\mathcal{I}(R)$ of (bilateral) ideals of $R$ and the set $\mathcal I(M_3(R))$ of ideals of $M_3(R)$. In particular, if $R$ is not simple, then neither is $M_3(R)$.
The bijection is the "obvious" one: if $I$ is an ideal in $R$, then the set $M_3(I)$ of matrices of $M_3(R)$ with all its entries in $I$ is an ideal of $M_3(I)$, and this correspondence gives us a function $$I\in\mathcal I(R)\mapsto M_3(I)\in\mathcal I(M_3(R))$$ and you should prove that this is a bijection.
Later. You originally asked whether $M_3(\mathbb C[X,Y,Z])$ was a simple ring, and now you edited the question to ask instead if it is a simple algebra. The answer to both questions is the same: if $R$ is a commutative ring and $A$ is a unitary $R$-algebra, then a bilateral ideal of $A$ viewed as a ring is the same thing as a bilateral ideal of $A$ viewed as an $R$-algebra.
Comment: Sorry ! I correct it ! Thank you very much Sear !  :-)

Is this algebra a simple ring?


Excel vba Underscore .Delete_

Question: I can't seem to find the right answer that fits to my code.
I'm trying to delete the first row on Sheet1
I'm sure my code below would work
But throws me a Run time error '438'. Object doesn't support this property or method.
Worksheets("Sheet1").Range("1:1").Delete_

The following is my code:
Option Explicit
Sub C2P()
        Worksheets("Sheet1").Range("C:C,F:F").Replace _
            What:=",", replacement:=".", LookAt:=xlPart
        Worksheets("Sheet1").Range("1:1").Delete_
End Sub

Any feedback would be appreciated. Thank you!
Comment: The line continuation token is [WS]+[UNDERSCORE]; in `Delete_` the underscore is considered part of the `Delete` method name (and `Delete_` doesn't exist as a member of `Range`, hence error 438); also a line continuation would be illegal there anyway. Avoid line continuations whenever possible.
Comment: nope it's not! Maybe that was causing issue @TnTinMn
Comment: @TnTinMn Ha! It does work! Please post a question, i'll accept it. Thank you!
Comment: @YowE3K OP is new to vba, and does not understand that the `_` indicates that the next line is part of the first.
Comment: @YowE3K My goal is delete the first row on Sheet1.
Since I used 'Replace_' I thought I also had to use 'Delete_'.
Comment: @ScottCraner thank you for the comment! Learning every day!
Comment: You actually used `...Replace _` (with a space to separate the underscore from the preceding token).  Without the space, `Replace_` would have given compilation errors on the `What...` line (as it isn't valid syntax).  If you had been consistent and used `...Delete _` (with a space) you would have also gotten syntax errors and it would have highlighted the line starting at the `W` on the `Delete` line and ending at the `B` of that line.
Comment: @Mat'sMug Thank you so much! I couldn't be more grateful!
Comment: @YowE3K Very wise answer. Underscore was the key. Thank you so so much as always!!
Answer: You have an extra character in the Delete method name.
Worksheets("Sheet1").Range("1:1").Delete_
Remove the underscore.
Learn to use the "F1" key to bring up the built in help system.  It is there for a reason.

Excel vba Underscore .Delete_


Do we need to update every release sequentially to get to the latest version?

Question: Drupal releases a minor release approximately every 6 months, and a patch release every 1 month. Do we need to update to each one of them sequentially in order to get to the latest version? E.g, if I'm on Drupal 8.5.0, and the current Drupal version is 8.6.1, do I need to follow the order and update each release in the order 8.5.0 -> 8.5.1 -> 8.5.2 -> 8.5.3 -> 8.5.4 -> 8.5.6 -> 8.6.0 -> 8.6.1, or can I directly update to 8.6.1 from 8.5.0 by replacing the core files?
If we can update to 8.6.1 directly, how do we handle the case if a release like 8.5.4 requires changes to 'default.settings.php' but 8.6.1 doesn't require?
Answer: You do not need to update Drupal sequentially. The Drupal update system will run all the needed updates so that you can go from (lets say) 8.3.0 to 8.6.1 directly.
Regarding your question about "If we can update to 8.6.1 directly, how do we handle the case if a release like 8.5.4 requires changes to 'default.settings.php' but 8.6.1 doesn't require?" ... If 8.5.4 requires a change to settings.php then 8.6.1 will assume that those changes are there already.
Note: its a good practice to update core (at least for minor versions) so that you are always in a position to quickly apply security releases. The Drupal security team has recently decided to support the most recent 2 minor releases, but still...
Check out this further reading and also this


Javascript não encontra o elemento pelo ID

Question: Aparentemente o JavaScript não está enxergando o ID que quero mudar o seu valor.
Já verifiquei todo o código e não consegui achar o erro.

  function SubMenu_EXIBE_OCULTA(menu){
    var obj=document.getElementById("menu");
      if(obj.style.display == 'block'){
        obj.style.display = 'none';
      } else {obj.style.display = 'block';}
  }
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a, .Menu_Principal_ITENS {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .Menu_Principal_ITENS {
    background-color: red;
}

li.dropdown {
    display: inline-block;
}

#SubMenus_MONTAGEM {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

#SubMenus_MONTAGEM a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    /* text-align: center; */
    text-align: left;
}

#SubMenus_MONTAGEM a:hover {background-color: #f1f1f1}

.CSS_Exibe_Oculta {display:block;}
<!DOCTYPE html>

Home

News

    Clique-me

      Link 1
      Link 2
      Link 3

Answer: Na verdade você está procurando por um id inexistente no seu HTML fazendo procurar por uma string e não a variável recebida no método.

var obj=document.getElementById("menu");

Tente assim:

 function SubMenu_EXIBE_OCULTA(menu){
    var obj=document.getElementById(menu);
      if(obj.style.display == 'block'){
        obj.style.display = 'none';
      } else {obj.style.display = 'block';}
  }
Comment: Victor, tinha acabado de encontrar o erro, daí vim aqui rapidão para excluir ou responder caso alguém tivesse respondido. De qualquer forma, muitíssimo obrigado e um forte abraço.
Comment: Nao esquece de marcar a resposta pra ajudar as outras pessoas também
Comment: Como faço para marcar @Victor Laio? Procurei aqui e não encontrei...
Comment: Logo abaixo da pontuação da resposta


Change href attribute in jquery with php

Question:
$('.buttonFinish').addClass('btn btn-default');

Jquery code for the submit looks like this:
finish  : $(''+options.labelFinish+'').attr("href","#").addClass("buttonFinish")

I need to replace "#" in href with a variable that I can send thru my PHP code.
I tried to do this:
 finish  : $(''+options.labelFinish+'').attr("href","<?php echo $someVariable;?>").addClass("buttonFinish")

where $someVariable is defined in the PHP code where the form submission link will point to
Comment: Your >?php  should be <?php
Comment: Please provide all the relevant script. Not at all clear how you are using this. Also the syntax `finish:` seems strange. See [mcve]
Comment: That was a typo just rectified the initial query, still the same problem, my link comes up as /localhost/
Comment: what happens if you remove the quotes?
Comment: By removing the comments I think I break the code or something as the buttons disappear and the form wizard goes bad, i.e. it shows all the steps in a single page with no javascript running
Comment: I try on selecting anchor tag with an ID or specific class.
Comment: Hi Abhijit, I am new to JS can you please tell how to do this with example
Answer: You can define a variable in php and call it in JS. For example...
PHP
$someVariable = <?php echo $something ?>

JS
finish  : $(''+options.labelFinish+'').attr("href", $someVariable).addClass("buttonFinish")

Comment: Hey, thanks for the suggestion, the problem is this is breaking the code.
This is what the link should look like  http://www.mankomal.com/school/form_wizards.html and this is what it looks like after this http://www.mankomal.com/school/addstudent_tpl.html
Answer: var someVariable = "<?php echo $something ?>";

finish  : $(''+options.labelFinish+'').attr("href", someVariable).addClass("buttonFinish")

Comment: Your answer is very similar to the other existing answer. Please clarify the context. Readers might confuse where to put which line, ie a file interpreted by PHP. I suggest adding an example file name and a wrapping


Importar vários arquivos KMZ ao mesmo tempo

Question: library(sf)

Arquivos kmz são arquivos do Google Earth. Tenho vários arquivos em uma pasta e gostaria de abrí-los de uma só vez no RStudio.
Defino o diretório:
setwd("C:/Users/fulano/Desktop/pasta_kmz")

Leio os arquivos kmz usando a função st_read() combinada com a função unzip().
No entanto, preciso repetir o processo para cada arquivo kmz
Assim:
arquivo_1 <- st_read(unzip("arquivo_1.kmz"))
arquivo_2 <- st_read(unzip("arquivo_2.kmz"))
arquivo_3 <- st_read(unzip("arquivo_3.kmz"))

Depois de fazer isso para cada arquivo, consigo empilhá-los usando rbind():
rbind(arquivo_1, arquivo_2, arquivo_3)

De certa forma, alcanço o meu objetivo.
No entanto, como eu poderia otimizar esse trabalho sem ter que ler cada arquivo kmz e gravá-lo em um objeto?
Tentei associar a função unzip() à função list.files(), mas não funcionou.
Imaginei que: como ao usar list.files(pattern = ".kmz") tenho listado todo os arquivos do tipo kmz que estão na pasta,
eu poderia ler todos os arquivos da seguinte forma:
st_read(unzip(list.files(pattern = ".kmz")))

No entanto, não funciona.
É possível ler todos os arquivos kmz em uma pasta e empilhá-los em um só objeto?
Answer: Pode definir uma função para ler os ficheiros que combine st_read e unzip. Depois aplica-se essa função aos ficheiros .kmz e empilha a lista de bases.
st_read_unzip <- function(x) st_read(unzip(x))

kmzfiles <- list.files(pattern = "\\.kmz")
kmz_data <- lapply(kmzfiles, st_read_unzip)
arquivo <- do.call(rbind, kmz_data)

Comment: Perfeito Rui. Muito obrigado


Tabela HTML em SVG

Question: Será possível criar uma tabela HTML, dentro da tag <svg>? Tenho um exemplo, mas não consigo ver os objetos.
Exemplo: http://jsfiddle.net/XmC2A/18/
Answer: tenta incluir o código na tag foreinObject
<foreignobject x="10" y="10" width="800" height="500" >

     Olá mundo
     <svg width="400" height="450">
            <rect id="rect1" width="300px" height="400px" fill="blue" />
        </svg>

</foreignobject>

Comment: `svg + html + svg` não estáva claramente dito no enunciado... (editei com base no teu exemplo remoto -- vê se faz sentido)
Comment: Sim é o que tenho no meu exemplo. Aparece a tabela, mas não os objetos svg dentro da mesma.

Tabela HTML em SVG


Post non-input fields in a form?

Question: This seems like a simple thing, and maybe I'm just not thinking straight today, but right now I don't see it: How do I post data from a form (in a PHP application) that is not an input field?
The reason I need this is I have a form where the user adds some information in input fields, and this should then update other values in the form based on what the user has entered (doing calculations on this input). This data should then on submit be posted, along with the input from the user.
I tried using form labels, but could not get it to work. For one I couldn't get the value of the form in the jQuery using either .val() or .text(). And I'm not sure if I could get the values of the label in the CodeIgniter function anyway. I also tried simple
 tags with ids, but that didn't work. I guess it has to be an element with the name attribute...
I'm using a helper in CodeIgniter to get the form values, like so:
$this->input->post('user')

This works fine for input fields, but as explained I need it for non-input elements. Of course I could have input fields that I update in jQuery, but there's a risk that the users will think they should fill them in...
So how do you do it?
Answer: How about using <input name="user" type="hidden"> and use Jquery to store the value in there.
Answer: Why are you storing input information in non-user-interface elements? Anything you want to be POSTed should be in an input field. Labels are not input elements, they are, well, labels. They label things. What exactly are you doing that you think you can't use input fields? You can disable them, set them to read-only mode, and modify their values in a similar way that you'd modify the text in any other element.
Comment: Well, it's a sort of calculation form. The user inputs values (hours) and gets different values calculated based on that. The calculated values need to be posted to the database with the input values.
Comment: @Anders: I still don't see why you can't put those calculated values into separate input fields. Just style the inputs to make them not look like inputs (if that's the effect you're going for).
Comment: Well yes, but also that the user should not be able to modify them, only the jQuery code should do that. And since I need the jQuery code to be able to modify them, I cannot make them readonly either...
Comment: @Anders: I've never heard of jQuery not being able to modify the value of a read-only input field. If that's really a problem, you can use jQuery to remove the read-only status, change the value, then reapply the read-only status. Or use disabled?
Comment: Ok, well I really actually assumed that jQuery wouldn't be able to modify it if it was read-only, but I'll try it. Otherwise I'll try your other suggestion.
Comment: You were right, it was as simple as using readonly, and jQuery could still modify it. Thanks!

Post non-input fields in a form?


Need help understanding the proof of the gaussian integral

Question: I am working with the Gaussian integral at the moment, and all the proofs I have seen involve a step where it is said that $\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}e^{-(x^2+y^2)}dxdy=\int_{0}^{2\pi}\int_{0}^{\infty}re^{-r^2}drdϕ$. I can see why that $might$ be the case, but I don't really understand it. Could anyone explain how exactly one arrives at this result?
Comment: This is just integration by [change of variables](https://en.wikipedia.org/wiki/Integration_by_substitution) to polar coordinates.
Comment: I know that but what I don't understand is how one does the switch to polar coordinates
Answer: Set
\begin{align}
  & x=r \cos \theta  \\
 & y=r \sin \theta  \\
\end{align}
Then
$$x^2+y^2=r^2$$
and
$$dxdy=\left| \frac{\partial (x,y)}{\partial (r ,\theta )} \right|dr\,d\theta={{r}\, dr\,d\theta  }$$


How to find out how many slices of pizza I need

Question: This seems like such a simple problem but I am stuck.
I have 50 different pizzas. There are 30 humans that have to share them.
I want that each person eats from 6 different pizzas. We can have two different persons eating from the same pizza, but each individual has to eat from 6 different pizzas.
Also each pizza has to be proved, else the solution would be to cut 6 pizzas in 30 pieces and ignoring the rest.
How many slices do I need to cut the pizzas, at the minimun?
First I thought about doing this with combinations and permutations but I am doing something wrong. Is this a minimization problem? Part of the problem for me is it has been a long while since I tried to solve this kind of problems, and I am having trouble finding the "context" or branch of mathematics I should use.
I am sorry if this is not the right place/way to ask.
Comment: With "each pizza has to be proved", do you mean that for each pizza, at least one person has to take a slice of it?
Comment: First thought: If you have 30 people and each eats from 6 different pizzas (that is, 6 slices per person), you must have at least $6\times 30 = 180$ pizza slices.
Comment: yes exactly @MattiP. And the 180 is as far as I have got so far!
Comment: Does the distribution of slices alter the total number of slices at all? Consider you have four people and two pizzas. You can split the pizzas into $2+2$ slices or $3+1$ slices. Are you considering only the number of slices (portions) or the number of actual cuts you have to make to the pizzas? In this example, $2+2$ would mean one cut per pizza (two cuts in total) and $3+1$ means three cuts (if you don't want any leftovers) or two cuts (one piece will be left over) plus zero cuts. You get what I'm saying?
Comment: @MattiP. I am not 100% sure I follow but as of right now I do not care if there are leftovers, as far as everyone eats 6. I know it makes sense to make the problem smaller but part of the difficulty for me is the restrictions: everyone has to eat from 6 different ones, and all pizzas have to be eaten
Answer: Think of the pizzas as an excel-sheet with 50 columns. Now in the first row start entering the first name, for six columns, then the next name, for the next six columns... 8x6=48, so you'll be able to fit eight names in the first row, with two pizzas not yet sampled.
As Matti P. said, 6 x 30 = 180 pizza-slices (or in our case excel-cells) need to be named. Three rows will get you 150 cells, four rows 200 cells, so depending on whether you have to cut all pizzas the same, you'll either have to cut them all into 4 pieces, or 30 into four pieces and 20 into three.
No cell (=piece) can be occupied by more than one name, because every tester eats one whole piece, therefore you need at least (Number_of_testers x number_of_samples) 180 servings. The minimal cutting depends on the rules for cutting (pizzas individually (30@4p 20@3), or stack the pizzas and cut all at once (50@4p, with some uneaten pieces).
Comment: Thanks for the help!!     That is a great way of looking at the problem but I feel like there is no guarantee that is the minimum, unless I am wrong? I mean, it is a solution but I do not see a way to go from there to conclude: this is the minimum.
Comment: Tried to put more emphasis on it being minimal.


Multi site Active Directory fail over

Question: Let say I have two site, connect with WAN link.
Site A have 1 DC.
Site B have 1 DC.
In general case, the fail over is working if one of DC down. Client will use any available DC.
What if the WAN link down? Will each DC still provide services to each site?
If someone changed the Group policy / Add new user at one site when the WAN link down, will the change correctly replicate after WAN link resume?
Comment: Assuming everything is configured appropriately... Yes to all.
Answer: Yes, all the domain controllers will synchronize changes when the connection comes back, and they can continue serving the site with all the roles installed on both servers. You'd only get problems if the link between domain controllers is down more than the tombstone lifetime for the forest.

The tombstone lifetime in an Active Directory forest determines how
  long a deleted object (called a "tombstone") is retained in Active
  Directory Domain Services (AD DS). The tombstone lifetime is
  determined by the value of the tombstoneLifetime attribute on the
  Directory Service object in the configuration directory partition.

Multi site Active Directory fail over


Keeping track of SSH private keys without comments

Question: SSH public keys support comments (which simply consist of text appended to the end of the key), which makes it easy to identify an otherwise unidentifiable id_rsa.pub file. You can use the comment to store information such as who the key belongs to, when it was created, and what machine it's for.
Private keys appear to lack this feature. ssh-keygen -C comment will generate a keypair with the comment appended to the public key, but the private key will remain uncommented. ssh-keygen has a -c argument that "requests changing the comment in the private and public key files", but
root@kitsune:~# ssh-keygen -c -f id_rsa
Comments are only supported for RSA1 keys.

So it would appear that the SSH2 private key format has no comment field. This is mostly fine as long as one keeps the pair of keys together and in the right place, but the files can get copied and moved around (which might happen when accounts/machines share a key) or overwritten accidentally, and they all have the same name (id_rsa), so one can lose track of which key is which. In the absence of commenting, what are the best practices for keeping private keys organized?
Comment: Store them in your configuration management system, with appropriate comments.
Answer: Storing the private key with public one gives you the opportunity to see the comment stored in the public part using the command below, but I see that it is not what you want. There is no way to store comment in the key itself (as you already mentioned).
$ ssh-keygen -lf ~/.ssh/id_rsa
2048 SHA256:abcdef[...] [comment] (RSA)

files can get copied and moved around

This is really bad idea. You don't want your private data moving around. In ideal case, you should have one key pair per device from where you are connecting. If you need more keys on the client, I would go with different naming, such as id_rsa-private-github (with appropriate naming of public part). With proper configuration in ~/.ssh/config and/or ssh-agent, there is no flaw in this set up.


Finding percentage land cover classes in a shapefile in R

Question: I have shapefile in R and a tiff file of land cover classes. How can I find the percentage of land cover classes in the shapefile? For instance how much land is present in the study area in that shapefile?
#example data for cover
rat <- levels(raster2 )[[1]]
rat[["landcover"]] <- c("land","ocean/lake", "rivers")
levels(raster2 ) <- rat

#and a raster
raster1 <-  raster(matrix(c(1,1,1,2,3,4,5,6,7),ncol =3))

Answer: Here is a minimal, self-contained, reproducible example:
Raster data
library(raster)
r <- raster(ncol=36, nrow=18)
set.seed(111)
values(r) <- sample(3, 18*36, replace=TRUE)

Polygon
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
polys <- spPolygons(cds1)

Solution
x <- extract(r, polys)
table(x)
#x
# 1  2  3
#16  9 13

Comment: My values are coming like these  124886  443141    2570   46059  395207 etc, are they form of area? As I would like to know the percentages of each land cover class.
Answer: I have written an R package to do this.
Package name is SpatialCover and can be found on Github. It requires packages raster and sp.
The Percent.cov function will do what you need. You'll need to ensure that your polygon/shapefile has an ID field. If there are multiple polygons in the shapefile, Percent.cov will calculate the frequency of each cover type within each polygon individually.
  library(SpatialCover)
  library(raster)
  library(sp)
  library(rgdal)

  shapefile<- readOGR(dsn=wd, layer="filename.shp")
  lcraster<- raster("filepathname/rasterfilename.tif")

  FreqTable<- Percent.cov(vectorlayer=shapefile, rasterlayer=lcraster, zoneID=ID)

You should then get a table that looks something like this

zoneID
CoverType
PercentCover

1
Land
20

1
Ocean/Lake
70

1
Rivers
10

Hopefully this helps. There is also an example with the package.


The expected outcome of a random distribution of marbles among several people

Question: The problem is:

On each round of a game, 20 marbles are distributed at random among five children: Alan, Ben, Carl, Dan, and Ed. Consider the following distributions:

I) Alan: 4, Ben: 4, Carl: 5, Dan: 4, Ed: 3
II) Alan: 4, Ben: 4, Carl:4, Dan: 4, Ed: 4

In many rounds of the game, will there be more results of type I or type II?
I guess number II is more probable because they are around $\mu=4$, but I'm not sure that the problem is that easy! Am I correct?
Comment: Crosspost: https://math.stackexchange.com/questions/3143960/the-expected-outcome-of-a-random-distribution-of-marbles-among-5-people.
Comment: @StubbornAtom I deleted the other one
Answer: Your intuition is correct, and can be verified by explicitly calculating the probability. This is a multinomial distribution so that the probably of getting $n_1,n_2,n_3,n_4,n_5$ marbles for Alan,Ben,Carl,Dan,Ed respective is:
$$\frac{20!}{n_1!n_2!n_3!n_4!n_5!}.$$
For type I, the denominator is $(4!)^33!5!$.
For type 2, the denominator is $(4!)^5$.
Then $(4!)^2 = 3!\cdot 4 \cdot 4!\leq 3!5!.$
You'll notice the denominator for type I is bigger than type II, hence type II is more probable.
Answer: Your intuition is correct, but it's better to approach from a more calculus perspective:
Distributing marbles according to Type I is equivalent to counting the number of permutations of the following string and dividing by $5^{20}$, i.e. total number of probabilities: $AAAABBBBCCCCDDDDEEE$, which is  $\left(\frac{20!}{(4!)^3 5!3!}\right)/5^{20}$.
For type II, this is $\left(\frac{20!}{(4!)^5}\right)/5^{20}$ since there are $4$ of each letter. The denominator of the second one is larger, since $5!3!>(4!)^2$, and therefore probability of obtaining type II is larger.
Seems I'm a little bit late :)


Failing to Integrate OpenWhisk Action that Posts to a PostgreSQL Database to API Connect

Question: I am trying to create a POST API Method in API Connect by invoking an OpenWhisk Action. I am using the GET Method in James Thomas' article Serverless APIs with OpenWhisk and API Connect, as a template for connection and configuration settings to integrate OpenWhisk actions into the API. The OpenWhisk Action I am using is successfully posting input data to a Compose PostgreSQL Database, so all I need to do is properly invoke it and send the input data in the correct format to the OpenWhisk function via API Connect.
My current request and response output on the IBM API Developer Console is:
Request
POST https://api.us.apiconnect.ibmcloud.com/spatvis-tutorial/sb/post-trial/student Headers:
Content-Type: application/json
Accept: application/json
X-IBM-Client-Id: ********************************
X-IBM-Client-Secret: *******************************
Response
Code: 401 Unauthorized Headers:
x-global-transaction-id: 114129529
content-type: application/json
 {}

The OpenWhisk function is not being invoked and I can't figure out why I am getting the security error.  What kind of credentials do I need and how do I set that up? Does it make sense to use either TLS, Basic, and Custom HTTP Security techniques outlined in the article Three approaches to securing access to Bluemix applications with IBM API Connect? If so, what are the pros and cons of each technique/method and which one makes most sense to use to secure access to OpenWhisk Actions?
Answer: OpenWhisk has released native API Gateway integration since that blog post was published.
Connecting actions to HTTP endpoints can be managed using through the wsk cli or a web management interface on Bluemix.
Here's an example of creating a HTTP endpoint using the API Gateway for POST requests.
$ wsk api create /api/action POST action
ok: created API /api/action POST for action /_/action
https://service.us.apiconnect.ibmcloud.com/gws/apigateway/api/<UUID>/api/action

This blog post gives a walkthrough on the new functionality.


Programmatically render an imagefield in Drupal 6 as defined in content-field.tpl.php

Question: What sounds like simple task in the first place, has taken me hours without getting a solution: All I want is to render single values of an imagefield just as in the normal node, i.e. as defined in content-field.tpl.php. This is important for me, because there I add captions from the Imagefield Extended module
I tried with content_format(), but with the "default" formatter it gives me just an icon and a link and with the "image_imagelink" formatter from the imagefield.module I get an image, but not as defined in content-field.tpl.php and in the node type's display settings:
print content_format('field_image', $vars['node']->field_image[1], 'default', $vars['node']);
print content_format('field_image', $vars['node']->field_image[1], 'image_imagelink', $vars['node'])

I have tried a couple of other things and searched for hours, but I cannot find an answer. Any ideas how I can render the image "just the normal way"?
The HTML out I want is a defined in the template something like this:

Caption Text

            Source:
            Source text

            Licence:
            Licence text

Answer: Do you have more than one image?
print content_format('field_image', $vars['node']->field_image[0], 'default', $vars['node']);
print content_format('field_image', $vars['node']->field_image[0], 'image_imagelink', $vars['node']);

Try again with [0] instead of [1]. I use those all the time and it works fine like that.
Comment: Hi Alexis, actually I was using a loop to print all the images, the "1" was just one instance, so that doesn't solve the problem. As I said, I changed some stuff in the field's template file and those changes are not reflected when I use content_format().
Comment: Ah! I have to say I try to avoid using theme() in general because of all the caching and stuff, it often does not come out exactly as you want it. But anyway, in your case, you may have a cache problem. The theme() functions save all sorts of things in the cache under the hood and if those caches exist, they ignore your other changes.


handling hidden field value in controller and model

Question: in my view
<select id="gender" name="gender">
                              <option value="">select gender</option>
                               <option value="0">Male </option>
                               <option value="1">Female </option>

                               </select>

if gender is female then i want to show another field called "surname". following is the code
Surname

<input type="text" name="surname" id="surname" />

And if gender is male then i want show another fields called village,district,etc. I have done hide and show code using js , so my question is how do i handle this field values in controller and model??
Comment: you have to write js code to show / hide fields. Then do same condition check in controller but you have to get value from different field based on selected option
Answer: Try this out:
switch($_POST['gender']){
case '0':
// do Something for 0
break;
case '1':
// do Something for 1
break;
default:
// Something went wrong or form has been tampered.
}


.htaccess - How to set a custom header according to an environement variable?

Question: How to set a custom header via .htaccess according to an environement variable using If/Else directive?
#Refresh-page
<If "%{ENV:DOCUMENT} == 'loading'">
    Header set Refresh "3"
</If>

I am trying to use the syntax described in the documentation for Apache 2.4
http://httpd.apache.org/docs/2.4/mod/core.html#if
TEST 1
According to anubhava's answer
RewriteCond %{ENV:DOCUMENT} ^widget$
RewriteRule ^.* - [E=REFRESH:1]

#refresh page
Header set Refresh "3" env=REFRESH

RewriteCond %{ENV:REFRESH} ^1$
RewriteRule ^.* loading.html [L]

Answer: Alter your env variable to store 0 or 1 and then you can use Header set like this:
You can use:
# set DOCUMENT=widget (remove if you are already setting this)
SetEnvIf Host ^ DOCUMENT=widget

# set isDoc=1 if DOCUMENT == widget
SetEnvIf DOCUMENT widget isDoc

# set header only if isDoc == 1
Header set Refresh "3" env=isDoc

Comment: Actually instead of `RewriteRule` you must use `SetEnvIf` to create the new env variable (since mod_rewrite runs later in the chain). I will update the answer in few minutes.
Comment: [Check this documentation for setenvif examples](http://httpd.apache.org/docs/2.2/mod/mod_setenvif.html#setenvif)
Comment: Thanks anubhava I am editing the question according to your suggestion
Comment: Can you please review the code test1 and tell me what is going wrong?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/64308/discussion-between-rafasashi-and-anubhava).


Natural followed by sharp in Chopin Waltz in C-sharp minor

Question: In Chopin's Waltz in C-sharp minor (Op. 64, No. 2), I'm a bit confused by the following notation in the third measure:

The F has a natural, cancelling out the sharp in the key signature. But then it instantly becomes an F-sharp again. Once more there is no note to play for the accidental, so I don't understand what this piece of notation is telling me.
I would guess I play the F-natural and then the G, then the next F in the bar I play as an F-sharp?
Comment: @JohnBelzaguy Looking back at the previous bar. There is an F double sharp. So would the accidental flatten it to an F and the sharp make it an F sharp again? Not sure.
Comment: There's your answer by @mattputnam, +1. The natural-sharp in your version is an odd way to cancel a double sharp. I think his version is much easier to read, after all we're all supposed to know that an accidental is good only for the bar it's in, right? ;)
Comment: Maybe there is a G natural in the preceding bars which would account for the courtesy accidental on the G...
Comment: a related question: [With sheet music, what happens with sharps and double sharps that are already sharped in the key signature?](https://music.stackexchange.com/questions/4641/with-sheet-music-what-happens-with-sharps-and-double-sharps-that-are-already-sh)
Comment: As other comments and answers observe: this is both awkward typesetting and dubious editor's choice about how to emphasize that the previous double-sharp has expired.
Comment: @paulgarrett awkward or not, dubious or not, it was the standard way of doing it for about 250 years, from the invention of the double sharp sign in the early 18th century until the late 20th century.
Comment: @phoog, hm, ok, but I my copy of that Chopin valse doesn't do that, and, although I've seen plenty of double sharps, I do not recall that pattern. Maybe I was just oblivious... :)
Answer: The previous measure has an F double-sharp:

The natural-sharp is to remind you that it's no longer double sharp.
Comment: Obviously the correct answer - made more clear with sight of the previous bar - as suspected, Fx. However, the OP's copy is poor. There's really no need for *anything*, but if *someything* was put in, it needed to be in parentheses, as a cutionary, surely? +1
Comment: Yes, the original score is bad practice - a # in front of an f means f sharp, NQA, no matter what the context and the key signature is. Writing "natural + accidental" just confuses this rule.
Comment: Natural-sharp like this is actually pretty common and not usually an issue. I don't like it here, mainly because with the F-G cluster it's easy to think one of the accidentals is for the F and the other is for the G (in this case, it would be F-natural and G#). Parentheses are optional.
Answer: You need to look at the previous bar as well.   There's a Fx (F double-sharp).  Technically, this reverts to the single sharp of the key signature in the next bar.  Some editions therefore omit any accidental.    Some (like the one below) add a cautionary # on the F.  Your example uses the old convention of cancelling a double-sharp with a natural-sharp.
Either way, the note in question is F♯.   The other note in the dyad is G♯, according to the key signature.  And it IS a dyad, a two-note chord. To be played together.  The offset - one note each side of the stem - is purely to avoid an ugly printing collision.
Answer: To address the last part of your question - both the F(♯) and G(♯) are played at the same time - they just got printed to look like they do, as there isn't room on one side of the stem! Don't ever think of playing them one after the other - that's not correct.
Comment: Certainly true! :)


How to display the input box next to the label in a form?

Question: My objective is to improve the look and feel of a form developed in Drupal 7.
By default, I have (as an example):

Name (label)
BLANK INPUT box (below the label)

How to display the label and input box as inline ?
Answer: you can do this with css float
A more difficult ways that render the items via php preprocessing before css adjusts the layout) would be to create a php template file and use theme functions for the form in your theme
Here is tutorial that uses both methods http://www.jaypan.com/tutorial/themeing-drupal-7-forms-including-css-and-js
also, it depends on what kind of form you are theming. Here is another example for webforms https://drupal.org/node/1157306


Rewrite Rule Config... Is this possible?

Question: So I have a set of pages like so:
domain.com/product/?_d=1
domain.com/product/?_d=2
domain.com/product/?_d=3

I have set up a rewrite map for cleaner URLs like so
domain.com/shoes
domain.com/pants
domain.com/gloves

So now I have nice URLs for people. But what I also want to do is start forwarding the existing URLs to the newer URLs. So for anyone who goes to:
domain.com/product/?_d=1

I want them to be forwarded or rewrite the URL to:
domain.com/shoes

I tried adding in another map where I have the following:
Original: domain.com/product/?_d=1
New Value: domain.com/shoes

And I got a 404. I guess I understand why because the other map won't apply since I am using the first map. But how can I set up a map for the old URLs? Or can I? I know if my query string value was like _d=shoes I could just do a rewrite rule, but it's not like that. I guess I could change my page to be that way, but was just looking for another way.
Answer: I ended up creating a rewrite rule that looked for the pattern to the old URLs and forwarded them to the new URL. Then in my Server side code I just did a check for those legacy variables and redirected with a 301 accordingly.


How to color stage to green if it was successful on the second retry?

Question: I faced a problem during building my pipeline job.
I have some stages and one of them contains "retry" block. Something like this:
<code>stage "1"
stage "other job call"
node{
    def job
    retry(3)
        {
            job = build job: 'Called job', parameters:
                        [
                            [$class: 'StringParameterValue', name: 'Branch', value: "Branch"],
                        ];
        }
    }
}

stage "2"
</code>
So, another job is called and it is successfully built from the second time. But the stage is colored to red, despite it was successful:

How to color this stage to green?
Answer: Like you, I was looking for the possibility to change the state or colour of one stage and finally it seems that we don't have access to this functionality (maybe if you create your own plugin…)
Anyway, in your case the function "Retry" allow to retry the block (up to N times) if any exception happens during its body execution. Then if you use retry function you will automatically get this stage state.
I don't really understand why you use "retry", but if you want to avoid this behaviour try to use some other functionality like:

try/catch/finally blocks
catchError block
currentBuild.result = 'UNSTABLE'     // 'SUCCESS' | 'FAILURE' | 'UNSTABLE'
sleep     // if you need to wait for something else
Comment: Do you know if it is possible to change the status of a single stage (without changing the whole build status)?
Comment: @OlivierTerrien Have you found a solution for this?


Mapeamento entre FHIR e OpenEHR

Question: Estou com uma dúvida sobre mapeamento entre modelos de persistência  e interoperabilidade de dados de saúde.
Existe algum mapeamento entre FHIR e OpenEHR? Se sim, como deve ser feito? Há alguma forma automática de fazê-lo?
Answer: Estou estudando o assunto também, e ao que me parece não existe uma forma automática de fazê-lo.
O FHIR e o OpenEHR já provém algumas estruturas similares, porém, não há um mapeamento 100% direto entre as estruturas, onde haja uma relação perfeita.
O que está indicado neste site link é que pode-se utilizar Profiles e Extensions do FHIR como auxiliadores para o mapeamento entre as abstrações.
Você pode acompanhar a thread link, que indica também que ainda não há esse mapeamento.
Espero ter ajudado,
Abraços

Mapeamento entre FHIR e OpenEHR


Reverting an android preference's value when a statement in another thread fails

Question: I have settings in my app that I allow the user to manipulate using a PreferenceScreen with Preferences. However, I want to store the settings on a server so that the settings can persist over multiple devices. I have the following code that lets me do this:
private void updateSettingOnPrefChange(final Preference pref, final Setting setting) {
    pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, final Object newValue) {
            try {
                setting.update(newValue, new Callback<Boolean>() {
                    @Override
                    public void call(Boolean succeeded) {
                        if (!succeeded) {
                            Toast.makeText(getActivity(), "Setting failed to update. Please try again.", Toast.LENGTH_LONG).show();
                            //here I need to revert the value of the Preference without again calling the onChangeListener
                        }
                    }
                }, getActivity());
            } catch (Exception ex) {
                if (BuildConfig.DEBUG)
                    ex.printStackTrace();
                Toast.makeText(getActivity(), "Setting failed to update. Please try again.", Toast.LENGTH_LONG).show();
                return false;
            }
            return true;
        }
    });
}

As you can see in the code the request is being run on a different thread using a custom Callback class to clean up based on the result of the call. The issue is the code will have already return true on the main thread.
How can I revert the value of the Preference in the callback function (preferably without also calling the onPrefChangeListener function so I don't get  infinite recursion)?
Comment: I think you need to think about your design ... I would first store the value locally, and then trying to upload it on server side ... also, you need to consider what you do when the upload of the value fails, like you would need to retry possibly exponentially ... last but not least, I recommend you to persist and upload the new value only if different than the actual value
Comment: The `Setting` class caches the value locally as well. When the upload fails I want to just alert the user and revert the shared preference (if they want to try again they can). Good tip on checking if they are equal though. Thanks!
Answer: Use the OnPreferenceClickListener instead of OnPreferenceChangeListener to listen for user taps on the setting field and then make your rpc request accordingly. If you have to update the value (in the case of a server failure) you can change the setting without firing the click listener and having the infinite loop.
https://developer.android.com/reference/android/preference/Preference.html#setOnPreferenceClickListener(android.preference.Preference.OnPreferenceClickListener)


@ObservedObject not updating after successful network call

Question: I've hit a brick wall in my widget extension. I'm using AlamoFire and ObjectMapper to match the networking we have in the main app. I can tell that my AlamoFire network call is getting triggered and that I'm getting results back, and in the correct, expected format. However, saving the response of that network call to a @Published var doesn't seem to be working. My view and models/structs are below:
struct WidgetEntryView: View {
    var entry: ResourceCategoryEntry

    @ObservedObject var viewModel = WidgetResourcesView(widgetSize: .medium)

    var body: some View {
        if UserDefaults.forAppGroup.object(forKey: "sessionToken") as? String == nil {
            PleaseLogIn()
        } else if viewModel.mediumResources.count < 1 {
            ErrorScreen()
        } else {
            MediumResourcesView(resources: viewModel.mediumResources)
        }
    }
}

class WidgetResourcesView: ObservableObject {

    @Published var resourceGroups: [WidgetResouceGroup] = [WidgetResouceGroup]()

    var widgetSize: WidgetSize = .small
    var selectedCategory: String?

    init(widgetSize: WidgetSize) {
        self.widgetSize = widgetSize
        self.selectedCategory = UserDefaults.forAppGroup.string(forKey: ResourceCategoryEntry.userDefaultKey)
        getResources()
    }

    func getResources() {
        WidgetNetworkService.getResources(widgetSize: self.widgetSize.rawValue, selectedCategory: self.selectedCategory) { resourceGroups in
            DispatchQueue.main.async {
                self.resourceGroups = resourceGroups
            }
        } failure: { _ in
            print("Error Received")
        }
    }

    var mediumResources: [WidgetResource] {
        var resources = [WidgetResource]()

        if let featuredResourceGroup = resourceGroups.featuredResourceGroup {
            for resource in featuredResourceGroup.resources { resources.append(resource) }
        }

        if let nonFeaturedResourceGroup = resourceGroups.nonFeaturedResourceGroup {
            for resource in nonFeaturedResourceGroup.resources { resources.append(resource) }
        }

        return resources
    }

}

class WidgetResouceGroup: NSObject, Mappable, Identifiable {

    var id = UUID()
    var widgetCategory: WidgetCategory = .featured
    var resources = [WidgetResource]()

    required init?(map: Map) {}

    func mapping(map: Map) {
        id <- map["section"]
        widgetCategory <- map["section"]
        resources <- map["resources"]
    }

}

typealias WidgetResourceGroupCollection = [WidgetResouceGroup]

extension WidgetResourceGroupCollection {

    var featuredResourceGroup: WidgetResouceGroup? {
        return first(where: {$0.widgetCategory == .featured})
    }

    var nonFeaturedResourceGroup: WidgetResouceGroup? {
        return first(where: {$0.widgetCategory != .featured})
    }

}

class WidgetResource: NSObject, Mappable, Identifiable {
    enum ResourceType: String {
        case text = "text"
        case audio = "audio"
        case video = "video"
    }

    var id = 0
    var title = ""
    var imageInfo: WidgetImageInfo?
    var resourceType: ResourceType = .text

    required init?(map: Map) {}

    func mapping(map: Map) {
        id <- map["object_id"]
        title <- map["title"]
        imageInfo <- map["image_info"]
        resourceType <- map["content_type"]
    }
}

Comment: There are plenty of tutorials that can be found from a search. Here's one that shows the the basic premise https://medium.com/swlh/advanced-widgets-network-calls-deeplinking-intent-configuration-30c697e09789
Comment: Widgets never listen. When you load a timeline it is like a screenshot of what you provide the widget in the `getTimeline` method. Anything that is loaded, updated , called, etc outside of a synchronous call in getTimeline will not be seen. When you have to update something because there is new data you have to reload the timeline and this is metered by apple.
Comment: You can't perform any network requests inside your widget. You need to perform them when you create the timeline.
Comment: Can you give an example of this?
Answer: You can use the objectWillChange - Property in your observable object to specifiy when the observable object should be refreshed.
Apple Dev Doku
Example by Paul Hudson
Comment: `objectWillChange` does not work in a widget
Comment: I tried adding that to my network call, before I update the @Published value, with no luck:
`self.objectWillChange.send()`
`self.resourceGroups = resourceGroups`
Comment: I followed the [Paul Hudson](https://www.hackingwithswift.com/quick-start/swiftui/how-to-send-state-updates-manually-using-objectwillchange) example with no luck
Answer: WidgetEntryView instantiates WidgetResourcesView using the ObservedObject wrapper. This causes a new instance of WidgetResourcesView to be instantiated again on every refresh. Try switching that to StateObject, and the original object will be kept in memory between view updates. I believe this is the only change needed, but I'm away so can't test it!
Comment: This applies to SwiftUI in general, but don't rule out a widget-specific issue like mentioned in another reply!
Comment: `StateObject` is irrelevant in a widget


Is there any way to avoid LEFT JOIN the same table

Question: There are two tables i.e user and attribute.
user table-
 -----------------------------------------------------------------------
|   user_id |   u_at1   |   u_at2   |   u_at3   |   u_at4   |   u_atN   |
 -----------------------------------------------------------------------
|   1       |    3      |     4     |   6       |   100     |   Null    |
 -----------------------------------------------------------------------
|   2       |    Null   |     623   |   Null    |   85      |    1      |
 -----------------------------------------------------------------------

attribute table
-----------------------
|   at_id   |   at_text |
 -----------------------
|    1      |    at1    |
 -----------------------
|    2      |    at2    |
 -----------------------
|    3      |    at3    |
 -----------------------
|    4      |    at4    |
 -----------------------
|    5      |    at5    |
 -----------------------
|    6      |    at6    |
 -----------------------
|    85     |    at85   |
 -----------------------
|    100    |    at100  |
 -----------------------
|    500    |    at500  |
 -----------------------
|    623    |    at623  |
 -----------------------

Attribute table store attribute id and attribute text. In the user table, the user attribute column (for example u_at3) store the attribute id. In the user table, u_atN column is for example purpose i.e the attribute column count can be u_at20. Thats why I did not include all column here.
Now my question is this ok if I make LEFT JOIN 20 times for the same table or is there any other method I can do this? Here is my query-
 SELECT
    `user`.*,
    `attribute1`.`at_text`,
    `attribute2`.`at_text`
    `attribute3`.`at_text`
    `attribute4`.`at_text`
    .....................
    .....................
    `attribute20`.`at_text`

FROM `user`
LEFT JOIN `attribute` `attribute1` ON `user`.`u_at1` = `attribute1`.`at_id`,
LEFT JOIN `attribute` `attribute2` ON `user`.`u_at2` = `attribute2`.`at_id`,
LEFT JOIN `attribute` `attribute3` ON `user`.`u_at3` = `attribute3`.`at_id`,
LEFT JOIN `attribute` `attribute4` ON `user`.`u_at4` = `attribute4`.`at_id`,
...................................................................
...................................................................
JOIN `attribute` `attribute20` ON `user`.`u_at20` = `attribute20`.`at_id`,
WHERE `user_id` = 2;

Comment: Normalise your schema
Answer: When using MySQL aggregation you can use MAX() aggregation function on strings so you can do a full join and use an if statement to use the value of the attribute or null for each field depending on the id matching. Then aggregate by user_id!
Example.
SELECT `user_id`,
  MAX(IF(`attribute`.`at_id`=`user`.`u_at1`,`attribute`.`at_text`,NULL)) as `u_at1_value`,
  MAX(IF(`attribute`.`at_id`=`user`.`u_at2`,`attribute`.`at_text`,NULL)) as `u_at2_value`,
  MAX(IF(`attribute`.`at_id`=`user`.`u_at3`,`attribute`.`at_text`,NULL)) as `u_at3_value`,
  MAX(IF(`attribute`.`at_id`=`user`.`u_at4`,`attribute`.`at_text`,NULL)) as `u_at4_value`
FROM `user`,`attribute`
GROUP BY `user_id`

Performance wise I think its faster to use subqueries for each field though, due to the MySQL optimizer.
SELECT `user_id`,
  (SELECT `at_text` FROM `attribute` WHERE `user`.`u_at1` = `attribute`.`at_id`) as `u_at1_value`,
  (SELECT `at_text` FROM `attribute` WHERE `user`.`u_at2` = `attribute`.`at_id`) as `u_at2_value`,
  (SELECT `at_text` FROM `attribute` WHERE `user`.`u_at3` = `attribute`.`at_id`) as `u_at3_value`,
  (SELECT `at_text` FROM `attribute` WHERE `user`.`u_at4` = `attribute`.`at_id`) as `u_at4_value`
FROM `user`

Answer: I think this is not a good approach. You may get a lot of duplicate results if attribute_ids are the same for different ids. Moreover, 20 left joins on RDBMS will make your DB crusted and is an unrealistic approach.
To resolve your problem, you can redesign the DB.
user table:
user_id
attribute_id

And
Attribute table:
    attribute_id,
    text1_column
    text2_column
    text3_column
    ....
    .....
    text20_column

Then, you just do a single join, pick data from your database. Process and in which column you find data, use that according to your need.
I am not saying this is the best solution but at least, this will decrease your complexity in a drastical way.
Comment: thanks for your comment. The duplicate result can be avoided by adding a column alias. But my main concern is for performance for 20 left join.
Comment: you are right about the duplicate results. And for performance, there is a huge possibility that your application will stuck and db will remain locked for a long time which is not desired. For each left join, the complexity increases like this MxN1xN2x....N20 which I assume you don't want in your system at all!


How to split panda dataframe based on colum value

Question: I know this question is being asked here multiple times, but I could not find a quick answer to my problem. I have the below dataframe. I want to split this dataframe based on two columns values. So I if the col1 value is 1 and column 2 is also has also value 1 split it. So from row 0 to 3 split it and also again from row 6 to 9 split it and put it in a separate dataframe. Is there any code where i can look for it. Thanks in advance. My real dataframe contains 1000+ rows
df
  col1    col2    col3
0  1        1      3
1  1        1      6
2  1        1      9
3  1        1     12
4 11        1     13
5  1        0      3
6  1        1      6
7  1        1      9
8  1        1      6
9  1        1      9

Comment: Can you please provide the exact expected output for clarity? Also, please don't undo my edits, the data is easier to copy/paste this way
Answer: IIUC, you can craft a mask with any to identify the valid rows and form a group with cumsum to use in groupby to split:
m = df[['col1', 'col2']].ne(1).any(axis=1)

dfs = [g for _,g in df[~m].groupby(m.cumsum())]

Output:
[   col1  col2  col3
0     1     1     3
1     1     1     6
2     1     1     9
3     1     1    12,
    col1  col2  col3
6     1     1     6
7     1     1     9
8     1     1     6
9     1     1     9]

Intermediates:
   col1  col2  col3      m     ~m  m.cumsum()
0     1     1     3  False   True           0
1     1     1     6  False   True           0
2     1     1     9  False   True           0
3     1     1    12  False   True           0
4    11     1    13   True  False           1
5     1     0     3   True  False           2
6     1     1     6  False   True           2
7     1     1     9  False   True           2
8     1     1     6  False   True           2
9     1     1     9  False   True           2

Comment: Its working. Thank you very much. Next step is to get only the lists which is longer than ten rows. Thanks againa mozway
Comment: @WilliamAshoti for that use `dfs = [g for _,g in df[~m].groupby(m.cumsum()) if len(g)>10]`
Comment: Then `m = df[['col1', 'col2']].ne(11).any(axis=1)`. Both both columns, if not equal (`ne`) to 11, in `any` of those two assign `True`
Comment: Then I guess `m1 = df['col1'].eq(11) ; df[['col1', 'col2']].eq(1).all(axis=1); [g for _,g in df[m1|m2].groupby(m1.cumsum())]` You should try to understand how it works, this is more or less always the same logic.
Comment: Hi mozway,  i just want to understand the code. can you explain a little bit? For example this code m = df[['col1', 'col2']].ne(1).any(axis=1) and what happend if I want to change the value of 1 and want 11 instead. What will be the solution then? Thanks in advance
Comment: One final question is. If I want to say find first in col1 the value 11 and if you find it take the the values below in col1 and col2 if the values in col1 and col2 are equal to 1. Thanks in advance mate


Syntax error in MIPS assembly

Question: I'm having a strange problem with an assembly file. Every time I load this file into PCSpim, it gives me a syntax error on line 23. I've looked at several references and asked several classmates for help, and nobody seems to understand what's wrong.
<code>.globl main

.data
test1:     .word 92
test2:     .word 81
finalExam: .word 90
a:         .ascii "Enter value A:\n"
b:         .ascii "Enter value B:\n"
grade:     .word 0
result:    .word 0
#More data...

.text
#Program calculates a final grade based off of two midterms and a final. Midterms are
#weighted 30% and the final is weighted 40%. Grade is out of 1000.
final:
li    $t4, 3 #PCSpim complains here.
li    $t5, 4
la    $t0, test1
lw    $t1, ($t0)
mult  $t1, $t4
mflo  $t1
la    $t0, test2
lw    $t2, ($t0)
mult  $t2, $t4
mflo  $t2
la    $t0, finalExam
lw    $t3, ($t0)
mult  $t3, $t5
mflo  $t3
add   $t4, $t1, $t2
add   $t4, $t4, $t3
la    $t0, grade
sw    $t4, ($t0)
#Print result to console
li    $v0, 1
move  $a0, $t4
syscall
jr    $ra

#Program continues...
</code>
Comment: What's the syntax error and which line is line 23?
Comment: Line 23 is the very beginning of the text section (li $t4, 3), and it does not specify what the syntax error is, which is biggest source of my confusion.
Comment: Just to clarify, Pseudo-ops, Bare Machine are enabled and Mapped I/O is disabled.
Comment: Can you provide a reduced example? You may also want to check for invisible characters (carriage returns, nonbreaking spaces, etc.) that may be causing problems.
Comment: You have `.globl main` as you should, but you don't have it defined. Instead you have label `final` at the entry point. I am guessing that's what's confusing pcspim. That's not an excuse for not giving sensible error message, of course.
Answer: Okay, figured it out, there were two problems in this situation. First, Bare Machine should have been disabled, and another problem came up when I used "b" as a label, because b is also used as an opcode.
Thanks for checking this out!

Syntax error in MIPS assembly


Como utilizar a classe vector do C++?

Question: Necessariamente precisa da biblioteca #include<vector.h>
Para cria-lo
vector <int> c;

Pergunta: Como armazenar valores nele e lê-los?
Comment: Não conheço muito sobre a linguagem, mas da uma olhada aqui: https://pt.wikibooks.org/wiki/Programar_em_C%2B%2B/Vetores
Comment: Por favor, não leve a mal este comentário, mas quando alguém que ainda está aprendendo a usar um recurso X começa uma pergunta com "necessariamente preciso de X", eu enxergo aí um belo começo de dogma. Cuidado, ok? Vetores têm suas utilidades, mas não são a única e/ou melhor estrutura de dados para toda e qualquer situação.
Answer: Para essas coisas é sempre interessante consultar a documentação quase oficial e aí fazer perguntas mais específicas do que não entendeu com um exemplo real do que está fazendo.
Uma das muitas formas seria:
vector <int> c { 1, 2, 3 }; //inicializa
c.push_back(4); //adiciona
cout << c[2]; //pega o elemento

Coloquei no GitHub para referência futura.
Buscas e outras operações são feitas em algoritmos gerais para qualquer coleção de dados.
Documentação alternativa.
Answer: Como descrito na documentação http://www.cplusplus.com/reference/vector/vector/
para colocar valores dentro do vector você deve utilizar push_back(valor) e para pegar um valor pode usar o operador [] ou a função at.
vector <int> c;
c.push_back(3);
c.push_back(4);
int a = c[0] // a recebe o valor 3
int b = c.at(1) // b recebe o valor 4

Comment: O site cplusplus.com não é considerado uma boa referẽncia.
http://stackoverflow.com/questions/6520052/whats-wrong-with-cplusplus-com
Answer: Não tem muito segredo, você usar o push_back para adicionar valores, depois pode pegar eles utilizando o indice ou um iterator.
Exemplo:
#include <iostream>
#include <vector>
using namespace std;

int main(){

    vector<int> vetor;
    int i;

    // INSERINDO 5 VALORES DE 1 A 5  USANDO PUSH_BACK
   for(i = 0; i < 5; i++){
      vetor.push_back(i);
   }
    // PEGANDO O TAMANHO DO VETOR
    cout << "Tamanho do Vetor = " << vetor.size() << endl;

    // ACESSANDO OS 5 VALORES DO VETOR PASSANDO PELO INDEX
    for(i = 0; i < 5; i++){
      cout << "Valor do vetor [" << i << "] = " << vetor[i] << endl;
   }

   // OU USANDO O ITERATOR PARA ACESSAR OS VALORES.
   vector<int>::iterator v = vetor.begin();
   while( v != vetor.end()) {
      cout << "Valor do vetor = " << *v << endl;
      v++;
   }
    return 0;
}

Veja funcionando no https://ideone.com/LllvB0

Como utilizar a classe vector do C++?


Can I create border-bottom without diagonal corner?

Question: I want to create a box with different color, left,right and top color red and bottom color is grey but I want flat bottom-border of box
HTML

CSS
.ts {
    height:100px;
    width:100px;
    border-width:10px 10px 20px 10px;
    border-style:solid;
    border-color:#f00 #f00 #ddd #f00;
}

When I create it with above code, It seems like this

But I don't want bottom-border as diagonal corner, I want it as;

http://jsfiddle.net/3jHG8/
Is there an easy way to do it as crossbrowser?
Comment: You could try a pseudo element, or does it have to be a border? http://jsfiddle.net/3jHG8/1/
Comment: SVG-objects are a second option
Answer: Just use css box-shadow as follow:
JSFIDDLE DEMO 1
HTML

CSS
.ts {
    height:100px;
    width:100px;
    border-width:10px 10px 0px 10px;
    border-style:solid;
    border-color:#f00 #f00 transparent #f00;
    box-shadow: 0 20px 0 #ddd;
}

or box-shadow only:
.ts {
height: 100px;
width: 100px;
box-shadow: inset 0 10px 0 0 #f00,inset 10px 0 0 0 #f00,inset -10px 0 0 0 #f00, 0 20px 0 #ddd;
}

JSFIDDLE DEMO 2

Use CSS3 PIE, to emulates some text-shadow in older versions of in IE7 and IE8.
Answer: What you are asking is not possible. Instead you can use something like this:

sample text sample text sample text sample text sample text

.ts {
 height:100px;
 width:100px;
 padding:10px;
 border-bottom:10px solid #dfd;
 background-color:#f00;
}

Hope this helps.


What statistical distribution test to use for comparing Dataset and its subset?

Question: I have two sets, A and B ,containing height of students. Set A contains height of all students in the class and Set B contains height of some students from the same class. Hence, Set B is a subset of Set A.
I am interested in finding whether the distribution of Set B is same as that of Set A or not and do hypothesis testing on it. But am unsure of what test (KS, Mann-Whitney, etc.) to use given the relation between Set A and Set B.
It would be great to know what test to use and rationale behind it.
Edit: A similar question focuses on mean comparison but it differs in a way that this question is asking for suggestions on tests that compares the distribution which may or may not depend on mean comparison.
Comment: If A is made up of disjoint subsets B and C, it is better to compare B with C that to compare A with B. The latter would compare some individuals with themselves.
Comment: The duplicate makes the salient point that you merely need to compare the subset to its complement.  That applies no matter what kind of comparison you are making and reduces your question to "how do I compare two datasets?"  That's too broad (as evidenced by a great many different answers in other threads on this site).
Answer: Brief demonstration.  x1 represents part of a class, x2 represents the rest of the class, and x3 represents the whole class.
set.seed(717)
x1 = rnorm(20, 90, 15);  x2 = rnorm(10, 120, 20)

A Welch t test (in R) finds a significant difference between the two parts; P-value below 1%.
t.test(x1,x2)$p.val
[1] 0.007744975

However, no significant difference at the 5% level is found between the whole class and the larger part of it.
This second t test is not only inconclusive, it is improper. The two "samples" are not independent, as required for
a two-sample t test. In fact, they consist largely of the same 20 students.
x3 = c(x1,x2)
t.test(x3,x1)$p.val
[1] 0.08184957

Here are boxplots:
boxplot(x1,x2,x3, col="skyblue2")

Hote: Disadvantages of comparing the whole with  one of its parts are discussed elsewhere on this site. Here is one such Q & A.


Binomial probability for a continuous variable

Question: I have some data that look like this:
<code>dist <- c(125,12,26,21,52,123)
exists <- c(0,1,0,0,1,0)
df <- cbind(dist, exists)
</code>
Basically its a bunch of observations of whether connections exist at different distances. I'd like to fit to this data some kind of probability function that predicts the likelihood of a connection existing given the distance. However, I just can't figure out what to use! Sure this kind of thing is really obvious, but I just don't know where to start looking. Does anyone have any ideas?
Comment: Logistic regression.
Answer: The most common approach would be binomial logistic regression:
<code>> fit <- glm(exists ~ dist, family=binomial)
> summary(fit)

Call:
glm(formula = exists ~ dist, family = binomial)

Deviance Residuals:
      1        2        3        4        5        6
-0.3814   1.0765  -1.1318  -1.1846   1.5117  -0.3907

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.54218    1.43780   0.377    0.706
dist        -0.02501    0.02771  -0.903    0.367

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 7.6382  on 5  degrees of freedom
Residual deviance: 6.4266  on 4  degrees of freedom
AIC: 10.427

Number of Fisher Scoring iterations: 5
</code>
So the predicted probability of a connection is $e^\eta/(1+e^\eta)$ where $\eta=0.54218-0.02501\times \mbox{dist}$.
However, from the data you give, there is no convincing evidence that the probability of a connection actually depends on distance (P=0.367).
Examining the Akaike Information Criterion (AIC) for the logistic regression shows a lower information loss for the null model with just an intercept:
<code>> AIC( glm(exists ~ 1, family=binomial) )
[1] 9.63817
</code>
So, with this limited amount of data to work with, you would likely be better off ignoring distance when making the prediction.
Comment: Amazing, thanks for your answer! I just gave some toy data, with my real data I get a highly significant result (<2e-16)! Very helpful, thanks!
Comment: Hi, just a quick question about this. If I want to add a binomial predictor (e.g. whether a connection existed at a previous timepoint or not)  how would I go about doing that? glm(formula = exists ~ dist + paststate, family = binomial) seems to always give a p-value for paststate as almost 1, even though they are obviously highly correlated.
Comment: @DomBurns See my answer here: https://stats.stackexchange.com/questions/312137


How to compute confidence intervals from *weighted* samples?

Question: Imagine we have a webserver, which serves a total of N static URLS.
There are users visiting the URLs every day. At the end of each day, we have data like this:
URL1   --> 500 visits
URL2   --> 450 visits
URL3   --> 370 visits
URL4   --> 330 visits
...
URLN-1 --> 1 visit
URLN   --> 0 visits

Then, we take a weighted sample out of these URLs. Each URL is included in the sample with probability proportional to the number of visits.
E.g. URLN will never be sampled, And URLN-1 (which was only visited once that day) is 500 times less likely to be selected than URL1.
Why we sample?
Each URL leads to a page which either has a white background or a black one. Assume that determining this background is a time-consuming task which we can't automate it. Hence, we would like to sample a small number of URLs, manually check their colors, and produce such an estimate for the whole set of URLs:

How likely will a URL visit lead to a page with a white background?

This is easy: given a set of sampled URLs, for which we have manually determined the colors, we compute the following:
  (SUM of visits of white URLs in the sample) / (SUM of all visits in the sample)

E.g. if this produced a number like 0.40, we could say "we estimate that 40% of URL visits lead to a page with white background".
But here's the tricky part:

How can we compute confidence intervals (say at 95%) for this quantity?

I've been reading various "resampling" or "bootstrap" techniques (wikipedia), for example Jackknife or Bootstrap, or even Poisson Bootstrap which seems a good choice for large data that need to be processed in a distributed way.
To get a 95% confidence interval with such a method, all I'd have to do would be to compute the 2.5% and 97.5% quantiles of the generated estimates.
But all these methods appear to assume that the sampled observations (URLs here) are selected with the same probability. In my case, they aren't, they are selected with probability proportional to the number of visits.
And again, let's assume that I can't avoid the use of weights, I can't process my data to remove the weights, e.g. by replacing "URL111 --> 2 visits, URL999 --> 3 visits" with [URL111, URL111, URL999, URL999, URL999]. Sure, in that case, these bootstrapping techniques would work without modification.
So: Is there a way to augment one of these techniques to take account of sampling weights, and to produce confidence intervals?
Comment: Do you sample with or without replacement from the url's? Since the propert White is nonrandom, without replacement should be best. Or did I misunderstand something?
Answer: You have a scheme of two-level sampling, first sampling the urls, then sampling from that empirical distribution over urls to detect some website property. I will assume that website property, White (W) is constant in time, so it is enough to visit each site once. So it would be best with sampling without replacement, but you didn't tell us how you sampled. So first I will assume sampling with replacement, since that is easier analysis, and good approximation if number of sites is large.
Some notation. There is a population of websites (urls) visited by some frequencies $\pi=(\pi_1, \dotsc, \pi_S)$. Each website has (or not) some property $W$, written $W_i$ for site $i$, which is 1 if site is $W$ and 0 else.  On the first level of sampling site $i$ is visited $N_i$ times, and so we have an estimate of $\pi_i$, $\hat{\pi}_1=N_i/N_\cdot$, where $N_\cdot=\sum_i N_i$.
On the second level of sampling, we sample websites from the distribution $\hat{\pi}$ (with replacement), $n$ times. Let the site being sampled be $I_j$, but first we concentrate on the first time and write only $I$. Under the second-level distribution, we have $\DeclareMathOperator{\P}{\mathbb{P}}  \P(I=i)=\hat{\pi}_i$. The observed property is $W_I$, and we have
$$
 \P(W_I=1)=\sum_i \P(W_I=1 \mid I=i)\hat{\pi}_i=\sum_i W_i \hat{\pi}_i
$$
and then taking the expectation of that expression over the first-level sampling, we find $\P(W_I=1)=\sum_i W_i \pi_i$ which we denote by $Q$ and is the weighted fraction of sites with the property, which is our estimand. So the $\sum_{j=1}^n W_{I_j}$ has a binomial distribution with parameters $n,Q$, and confidence intervals can be based on that.


métrica para trazer visitas por dia google-analytics

Question: Alguém conhece alguma métrica ou dimensão do google analytics que dado um periodo de data, ele traga número de acessos por cada dia desse período?
Exemplo:
<code>dateRanges: [
          {
            startDate: '23-11-2017',
            endDate: '25-11-2017'
          }
        ],
        metrics: [
          {
            expression: 'ga:UsuariosPorDia'
          }
</code>
Resposta:
"2017-11-23" : 25,
"2017-11-24" :50,
"2017-11-25"
Answer: Consegui o que eu precisava, adicionando o parametro "ga:date" no dimensions.
Exemplo:
<code> metrics: [
          {
            expression:'ga:users'
          },

        ],
        dimensions: [
        {
          name: "ga:date"
        }]
</code>


Verification of few Riemann integration functions

Question: Pick out the functions which are Riemann integrable on $[0,1]$
(a) $f(x)= 1$ , if $x$ is rational     and $f(x)=0$,  if $x$ is irrational
(b)   $f(x)= 1$ , if $x∈{\alpha_1, \alpha_2, ….,\alpha_n}$ is rational     and $f(x)=0$,  otherwise,    where $\alpha_1, \alpha_2, ….,\alpha_n$  are fixed , but arbitrarily chosen numbers in $[0,1]$
(c)  and $f(x)=0$,  if $x$ is irrational    or if $x=0$   And $f(x)=\sin(q\pi)$,  if $x=\frac{p}{q}$ , and $q$ positive and coprime integers.
(d) $f(x) = \lim_{n\to\infty} \cos^{2n}(24\pi x)$.
(e) $f(x)= \cos x$ , if $0≤x≤\frac{1}{2}$ and $f(x)=\sin x $,  if $\frac{1}{2}<x≤1$
(a) is not true and it it a very common example.
(b) since only finitely many dis continuities so it is true.
(c) no idea
(d) no idea
(e) true. Since only one point of discontinuity.
Can anybody help me please.
Answer: For ($c$), simply note that $\sin(q\pi)=0$ for all integers $q$, hence $f(x)=0$ for all $x\in[0,1]$. For $(d)$, recall that $\lim_{n\to\infty}x^n=0$ for all $x\in[0,1)$. What is the range of $\cos^{2n}(24\pi x)$ and when does it equal the maximum? This should provide you with enough information to answer the question.
Comment: then both the functions are true in c and d . am i right
Comment: That is correct @poton.
Comment: are my views correct for the other options?
Comment: Yes, your other answers are correct.