How to replace only part of the match with python re.sub

Question: I need to match two cases by one reg expression and do replacement
'long.file.name.jpg' -> 'long.file.name_suff.jpg'
'long.file.name_a.jpg' -> 'long.file.name_suff.jpg'
I'm trying to do the following
re.sub('(\_a)?\.[^\.]*$' , '_suff.',"long.file.name.jpg")

But this is cut the extension '.jpg' and I'm getting
long.file.name_suff. instead of long.file.name_suff.jpg
I understand that this is because of [^.]*$ part, but I can't exclude it, because
I have to find last occurance of '_a' to replace or last '.'
Is there a way to replace only part of the match?
Comment: why are you escaping underscore `(\\_a)?`
Answer: Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text.
re.sub(r'(\_a)?\.([^\.]*)$' , r'_suff.\2',"long.file.name.jpg")

Comment: @cryanbhu Anything in brackets becomes a group. Groups are numbered in order of appearance and can subsequently be referenced by a backslash followed by the number. In the example, \2 references the second group. The single backslash is sufficient because putting r before the string has it treated as raw string. Without the preceding r , \\2 would reference the group.
In the "Regular expression syntax" documentation of python's re package, the relevant sections are (...) and \number . Furthermore, the \\ business is explained right in the beginning (3rd paragraph, as of today).
Comment: @Amber: I infer from your answer that unlike str.replace(), we can't use variables a) in raw strings; or  b) as an argument to re.sub; or c) both.  a) makes sense (I think) but I'm not sure about b). It seems we can use a variable name for the string the regex is going through, though. Would you care to elucidate? Thanks.
Comment: what are the parts that are capturing and referencing it?
Answer:  re.sub(r'(?:_a)?\.([^.]*)$', r'_suff.\1', "long.file.name.jpg")

?: starts a non matching group (SO answer), so (?:_a) is matching the _a but not enumerating it, the following question mark makes it optional.
So in English, this says, match the ending .<anything> that follows (or doesn't) the pattern _a
Another way to do this would be to use a lookbehind (see here).  Mentioning this because they're super useful, but I didn't know of them for 15 years of doing REs
Answer: Just put the expression for the extension into a group, capture it and reference the match in the replacement:
re.sub(r'(?:_a)?(\.[^\.]*)$' , r'_suff\1',"long.file.name.jpg")

Additionally, using the non-capturing group (?:…) will prevent re to store to much unneeded information.
Answer: You can do it by excluding the parts from replacing. I mean, you can say to the regex module; "match with this pattern, but replace a piece of it".
re.sub(r'(?<=long.file.name)(\_a)?(?=\.([^\.]*)$)' , r'_suff',"long.file.name.jpg")
>>> 'long.file.name_suff.jpg'

long.file.name and .jpg parts are being used on matching, but they are excluding from replacing.
Comment: A lookbehind `?<=` only allows for fixed-width patterns.  If you have one, this is a good option.
Answer: I wanted to use capture groups to replace a specific part of a string to help me parse it later. Consider the example below:
s= ' <address> 110 SOLANA ROAD, SUITE 102
PONTE VEDRA BEACH, FL32082 </address> 	'

re.sub(r'(<address>\s.*?)(
)(.*?\<\/address>)', r'\1 -- \3', s)
##' <address> 110 SOLANA ROAD, SUITE 102 -- PONTE VEDRA BEACH, FL32082 </address> 	'

Answer: print(re.sub('name(_a)?','name_suff','long.file.name_a.jpg'))
# long.file.name_suff.jpg

print(re.sub('name(_a)?','name_suff','long.file.name.jpg'))
# long.file.name_suff.jpg

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Jquery atualização de dados

Question: Tenho uma dúvida pertinente quanto a atualização de forma dinâmica:
Possuo um sistema de pedidos.
O problema é que os valores não estão sendo somados corretamente no evento de click.

Na primeira imagem eu apenas clico no botão "+" e a caixa de texto adiciona o número.
Na segunda o valor do pedido recebe todo o valor já somado.
HTML

    <form action="#">

        <input type="text" class="qtdpedidos" />

    </form>

 10.00

Valor do Pedido: R$0.00

JS
 $(".pizza-add-sub").append('
+

-
');
$(".qty-pizza").on("click", function() {

var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
  var newVal = parseFloat(oldValue) + 1;
} else {
  // Don't allow decrementing below zero
 if (oldValue > 0) {
    var newVal = parseFloat(oldValue) - 1;
    } else {
    newVal = 0;
  }
  }
$button.parent().find("input").val(newVal);
var total = 0;
var valorPizza = $('.pizza').text().substring(0, $('.pizza').text().indexOf('.'));

Answer:

 $(document).ready(function() {

     $(".pizza-add-sub").append('
+

-
');
     $(".qty-pizza").on("click", function() {

     var $button = $(this);
     var oldValue = $button.parent().find("input").val();
  if ($button.text() == "+") {
    var newVal = parseFloat(oldValue) + 1;
  } else {
    // Don't allow decrementing below zero
    if (oldValue > 0) {
       var newVal = parseFloat(oldValue) - 1;
       } else {
       newVal = 0;
     }
  }
     $button.parent().find("input").val(newVal);
  var v1 = $('#item1 span').text();
  var v2 = Number(document.getElementById("qtdpedidos").value);
     document.getElementById("resultado").innerHTML = parseFloat(v1 * v2).toFixed(2);

  });
 });

<form action="#">

        <input type="text" id="qtdpedidos" class="qtdpedidos" value="0"/>

    </form>

 10.00

</form>

Valor do Pedido: R$0.00

Jquery atualização de dados


Como chamar uma função server side no evento onclick NextJS

Question: Estou montando uma loja virtual e NextJs.
Onde na listagem dos produtos há o botão "ADICIONAR AO CARRINHO".
A ideia é que ao clicar nesse botão (client side) seja salvo no banco o item adicionado sem sair da pagina em que está.
A ideia é mais ou menos essa:
"use client";

import addProdutoCarrinho from "@/lib/store/addProdutoCarrinho";

export default function ButtonCart() {

function addCart(){

  addProdutoCarrinho();

}

  return (
    <button
      onClick={addCart}
      className="bg-brand text-white p-2 mt-3 uppercase"
    >
      Adicionar Carrinho
    </button>
  );
}

Onde addProdutoCarrinho() já faz o cadastro corretamente.
O problema é que é server side, ou seja, não executa no onClick dando erro.
Comment: Use AJAX, e faça uma requisição para API. Veja https://nextjs.org/docs/api-routes/introduction
Answer: Utilizando o padrão do NextJs 13, você pode utilizar Hooks (useEffect) para executar um fetch (POST) onde ficará o backend dessa interação.


Python customtkinter AttributeError: 'int' object has no attribute '_root'

Question: i just took over a project in python after a year and i wanted to rebuild it with customtkinter using the documentation. Here is the code:
import customtkinter
import tkinter
from pytube import YouTube
from PIL import Image

customtkinter.set_appearance_mode("system")
customtkinter.set_default_color_theme("blue")

app = customtkinter.CTk()
app.geometry("800x760")
app.title("YouTube Unlocked")

logo = customtkinter.CTkImage(dark_image=Image.open("G:\\ytdownloader\\assets\\icon.png"), size=(260,190))
logoDisplay = customtkinter.CTkLabel(app, text="", image=logo)
logoDisplay.pack(padx=10, pady=10)

linkLabel = customtkinter.CTkLabel(app, text="Video link", font=("Arial", 15))
linkLabel.pack(padx=10, pady=10)

linkTextbox = customtkinter.CTkEntry(app, width=400)
linkTextbox.pack(padx=10, pady=10)

radio_var = tkinter.IntVar(0)
radiobutton_1 = customtkinter.CTkRadioButton(app, text="Video", variable=radio_var, value=1)
radiobutton_2 = customtkinter.CTkRadioButton(app, text="Audio", variable=radio_var, value=2)
radiobutton_1.pack(padx=10, pady=10)
radiobutton_2.pack(padx=10, pady=10)

app.mainloop()

But after writing the radio buttons code (always from the documentation) I got this error:
Traceback (most recent call last):
  File "g:\ytdownloader\main.py", line 23, in <module>
    radio_var = tkinter.IntVar(0)
  File "C:\Users\gp_ga\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 564, in __init__
    Variable.__init__(self, master, value, name)
  File "C:\Users\gp_ga\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 372, in __init__
    self._root = master._root()
AttributeError: 'int' object has no attribute '_root'

Is there any way to fix this? Thanks! (by the way if it's a bad english I want to let you know that i'm using google translate)
Comment: Did you try `customtkinter.IntVar`?  Since you didn't create a Tk root, the library has not been initialized.
Comment: If you want to supply an initial value when creating a Tkinter Var object, that's the *second* parameter - more commonly written as a `value=` keyword parameter.  The first parameter is a widget (defaulting to the root window), which indirectly specifies the `Tk()` instance that owns the Var.
Answer: tkinter.IntVar() already has a default value of 0. The documentation says the following about the arguments that tkinter.IntVar() can take:

tkinter.IntVar(master=None, value=None, name=None)

Since master comes first and you provided 0 as the first positional argument, it believes that it is the master argument. What you want to do is specify the argument value. Like so:
radio_var = tkinter.IntVar(value=0)


Using python and matplotlib on android

Question: Is there a way to set up python 2.7.x + matplotlib on an android tablet so that you can run simple standard python code? I would like to be able to run the same scripts I run on my Linux desktop. This is just for my own use and I don't need to distribute the code to anyone else.
As a concrete example, is it possible to run this script?
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)

Comment: There is a similar topic:

http://stackoverflow.com/questions/13793158/python-interpreter-on-android
Answer: Is it easy, no.
Can it be done? Yes. I believe a skilled Python / Android developer could do it in 2 to 8 hours of effort..  It's a rare and complex request.
Why do I think it can be done? This sample: http://matplotlib.org/examples/pylab_examples/webapp_demo.html
Using a different library, and not abstracted for data without live hardware, this sample shows me that SL4A can do web-based graphics:
http://www.smartphonedaq.com/android-python-ecg.page
Now, if you were talking native GUI graphics in Android - then I'm focused way too much on the web methods of publishing with SL4A ;)
Answer: Pydroid is great for Matplotlib on Android, supports Numpy and many other libraries:
Pydroid for Python 2.7
Pydroid 3 for Python 3.6
Answer: There is an app called Gnuroot that allows you to run a kind-of chroot (proot), where you can install a linux distro such as debian, archlinux...
For the gui, there is the option to run a vncserver for an X server and use some android vnc client app to show the screen.
I use the non-gui version of gnuroot and it works well. I now have a command line debian wheezy on android lollipop arm. One minor thing i miss, is armhf (hardware floating point which my nexus7's processor can do) support instead of armel (software floating point).
Answer:  Upon searching numpy android on Google, I found a very nice library. I guess it might be helpful.
The above link no longer works. Please find more information regarding the library here.
Comment: Link seems dead.
Answer: Yes, it can be done, even without root. You need the termux app, it basically is a terminal emulator with a full Linux environment and via apt install python, for example, you can install python.
The main webpage is here, and it is of course available via the standard market. (The termux wiki is a helpful place.)
Answer: ever heard of qpython?
http://qpython.com/
i personally never used it, but my colleague were quite handy with it
so you may want to look at that
Comment: I don't think it supports matplotlib does it?
Comment: maybe this?
http://qpython.org/question/62/how-to-install-3rd-part-python-modules-for-qpython/
or just check the FAQ
Comment: The link is dead, [archived version here](http://web.archive.org/web/20131210104710/http://qpython.org/question/62/how-to-install-3rd-part-python-modules-for-qpython/)
Answer: I've read somewhere that scipy and matplotlib cannot be compiled for android, someone did it for numpy though
https://code.google.com/p/android-scripting/issues/detail?id=260
Answer: You could set up a cheap server (Raspberry Pi?) and create an ssh connection to it to access full python functionality through a vnc viewer android app or the shell
Answer: You can try MathSys. It's a wrapper around Python, and it has matplotlib inside.
Unfortunately, MathSys is rather convoluted, and it's an alpha version. Apparently, nobody is working on a beta version. You'll want to write any complicated code in an external file. import works fine in MathSys.
Answer: Here is the code, this works after installing GNURoot Debian as you said. Just a detail : my graph is exported directly in a .png file :
from pylab import *
import matplotlib.pyplot as plt
plt.switch_backend('agg')
x = linspace(-5, 5, 100)
y = sin(x)
plot(x, y)
out_png = 'out_file.png'
plt.savefig(out_png, dpi=150)

Answer: There is a lot of incorrect information in this thread!  I first tried Termux, using the information from this thread:
How do I install Jupyter notebook on an Android device?
but could not get Matplotlib downloaded for the life of me.  The error messages suggested I needed to install wheel, which I did, but the install crash was only postponed.  I am not saying it is not possible to install Matplotlib from Termux on a Galaxy Tab A, but I cannot do it.
On the other hand, downloading Pyroid3 was straightforward, as was installing numpy, scipy and matplotlib.  So that's my recommendation, based on success in doing so.
Answer: I just got this running for myself and these are the steps I used:

install termux (from the Play Store or FDroid)
install python in termux:

pkg install python

install matplotlib
install a graphical environment for matplotlib (I installed tkinter):

pkg install python-tkinter

install an X server
(I used XServer XSDL)
use this initialization sequence in your python:

import os
from time import sleep
os.environ["MPLBACKEND"] = "TkAgg"
os.environ["DISPLAY"] = ":0.0"
print('Loading X server...')
os.system("am start --user 0 -n x.org.server/.RunFromOtherApp 2>/dev/null")
os.environ["DISPLAY"] = ":0.0"
sleep(8) # give the X server an opportunity to start
print('Done')
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
plt.show()

There's probably a better way to detect whether the X server is already running so you don't have to launch it every time, but I haven't figured out how to do that yet.
Answer: Use the linux shell, I have it git python and pip installed on my phone. I used gnuroot in the play store.. You can apt-get install python pip from there
Comment: Very unclear answer. You could edit it and at least use formatting to clearly differentiate between `commands` and plain `words` (and while there maybe clean the grammer a bit?): http://stackoverflow.com/help/how-to-answer
Comment: Use the linux shell? I think on Linux it's already running but not on Android

Using python and matplotlib on android


Quantum computing and resampling techniques

Question: Maybe I miss interpreted how does quantum computing work.
If I understood well it would allow to perform extreme parallelization by making using a single qubit to perform many calculations at the same time by exploiting superposition.
I though that maybe calculation based on resampling or iteration could particularly benefit from it. For example one could perform bootstrap or cross validation using all possible combinations instead of relying on chance, hoping to find the right compromise between sampling bias and computation time.
Or even if you don't investigate all possible sample, one could perform montecarlo techniques instantly.
Now, I know we are talking about something that won't become mainstream in at least 50 years, but I just wanted to know if this intuition regarding parallelization is correct.
Thanks
Comment: It's not clear that we really can benefit from $2^n$ calculations from $n$ qubits (let alone 1 - - I don't think there's a way to do that in current models). Certainly if we're looking for a particular solution in $2^n$ possibilities, I think the best increase we know we can get is $2^{n/2}$ on $n$ qubits (e.g. see [here](https://rjlipton.wordpress.com/2013/04/27/sex-lies-and-quantum-computers/)). I guess it might depend on what exact sorts of calculations are being done.
Comment: Uhm, I'm missing something. In a full bootstrap calculation (no monte carlo) you have n^n possible resamples, not 2^n
Comment: 1. My comment related to how qubits work, not how bootstrapping works (see the link I offered, or a number of posts on Scott Aaronson's blog). The fact that there are $n^n$ bootstrap samples doesn't mean that you can calculate $n^n$ alternatives at once, with even $n$ qubits. 2. In any case, your question was about resampling and iteration, which includes but is not limited to bootstrapping. As an example, the number of possible samples in a paired permutation test is $2^n$
Comment: ok, got your point
Comment: I could turn this into an answer, but I am not sure it necessarily gives the kind of information you were seeking.
Answer: In theory...Maybe?
In our bootstrap method there is n^n possible resamples. When we do classical monte carlo we pick B random resample and pick B so that it is large enough to represent all the possible resamples. For each monte carlo simulation we just calculate the test-statistic.
In quantum monte carlo we would start with M independent quantum states, each of which are a superposition of the n^n possible resamples. When we measure a quantum state it will converge to one of the superposition states. If we want some quantum advantage we need to keep the M states in superposition while performing the next step in the bootstrap method. How you do this next step in the bootstrap method will determine if quantum monte carlo would be better or not. This is still a growing field, no one has proven whether you can this next step such that you gain an advantage.
My guess would be that bootstrap may not benefit from quantum monte-carlo. Even if you had a super-postion of all the possible test-statistics measuring this state would collapse it to one of the test-statistics, making it no diffrent from the classical case.


Payment through online banking in android

Question: I am in need to develop an android application which facilitate payment or money transfer to another user account using online banking service.
Is there any api available in android for online banking ?
Please suggest some solution.
Thanks!
Comment: check this http://www.zooz.com/
Answer: What I have done is implementing the same payment gateway which I used in my websites.We can use those gateways in Android Webviews.So if you are currently using any getways just proceed with the same.Otherwise go for some mobile gateways mentioned here


Split by gender, or pool them into the same model?

Question: Could someone please explain to me in layman's terms the difference between the following 3 scenarios in OLS multiple regression? Let's assume my DV is income, and my IVs are White race, Asian race, age, and residence region.
1) Split the entire sample by male/female, and run the models seperately.
2) Just run a single model, but add a control for gender (0/1).
3) Create distinct binary variables for each gender of each race, as if it's a categorical variable (e.g. White male (ref), White female, Asian male, Asian female).
So which method of these 3 is the best? And what are the reasons the other ones are not ideal? Any help would be greatly appreciated!
Thanks
Answer: Each of these methods is different, and I will first explain the differences before making a recommendation.  Method (2) uses a single linear model with a main-effect term for gender, but no interaction terms.  In this model you would get a single "shift" effect for the gender variable, but since there are no interaction terms, the effects of the other IVs would be assumed to be equal for males and females.  Method (3) generalises this, and is equivalent to a model with a main-effect variable for gender, plus interaction terms.  (There is no need to construct this by creating the interaction variables individually.  In standard statistical software you can add interaction terms from the original IVs without having to manually construct these as variables.)  Method (1) is a variation of this where instead of adding interaction effects, you split the two gender groups into completely separate models.  This latter method also effectively includes variable interaction, but each model ignores the data from the other gender.
The type of model you use will depend on your objective and the nature of your available data.  For simplicity, I'm going to assume that you simply want to make a predictive model for income.  If you have sufficient data to ensure reasonable residual degrees-of-freedom, I recommend starting with a single model with a main-effects term and interaction terms for the gender variable.  That model form will give you reasonable flexibility, but you will obviously still need to check its diagnostic plots to see if the data fit the assumed model form.  As I have argued in another answer, it is generally a bad idea to split your data into multiple models; it is far preferable to have a single model that can adequately describe your entire data set.  Because you are dealing with an income variable, you might also find that you get a better model if you put it on a logarithmic scale in the linear model, or use some other model that is appropriate for this type of variable.
Comment: Hi Ben, thank you for your answer. So you are recommending Method 3, right? If so, wouldn't the coefficients for the other IVs (let's say residence region) be assumed to be equal for both males and females?

Also, when I run both Method 3 and Method 1, the coefficients for the races differ--though only slightly. For example, in Method 3 (interactions), the Asian males yield a coefficient lower than the Asian males' coefficient in Method 1 (split by gender). Why would this be the case?
Comment: It is up to you what interaction terms you add to your model, but if you would like to allow the "effects" of other variables to vary by gender then you should add an interaction term.  Model 3 would be a reasonable starting point, but I'd recommend framing the model as a linear model for log-income rather than income.  The difference you are getting between Models 1 and 3 is likely to be due to the fact that the former excludes data on the other gender, and thereby alters the estimates.
Comment: Okay, I understand all of that; including data on the other gender alters the estimates.

However, do you know what is the exact effect that the females' data is having on the coefficients of the males? Generally speaking of course.


How do I revoke Amazon SES SMTP rights

Question: How do I revoke Amazon SES SMTP credentials? Do I just remove the SES-specific IAM user or can I revoke SMTP credentials and recreate them for the same user?
Answer: The Amazon SES SMTP credentials are entirely derived from the access key id and secret key for an IAM user. The SMTP credentials will no longer work if you do any of the following:

Update the policy for the user so it no longer has the SendRawEmail permission
Delete or deactivate the access key from which the credentials are derived
Delete the IAM user

If you want to create a new set of credentials then create a new access key for that user and follow the documented process to generate the SMTP credentials for that access key.

How do I revoke Amazon SES SMTP rights


Test Before Attempting Exclusive Lock

Question: I've written some code to upgrade a SQL Server database. Before I upgrade the database, I attain an exclusive lock via:
ALTER DATABASE Test SET SINGLE_USER WITH NO_WAIT

However, I'd like to test the database to see if the exclusive lock is possible before I run the above code. The test doesn't have to be 100% perfect, I'd just like to avoid the possibility of a timeout when attempting to gain an exclusive lock.
To that end, I've written the code below:
SELECT
    *
FROM
    sys.db_tran_locks
WHERE
    resource_database_id = DB_ID('Test') AND
    request_session_id <> @@SPID

I'm assuming that if there's 1 or more row returned, then the database must be in use. Is this true? Or is it not that simple?
UPDATE Taking @gbn's comments into account, I've decided to force rollback of existing connections using the following statement:
ALTER DATABASE Test SET SINGLE_USER WITH ROLLBACK IMMEDIATE

Before running this code, I'll give the user the an opportunity to opt out. However, I'd like the user to be able to see the list of active connections to the database - so they can make an informed decision. Which leads me onto this question.
Answer: Mainly, a DB lock is just to show it is in use. Databases don't really have many exclusive locks situations compared to code/table objects.
Single user mode is not a lock, but the number of connections allowed.
I'd wrap the ALTER DATABASE in a TRY/CATCH block because there is no guarantee the state won't change between check and ALTER DB.
However, I could be wrong or misunderstanding the question... so you'll also have to test for the exclusive lock mode on the database resource in the query above. Your code above will show you any lock, which could be someone having a blank query window open in SSMS...
Edit, based on comment
You can detect who is using it by these:

sys.dm_exec_connections
sys.dm_exec_sessions
sys.dm_exec_requests

To be honest, it's difficult to stop auto stats update or a user taking the single connection. Normally, you'd this which disconnects all other users and not bother waiting...
ALTER DATABASE MYDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

Comment: In that case, what I'm trying to do is determine whether I can reduce the database to one connection. Is there a way to query the current set of connections?
Answer: What if the database becomes busy from the time you determined that it was not in use, until the point where you try to acquire the exclusive lock?
Comment: There's nothing to stop this from happening, of course. However, part of the upgrade process is for users to eliminate connections to the database. So hopefully it's more likely that the database will not be busy.

Test Before Attempting Exclusive Lock


Problem with the Möbius Inversion Formula

Question: (Edit) Can someone explain where the mistake is and what is wrong with the following "proof"?:
(i) $\sum_{d\mid n}(\sigma_k(d))$ = $\sum_{d|n}(\tau(\frac{n}{d})d^k)$ (True)
(ii) Define a function $S(n)$ such that $\sum_{d\mid n}(\sigma_k(d)) = S(n) = \sum_{d|n}(\tau(\frac{n}{d})d^k)$
(iii) The möbius inversion formula as it is stated in [Apostal, Analytic Number Theory, pg 32] says: If $f(n) = \sum_{d|n}g(d)$, then $g(n) = \sum_{d|n}f(d)\mu(\frac{n}{d})$
(iv)(a) $S(n) = \sum_{d\mid n}(\sigma_k(d))$, so we have $\sigma_k(n) = \sum_{d|n}S(d)\mu(\frac{n}{d})$
(iv)(b) $S(n) = \sum_{d\mid n}(\tau(\frac{n}{d})d^k))$, so we have $\tau(\frac{n}{n})n^k = n^k = \sum_{d|n}S(d)\mu(\frac{n}{d})$
(v) Therefore $\sigma_k(n) = n^k$
If anyone can tell me which line(s) is wrong and why it's wrong, that would be incredibly helpful. Thanks.
Comment: What are $\sigma_k$ and $\tau$?
Comment: $\sigma_k(n)$ is the sum of the divisors of n, each raised to the kth power, and $\tau(n)$ is the number of divisors of n.
Comment: How exactly did you use the MIF on the right side of your summation equation to get $n^k$?
Comment: If you let both sums equal some function dependent on n, say S(n), by taking the right hand side term outside the summation you get $\tau(\frac{n}{n})*n^k = \sum_{d|n}(\mu(\frac{n}{d})*S(d))$
Comment: What do you mean with "taking the right hand side term outside the summation"?
Comment: Using the Mobius Inversion on the term in the sum on the right i.e. $\tau(\frac{n}{d})*d^k$
Comment: Step (iv)(b) is wrong. Mobius inversion states that if $g(d)$ is a multiplicative function and $f(n) = \sum_{d \mid n} g(d)$, then $g(n) = \sum_{d \mid n} f(d) \mu(n/d)$. In step (iv)(b), you seem to be thinking that the function $g(m) = \tau(n/m) m^k$ is a multiplicative function, but this is not the case (indeed, this is only well-defined when $m \mid n$, rather than for all $m \in \mathbb{N}$).
Comment: I never saw the condition that g(d) had to be multiplicative in Apostal, I thought it was true for f and g being arithmetic?
Comment: @PeterHumphries Multiplicativity isn't needed. The problem is that $\tau(n/m)m^k$ depends on $n$.
Answer: Let $f_k(n)=n^k$, then $\sigma_k=1* f_k$, thus $1*\sigma_k=1*(1*f_k)=(1*1)*f_k=\tau*f_k$. If you use Möbius inversion formula to $\sigma_k=1*f_k$, you get $f_k=\mu*\sigma_k$, not $f_k=\sigma_k$.
Comment: Is 1 the identity function?
Comment: It's the constant function $n\mapsto 1$.
Answer: The mistake is in (iv)(b). In
$$\sum_{d \mid n} \Biggl(\tau\biggl(\frac{n}{d}\biggr)d^k\Biggr) \tag{1}$$
the expression we sum over is not of the form $f(d)$, as it would need to be to apply the Möbius inversion formula (iii). The summands in $(1)$ depend on $n$ as well as on $d$, we have the form
$$S(n) = \sum_{d \mid n} f(n,d)\,.$$
If we write things using the Dirichlet convolution using $u \colon n \mapsto 1$ and $\nu_k \colon n \mapsto n^k$ (thus we could write $\nu_0$ instead of $u$, but $u$ is a widely used name for that function), then the Möbius inversion formula can succinctly be stated as
$$g = u \ast f \iff f = \mu \ast g\,. \tag{2}$$
The left hand side of (i) gives you $S$ in the form $u \ast \sigma_k$, precisely what $(2)$ is about, thus $\sigma_k = \mu \ast S$, or written in long form
$$\sigma_k(n) = \sum_{d \mid k} \mu\biggl(\frac{n}{d}\biggr)S(d)\,,$$
by the Möbius inversion formula.
The right hand side of (i) however gives you $S$ in the form $S = \tau \ast \nu_k$, and $(2)$ says nothing about that form. A more general form of $(2)$ applies to that form however, and gives $\nu_k = \tau^{-1} \ast S$, or in long form
$$n^k = \sum_{d \mid n} \tau^{-1}\biggl(\frac{n}{d}\biggr)S(d)\,,$$
where $\tau^{-1}$ is the Dirichlet inverse of $\tau$. (Since $\tau = u\ast u$ and $\mu$ is the Dirichlet inverse of $u$ we have $\tau^{-1} = \mu \ast \mu$.)
Comment: Ah, never even occurred to me to consider the problem might be with n, thank you so much!!


App-Wide Styling Using VisualStates in UWP (since Style Triggers Aren't Supported)

Question: I'm new to UWP and have been banging my head against the wall trying to figure out something that was very easy in WPF. Basically, I want the equivalent of Style Triggers to allow me to define control appearances in different states. What I desire:

I want all TextBoxes in the app to have an AliceBlue BorderBrush when they are focused.

All TextBoxes. Across the entire app. In WPF, I could define this in my App.xaml using a Style with Triggers targeting all TextBoxes. It was easy. But I'm struggling to do the same using VisualStates. All examples I see define VisualStates per Page, not at the app level. The only way I've found to do this is to copy the entire UWP TextBox style into my app and change the properties I want in the "Focused" state.
Is there a better way? Thanks.
Comment: IMHO changing the *Focused* state is the best way here.
Answer: If you are targeting Windows 10, version 1607 (Build 14393) and above, there are some resource values that you can change for this (the full list is here).
If you override this in your Application.Resources as below:
<SolidColorBrush x:Key="TextControlBorderBrushFocused" Color="Fuchsia" />

It should take affect everywhere.
Answer:
I want all TextBoxes in the app to have an AliceBlue BorderBrush when they are focused.

For you scenario you could also create the textbox style in Application.Resources, which is located in App.xaml file. One thing you need to pay attention to is that you could't set x:Key="XXXXStyle" for style. And it will modify the default system styles. The following is sample code.
<Application.Resources>

                            </Grid.Resources>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="*" />
                            </Grid.RowDefinitions>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="HeaderContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundDisabled}" />
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Normal" />
                                    <VisualState x:Name="PointerOver">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundPointerOver}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}" />
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Focused">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Red" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="RequestedTheme" Storyboard.TargetName="ContentElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Light" />
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="ButtonStates">
                                    <VisualState x:Name="ButtonVisible">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="DeleteButton">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="ButtonCollapsed" />
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Border x:Name="BorderElement" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" Grid.Row="1" Grid.RowSpan="1" />
                            <ContentPresenter x:Name="HeaderContentPresenter" Grid.ColumnSpan="2" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Foreground="{ThemeResource TextControlHeaderForeground}" FontWeight="Normal" Margin="0,0,0,8" Grid.Row="0" Visibility="Collapsed" x:DeferLoadStrategy="Lazy" />
                            <ScrollViewer x:Name="ContentElement" AutomationProperties.AccessibilityView="Raw" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" IsTabStop="False" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" Margin="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Row="1" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" ZoomMode="Disabled" />
                            <ContentControl x:Name="PlaceholderTextContentPresenter" Grid.ColumnSpan="2" Content="{TemplateBinding PlaceholderText}" Foreground="{ThemeResource TextControlPlaceholderForeground}" IsHitTestVisible="False" IsTabStop="False" Margin="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Row="1" />
                            <Button x:Name="DeleteButton" AutomationProperties.AccessibilityView="Raw" BorderThickness="{TemplateBinding BorderThickness}" Grid.Column="1" FontSize="{TemplateBinding FontSize}" IsTabStop="False" Margin="{ThemeResource HelperButtonThemePadding}" MinWidth="34" Grid.Row="1" Style="{StaticResource DeleteButtonStyle}" Visibility="Collapsed" VerticalAlignment="Stretch" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>

If you want want all TextBoxes in the app to have an AliceBlue BorderBrush when they are focused you just set the BorderBrush of BorderElement as your desired color.
 <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Red" />

Usage
<TextBox x:Name="MyTextBox" Width="100" Height="44" />

Effect
Comment: Thank you for an answer that fulfills my requirements. However, I was already aware of this option and was hoping that there would be a way of changing these properties on element focus *without* having to copy the entire `TextBox` style into my `App.xaml`. I would prefer to be able to just override the few properties I need (as I used to do with Triggers) while leaving the rest to the system.
Comment: @NSouth The Darshan's answer  is perfect. Starting in Windows 10, version 1607 (Windows Software Development Kit (SDK) version 10.0.14393.0), generic.xaml includes resources that you can use to modify the colors of a control in different visual states without modifying the control template. In apps that target this software development kit (SDK) or later, modifying these resources is preferred to setting properties such as Background and Foreground. For more info, see the  Light-weight styling section of the Styling controls article.


Windows Phone 7 sniffer

Question: Does any know some good http (at least) sniffer which works under Windows Phone 7 OS?
Currently I use wireshark/fiddler + windows phone 7 emulator for testing, but anyway I want to test my app using real phone + some win 7 phone sniffer too.
I'll appreciate any help.
Comment: Why? Are you seeing behaviour on a real device which indicates different network traffic?
Comment: I'm just curious :)
Btw from time to time I face with strange exception. It occures *only* when I use fiddler. So it will be much better to have some extra sniffing soft.
Comment: I mean this exception occured *only* when I use consume asmx web service by WP7 application while Fiddler is running.
*There was no endpoint listening at http://site.com/service.asmx that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.*
When I turn Fiddler off, then this error dissapears. So from time to time I want test app at device, not in emulator. So now I'm searching for WP7 sniffer.
Answer: You can use Fiddler with your device also.
Mike Ormond demonstrates here.
More Monitoring Web Requests on Windows Phone
Answer: The current Windows Phone platform SDK does not expose access to the network stack or the radio interface at all, so in the current incarnation there is no way to create a sniffer for the platform.
Comment: Thanks. That's sad but at least bad news are much better than no news at all.

Windows Phone 7 sniffer


Sum of $1^2+3^2+\cdots+(2n+1)^2$ Have trouble with proof.

Question: I've been working through a question on Courant's What is Mathematics?
This is the question: Prove $1^2+3^2+\cdots+(2n+1)^2=\frac{n(n+1)(2n+1)(2n+3)}{3}$. I called this $S_{(2n+1)^2}$.
What I've been given as a hint is that I can use the sum $1+2^2+3^2+\cdots+n^2=\frac{n(n+1)(2n+1)}{6}$ (I called this $S_{n^2}$) in some way.
So here's my line of thought:
What do I need to do to $S_{n^2}=1^2+2^2+3^2+\cdots+n^2$ to get $S_{(2n+1)^2}=1^2+3^2+\cdots+(2n+1)^2$?
When I compared them, I thought that $S_{n^2}-(2^2+4^2+\cdots+(2n)^2) = S_{(2n+1)^2}$.
I defined $2^2+4^2+\cdots+(2n)^2$ as $S_{(2n)^2}$.
After a bit of head-scratching I managed to figure out $S_{(2n)^2}=2^2(0)+2^2(1)^2+2^2(2)^2+\cdots+2^2(n)^2=4(1^2+2^2+3^2+\cdots+n^2)=4S_{n^2} =\frac{2}{3}n(n+1)(2n+1)$
Now is where my confusion starts. So from my logic above I went forward with $S_{n^2}-S_{(2n)^2}=S_{(2n+1)^2}$ which gave me $-\frac{1}{2}(n(n+1)(2n+1))$ which isn't $S_{(2n+1)^2}$.
I don't know where I really went wrong. One of my main suspicions is that $S_{n^2}-S_{(2n)^2}=S_{n^2}-4S_{n^2}=-3S_{n^2}\neq S_{(2n+1)^2}$. But I don't see why.
Comment: You're making matters worse for yourself with inconsistent use of $S_k$. First it's the sum of the squares of the odd numbers below $k$, the you start using it for the sum of the squares of all numbers below $k$. Try using different names and see if you can get through.
Comment: Proof by induction may be more appropriate since you are already told what the result will be.
Answer: Very easy proof
$$\sum_{k=1}^n(2k+1)^2=4\sum_{k=1}^n k^2+4\sum_{k=1}^nk+\sum_{k=1}^n1.$$
Using your hint, you can very easily conclude.
Comment: @george: you right, i corrected it.
Comment: Shouldn't there be 4 lots of the sum of K when you expand the quadratic?
Comment: @george $(a+b)^2=a^2+2ab+b^2$..
Comment: indeed for a+b but isn't it $(2a+b)^2$
Answer: $$1^2+2^2+\cdot\cdot\cdot+n^2=\dfrac{n(n+1)(2n+1)}{6}$$
This leads to the following:

$$1^2+\cdot\cdot\cdot+n^2+\cdot\cdot\cdot+(2n+1)^2=\dfrac{(2n+1)(2n+1+1)(2(2n+1)+1)}{6}$$
$$2^2+4^2+\cdot\cdot\cdot+(2n)^2=2^2(1^2+2^2+\cdot\cdot\cdot+n^2)=4\cdot\dfrac{n(n+1)(2n+1)}{6}$$

Thus,

$$1^2+3^2+\cdot\cdot\cdot+(2n+1)^2=\dfrac{(2n+1)(2n+1+1)(2(2n+1)+1)}{6}-\quad4\cdot\dfrac{n(n+1)(2n+1)}{6}=\dfrac{(n+1)(2n+1)(2n+3)}{3}=\sum_{i=0}^n (2i+1)^2$$

Note: You have an extra $n$ in your answer.
Answer: You are using a misleading notation. Let
$$
Q_n=\sum_{k=1}^n k^2=1^2+2^2+\dots+n^2={n(n+1)(2n+1)\over6},
$$
so that
$$
Q_{2n+1}=\sum_{k=1}^{2n+1} k^2=1^2+2^2+\dots+(2n)^2+(2n+1)^2={(2n+1)(2n+2)(4n+3)\over6}.
$$
As you noticed:
$$
1^2+3^2+\dots+(2n-1)^2+(2n+1)^2=Q_{2n+1}-4Q_n={(n+1)(2n+1)(2n+3)\over3}.
$$
Comment: I've just added the definitions of $Q_n$ and $Q_{2n+1}$ using the summation symbol. Hope that helps.
Comment: Could you please express your first two sums in sigma-notation form? I believe it will help me further clarify where I went wrong. Many thanks.
Comment: Thank you very much; it really cleared up where I went wrong.
Answer: Hint: Let $S_k$ denote the sum of the first $k$ squares. You should know a formula for this. Now
$$1^2+3^2+\cdots+(2n+1)^2$$
$$= (1^2+2^2+\cdots+(2n+2)^2)-(2^2+4^2+\cdots+(2n+2)^2)$$
$$=(1^2+2^2+\cdots+(2n+2)^2)-2^2(1^2+2^2+\cdots+(n+1)^2)$$
$$=S_{2n+2}-4S_{n+1}$$
Can you take it from here?
Answer: Using your hint, here is one way to go:
$$1^2 + 3^2 +\cdots +(2n+1)^2 = (1^2 + 2^2 + 3^2 + 4^2+\cdots +(2n+1)^2) - (2^2 + 4^2 + 6^2+\cdots+ (2n)^2)\\
(1^2 + 2^2 + 3^2 + 4^2+\cdots+ (2n+1)^2) - 4(1^2 + 2^2 + 3^2+\cdots+ n^2)$$
$$\frac{(2n+1)(2n+2)(4n+3)}{6} - \frac{4(n)(n+1)(2n+1)}{6}$$
Alternatively, you could use a proof by induction.
Base case:
$$n = 1\\
1^2 + 3^2 = \frac {1\cdot2\cdot3\cdot5}{3} = 10$$
Suppose:
$$1^2+3^2+\cdots+(2n+1)^2=\frac{n(n+1)(2n+1)(2n+3)}{3}$$
We will show that:
$$1^2+3^2+\cdots+(2n+1)^2 + (2n+3)^2=\frac{(n+1)(n+2)(2n+3)(2n+5)}{3}$$
By our hypothesis:
$$\frac{n(n+1)(2n+1)(2n+3)}{3} + (2n+3)^2=\frac{(n+1)(n+2)(2n+3)(2n+5)}{3}$$
And simplify.


What is the reason of error on git push?

Question: I cloned remote repo from bitbucket.
i didn't do yet any changes and already have one file as changed:
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   www/src/app/locale/Test.csv

no changes added to commit (use "git add" and/or "git commit -a")

in fact its a symlink in the repo.
I tried to remove it and push this change then but get this error:
➜  git:(master) git push origin master
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 535 bytes | 0 bytes/s, done.
Total 7 (delta 5), reused 0 (delta 0)
remote:
remote: One of your commit messages is missing an issue ID:
remote:
remote:   0df2153: test
remote:
remote: For more information, see https://confluence.atlassian.com/x/ZwjoE.
remote:
To https://bitbucket.org/[replaced_url_path].git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://[replaced_url_path].git'

I noticed that in the remote repo Test.csv comes with the low registry in the name of file:
www/src/app/locale/test.csv
I tried to rename it and push it. The result the same - i cannot push it with the same error.
I tried to use git config option
git config --system core.ignorecase false/true
tried to do like here:
How do I commit case-sensitive only filename changes in Git?
always result is the same.
Comment: Did you read the error message? It has nothing to do with case sensitivity.
Answer:
What is the reason of error on git push?

The reason is contained in the response from the server:

remote: One of your commit messages is missing an issue ID:

The remote repo requires that all commit messages must reference a corresponding entry in the bug tracker. Your commit message, however, is simply the word "test".
Comment: I read it, but i do not understand what git wants) what is the issue ID. Google says nothing about this. It would be more clearer if it sounds just smth like "your commit message is missing". Without "issue ID"

anyway thanks a lot for an idea! it helped me.
Comment: "I read it, but i do not understand what git wants" – Git doesn't want anything. The requirement comes from the owner of the repository, and the text of the error message either also comes from the owner of the repository, from the service they are using to implement this requirement, or from Bitbucket. By the way, I would be surprised if the owner of the repository allowed random people from the Internet to push to his repository anyway, I'm willing to bet that even if you supply an issue ID in the commit message, your push would be rejected with a different message. BTW: all of this is …
Comment: … explained in the "[For more information, see https://confluence.atlassian.com/x/ZwjoE.](https://confluence.atlassian.com/x/ZwjoE)" link in the error message.
Comment: one year ago it worked with "init" in the commit. Now i can push without ID but i need to write more words. I tried to push with "test update" and it did not work. After that i tried to add "update fix" and it works. What is the difference here? If ID must be there and its a strict rule according to the link so why smth like "update fix" or "init" works? (actually that was a reason why i did not think on ID)
Comment: You will have to ask the owner of the repository how he configured it and what kinds of commit messages he allows.


Biased coin game

Question: Assume, there's a 50% chance I get a fair coin and 50% I get a biased coin with 0.6 chance of getting heads.
Then, I get to toss the coin I got as many times as I want, but each toss costs a dollar.
The goal of the game is to determine if the coin is fair or not. Let's say I win 10000 dollars for the correct guess and lose 20000 dollars for the wrong one.
Again, I can toss the coin I got as many times as I want, but it's clear I don't want to toss it more than 10k times because then my profit is 0.
So, should I play the game? And what's the best number of tosses to maximize the profit/minimize loss?
What I've done so far, is found a Neyman-Pearson test statistic to see if the coin is biased:
$$T = \frac{n_0-n_1}{\sqrt{n_0+n_1}}$$
So, if I set the false alarm rate and missed signal rate I can find the number of tosses. But I'm not sure how to correctly set them.
Comment: Have you considered Sequential Probability Ratio Tests (SPRTs)?
Answer: Well, I've done a simulation where I used a simple criterion of saying the coin is biased if the current proportion is >0.55 else the coin is fair (middle between 0.5 and 0.6). Code in R:
res=replicate(1e3,{
  k=sample(c(0.5,0.6),1)
  s=sample(0:1,2e3,prob=c(1-k,k),replace=T)
  tmp=cumsum(s)/seq_along(s)
  ifelse(ifelse(k==0.6,1,0)==ifelse(tmp>0.55,1,0),1e4,-2e4)-seq_along(tmp)
})

and this is what the average reward plot looks like

note: i only tried up to 2000 draws as it has already converged somewhat by this time.
Answer: I'd keep track of the Bayes factor for the two hypotheses over time, and make a decision once the evidence passes a threshold.
Let $F$ be the event that the coin is fair and $B$ be the event that the coin is biased. Let $n$ be the number of coin tosses observed, and let $h, t$ be the observed number of heads and tails. The Bayes factor here is
$$K(h, t) = \frac{P(F \mid h, t)}{P(B \mid h, t)} = \frac{\binom{n}{h}0.5^h0.5^t}{\binom{n}{h}0.6^h0.4^t} \frac{P(F)}{P(B)}.$$
You told us that there's a 50% chance we get a fair coin, so $P(F) = P(B) = 0.5$. The Bayes factor is a measure of how many times more likely one model is than another. My proposal is that you stop once $K(h, t)$ is greater than some threshold $T$, or less than $1/T$.
Cancelling out common terms and taking logarithms to make the Bayes factor nice to work with, we have
$$\log K(h, t) = n \log 0.5 - h \log 0.6 - t \log 0.4.$$
You stop once $\log K(h, t) > \log T$, or $\log K < -\log T$.
We need an estimate of how many observations we will see before we make a decision for a given threshold $T$. We can approximate this by taking the expectation of $\log K$. If $F$, then
$$\log K(h, t) = n \log 0.5 - (n/2) \log 0.6 - (n/2) \log 0.4 = n\log(0.5\cdot0.6^{-0.5}\cdot0.4^{-0.5}) \approx 0.02n.$$
For $\log K$ to exceed $\log T$, we will therefore need $0.02n \approx \log T$, or $n \approx 50 \log T$. I quickly checked that this is an OK approximation in R (code below). If we observe $\log K$ until it exceeds $1$ then we should wait approximately 50 steps. And running the code below shows that it is approximately 50:
set.seed(1)
samples = numeric(1000)
for (i in 1:1000) {
  samples[i] = min(which((1:1000)*log(0.5/0.4) - cumsum(rbinom(1000, 1, 0.5))*log(0.6/0.4) > 1))
}
mean(samples)
53.961

If $B$, then
$$\log K(h, t) = n \log 0.5 - 0.6n \log 0.6 - 0.4n \log 0.4 = n\log(0.5\cdot0.6^{-0.6}\cdot0.4^{-0.4}) \approx -0.02n.$$
For $\log K$ to be less than $-\log T$ we need $n \approx 50 \log T$ again.
If we stop when $K > T$, then
$$\frac{P(F \mid h, t)}{1 - P(F \mid h, t)} = T,$$
so
$$P(F \mid h, t) = \frac{T}{T + 1}.$$
Similarly, if we stop when $K < 1/T$ then
$$P(B \mid h, t) = \frac{T}{T + 1}.$$
Hence the probability that we make the right decision is $T/(T + 1)$.
The expected benefit to the game is the expected value of the \$10k vs -\$20k payoff given that the probability we're choosing correctly minus the expected number of turns until we get to threshold $T$ or $1/T$:
$$E_T = \frac{T}{T + 1}10{,}000 - \frac{1}{T + 1}20{,}000 - 50\log T.$$
Differentiation w.r.t. $T$ gives
$$\frac{1}{(T + 1)^2} 10{,}000 + \frac{1}{(T + 1)^2} 20{,}000 - \frac{1}{T} 50.$$
Setting this to $0$ and solving gives:
$$\hat{T} = 299 - 10\sqrt{894} \approx 600, \log \hat{T} \approx 6.4.$$
That's quite a high threshold! Here's a plot of the expected value depending on $T$ from Wolfram:
Comment: This makes sense, but there seems to be a logical gap: why would maximizing the chance of "making the right decision" also maximize the expected reward?
Comment: Agreed, I should have made it clear that the 'make a choice once $K$ hits a threshold' strategy might not be the overall expectation-maximising one. But this solution is straightforward to implement and I could solve for the threshold to maximise the expected value
Comment: But how many tries does this method need to achieve this reward? And did you take into account that each try costs 1 unit?
Comment: @user2974951 For a threshold $T$ the average number of tries is roughly $50 \log T$, so if you set $\log T  = 6.4$ then the average number of tries will be $320$. Yes I did take the fact that each try costs one unit into account - it's the term $-50 \log T$ in the formula for $E_T$.

Biased coin game


Tracking Security Vulnerability remediation

Question: I've been looking into this for a little while, but havn't really found anything suitable.
What I am looking for is a system to track security vulnerability remdiation status. Something like "bugzilla for IT"
What I am looking for is something pretty simple that allows the following:

batch entry of new vulnerabilities that need to be remediated
Per user assignment
AD/LDAP Authentiation
Simple interface to track progress - research, change control status, remediated, etc.
Historical search ability
Ability to divide by division
Ability to store proof of resolution for the Security Team to access
Dependency tracking
Linux based is best (that's my group :) )
Free is good, but cost doesn't matter so much if the system is worth it

The systems doesn't have to have all of these features, but if it did that would be great.
yes we could use our helpdesk software, but that has a bunch of pitfalls such as triggering SLA alerts and penalties as well as not easily searchable outside of a group.
Most of what I have found are bug tracking systems that are geared towards developers, and are honstely way overkill for what I am looking for.
Server Faults input is greatly appreciated as always!
Comment: Red Hat Insights, maybe?
Answer: Ok, as far as I know, there is no product that will do this; would have to roll your own.
As far as starting points, I would start with Metasploit and nmap to gather your vulns, drop them into a db (mysql, postgres, etc.), and use that input as creation items for a bug-tracker (Trac, Redmine, etc) and use that as your ticketing engine.
As far as getting your AD/LDAP authentication records, you could probably do that input with syslog collection; I'm not sure if you could collect directly from there into your db.
I won't go as far as to say that 'if you productized this, you'd get rich', but with the right SEO, you could certainly get a lot of pageviews and/or consulting offers.
In any case, I hope it's worth it to you, because it's going to be a lot of work!  ;-)
UPDATE: Have you looked into Metasploit?
Answer: I realize this question is very old and you likely have found a solution that works for you, but if not - have you looked into the Dradis Framework? It ticks most of your boxes. Full disclosure, I work for the team that makes Dradis.
After you gather the output of your favorite tools from your assessment - Nmap, Burp, Nessus, etc. then use Dradis to compile them to a single project.
Use the rules engine to deduplicate findings, update the vendor's description to your own from the issue library.
Assign issues to users to remediate and customize the interface for the status categories that make sense for you.
If you are interested in taking a look - here are how the different plans and community edition compare: https://dradis.com/pro/editions.html


Profit or Loss Justification

Question: What is the justification of the following two sentences:
1.If an article is sold at a gain of 35% then its selling price is 135% of Cost price.

If an article is sold at a loss of 35% then its selling price is 65% of cost price.
Answer: Remember that the base value is $1$ times of its original value, which translates to $100$% of the original value. We can say this because by definition, $100$ lots of $1$ percent make up a whole part (equal to $1$).
Therefore, a percentage gain of $35$% results in $100$% + $35$% = $135$%,
and a percentage loss of $35$% results in $100$% - $35$% = $65$%.
Answer: I am not sure what justification you want here but If ideally you consider all the other expenses to be null(i. e transporting, maintaining, etc.)  or consider the cost price to include all the other expenses only then are the above statements justified...
Comment: I want to know how do we conclude the above two sentences. Like you have some proof or something ?

Profit or Loss Justification


Test if Anonymous users can sign up for a new account

Question: In a Drupal theme, how can you test if Anonymous users are able to sign up for a new account?
Background:
I am theming my user login form according to this tutorial.
On my themed user loser login form, there is an option for users to sign up if they do not have account.
On my site, I periodically disable anonymous sign ups, so when this happens, I want the sign up link in my theme to be not printed out.
Answer: If you look at the implementation of the login block in the core user module:
$items = array();
if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
  $items[] = l(t('Create new account'), 'user/register', array('attributes' =>
    array('title' => t('Create a new user account.'))));
}

you'll see that it queries a variable name user_register. If you disable anonymous registration, this becomes 0, and the link to "Create a new account" doesn't show.
This logic should work, no matter how you theme your site.
If your theme breaks this logic in the core user module, then you need to rework your theme until it don't break the core user module.
(Btw - this also tells you how to "test if Anonymous users are able to sign up for a new account" - check the status of the user_register variable, and if it is non-zero they should be able to sign up.  But this does not belong in your theme.  It belongs where it already is: In the core user module. I will advice against putting it in the theme.)


Predicting count data (clicks) based on the words used in a title

Question: So I have a data set of articles like so.
'Difference of Python and Ruby'    537
'Advanced Tutorial on Python'     1438
'HTTP library'                     134

The numbers next to them are click data. I am looking to do regression analysis between the words in each of the titles and the number of resulting view the article received, i.e. to draw conclusion on which words are best to use when titling an article for a specific community or group.
Also, I would love to hear other ideas as well as to what other cool conclusion I could draw from such data.
Edit
Requested Data I also added unique visits data as well.
[('Travis CI: Announcing Python and Perl support on Travis CI',
  {u'clicks': 81, u'unique': 74}),
 ('Software Maniacs blog \xc2\xbb Django as a micro-framework',
  {u'clicks': 333, u'unique': 318}),
 ('Interpreted Languages: Perl, PHP, Python, Ruby (Sheet One) - Hyperpolyglot',
  {u'clicks': 236, u'unique': 221}),
 ('PyCon 2012 has gone mobile on Guidebook!', {u'clicks': 1, u'unique': 1}),
 ('Twitter', {u'clicks': 17, u'unique': 17}),
 ('Static Modification of Python with Python: the AST Module - Blueprint Forge.',
  {u'clicks': 122, u'unique': 109}),
 ('Python for iOS - A Python interpreter and development environment for the iPod Touch, iPhone, and iPad',
  {u'clicks': 151, u'unique': 142}),
 ("Vivek's blog - Roll your own autocomplete solution using Tries.",
  {u'clicks': 211, u'unique': 203}),
 ('Twitter', {u'clicks': 4, u'unique': 4}),
 ('Ian Bicking: a blog :: Python Application Package',
  {u'clicks': 114, u'unique': 111}),
 ('PEP 414 -- Explicit Unicode Literal for Python 3.3',
  {u'clicks': 50, u'unique': 50}),
 ('Static Modification of Python with Python: the AST Module - Blueprint Forge.',
  {u'clicks': 0, u'unique': 0}),
 ('Requests: HTTP for Humans \xe2\x80\x94 Requests 0.10.6 documentation',
  {u'clicks': 18, u'unique': 17}),
 ('Haskell, Python and readability : programming',
  {u'clicks': 246, u'unique': 236}),
 ('PyCon 2012 has gone mobile on Guidebook!', {u'clicks': 40, u'unique': 38}),
 ('Pycoders Weekly (pycoders) on Twitter', {u'clicks': 12, u'unique': 12}),
 ('SWIX social media optimization, and social network marketing ROI',
  {u'clicks': 1, u'unique': 1}),
 ('PEP 414 -- Explicit Unicode Literal for Python 3.3',
  {u'clicks': 0, u'unique': 0}),
 ('[Python-Dev] PEP 414 - Unicode Literals for Python 3',
  {u'clicks': 82, u'unique': 82}),
 ('Google App Engine Blog: Announcing the General Availability of the Python 2.7 Runtime for App Engine',
  {u'clicks': 57, u'unique': 56}),
 ('What\xe2\x80\x99s new in Celery 2.5 \xe2\x80\x94 Celery 3.0.21 documentation',
  {u'clicks': 237, u'unique': 231}),
 ('Python Closures and Decorators (Pt. 2)', {u'clicks': 59, u'unique': 57}),
 ('Python for iOS - A Python interpreter and development environment for the iPod Touch, iPhone, and iPad',
  {u'clicks': 0, u'unique': 0}),
 ('Travis CI: Announcing Python and Perl support on Travis CI',
  {u'clicks': 1, u'unique': 1}),
 ('Quiz & Learn Python - Learn Python on Your Mobile Device',
  {u'clicks': 259, u'unique': 244}),
 ('Python Closures and Decorators (Pt. 1)', {u'clicks': 1, u'unique': 1}),
 ('Python Closures and Decorators (Pt. 1)', {u'clicks': 219, u'unique': 207}),
 ('Trie - Wikipedia, the free encyclopedia', {u'clicks': 18, u'unique': 15}),
 ('Ian Bicking: a blog :: Python Application Package',
  {u'clicks': 0, u'unique': 0}),
 ('Software Maniacs blog', {u'clicks': 42, u'unique': 41}),
 ('Quiz & Learn Python - Learn Python on Your Mobile Device',
  {u'clicks': 1, u'unique': 1}),
 ('Python Closures and Decorators (Pt. 2)', {u'clicks': 0, u'unique': 0}),
 ('SWIX social media optimization, and social network marketing ROI',
  {u'clicks': 71, u'unique': 69}),
 ('Twitter', {u'clicks': 6, u'unique': 6}),
 ('Software Maniacs blog \xc2\xbb Django as a micro-framework',
  {u'clicks': 4, u'unique': 4}),
 ('Haskell, Python and readability : programming',
  {u'clicks': 0, u'unique': 0})]

Comment: @MichaelLugo +1 on your irony detection -1 on your helpfulness.
Comment: I tried to write a more specific title to attract attention. Please let me know if I misunderstood your question.
Comment: @GaëlLaurans totally correct.
Comment: Can you make the data available? :P
Comment: @zx8754 yes I could incoming. I would love how to go about it myself using that sample there as an example
Comment: It's interesting to see that this post, on determining how to title a post well, was badly titled.
Comment: @zx8754 here is the data, updated the answer!
Answer: The first thing you need to do is make a matrix, where each column is a word and each row is a document.  The entries in this matrix will be counts of that word's frequency in the document.  This is known as the bag of words model.  You might consider removing words that occur in almost all documents as well as words that occur in almost no documents. It looks like you are using python, and I'm sure python has tools for doing this.
Now, it's a simple matter of doing a regression, where your matrix of word frequencies is the x variable, and number of clicks is the y variable.  Note that you're looking at count data, so you probably should be doing a poisson regression.  In R you would do this by specifying family='poission' to the glm function.
Additionally, you might want to include an "offset" or exposure variable.  This accounts for the fact that different documents might not have shown up the same number of times, and thus might not have had the same number of chances to be clicked on.  In R, you would do this by adding an offset() to your regression formula.  The offset has a known coefficient of 1.
It also might be a good idea to include a lasso penalty in your regression model.  This will remove some words from the equation if they do not contribute a lot to the model's accuracy.  In R you would do this with the glmnet package.
Finally, if you have a large number of documents and potential words, it might be a good idea to use a sparse matrix to represent your data (e.g. using the Matrix package in R).  glmnet can operate on sparse matrices, which will save you a lot of computation time.
The end result of this process will be a regression model based on each word's presence or absence in the title, where the coefficient represents how many clicks that word adds to the document.
Comment: sklearn has lasso: http://scikit-learn.org/0.13/modules/generated/sklearn.linear_model.Lasso.html
Comment: awesome! I am using pandas in place of R. Thanks for the pointers on where to begin here.
Comment: @myusuf3 Then you should probably check out NLTK and scikit-learn.  I think there's a lot of tools there for representing text and using it in regression.
Comment: @DavidMarx any suggestions on how to do the rest with scikit-learn
Comment: As Zach suggested, you'll probably want to use NLTK for the text processing. I believe scipy or numpy has a sparse matrix data type. Poke around in the documentation a bit.
Comment: @DavidMarx I am completely new at this, I would love to see a simple example illustrating the process.
Comment: @myusuf3 check the earlier link for a demo of lasso using sklearn. This SO question shows how to use NLTK and sklearn to set up a bag of words model for a naive bayes classifier: http://stackoverflow.com/questions/10098533/implementing-bag-of-words-naive-bayes-classifier-in-nltk . This link shows how to do a poisson regression using statsmodels: http://statsmodels.sourceforge.net/stable/examples/generated/example_discrete.html . Not sure if the sklearn lasso supports poisson regression, so you may need to use some other variable selection technique (such as "k best" in the NLTK demo).


Slideshow background images in Background

Question: I'm building a site in Drupal 7. Using the JCarousel module I'm trying to create something similar to this:
http://dale.no/
It's simple enough to create a full width slideshow and adding text over images is not too bothersome with a few adjustments to CSS.
But is it possible to make the images into backgrond CSS images, the same as on the dale.no site? The reason is, when you resize the browser, or use a different size monitor, I would like the centre of the image to remain in the centre of the browser. At the moment, on a square monitor, the centre of the images are cropped by the right hand side of the view port.
Is this possible with this module? Are there are other modules that can achieve this?
Answer: There are few jquery library which are not using images directly. They are using images as css background.
I found one link for you - http://demo.marcofolio.net/bgimg_slideshow/
The following tutorial might be useful for you-
http://www.techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/
This tutorial explains how to use css background images for slideshow.
Answer: I'm actually working on a Supersized.js module.   It is not quite ready for production but I can send you a dev version if you want to test it out in it's current stage/provide feedback.
I think this will provide all of the functionality you are after. It is an addon module to the views jqfx module.
Comment: Hi Chance, just wondering if is there any chance you send me supersized module.
Comment: I actuall just posted it to a sandbox on Drupal. http://drupal.org/sandbox/thechanceg/1358600 . Please add any bugs/issues to the issue queue.
Answer: Open source contributed Drupal 7 theme is available for this purpose. Photo theme.
https://drupal.org/project/photo
From the theme's project page:

Photo is a photography and multimedia theme with a full screen slideshow. Showcase your important work, imagination with full screen photo slider. Photo is Drupal theme for photographic professionals, photo artist, amateur photographers to create photo gallery, portfolio with photos, video blogs. It is also useful for architecture, travel sites, hotels, restaurants, sculpture artist and for any purpose who want to emphasis on photos for the website.
Comment: Hello. Could you expand your answer a bit? Is it doing it via CSS, how does it handle image positioning, things that concerned OP?


List out of index - Python but it should not be

Question: I was going through my lecture notes and was redoing an example the prof was doing in class. But I keep on getting a list out of index error. Any help or explanation would be great. I tried to read up on it but did not understand it hence am posting it here hoping that someone could explain it to me.
This is what I did:
def sortList(list1):

   sorted = []

   while len(list1)> 0:

     lowest = list1[0]

     for value in list1:
        #we need to place the items in order so first we will find the lowest value
        if value < lowest:
            lowest = value
        #lowest is the smallest number in list1
    # now we can add it to the sorted list

    sorted.append(lowest)

    #we can remove the item from list one
    list1.remove(lowest)

  return sorted

def median(list1):
  list1 = sortList(list1)
  #list one is now in sorted order

  while len(list1)> 2: # we are trying to take out all the numbers till 2 left (if 3 left it will execute and leave 1)
    list1.pop(0) #takes out the first item in the list
    list1.pop() #takes out the last item in the list

  if len(list1) == 1: # if there is only one item we return it
    return list1[0]
  else: #returns the avg of those
    return((list1[0] + list1[1])/2)

x = [45, -1, 0, 54, 101, 2, 7,11]

print(sortList(x))
print(median(x))

However when I do
print(sortList([45, -1, 0, 54, 101, 2, 7,11]))
print(median([45, -1, 0, 54, 101, 2, 7,11]))

it prints out fine. Why is that?
This is the error am getting:
print(median(x)) ... return((list1[0] + list1[1])/2)
IndexError: list index out of range.
Comment: Can you post your error traceback?
Comment: What's the exact problem with the first one? I feel like you neglected to mention that. Could you post a stack trace please?
Comment: btw, `sorted` is a built in function, you'd not want to overwrite it.
Comment: @KevinFang the prof did mention that sorted is a built in function. for this example, he used sorted as an empty list to help us understand what was happening in the code.
Answer: The reason is because the x has been modified in sortList function called at print(sortList(x)) statement. If you check, the value of x after that statement is []. Therefore, an empty list is inserted to median function, which causes out of index error when executing return((list1[0] + list1[1])/2) (since the length of empty list is 0 and 0 != 1)
print(sortList([45, -1, 0, 54, 101, 2, 7,11])) and print(median([45, -1, 0, 54, 101, 2, 7,11])) works because the median function did not get an empty list as the input.
Another reason is also because you are returning the sorted list from sortList function, but you are not storing it back to x. So, this should work
x = [45, -1, 0, 54, 101, 2, 7,11]
x = sortList(x)

print(x)
print(median(x))

Comment: Ah I see. Thanks for the explanation. This helps somewhat.
Comment: Edited my answer to include example
Comment: Thanks for the help. This definitely helped me understand the reason behind it.
Answer: This is because of your implementation of sortList() method. In that method x and list1 are reference to same list and as you removing the elements from list1 at the end of the method list x become empty list. so when you try to access elements from empty list ((list1[0] + list1[1])/2), it will give you index out of bound error.
You can visualize you code execution line by line http://www.pythontutor.com/visualize.html#mode=edit
Solution : copy list1 in new list in sortList(). you can use new_list = old_list.copy() or new_list = old_list[:]


Views Remember Last Selection Back Button D8

Question: I am having trouble with "Remember last selection" on views in D8. If I click a link away from the view and click back it does not remember my last selection. If I then refresh the page it does. This view does use Ajax and I cannot change that. Also I read somewhere that it may be due to caching from the headers.
If so what is the best way to add / change headers on a View response?
Answer: Looks like you have to subscribe to an event and manipulate the headers from there. I originally found this answer on how to manipulate headers in D8 here.
This will force a request to the server:
This file will go into your mymodule/src/EventSubscriber folder.
<code>namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class NoCacheSubscriber implements EventSubscriberInterface {

  public function RemoveCacheHeaders(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->set('Cache-Control', 'private, must-revalidate, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('RemoveCacheHeaders', -10);
    return $events;
  }
}
</code>
Then this will go into the your mymodule folder as mymodule.services.yml
<code>    services:
  remove_cache_options_subscriber:
    class: Drupal\mymodule\EventSubscriber\NoCacheSubscriber
    tags:
      - { name: event_subscriber }
</code>
Comment: this would completly disable cache browser cache, wouldnt it?
Comment: I think this will disable the cache for the whole site.
Comment: For that specific page yes
Comment: Oh yes you are correct it does. You could get the current route and determine it by that.


How does VAE generate the value of mean and sd for the latent space?

Question: I am just trying to understand the detailed mechanisms of VAE (variational autoencoder), and even new to Deep Learning.
I was wondering, how does the encoder part of the VAE can make sure to generate the value of Gaussian mean and sd?
I checked the code from Keras, it seems they used the same function to generate this two values? Then how do you know which is which?

Thanks for any replies.
Answer: layers.Dense is a dense layer. The code uses a different dense layer for each of the mean and the log-standard deviation. We know that it uses a different dense layer for each because  layers.Dense instantiates a new dense layer object, and that class is used twice.
You're right, there's nothing about this network that mandates that one must be the mean (except for the fact of how they're used). The one that you use for the mean is the mean; the one that you use for the standard deviation is the standard deviation. The advantage to working with log-standard deviation in this model is that you don't have to worry about the non-negativity constraint on the standard deviation because logs of positive numbers are real.


Delete operator behavior on non existing indexed element of an array?

Question: Why does delete operator return true if I try to delete non existing indexed element of an array?
More precisely deletion of undefined is true in javascript?
var arr = ['a','b','c','d'];

console.log(delete arr[2000]);  //true why?

console.log(delete aaaaa);     //true  why not reference error?

console.log(delete arrr[2000]);  //reference error  it's okay i think

I don't understand difference between 2nd and 3rd deletion. Both should ideally give reference error.
Comment: because it worked, arr[2000] is not there anymore.
Comment: do u mean deletion of undefined is true? arr[2000] was undefined
Comment: The real question is what are you trying to do, this might be a classical XY Problem case.
Comment: updated my answer to your edits
Answer: From the MDN:

Returns false only if the property exists and cannot be deleted. It
  returns true in all other cases.

edit:
here you just delete a in your scope, mostly the window scope
console.log(delete aaaaa);     //true  why not reference error?

so its the same as:
console.log(delete window.aaaaa);     //true

here arrr is undefined and you get an reference error before the delete method is called
console.log(delete arrr[2000]);  //reference error  it's okay i think


Can I let mean_iou depend on update_op? Both of them are returned by tf.metrics.mean_iou()

Question: Inspired by API of
accuracy, update_op = tf.metrics.accuracy()

which said I can only use
acc_value = sess.run(update_op)

to get the most updated accumulated accuracy value and update the accuracy at the same time.
But I didn't find the a similar feature in API of
mean_iou, update_op = tf.metrics.mean_iou()

So, can I use
with tf.control_dependencies([update_op]):
    get_miou_value_and_update_it = mean_iou

# in a session
sess.run(get_miou_value_and_update_it,feed_dict={...})

to perform similar function?
Answer: No, you would have to add an identity operation, otherwise you are not creating any actual dependency:
mean_iou, update_op = tf.metrics.mean_iou()
with tf.control_dependencies([update_op]):
    get_miou_value_and_update_it = tf.identity(mean_iou)


How can I find the length in seconds of a quarter-note (crotchet) if I have a tempo marking?

Question: Given a tempo marking in bpm (beats-per-minute), how can I work out the length of a crotchet (quarter-note) beat?
Answer: To find the length in seconds of each beat for any given metronome marking in beats-per-minute (bpm), you would divide 60 (the number of seconds in a minute) by the bpm marking. For instance, if a piece has a metronome marking of crotchet (quarter-note) = 120, each crotchet beat is 0.5 seconds long (60/120).
You can follow this simple rule to find the length of a crotchet whenever the tempo marking shows how many crotchet beats per minute there are. This will usually be for time-signatures with crotchet beats (i.e. with a 4 at the bottom, eg. 4/4, 3/4, 2/4 etc.)

However, if you wanted to find the length of a crotchet beat where the tempo marking shows the bpm of a different note value, you need to do an extra calculation. For instance, a time-signature of 3/8, tells you that there are 3 quaver (eighth) beats per bar. So, this would probably have a tempo marking showing the number of eighth beats per minute. You could follow the calculation above to find the length of each quaver beat, but would then need to double it to find the length of a crotchet beat, as a crotchet is twice the length of a quaver.

Of course, other types of beat can be used for a tempo marking. To continue the 3/8 example above, this could be shown with how many dotted crotchet beats there are per minute. (In other words, how many whole-bar, but not whole-note, beats there are per minute.) In this case, a crotchet is two-thirds the length of a dotted-crotchet, so each crotchet beat is two-thirds the length in seconds you would arrive at following the initial calculation.
Comment: Then you count up the number of beats in the whole tune, and it can tell you how long the tune should last...


Customizing Search File Attachments result page

Question: I'm using search_file_attachments module for my search, And also Search combine module to show all the results in one page. In the search results page, I like to maintain a structure. I need to show the node title instead of attached file name, and redirect to node url instead of attached file path when a user click on a result. So implement the template_preprocess_search_results() in my module overwrite the results. I tried to figure out the array result using devel.
function template_preprocess_search_result(&$variables) {
  dpm($variables);
}

And this my Devel results:

I cannot see any node details here, I guess this module only searching files in the folders. I'm finding a way to get the node details related to this results. Hope you guys got my question, Thanks in advance,
Answer: Finally I ended up with some advanced search modules, Which made the search so much better. I used Apache solr and Apache solr attachments modules. This gave me ability to make my search results in a customized way via hooks. I use hook_apachesolr_process_results() to change my results.
First I add a extra field to the file type entities in the solr index, which contain the node title.
/**
 * Implements hook_apachesolr_index_document_build().
 */
function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
    //dsm($entity_type);
    //if the type is file
    if($entity_type == 'file'){
        //add a field node title
        $title = code for getting the node tile of this file
        $document->addField('ts_field_node_title', $title);
    }
}

Now this extra field will be available in your search results. So you can directly use the title instead of file name.
/**
* Implements hook_apachesolr_process_results().
*/
function mymodule_apachesolr_process_results(&$arg) {

    for($i = 0, $l = count($arg); $i < $l; $i++) {
        //if entity type is file change the title
        if($arg[$i]['node']->entity_type != 'node'){
           $arg[$i]['title'] = $arg[$i]['fields']['ts_field_node_title'];
        }
    }

}

Peace! :)


How to find a lower bound for a sorting algorithm which involves super-comparisons?

Question: Suppose there is a sorting algorithm that in addition to regular comparisons, is also allowed super-comparisons: a super-comparison takes in three elements and outputs those elements in order from smallest to largest.
I want to find a lower bound.
Since unlike a regular comparison that only has two possible outcomes, a super-comparison will have 3! possible outcomes, I believe it should be log3(n!).
I am not sure though, any ideas?
Comment: You didn't specify the algorithm. Give us pseudocode otherwise what you ask is called a lower bound for the **problem** which is something different and may require a hard proof depending on the problem.
Comment: I am studying for an exam tomorrow. And this was a question in the book.
Answer: Actually, the number of super-comparisons is log_6(n!), this is because you have 6 possible outcomes per super-compare op, and not 3 (3! = 6). Thus, by repeatedly invoking these super-comparisons on the tree representing the random permutation, you get to a sorted array within log_6(n!) compare ops.
Note that when it comes to asymptotic time complexity - it remains O(nlogn) the base of the logarithm does not matter because you can switch bases easily:
log_6(n!) = log_2(n!)/log_2(6) = log_2(n!) / CONST
=> log_6(n!) is in O(log_2(n!))
=> log_6(n!) is in O(nlogn)

P.S A good intuition will be to see what happens at "infinity" i.e. what you have a super-comparison that sorts n elements. Obviously, you will need a single such op to sort an array, and indeed log_n!(n!) = 1, while log_n(n!) > 1.
Answer: in ocaml,
let rec quicksort = function
    | [] -> []
    | x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs
               in quicksort smaller @ (x::quicksort larger)

Comment: How does that answer the question?


Update em duas tabelas SQL Server

Question: Como faço para realizar um update ao mesmo tempo em duas tabelas diferentes?
Tenho uma tabela chamada Tarefa e outra chamado VinculoReferencia, ambas tem o campo Taridinclusao onde é esse campo que precisa ser atualizado ao mesmo tempo, e o campo TarID, que é a referência das tabelas.
Na query abaixo é um update simples se fosse pra atualizar somente na tabela vinculoreferencia, mas quero também que quando atualizar esta, atualizar também na tabela tarefa no campo taridinclusao:
update vinculoreferencia set taridinclusao = 168228 where tarid = 168261.

Comment: Com Stored Procedure você consegue fazer isso.
Answer: Entre as suas tabelas, qual possui a chave primaria?
Caso seja tarid, crie a foreign key com VinculoReferencia como cascade on update, assim ao atualizar tarid, Taridinclusao também será atualizado.
ALTER TABLE VinculoReferencia
ADD CONSTRAINT FK_Taridinclusao
    FOREIGN KEY (Taridinclusao)
    REFERENCES Tarefa(TarID)
    ON UPDATE CASCADE;

Referências:

Restrições de integridade referencial em cascata
Quando usar ON UPDATE CASCADE en

Update em duas tabelas SQL Server


Get touch event coordinate on an imageview

Question: I have an onTouchListener on an ImageView and I use event.getX() or getY().
My goal is to display an image and launch a dialog or something when the user touch a particular part of my image.
The problem is that with different screen, the X et Y values change for the same part of my image view.
How can I get the real position of the event in pixel on every screen ?
For instance I would like to display an Android face, and do something when the user click in his eyes...
Answer: Write your code to detect the touch at a specified point using a fixed resolution, e.g. 480x640.  Then get the resolution of the device the app is running on using DisplayMetrics.  Calculate xScale and yScale (e.g. DisplayMetrics.widthPixels / 480) and multiply your x and y by these scale factors.
Comment: Works great by using the current density value of the screen.


Firebase firestore - use collectionGroup queries in cloud function

Question: I want to use collectionGroup queries in a cloud function, and it only appears to be available if I import from firebase/app:
import * as firebase from 'firebase/app';
const db = firebase.firestore();

...
const snap = await db.collectionGroup('comments').where('foo', '==', 'bar').get();

But when I try to deploy I get

TypeError: firebase.firestore is not a function

In my other cloud functions, I have always imported from firebase-admin, but typescript tells me it has no collectionGroup method.
import * as admin from 'firebase-admin';
const db = admin.firestore();

Currently my versions are sitting at the following which should be latest:
"firebase": "^6.2.4",
"firebase-admin": "^8.2.0",

It would also be nice to understand why you would get your db instance from 'firebase-admin' or 'firebase/app'. I don't understand why there are 2 separate instances.
Answer: This should work:
import * as admin from 'firebase-admin'
const db = admin.firestore()

const snap = db.collectionGroup('comments').where('foo', '==', 'bar').get()

The collectionGroup type is supported on the last version
I would recommend to delete node_modules and install again (I just sanity check your sample and it went good, no issues on "firebase-admin": "8.0.0").
Comment: Thanks! VScode cached the interface from the older version. It wasn't until I option clicked through to the class that it refreshed the interface.


Direcionar via .htaccess uma query string

Question: Tenho um sistema onde haverá múltiplos usuários. Cada usuário terá seu próprio subdomínio. Ex.:
usuario1.sistema.com.br
usuario2.sistema.com.br

Para isso criei os subdiretórios e em cada um deles criei um .htaccess fazendo o redirecionamento para o sistema que se encontra na pasta raíz. Vejam:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^cliente1.sistema.com.br$ [OR]
RewriteCond %{HTTP_HOST} ^www.cliente1.sistema.com.br$
RewriteRule ^(.*)$ http://www.sistema.com.br/acesso/$1 [P]

O problema é que quando ele cria esse redirecionamento para o sistema, não consigo identificar quem é o cliente, ou seja, se é o cliente1 ou cliente2, etc.
Como eu poderia fazer para identificar esse cliente? Não tenho muita experiência com .htaccess, mas acredito que eu poderia usar RewriteCond %{QUERY_STRING} e no arquivo do sistema pegar no PHP com  $_REQUEST.  Algo como:
RewriteCond %{QUERY_STRING}^cliente=cliente1

E no PHP:
$cliente = $_REQUEST["cliente"];

Se essa for a solução, como eu faria para aplicar o RewriteCond %{QUERY_STRING} no meu .htaccess?
Answer: montei essa regra:
RewriteEngine on
RewriteRule ^cliente([0-9]+).sistema.com.br$ http://www.sistema.com.br/acesso/$1 [P]

Adicionei ([0-9]+) qualquer numero de 0 até 9 podendo ser um ou mais caracteres, em seguida coloquei ao final de acesso no redirecionamento. O teste está abaixo na imagem.

Pode usar essa ferramenta e melhorar a gosto :
https://htaccess.madewithlove.be/
Atualização:
Nesse caso Rei bastaria adaptarmos a regra assim :
RewriteEngine on
RewriteRule ^([a-z0-9-]+).sistema.com.br$ http://www.sistema.com.br/acesso/$1 [P]

Ou como você disse na pergunta que queria fazer um GET por cliente no php poderia ser:
RewriteEngine on
RewriteRule ^([a-z0-9-]+).sistema.com.br$ http://www.sistema.com.br/acesso?cliente=$1 [P]

Qualquer conjunto de carácteres de a até z minúsculos ou zero até nove podendo conter traços, e o + fora do colchetes significa um ou mais caracteres.

Espero que isto te ajude!
Comment: A pessoa que deu downvotes na minha resposta, poderia justificar qual o problema?Uma vez que colei o report do teste que comprova o funcionamento!
Comment: Não há de que meu Rei!
Comment: Olá Rafael. Obrigado pela resposta, mas se no caso em vez do nome ser cliente1, cliente2, for o nome real do cliente. Ex.: fernandopessoa.sistema.com.br, carloschagas.sistema.com.br,... Como eu faria? Me desculpe, coloquei cliente1, cliente2, como forma de exemplo.
Comment: Perfeito Rafael. Funcionou! Muito obrigado!